ColossalAI/tests/test_tensor/test_op.py

35 lines
936 B
Python
Raw Normal View History

import torch
from colossalai.tensor import ColoTensor, ColoParameter
2022-04-25 03:49:20 +00:00
from colossalai.utils import get_current_device
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())
input_t_colo = ColoTensor.from_torch_tensor(input_t.clone().detach())
2022-04-25 03:49:20 +00:00
# prepare colossalai LN
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)
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
assert torch.allclose(output_colo, output)
2022-04-25 03:49:20 +00:00
torch.mean(output).backward()
torch.mean(output_colo).backward()
assert torch.allclose(ln_op.weight.grad, weight.grad)
2022-04-21 09:18:56 +00:00
def check_all():
test_layernorm()
2022-04-21 09:18:56 +00:00
if __name__ == '__main__':
check_all()