2022-05-13 07:13:52 +00:00
|
|
|
from torch.nn import functional as F
|
2022-04-28 09:45:06 +00:00
|
|
|
from functools import partial
|
|
|
|
|
|
|
|
import colossalai
|
|
|
|
import pytest
|
|
|
|
import torch
|
|
|
|
import torch.multiprocessing as mp
|
2022-05-06 03:16:40 +00:00
|
|
|
from colossalai.testing import rerun_if_address_is_in_use
|
2022-04-28 09:45:06 +00:00
|
|
|
from colossalai.utils import free_port
|
2022-07-12 15:26:45 +00:00
|
|
|
from colossalai.tensor import ColoTensorSpec, ProcessGroup, ColoTensor
|
|
|
|
from _utils import tensor_equal, tensor_shard_equal, split_param_col_tp1d, split_param_row_tp1d
|
2022-05-13 07:13:52 +00:00
|
|
|
|
|
|
|
|
2022-07-04 10:54:37 +00:00
|
|
|
def run_with_spec(spec_init_func, pg: ProcessGroup):
|
2022-05-13 07:13:52 +00:00
|
|
|
model = torch.nn.Embedding(12, 32).cuda()
|
2022-07-06 08:15:16 +00:00
|
|
|
weight = ColoTensor(torch.nn.Parameter(model.weight.detach()), ColoTensorSpec(pg))
|
2022-07-12 15:26:45 +00:00
|
|
|
|
2022-07-04 10:54:37 +00:00
|
|
|
spec_init_func(weight, pg)
|
2022-07-12 15:26:45 +00:00
|
|
|
|
2022-05-13 07:13:52 +00:00
|
|
|
x = torch.tensor((0, 3, 6, 9)).cuda()
|
|
|
|
out = model(x)
|
|
|
|
colo_out = F.embedding(x, weight)
|
2022-05-19 10:57:56 +00:00
|
|
|
assert tensor_equal(out, colo_out)
|
2022-05-13 07:13:52 +00:00
|
|
|
grad = torch.rand_like(out)
|
|
|
|
out.backward(grad)
|
|
|
|
colo_out.backward(grad)
|
2022-07-04 10:54:37 +00:00
|
|
|
# compare grad inside a TP group
|
|
|
|
assert tensor_shard_equal(model.weight.grad, weight.grad, pg.tp_local_rank(), pg.tp_world_size())
|
2022-04-29 06:10:05 +00:00
|
|
|
|
|
|
|
|
2022-04-28 09:45:06 +00:00
|
|
|
def run_dist(rank, world_size, port):
|
2022-07-04 10:54:37 +00:00
|
|
|
# config = dict(parallel=dict(tensor=dict(mode="1d", size=world_size),))
|
|
|
|
colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl')
|
|
|
|
pg = ProcessGroup(tp_degree=world_size)
|
2022-07-12 15:26:45 +00:00
|
|
|
run_with_spec(split_param_row_tp1d, pg)
|
|
|
|
run_with_spec(split_param_col_tp1d, pg)
|
2022-05-13 07:13:52 +00:00
|
|
|
|
2022-04-28 09:45:06 +00:00
|
|
|
|
|
|
|
@pytest.mark.dist
|
2022-05-06 03:16:40 +00:00
|
|
|
@pytest.mark.parametrize('world_size', [1, 4])
|
2022-04-28 09:45:06 +00:00
|
|
|
@rerun_if_address_is_in_use()
|
|
|
|
def test_embedding_1d(world_size):
|
|
|
|
run_func = partial(run_dist, world_size=world_size, port=free_port())
|
|
|
|
mp.spawn(run_func, nprocs=world_size)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2022-05-13 07:13:52 +00:00
|
|
|
test_embedding_1d(4)
|