2022-04-21 03:42:37 +00:00
|
|
|
import torch
|
2022-05-09 08:11:47 +00:00
|
|
|
from colossalai.tensor import ColoTensor, ColoParameter
|
2022-04-25 03:49:20 +00:00
|
|
|
from colossalai.utils import get_current_device
|
2022-05-19 04:44:59 +00:00
|
|
|
from torch.nn import Parameter
|
|
|
|
import torch.nn.functional as F
|
2022-04-25 03:49:20 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_layernorm():
|
|
|
|
ln_op = torch.nn.LayerNorm(2, 3, device=get_current_device())
|
|
|
|
|
|
|
|
input_t = torch.randn(3, 2, device=get_current_device())
|
2022-05-19 04:44:59 +00:00
|
|
|
input_t_colo = ColoTensor.from_torch_tensor(input_t.clone().detach())
|
2022-04-25 03:49:20 +00:00
|
|
|
|
|
|
|
# prepare colossalai LN
|
2022-05-19 04:44:59 +00:00
|
|
|
weight = ColoTensor(Parameter(ln_op.weight.detach()))
|
|
|
|
bias = ColoTensor(Parameter(ln_op.bias.detach()))
|
2022-04-25 03:49:20 +00:00
|
|
|
|
|
|
|
output = ln_op(input_t)
|
2022-05-19 04:44:59 +00:00
|
|
|
output_colo = F.layer_norm(input_t_colo, ln_op.normalized_shape, weight, bias, ln_op.eps)
|
2022-04-25 03:49:20 +00:00
|
|
|
|
2022-05-19 04:44:59 +00:00
|
|
|
assert torch.allclose(output_colo, output)
|
2022-04-25 03:49:20 +00:00
|
|
|
|
|
|
|
torch.mean(output).backward()
|
|
|
|
torch.mean(output_colo).backward()
|
|
|
|
|
2022-05-19 04:44:59 +00:00
|
|
|
assert torch.allclose(ln_op.weight.grad, weight.grad)
|
2022-04-21 06:21:10 +00:00
|
|
|
|
2022-04-24 04:32:10 +00:00
|
|
|
|
2022-04-21 09:18:56 +00:00
|
|
|
def check_all():
|
2022-05-19 04:44:59 +00:00
|
|
|
test_layernorm()
|
2022-04-27 02:57:49 +00:00
|
|
|
|
2022-04-24 04:32:10 +00:00
|
|
|
|
2022-04-21 09:18:56 +00:00
|
|
|
if __name__ == '__main__':
|
2022-04-26 07:10:47 +00:00
|
|
|
check_all()
|