2023-01-18 10:12:27 +08:00
|
|
|
# Copyright (c) 2023, Tri Dao.
|
2022-12-24 09:53:16 +08:00
|
|
|
# Inspired by https://github.com/NVIDIA/apex/blob/master/apex/fused_dense/fused_dense.py
|
2022-11-14 13:52:00 +08:00
|
|
|
# We make it work with pytorch amp and with bfloat16.
|
2022-12-24 09:53:16 +08:00
|
|
|
# The TensorParallel linear modules are inspired by https://github.com/NVIDIA/apex/blob/master/apex/transformer/tensor_parallel/layers.py
|
2022-12-23 11:21:12 +08:00
|
|
|
from typing import Optional
|
2023-01-18 10:12:27 +08:00
|
|
|
from functools import partial
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
import torch
|
|
|
|
|
import torch.nn as nn
|
|
|
|
|
import torch.nn.functional as F
|
2022-12-23 11:21:12 +08:00
|
|
|
from torch import Tensor
|
2022-12-24 09:53:16 +08:00
|
|
|
from torch.distributed import ProcessGroup
|
2022-11-14 13:52:00 +08:00
|
|
|
from torch.cuda.amp import custom_bwd, custom_fwd
|
|
|
|
|
|
|
|
|
|
# import fused_dense_cuda # from apex
|
|
|
|
|
import fused_dense_lib as fused_dense_cuda
|
2022-12-24 09:53:16 +08:00
|
|
|
|
2023-04-14 06:28:44 +08:00
|
|
|
from flash_attn.ops.activations import gelu_bwd, relu_bwd, sqrelu_fwd, sqrelu_bwd
|
2023-01-08 05:45:22 +08:00
|
|
|
from flash_attn.utils.distributed import all_gather_raw, reduce_scatter_raw, all_reduce_raw
|
|
|
|
|
from flash_attn.utils.distributed import reduce_scatter, all_reduce
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
|
2022-12-23 11:21:12 +08:00
|
|
|
class FusedDenseFunc(torch.autograd.Function):
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
@custom_fwd
|
2023-01-08 05:45:22 +08:00
|
|
|
def forward(ctx, x, weight, bias, return_residual=False, process_group=None,
|
|
|
|
|
sequence_parallel=True):
|
2022-12-24 09:53:16 +08:00
|
|
|
"""
|
2023-01-08 05:45:22 +08:00
|
|
|
If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel
|
|
|
|
|
with sequence parallelism: we do an all_gather_raw of x before doing the matmul.
|
2022-12-24 09:53:16 +08:00
|
|
|
"""
|
2022-12-26 03:40:14 +08:00
|
|
|
ctx.compute_weight_gradient = weight.requires_grad
|
|
|
|
|
ctx.return_residual = return_residual
|
|
|
|
|
ctx.process_group = process_group
|
2023-01-08 05:45:22 +08:00
|
|
|
ctx.sequence_parallel = sequence_parallel
|
2022-12-26 03:40:14 +08:00
|
|
|
|
2022-11-14 13:52:00 +08:00
|
|
|
if torch.is_autocast_enabled():
|
2023-01-01 14:47:34 +08:00
|
|
|
x = x.to(dtype=torch.get_autocast_gpu_dtype())
|
2022-11-14 13:52:00 +08:00
|
|
|
x = x.contiguous()
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2023-01-01 14:47:34 +08:00
|
|
|
# We want to kick off the all_gather early, before weight dtype conversion
|
|
|
|
|
total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
|
|
|
|
|
else:
|
|
|
|
|
total_x = x
|
|
|
|
|
|
|
|
|
|
if torch.is_autocast_enabled():
|
|
|
|
|
weight = weight.to(dtype=torch.get_autocast_gpu_dtype())
|
|
|
|
|
bias = bias.to(dtype=torch.get_autocast_gpu_dtype()) if bias is not None else None
|
2022-11-14 13:52:00 +08:00
|
|
|
weight = weight.contiguous()
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2023-01-01 14:47:34 +08:00
|
|
|
handle_x.wait()
|
2023-01-02 09:06:39 +08:00
|
|
|
batch_shape, n = total_x.shape[:-1], total_x.shape[-1]
|
2023-01-01 14:47:34 +08:00
|
|
|
batch_dim = batch_shape.numel()
|
2023-01-02 09:06:39 +08:00
|
|
|
# https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174
|
|
|
|
|
if min(batch_dim, n, *weight.shape) > 65535 * 32:
|
|
|
|
|
raise RuntimeError('fused_dense only supports matrix dims <= 2M')
|
2023-01-01 14:47:34 +08:00
|
|
|
output = F.linear(total_x, weight, bias)
|
2022-12-24 09:53:16 +08:00
|
|
|
if ctx.compute_weight_gradient:
|
|
|
|
|
ctx.save_for_backward(x, weight)
|
|
|
|
|
else:
|
|
|
|
|
ctx.save_for_backward(weight)
|
2022-12-23 11:21:12 +08:00
|
|
|
return output if not return_residual else (output, x)
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
@custom_bwd
|
2022-12-23 11:21:12 +08:00
|
|
|
def backward(ctx, grad_output, *args):
|
2022-11-14 13:52:00 +08:00
|
|
|
grad_output = grad_output.contiguous()
|
2022-12-23 11:21:12 +08:00
|
|
|
if ctx.return_residual:
|
|
|
|
|
grad_input, = args
|
|
|
|
|
grad_input = grad_input.contiguous()
|
2022-12-24 09:53:16 +08:00
|
|
|
process_group = ctx.process_group
|
2023-01-08 05:45:22 +08:00
|
|
|
sequence_parallel = ctx.sequence_parallel
|
2022-12-24 09:53:16 +08:00
|
|
|
if ctx.compute_weight_gradient:
|
|
|
|
|
x, weight = ctx.saved_tensors
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2022-12-24 09:53:16 +08:00
|
|
|
total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
|
|
|
|
|
else:
|
|
|
|
|
total_x = x
|
|
|
|
|
else:
|
|
|
|
|
weight, = ctx.saved_tensors
|
|
|
|
|
total_x = None
|
|
|
|
|
batch_shape = grad_output.shape[:-1]
|
2022-11-14 13:52:00 +08:00
|
|
|
batch_dim = batch_shape.numel()
|
2022-12-23 11:21:12 +08:00
|
|
|
grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
|
|
|
|
|
if ctx.needs_input_grad[0]:
|
|
|
|
|
if not ctx.return_residual:
|
|
|
|
|
grad_input = F.linear(grad_output, weight.t())
|
|
|
|
|
else:
|
2022-12-24 09:53:16 +08:00
|
|
|
grad_input = torch.addmm(grad_input.reshape(batch_dim, grad_input.shape[-1]),
|
|
|
|
|
grad_output, weight)
|
|
|
|
|
grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1])
|
|
|
|
|
if process_group is not None:
|
2023-01-08 05:45:22 +08:00
|
|
|
reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw
|
|
|
|
|
grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True)
|
2022-11-14 13:52:00 +08:00
|
|
|
else:
|
|
|
|
|
grad_input = None
|
2022-12-24 09:53:16 +08:00
|
|
|
if ctx.needs_input_grad[1]:
|
|
|
|
|
assert ctx.compute_weight_gradient
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2022-12-24 09:53:16 +08:00
|
|
|
handle_x.wait()
|
|
|
|
|
grad_weight, grad_bias = fused_dense_cuda.linear_bias_wgrad(
|
|
|
|
|
total_x.reshape(batch_dim, total_x.shape[-1]), grad_output, ctx.needs_input_grad[2]
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
grad_weight = None
|
|
|
|
|
grad_bias = grad_output if ctx.needs_input_grad[2] else None
|
|
|
|
|
if process_group is not None and ctx.needs_input_grad[0]:
|
|
|
|
|
handle_grad_input.wait()
|
2023-01-08 05:45:22 +08:00
|
|
|
return grad_input, grad_weight, grad_bias, None, None, None
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
|
2022-12-23 11:21:12 +08:00
|
|
|
def fused_dense_func(x: Tensor, weight: Tensor, bias: Optional[Tensor] = None,
|
2023-01-08 05:45:22 +08:00
|
|
|
return_residual: bool = False, process_group: Optional[ProcessGroup] = None,
|
|
|
|
|
sequence_parallel: bool = True):
|
2022-12-23 11:21:12 +08:00
|
|
|
dtype_eligible = (x.dtype in [torch.float16, torch.bfloat16]
|
|
|
|
|
or (x.dtype == torch.float32 and torch.is_autocast_enabled()))
|
2023-01-02 09:06:39 +08:00
|
|
|
if x.is_cuda and weight.is_cuda and (bias is None or bias.is_cuda) and dtype_eligible:
|
2023-01-08 05:45:22 +08:00
|
|
|
return FusedDenseFunc.apply(x, weight, bias, return_residual, process_group,
|
|
|
|
|
sequence_parallel)
|
2022-12-23 11:21:12 +08:00
|
|
|
else:
|
2022-12-24 09:53:16 +08:00
|
|
|
assert process_group is None
|
2022-12-23 11:21:12 +08:00
|
|
|
out = F.linear(x, weight, bias)
|
|
|
|
|
return out if not return_residual else (out, x)
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
|
2022-12-23 11:21:12 +08:00
|
|
|
class FusedDense(nn.Linear):
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
def __init__(self, in_features: int, out_features: int, bias: bool = True,
|
2022-12-23 11:21:12 +08:00
|
|
|
return_residual: bool = False, device=None, dtype=None) -> None:
|
2022-11-14 13:52:00 +08:00
|
|
|
super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype)
|
2022-12-23 11:21:12 +08:00
|
|
|
self.return_residual = return_residual
|
2022-11-14 13:52:00 +08:00
|
|
|
|
2022-12-24 09:53:16 +08:00
|
|
|
def forward(self, x, process_group=None):
|
|
|
|
|
"""
|
|
|
|
|
If process_group is not None, we're doing Tensor Parallel with sequence parallelism:
|
|
|
|
|
we do an all_gather of x before doing the matmul.
|
|
|
|
|
"""
|
|
|
|
|
return fused_dense_func(x, self.weight, self.bias, return_residual=self.return_residual,
|
|
|
|
|
process_group=process_group)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ColumnParallelLinear(nn.Linear):
|
|
|
|
|
|
|
|
|
|
def __init__(self, in_features: int, out_features: int, process_group: ProcessGroup,
|
2023-01-08 05:45:22 +08:00
|
|
|
bias: bool = True, sequence_parallel=True, device=None, dtype=None) -> None:
|
2022-12-24 09:53:16 +08:00
|
|
|
world_size = torch.distributed.get_world_size(process_group)
|
|
|
|
|
if out_features % world_size != 0:
|
|
|
|
|
raise ValueError(f'out_features ({out_features}) must be divisible by '
|
|
|
|
|
f'world_size ({world_size})')
|
|
|
|
|
super().__init__(in_features, out_features // world_size, bias=bias,
|
|
|
|
|
device=device, dtype=dtype)
|
|
|
|
|
self.process_group = process_group
|
2023-01-08 05:45:22 +08:00
|
|
|
self.sequence_parallel = sequence_parallel
|
2022-12-24 09:53:16 +08:00
|
|
|
|
2022-11-14 13:52:00 +08:00
|
|
|
def forward(self, x):
|
2023-01-08 05:45:22 +08:00
|
|
|
# If self.sequence_parallel is True, we're doing Tensor Parallel with sequence parallelism:
|
|
|
|
|
# we do an all_gather of x before doing the matmul.
|
|
|
|
|
# If not, then the input is already gathered.
|
|
|
|
|
return fused_dense_func(x, self.weight, self.bias, process_group=self.process_group,
|
|
|
|
|
sequence_parallel=self.sequence_parallel)
|
2022-12-24 09:53:16 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class RowParallelLinear(nn.Linear):
|
|
|
|
|
|
|
|
|
|
def __init__(self, in_features: int, out_features: int, process_group: ProcessGroup,
|
2023-01-08 05:45:22 +08:00
|
|
|
bias: bool = True, sequence_parallel=True, device=None, dtype=None) -> None:
|
2022-12-24 09:53:16 +08:00
|
|
|
world_size = torch.distributed.get_world_size(process_group)
|
|
|
|
|
rank = torch.distributed.get_rank(process_group)
|
|
|
|
|
if in_features % world_size != 0:
|
|
|
|
|
raise ValueError(f'in_features ({in_features}) must be divisible by '
|
|
|
|
|
f'world_size ({world_size})')
|
|
|
|
|
# Only rank 0 will have bias
|
|
|
|
|
super().__init__(in_features // world_size, out_features, bias=bias and rank == 0,
|
|
|
|
|
device=device, dtype=dtype)
|
|
|
|
|
self.process_group = process_group
|
2023-01-08 05:45:22 +08:00
|
|
|
self.sequence_parallel = sequence_parallel
|
2022-12-24 09:53:16 +08:00
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
|
"""
|
|
|
|
|
We're doing Tensor Parallel with sequence parallelism: we do the matmul and then
|
|
|
|
|
a reduce_scatter of the result.
|
|
|
|
|
"""
|
|
|
|
|
out = fused_dense_func(x, self.weight, self.bias)
|
2023-01-08 05:45:22 +08:00
|
|
|
reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce
|
|
|
|
|
return reduce_fn(out, self.process_group)
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
|
2023-01-18 10:12:27 +08:00
|
|
|
class FusedMLPFunc(torch.autograd.Function):
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
@custom_fwd
|
2023-01-18 10:12:27 +08:00
|
|
|
def forward(ctx, x, weight1, bias1, weight2, bias2, activation='gelu_approx', save_pre_act=True,
|
|
|
|
|
return_residual=False, checkpoint_lvl=0, heuristic=0, process_group=None,
|
|
|
|
|
sequence_parallel=True):
|
2022-12-24 09:53:16 +08:00
|
|
|
"""
|
2023-01-08 05:45:22 +08:00
|
|
|
If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel
|
|
|
|
|
with sequence parallelism: we do an all_gather of x before doing the matmul.
|
|
|
|
|
If sequence_parallel=False, then the input is already gathered.
|
2022-12-24 09:53:16 +08:00
|
|
|
|
|
|
|
|
checkpoint_lvl:
|
2022-11-14 13:52:00 +08:00
|
|
|
0: no recomputation in the bwd
|
2023-01-18 10:12:27 +08:00
|
|
|
1: recompute gelu_out / relu_out in the bwd
|
|
|
|
|
2: recompute pre_act and gelu_out / relu_out in the bwd
|
2022-11-14 13:52:00 +08:00
|
|
|
"""
|
|
|
|
|
assert -1 <= heuristic <= 4
|
2023-04-14 06:28:44 +08:00
|
|
|
assert activation in ['gelu_approx', 'relu', 'sqrelu']
|
|
|
|
|
if activation == 'sqrelu':
|
|
|
|
|
assert heuristic == -1
|
2022-12-24 09:53:16 +08:00
|
|
|
if not save_pre_act:
|
2022-12-23 11:21:12 +08:00
|
|
|
checkpoint_lvl = 2
|
2022-11-14 13:52:00 +08:00
|
|
|
assert checkpoint_lvl in [0, 1, 2]
|
2022-12-23 11:21:12 +08:00
|
|
|
ctx.return_residual = return_residual
|
2022-12-24 09:53:16 +08:00
|
|
|
ctx.process_group = process_group
|
2023-01-08 05:45:22 +08:00
|
|
|
ctx.sequence_parallel = sequence_parallel
|
2023-01-01 14:47:34 +08:00
|
|
|
ctx.checkpoint_lvl = checkpoint_lvl
|
2023-01-18 10:12:27 +08:00
|
|
|
ctx.activation = activation
|
2023-01-01 14:47:34 +08:00
|
|
|
ctx.heuristic = heuristic
|
|
|
|
|
|
|
|
|
|
if torch.is_autocast_enabled():
|
|
|
|
|
x = x.to(dtype=torch.get_autocast_gpu_dtype())
|
2022-11-14 13:52:00 +08:00
|
|
|
x = x.contiguous()
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2023-01-01 14:47:34 +08:00
|
|
|
# We want to kick off the all_gather early, before weight dtype conversion
|
|
|
|
|
total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
|
|
|
|
|
else:
|
|
|
|
|
total_x = x
|
|
|
|
|
|
|
|
|
|
if torch.is_autocast_enabled():
|
|
|
|
|
dtype = torch.get_autocast_gpu_dtype()
|
|
|
|
|
weight1, weight2 = [a.to(dtype=dtype) for a in [weight1, weight2]]
|
|
|
|
|
bias1 = bias1.to(dtype=dtype) if bias1 is not None else None
|
|
|
|
|
bias2 = bias2.to(dtype=dtype) if bias2 is not None else None
|
2022-11-14 13:52:00 +08:00
|
|
|
weight1 = weight1.contiguous()
|
2022-12-23 11:21:12 +08:00
|
|
|
bias1 = bias1.contiguous() if bias1 is not None else None
|
2022-11-14 13:52:00 +08:00
|
|
|
weight2 = weight2.contiguous()
|
2022-12-23 11:21:12 +08:00
|
|
|
bias2 = bias2.contiguous() if bias2 is not None else None
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2023-01-01 14:47:34 +08:00
|
|
|
handle_x.wait()
|
2022-12-24 09:53:16 +08:00
|
|
|
batch_shape, n = total_x.shape[:-1], total_x.shape[-1]
|
2022-11-14 13:52:00 +08:00
|
|
|
batch_dim = batch_shape.numel()
|
2023-01-02 09:06:39 +08:00
|
|
|
# https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174
|
|
|
|
|
if min(batch_dim, n, *weight1.shape, *weight2.shape) > 65535 * 32:
|
|
|
|
|
raise RuntimeError('fused_dense only supports matrix dims <= 2M')
|
2022-11-14 13:52:00 +08:00
|
|
|
if heuristic == -1:
|
2023-01-18 10:12:27 +08:00
|
|
|
pre_act = F.linear(total_x, weight1, bias1)
|
|
|
|
|
activation_fn = (partial(F.gelu, approximate='tanh') if activation == 'gelu_approx'
|
2023-04-14 06:28:44 +08:00
|
|
|
else (sqrelu_fwd if activation == 'sqrelu' else F.relu))
|
|
|
|
|
with torch.jit.fuser('fuser2'):
|
|
|
|
|
output1 = activation_fn(pre_act)
|
2023-01-01 14:47:34 +08:00
|
|
|
# This is before adding bias1
|
2023-01-18 10:12:27 +08:00
|
|
|
# pre_act = F.linear(total_x.reshape(batch_dim, n), weight1)
|
2022-11-14 13:52:00 +08:00
|
|
|
# with torch.jit.fuser('fuser2'):
|
2023-01-18 10:12:27 +08:00
|
|
|
# output1 = bias_gelu(pre_act, bias1)
|
2022-11-14 13:52:00 +08:00
|
|
|
else:
|
2023-01-18 10:12:27 +08:00
|
|
|
is_gelu = activation == 'gelu_approx'
|
|
|
|
|
output1, *rest = fused_dense_cuda.linear_act_forward(
|
|
|
|
|
total_x.reshape(batch_dim, n), weight1, bias1, is_gelu, save_pre_act, heuristic
|
2022-12-24 09:53:16 +08:00
|
|
|
)
|
|
|
|
|
if save_pre_act:
|
2023-01-18 10:12:27 +08:00
|
|
|
pre_act = rest[0]
|
2022-12-23 11:21:12 +08:00
|
|
|
output2 = F.linear(output1, weight2, bias2)
|
2023-01-18 10:12:27 +08:00
|
|
|
if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == 'relu'):
|
|
|
|
|
# For RELU the pre_act is very small (just a bit-mask) so we just save it
|
|
|
|
|
ctx.save_for_backward(x, weight1, weight2, pre_act, output1)
|
2022-11-14 13:52:00 +08:00
|
|
|
elif checkpoint_lvl == 1:
|
2023-01-18 10:12:27 +08:00
|
|
|
ctx.save_for_backward(x, weight1, weight2, pre_act)
|
2022-11-14 13:52:00 +08:00
|
|
|
elif checkpoint_lvl == 2:
|
2022-12-23 11:21:12 +08:00
|
|
|
ctx.save_for_backward(x, weight1, weight2, bias1)
|
|
|
|
|
output2 = output2.reshape(*batch_shape, output2.shape[-1])
|
|
|
|
|
return output2 if not return_residual else (output2, x)
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
@custom_bwd
|
2022-12-23 11:21:12 +08:00
|
|
|
def backward(ctx, grad_output, *args):
|
2022-11-14 13:52:00 +08:00
|
|
|
grad_output = grad_output.contiguous()
|
|
|
|
|
checkpoint_lvl = ctx.checkpoint_lvl
|
2023-01-18 10:12:27 +08:00
|
|
|
activation = ctx.activation
|
|
|
|
|
activation_fn = (partial(F.gelu, approximate='tanh') if activation == 'gelu_approx'
|
2023-04-14 06:28:44 +08:00
|
|
|
else (sqrelu_fwd if activation == 'sqrelu' else F.relu))
|
2022-12-23 11:21:12 +08:00
|
|
|
if ctx.return_residual:
|
|
|
|
|
grad_input, = args
|
|
|
|
|
grad_input = grad_input.contiguous()
|
2022-12-24 09:53:16 +08:00
|
|
|
process_group = ctx.process_group
|
2023-01-08 05:45:22 +08:00
|
|
|
sequence_parallel = ctx.sequence_parallel
|
2022-12-23 11:21:12 +08:00
|
|
|
x, weight1, weight2, *rest = ctx.saved_tensors
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is None or not sequence_parallel:
|
2022-12-24 09:53:16 +08:00
|
|
|
total_x = x
|
|
|
|
|
batch_shape = grad_output.shape[:-1]
|
2022-11-14 13:52:00 +08:00
|
|
|
batch_dim = batch_shape.numel()
|
2022-12-24 09:53:16 +08:00
|
|
|
if checkpoint_lvl in [0, 1]:
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2022-12-24 09:53:16 +08:00
|
|
|
total_x, handle_x = all_gather_raw(x, process_group, async_op=True)
|
2023-01-18 10:12:27 +08:00
|
|
|
if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == 'relu'):
|
|
|
|
|
pre_act, output1 = rest
|
2022-12-24 09:53:16 +08:00
|
|
|
elif checkpoint_lvl == 1:
|
2023-01-18 10:12:27 +08:00
|
|
|
pre_act, = rest
|
2023-04-14 06:28:44 +08:00
|
|
|
with torch.jit.fuser('fuser2'):
|
|
|
|
|
output1 = activation_fn(pre_act)
|
2022-11-14 13:52:00 +08:00
|
|
|
elif checkpoint_lvl == 2:
|
2022-12-23 11:21:12 +08:00
|
|
|
bias1, = rest
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2022-12-24 09:53:16 +08:00
|
|
|
total_x, _ = all_gather_raw(x, process_group)
|
2022-11-14 13:52:00 +08:00
|
|
|
if ctx.heuristic == -1:
|
2023-01-18 10:12:27 +08:00
|
|
|
pre_act = F.linear(total_x, weight1, bias1)
|
2023-04-14 06:28:44 +08:00
|
|
|
with torch.jit.fuser('fuser2'):
|
|
|
|
|
output1 = activation_fn(pre_act)
|
2022-11-14 13:52:00 +08:00
|
|
|
else:
|
2023-01-18 10:12:27 +08:00
|
|
|
output1, pre_act = fused_dense_cuda.linear_act_forward(
|
|
|
|
|
total_x.reshape(batch_dim, total_x.shape[-1]), weight1, bias1,
|
|
|
|
|
activation == 'gelu_approx', True, ctx.heuristic
|
2022-12-23 11:21:12 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1])
|
|
|
|
|
output1 = output1.reshape(batch_dim, output1.shape[-1])
|
2023-01-18 10:12:27 +08:00
|
|
|
pre_act = pre_act.reshape(batch_dim, pre_act.shape[-1])
|
2022-12-23 11:21:12 +08:00
|
|
|
if ctx.needs_input_grad[3]:
|
|
|
|
|
grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(
|
|
|
|
|
output1, grad_output, ctx.needs_input_grad[4]
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
grad_weight2 = None
|
|
|
|
|
grad_bias2 = grad_output if ctx.needs_input_grad[4] else None
|
2022-11-14 13:52:00 +08:00
|
|
|
if ctx.heuristic == -1:
|
2023-01-18 10:12:27 +08:00
|
|
|
# grad_pre_act = matmul_dgelu(grad_output, weight2, pre_act)
|
2022-12-23 11:21:12 +08:00
|
|
|
grad_output1 = F.linear(grad_output, weight2.t())
|
2023-04-14 06:28:44 +08:00
|
|
|
activation_grad_fn = (gelu_bwd if activation == 'gelu_approx'
|
|
|
|
|
else (sqrelu_bwd if activation == 'sqrelu' else relu_bwd))
|
2022-11-14 13:52:00 +08:00
|
|
|
with torch.jit.fuser('fuser2'):
|
2023-01-18 10:12:27 +08:00
|
|
|
grad_pre_act = activation_grad_fn(grad_output1, pre_act)
|
2022-11-14 13:52:00 +08:00
|
|
|
else:
|
2023-01-18 10:12:27 +08:00
|
|
|
# The cublasLt epilogue has to compute both gelu/relu grad and bias grad, we can't
|
|
|
|
|
# just compute gelu/relu grad
|
|
|
|
|
grad_pre_act, grad_bias1 = fused_dense_cuda.bias_act_linear_dgrad_bgrad(
|
|
|
|
|
weight2, grad_output, pre_act, activation == 'gelu_approx', ctx.heuristic
|
2022-11-14 13:52:00 +08:00
|
|
|
)
|
2022-12-23 11:21:12 +08:00
|
|
|
if not ctx.needs_input_grad[2]:
|
|
|
|
|
grad_bias1 = None
|
|
|
|
|
if ctx.needs_input_grad[0]:
|
|
|
|
|
if not ctx.return_residual:
|
2023-01-18 10:12:27 +08:00
|
|
|
grad_input = F.linear(grad_pre_act, weight1.t())
|
2022-12-23 11:21:12 +08:00
|
|
|
else:
|
2022-12-24 09:53:16 +08:00
|
|
|
grad_input = torch.addmm(grad_input.reshape(batch_dim, grad_input.shape[-1]),
|
2023-01-18 10:12:27 +08:00
|
|
|
grad_pre_act, weight1)
|
2022-12-24 09:53:16 +08:00
|
|
|
grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1])
|
|
|
|
|
if process_group is not None:
|
2023-01-08 05:45:22 +08:00
|
|
|
reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw
|
|
|
|
|
grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True)
|
2022-12-23 11:21:12 +08:00
|
|
|
else:
|
|
|
|
|
grad_input = None
|
2022-12-24 09:53:16 +08:00
|
|
|
if ctx.heuristic == -1:
|
|
|
|
|
if ctx.needs_input_grad[1]:
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2022-12-24 09:53:16 +08:00
|
|
|
handle_x.wait()
|
|
|
|
|
grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_wgrad(
|
2023-01-18 10:12:27 +08:00
|
|
|
total_x.reshape(batch_dim, total_x.shape[-1]), grad_pre_act,
|
2022-12-24 09:53:16 +08:00
|
|
|
ctx.needs_input_grad[2]
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
grad_weight1 = None
|
2023-01-18 10:12:27 +08:00
|
|
|
grad_bias1 = grad_pre_act if ctx.needs_input_grad[2] else None
|
2022-12-24 09:53:16 +08:00
|
|
|
else:
|
|
|
|
|
if ctx.needs_input_grad[1]:
|
2023-01-08 05:45:22 +08:00
|
|
|
if process_group is not None and sequence_parallel:
|
2022-12-24 09:53:16 +08:00
|
|
|
handle_x.wait()
|
2023-01-18 10:12:27 +08:00
|
|
|
grad_weight1 = F.linear(grad_pre_act.t(),
|
2022-12-24 09:53:16 +08:00
|
|
|
total_x.reshape(batch_dim, total_x.shape[-1]).t())
|
|
|
|
|
else:
|
|
|
|
|
grad_weight1 = None
|
|
|
|
|
if process_group is not None and ctx.needs_input_grad[0]:
|
|
|
|
|
handle_grad_input.wait()
|
|
|
|
|
return (grad_input, grad_weight1, grad_bias1, grad_weight2, grad_bias2,
|
2023-01-18 10:12:27 +08:00
|
|
|
None, None, None, None, None, None, None)
|
2022-12-23 11:21:12 +08:00
|
|
|
|
|
|
|
|
|
2023-01-18 10:12:27 +08:00
|
|
|
def fused_mlp_func(
|
2022-12-23 11:21:12 +08:00
|
|
|
x: Tensor, weight1: Tensor, weight2: Tensor, bias1: Optional[Tensor] = None,
|
2023-01-18 10:12:27 +08:00
|
|
|
bias2: Optional[Tensor] = None, activation: str = 'gelu_approx',
|
2022-12-24 09:53:16 +08:00
|
|
|
save_pre_act: bool = True, return_residual: bool = False,
|
|
|
|
|
checkpoint_lvl: int = 0, heuristic: int = 0,
|
2023-01-08 05:45:22 +08:00
|
|
|
process_group: Optional[ProcessGroup] = None,
|
|
|
|
|
sequence_parallel: bool = True
|
2022-12-23 11:21:12 +08:00
|
|
|
):
|
2023-04-14 06:28:44 +08:00
|
|
|
assert activation in ['gelu_approx', 'relu', 'sqrelu']
|
2022-12-23 11:21:12 +08:00
|
|
|
dtype_eligible = (x.dtype in [torch.float16, torch.bfloat16]
|
|
|
|
|
or (x.dtype == torch.float32 and torch.is_autocast_enabled()))
|
2023-01-18 10:12:27 +08:00
|
|
|
# If we save pre-activation, dimension must be divisible by 128 (relu) or 8 (gelu)
|
|
|
|
|
dim_eligible = not save_pre_act or (x.shape[-1] % (128 if activation == 'relu' else 8) == 0)
|
2022-12-23 11:21:12 +08:00
|
|
|
if (x.is_cuda and weight1.is_cuda and weight2.is_cuda and (bias1 is None or bias1.is_cuda)
|
2023-01-18 10:12:27 +08:00
|
|
|
and (bias2 is None or bias2.is_cuda) and dtype_eligible and dim_eligible):
|
|
|
|
|
return FusedMLPFunc.apply(
|
|
|
|
|
x, weight1, bias1, weight2, bias2, activation, save_pre_act, return_residual,
|
2023-01-08 05:45:22 +08:00
|
|
|
checkpoint_lvl, heuristic, process_group, sequence_parallel
|
2022-12-23 11:21:12 +08:00
|
|
|
)
|
|
|
|
|
else:
|
2022-12-24 09:53:16 +08:00
|
|
|
assert process_group is None
|
2023-01-18 10:12:27 +08:00
|
|
|
pre_act = F.linear(x, weight1, bias1)
|
|
|
|
|
activation_fn = (partial(F.gelu, approximate='tanh') if activation == 'gelu_approx'
|
|
|
|
|
else partial(F.relu, inplace=True))
|
|
|
|
|
output1 = activation_fn(pre_act)
|
2022-12-23 11:21:12 +08:00
|
|
|
output2 = F.linear(output1, weight2, bias2)
|
|
|
|
|
return output2 if not return_residual else (output2, x)
|
2022-11-14 13:52:00 +08:00
|
|
|
|
|
|
|
|
|
2023-01-18 10:12:27 +08:00
|
|
|
class FusedMLP(nn.Module):
|
2022-11-14 13:52:00 +08:00
|
|
|
|
2023-04-18 18:37:14 +08:00
|
|
|
def __init__(self, in_features, hidden_features=None, out_features=None, bias1=True,
|
2023-01-18 10:12:27 +08:00
|
|
|
bias2=True, activation='gelu_approx', return_residual=False,
|
|
|
|
|
checkpoint_lvl=0, heuristic='auto', device=None, dtype=None):
|
2022-11-14 13:52:00 +08:00
|
|
|
"""
|
2022-12-24 09:53:16 +08:00
|
|
|
If process_group is not None, we're doing Tensor Parallel with sequence parallelism:
|
|
|
|
|
we do an all_gather of x before doing the matmul, gelu, then matmul.
|
|
|
|
|
Finally we do a reduce_scatter of the output.
|
|
|
|
|
|
2022-11-14 13:52:00 +08:00
|
|
|
checkpoint_lvl (increasing lvl means slower but more memory saving):
|
|
|
|
|
0: no recomputation in the bwd
|
|
|
|
|
1: recompute gelu_out in the bwd
|
2023-01-18 10:12:27 +08:00
|
|
|
2: recompute pre_act and gelu_out in the bwd
|
2022-11-14 13:52:00 +08:00
|
|
|
heuristic:
|
|
|
|
|
-1: don't fuse gemm + gelu (separate kernel)
|
|
|
|
|
0..4: use this heuristic for the algo section in the fused gemm + gelu
|
2023-01-18 10:12:27 +08:00
|
|
|
'auto': heuristic will be picked automatically:
|
|
|
|
|
For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf.
|
|
|
|
|
For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16.
|
2023-03-16 07:59:27 +08:00
|
|
|
For H100, we set heuristic=-1 for both fp16 and bf16 as the fused cuBlasLt implementation
|
|
|
|
|
is slower than the unfused version.
|
2022-12-23 11:21:12 +08:00
|
|
|
return_residual: whether to return the input x along with the output. This is for
|
|
|
|
|
performance reason: for post-norm architecture, returning the input allows us
|
|
|
|
|
to fuse the backward of nn.Linear with the residual connection.
|
2022-11-14 13:52:00 +08:00
|
|
|
"""
|
|
|
|
|
assert checkpoint_lvl in [0, 1, 2]
|
2023-04-14 06:28:44 +08:00
|
|
|
assert activation in ['gelu_approx', 'relu', 'sqrelu']
|
2022-11-14 13:52:00 +08:00
|
|
|
factory_kwargs = {'device': device, 'dtype': dtype}
|
|
|
|
|
super().__init__()
|
2023-04-18 18:37:14 +08:00
|
|
|
out_features = out_features or in_features
|
|
|
|
|
hidden_features = hidden_features or in_features * 4
|
2023-01-18 10:12:27 +08:00
|
|
|
self.activation = activation
|
2022-12-23 11:21:12 +08:00
|
|
|
self.return_residual = return_residual
|
2022-11-14 13:52:00 +08:00
|
|
|
self.checkpoint_lvl = checkpoint_lvl
|
2023-04-14 06:28:44 +08:00
|
|
|
self.heuristic = heuristic if activation != 'sqrelu' else -1
|
2022-12-23 11:21:12 +08:00
|
|
|
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs)
|
|
|
|
|
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs)
|
2022-11-14 13:52:00 +08:00
|
|
|
|
2022-12-24 09:53:16 +08:00
|
|
|
def forward(self, x, process_group=None):
|
2023-01-18 10:12:27 +08:00
|
|
|
dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype()
|
|
|
|
|
if self.heuristic == 'auto':
|
|
|
|
|
if self.activation == 'gelu_approx':
|
2023-03-16 07:59:27 +08:00
|
|
|
if torch.cuda.get_device_capability('cuda') == (9, 0):
|
|
|
|
|
heuristic = -1
|
|
|
|
|
else:
|
|
|
|
|
cuda_ver = tuple(map(int, torch.version.cuda.split('.')))
|
|
|
|
|
heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1)
|
2023-01-18 10:12:27 +08:00
|
|
|
else:
|
|
|
|
|
heuristic = 0
|
|
|
|
|
else:
|
|
|
|
|
heuristic = self.heuristic
|
|
|
|
|
out = fused_mlp_func(
|
2022-12-24 09:53:16 +08:00
|
|
|
x, self.fc1.weight, self.fc2.weight, self.fc1.bias, self.fc2.bias,
|
2023-01-18 10:12:27 +08:00
|
|
|
activation=self.activation, save_pre_act=self.training,
|
|
|
|
|
return_residual=self.return_residual, checkpoint_lvl=self.checkpoint_lvl,
|
|
|
|
|
heuristic=heuristic, process_group=process_group
|
2022-12-24 09:53:16 +08:00
|
|
|
)
|
|
|
|
|
if self.return_residual:
|
|
|
|
|
out, x = out
|
|
|
|
|
if process_group is not None:
|
|
|
|
|
out = reduce_scatter(out, process_group)
|
|
|
|
|
return out if not self.return_residual else (out, x)
|
|
|
|
|
|
|
|
|
|
|
2023-01-18 10:12:27 +08:00
|
|
|
class ParallelFusedMLP(nn.Module):
|
2022-12-24 09:53:16 +08:00
|
|
|
|
2023-04-18 18:37:14 +08:00
|
|
|
def __init__(self, in_features, hidden_features=None, out_features=None,
|
|
|
|
|
activation='gelu_approx', process_group: ProcessGroup = None,
|
|
|
|
|
bias1=True, bias2=True, sequence_parallel=True, checkpoint_lvl=0, heuristic='auto',
|
2023-01-18 10:12:27 +08:00
|
|
|
device=None, dtype=None):
|
2022-12-24 09:53:16 +08:00
|
|
|
"""
|
|
|
|
|
process_group is required. We're doing Tensor Parallel with sequence parallelism:
|
|
|
|
|
we do an all_gather of x before doing the matmul, gelu, then matmul.
|
|
|
|
|
Finally we do a reduce_scatter of the output.
|
|
|
|
|
|
|
|
|
|
checkpoint_lvl (increasing lvl means slower but more memory saving):
|
|
|
|
|
0: no recomputation in the bwd
|
|
|
|
|
1: recompute gelu_out in the bwd
|
2023-01-18 10:12:27 +08:00
|
|
|
2: recompute pre_act and gelu_out in the bwd
|
2022-12-24 09:53:16 +08:00
|
|
|
heuristic:
|
|
|
|
|
-1: don't fuse gemm + gelu (separate kernel)
|
|
|
|
|
0..4: use this heuristic for the algo section in the fused gemm + gelu
|
2023-01-18 10:12:27 +08:00
|
|
|
'auto': heuristic will be picked automatically:
|
|
|
|
|
For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf.
|
|
|
|
|
For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16.
|
2022-12-24 09:53:16 +08:00
|
|
|
"""
|
|
|
|
|
assert checkpoint_lvl in [0, 1, 2]
|
2023-04-14 06:28:44 +08:00
|
|
|
assert activation in ['gelu_approx', 'relu', 'sqrelu']
|
2022-12-24 09:53:16 +08:00
|
|
|
assert process_group is not None
|
|
|
|
|
factory_kwargs = {'device': device, 'dtype': dtype}
|
|
|
|
|
super().__init__()
|
2023-04-18 18:37:14 +08:00
|
|
|
out_features = out_features or in_features
|
|
|
|
|
hidden_features = hidden_features or in_features * 4
|
2023-01-18 10:12:27 +08:00
|
|
|
self.activation = activation
|
2022-12-24 09:53:16 +08:00
|
|
|
self.process_group = process_group
|
2023-01-08 05:45:22 +08:00
|
|
|
self.sequence_parallel = sequence_parallel
|
2022-12-24 09:53:16 +08:00
|
|
|
self.checkpoint_lvl = checkpoint_lvl
|
2023-04-14 06:28:44 +08:00
|
|
|
self.heuristic = heuristic if activation != 'sqrelu' else -1
|
2022-12-24 09:53:16 +08:00
|
|
|
self.fc1 = ColumnParallelLinear(in_features, hidden_features, process_group,
|
|
|
|
|
bias=bias1, **factory_kwargs)
|
|
|
|
|
self.fc2 = RowParallelLinear(hidden_features, out_features, process_group,
|
|
|
|
|
bias=bias2, **factory_kwargs)
|
|
|
|
|
|
2022-11-14 13:52:00 +08:00
|
|
|
def forward(self, x):
|
2023-01-18 10:12:27 +08:00
|
|
|
dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype()
|
|
|
|
|
if self.heuristic == 'auto':
|
|
|
|
|
if self.activation == 'gelu_approx':
|
|
|
|
|
cuda_ver = tuple(map(int, torch.version.cuda.split('.')))
|
|
|
|
|
heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1)
|
|
|
|
|
else:
|
|
|
|
|
heuristic = 0
|
|
|
|
|
else:
|
|
|
|
|
heuristic = self.heuristic
|
|
|
|
|
out = fused_mlp_func(
|
2022-12-23 11:21:12 +08:00
|
|
|
x, self.fc1.weight, self.fc2.weight, self.fc1.bias, self.fc2.bias,
|
2023-01-18 10:12:27 +08:00
|
|
|
activation=self.activation, save_pre_act=self.training,
|
|
|
|
|
checkpoint_lvl=self.checkpoint_lvl, heuristic=heuristic,
|
2023-01-08 05:45:22 +08:00
|
|
|
process_group=self.process_group,
|
|
|
|
|
sequence_parallel=self.sequence_parallel
|
2022-11-14 13:52:00 +08:00
|
|
|
)
|
2023-01-08 05:45:22 +08:00
|
|
|
reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce
|
|
|
|
|
return reduce_fn(out, self.process_group)
|