test_collective_api_base.py 25.6 KB
Newer Older
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import pickle
17
import socket
18 19
import subprocess
import sys
20
import tempfile
21
import unittest
22
from contextlib import closing
23 24 25 26

import numpy as np
from paddle_bfloat import bfloat16

27
import paddle
TaoTao Li's avatar
TaoTao Li 已提交
28
import paddle.distributed as dist
29
import paddle.fluid as fluid
30
from paddle.distributed.utils.nccl_utils import get_nccl_version_str
31 32 33
from paddle.fluid import core


34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
def create_bool_test_data(shape=None, seed=None):
    if seed:
        np.random.seed(seed)
    data = np.random.choice([True, False], size=shape)
    return data


def create_float_test_data(shape=None, dtype=None, seed=None):
    if seed:
        np.random.seed(seed)
    data = np.random.random(shape).astype(dtype)
    return data


def create_int_test_data(shape=None, dtype=None, seed=None):
    if seed:
        np.random.seed(seed)
TaoTao Li's avatar
TaoTao Li 已提交
51
    data = np.random.randint(0, high=12, size=shape).astype(dtype)
52 53 54 55 56 57 58 59 60 61 62
    return data


def create_complex_test_data(shape=None, dtype=None, seed=None):
    if seed:
        np.random.seed(seed)
    data = np.random.random(shape).astype(dtype)
    data.imag = np.random.random(shape)
    return data


63
def create_pyobject_test_data(shape=None, seed=None):
64 65
    if seed:
        np.random.seed(seed)
66 67 68 69 70 71
    list_shape = np.random.randint(0, high=100, size=(2)).tolist()
    list_data = np.random.random(shape).tolist()
    dict_key = [i for i in range(0, shape[0])]
    dict_val = np.random.random(shape).tolist()
    dict_data = dict(zip(dict_key, dict_val))
    return [list_data, dict_data]
72 73 74 75 76 77


def create_test_data(shape=None, dtype=None, seed=None):
    assert shape, "Shape should be specified"
    if dtype == "float32" or dtype == "float16" or dtype == "float64":
        return create_float_test_data(shape=shape, dtype=dtype, seed=seed)
78 79 80
    elif dtype == "bfloat16":
        # since numpy does not support bfloat16 yet, use `paddle_bfloat` to replace
        return create_float_test_data(shape=shape, dtype=bfloat16, seed=seed)
81 82
    elif dtype == "bool":
        return create_bool_test_data(shape=shape, seed=seed)
83 84 85 86 87 88
    elif (
        dtype == "int32"
        or dtype == "int64"
        or dtype == "int8"
        or dtype == "uint8"
    ):
89 90 91
        return create_int_test_data(shape=shape, dtype=dtype, seed=seed)
    elif dtype == "complex64" or dtype == "complex128":
        return create_complex_test_data(shape=shape, dtype=dtype, seed=seed)
92 93
    elif dtype == "pyobject":
        return create_pyobject_test_data(shape=shape, seed=seed)
94 95 96 97
    else:
        raise NotImplementedError("Unsupported dtype for creating test data.")


98
class TestCollectiveAPIRunnerBase:
99 100 101
    def get_model(
        self, train_prog, startup_prog, rank, indata=None, dtype=None
    ):
102
        raise NotImplementedError(
103 104
            "get model should be implemented by child class."
        )
105 106 107 108 109 110 111 112

    def run_trainer(self, args):
        train_prog = fluid.Program()
        startup_prog = fluid.Program()
        endpoints = args["endpoints"].split(",")
        rank = args["trainerid"]
        current_endpoint = args["currentendpoint"]
        nranks = 2
113 114 115 116
        if args["use_comm_context"]:
            paddle.distributed.collective._init_parallel_env(args["backend"])
        else:
            paddle.distributed.init_parallel_env()
117 118 119
        if args['backend'] == 'nccl':
            device_id = int(os.getenv("FLAGS_selected_gpus", "0"))
            place = fluid.CUDAPlace(
120 121
                device_id
            )  # if args.use_gpu else fluid.CPUPlace()
122 123 124
        elif args['backend'] == 'bkcl':
            device_id = int(os.getenv("FLAGS_selected_xpus", "0"))
            place = fluid.XPUPlace(device_id)
125 126
        else:
            place = fluid.CPUPlace()
127 128 129
        indata = create_test_data(
            shape=(10, 1000), dtype=args["dtype"], seed=os.getpid()
        )
L
lilong12 已提交
130
        if args['static_mode']:
131
            result = (
TaoTao Li's avatar
TaoTao Li 已提交
132 133 134 135
                self.get_model_new(
                    train_prog,
                    startup_prog,
                    rank,
136
                    dtype=args['dtype'],
TaoTao Li's avatar
TaoTao Li 已提交
137 138
                    reduce_type=args['reduce_type'],
                )
139 140 141
                if args["use_comm_context"]
                else self.get_model(train_prog, startup_prog, rank)
            )
L
lilong12 已提交
142 143 144 145 146
            exe = fluid.Executor(place)
            exe.run(startup_prog)
            fetch_list = []
            for elem in result:
                fetch_list.append(elem.name)
147 148 149
            out = exe.run(
                train_prog, feed={'tindata': indata}, fetch_list=fetch_list
            )
L
lilong12 已提交
150 151
        else:
            out = self.get_model(train_prog, startup_prog, rank, indata)
152
            # print(out, sys.stderr)
T
tianshuo78520a 已提交
153
        sys.stdout.buffer.write(pickle.dumps(out))
154 155 156 157 158 159 160 161 162 163 164 165


def runtime_main(test_class, col_type):
    args = {}
    model = test_class()
    args["trainerid"] = int(os.getenv("PADDLE_TRAINER_ID"))
    args["trainernum"] = int(os.getenv("PADDLE_TRAINERS_NUM"))
    args["endpoints"] = os.getenv('PADDLE_TRAINER_ENDPOINTS')
    args["currentendpoint"] = os.getenv("PADDLE_CURRENT_ENDPOINT")
    args["col_type"] = col_type
    args["backend"] = os.getenv("BACKEND")
    args["path_id"] = int(os.getenv("PATH_ID"))
L
lilong12 已提交
166
    args["static_mode"] = int(os.getenv("STATIC_MODE"))
167
    args["dtype"] = os.getenv("DTYPE")
TaoTao Li's avatar
TaoTao Li 已提交
168
    args["reduce_type"] = os.getenv("REDUCE_TYPE")
169
    args["use_comm_context"] = bool(int(os.getenv("USE_COMM_CONTEXT", "0")))
170 171 172 173 174 175 176 177
    model.run_trainer(args)


class TestDistBase(unittest.TestCase):
    def setUp(self):
        self._port_set = set()
        self._trainers = 2
        self._ps_endpoints = "127.0.0.1:%s,127.0.0.1:%s" % (
178 179 180
            self._find_free_port(),
            self._find_free_port(),
        )
181
        self._python_interp = sys.executable
182
        self._master_endpoints = "127.0.0.1:%s" % (self._find_free_port())
183

184 185
        self.temp_dir = tempfile.TemporaryDirectory()

186 187
        # NOTE: this is a hack to get int format nccl version, like 2134
        # if current platform is not linux, version number will be 0
188
        nccl_version_str = get_nccl_version_str()
189 190 191
        self._nccl_version = (
            int("".join(nccl_version_str.split("."))) if nccl_version_str else 0
        )
192

193 194 195
    def tearDown(self):
        self.temp_dir.cleanup()

196 197
    def _find_free_port(self):
        def __free_port():
198 199 200
            with closing(
                socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            ) as s:
201 202 203 204 205 206 207 208 209 210 211 212
                s.bind(('', 0))
                return s.getsockname()[1]

        while True:
            port = __free_port()
            if port not in self._port_set:
                self._port_set.add(port)
                return port

    def _run_cluster(self, model_file, envs):
        worker_endpoints = self._ps_endpoints.split(",")
        w0_ep, w1_ep = worker_endpoints
213
        # print("w0_ep:",w0_ep," w1_ep:",w1_ep)
214 215 216 217 218 219
        if core.is_compiled_with_cuda():
            env0 = {
                "FLAGS_selected_gpus": "0",
                "PADDLE_TRAINER_ID": "0",
                "PADDLE_TRAINERS_NUM": "2",
                "PADDLE_TRAINER_ENDPOINTS": self._ps_endpoints,
220
                "PADDLE_CURRENT_ENDPOINT": w0_ep,
221
                "PADDLE_MASTER": self._master_endpoints,
222 223 224 225 226 227 228
            }

            env1 = {
                "FLAGS_selected_gpus": "1",
                "PADDLE_TRAINER_ID": "1",
                "PADDLE_TRAINERS_NUM": "2",
                "PADDLE_TRAINER_ENDPOINTS": self._ps_endpoints,
229
                "PADDLE_CURRENT_ENDPOINT": w1_ep,
230
                "PADDLE_MASTER": self._master_endpoints,
231 232 233 234 235 236 237
            }
        elif core.is_compiled_with_xpu():
            env0 = {
                "FLAGS_selected_xpus": "0",
                "PADDLE_TRAINER_ID": "0",
                "PADDLE_TRAINERS_NUM": "2",
                "PADDLE_TRAINER_ENDPOINTS": self._ps_endpoints,
238
                "PADDLE_CURRENT_ENDPOINT": w0_ep,
239 240 241 242 243 244 245
            }

            env1 = {
                "FLAGS_selected_xpus": "1",
                "PADDLE_TRAINER_ID": "1",
                "PADDLE_TRAINERS_NUM": "2",
                "PADDLE_TRAINER_ENDPOINTS": self._ps_endpoints,
246
                "PADDLE_CURRENT_ENDPOINT": w1_ep,
247
            }
248
        # update environment
249 250
        env0.update(envs)
        env1.update(envs)
251 252 253 254
        if os.getenv('WITH_COVERAGE', 'OFF') == 'ON':
            tr_cmd = "%s -m coverage run --branch -p %s"
        else:
            tr_cmd = "%s %s"
255 256
        tr0_cmd = tr_cmd % (self._python_interp, model_file)
        tr1_cmd = tr_cmd % (self._python_interp, model_file)
257 258 259 260 261 262
        path0 = os.path.join(
            self.temp_dir.name, "/tmp/tr0_err_%d.log" % os.getpid()
        )
        path1 = os.path.join(
            self.temp_dir.name, "/tmp/tr1_err_%d.log" % os.getpid()
        )
263 264
        tr0_pipe = open(path0, "w")
        tr1_pipe = open(path1, "w")
265 266 267 268 269 270 271 272 273 274 275 276 277 278
        # print(tr0_cmd)
        tr0_proc = subprocess.Popen(
            tr0_cmd.strip().split(),
            stdout=subprocess.PIPE,
            stderr=tr0_pipe,
            env=env0,
        )

        tr1_proc = subprocess.Popen(
            tr0_cmd.strip().split(),
            stdout=subprocess.PIPE,
            stderr=tr1_pipe,
            env=env1,
        )
279 280 281 282 283 284 285 286

        tr0_out, tr0_err = tr0_proc.communicate()
        tr1_out, tr1_err = tr1_proc.communicate()
        sys.stderr.write('trainer 0 stderr: %s\n' % tr0_err)
        sys.stderr.write('trainer 1 stderr: %s\n' % tr1_err)
        # close trainer file
        tr0_pipe.close()
        tr1_pipe.close()
287
        with open(path0, "r") as f:
288
            sys.stderr.write('trainer 0 stderr file: %s\n' % f.read())
289
        with open(path1, "r") as f:
290
            sys.stderr.write('trainer 1 stderr file: %s\n' % f.read())
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
        return (
            pickle.loads(tr0_out),
            pickle.loads(tr1_out),
            tr0_proc.pid,
            tr1_proc.pid,
        )

    def check_with_place(
        self,
        model_file,
        col_type,
        backend="nccl",
        path_id="0",
        static_mode="1",
        check_error_log=False,
        need_envs={},
        eager_mode=True,
        dtype=None,
TaoTao Li's avatar
TaoTao Li 已提交
309
        reduce_type=None,
310
    ):
311 312 313 314
        if backend == "nccl" or backend == "bkcl":
            with_gloo = '0'
        else:
            with_gloo = '1'
315
        required_envs = os.environ.copy()
316
        dtype = "float32" if dtype is None else dtype
TaoTao Li's avatar
TaoTao Li 已提交
317
        reduce_type = dist.ReduceOp.SUM if reduce_type is None else reduce_type
318
        additional_envs = {
319
            "NCCL_P2P_DISABLE": "1",
L
lilong12 已提交
320
            "STATIC_MODE": static_mode,
L
lilong12 已提交
321
            "PADDLE_WITH_GLOO": with_gloo,
322
            "PADDLE_DISTRI_BACKEND": backend,
323
            "BACKEND": backend,
324
            "PATH_ID": path_id,
325
            "DTYPE": dtype,
TaoTao Li's avatar
TaoTao Li 已提交
326
            "REDUCE_TYPE": str(reduce_type),
327
        }
328
        required_envs.update(additional_envs)
329 330 331 332
        required_envs.update(need_envs)
        if check_error_log:
            required_envs["GLOG_v"] = "3"
            required_envs["GLOG_logtostderr"] = "1"
333
            required_envs["GLOO_LOG_LEVEL"] = "TRACE"
334

335 336
        if os.getenv('NVIDIA_TF32_OVERRIDE', '') is not None:
            required_envs['NVIDIA_TF32_OVERRIDE'] = os.getenv(
337 338
                'NVIDIA_TF32_OVERRIDE', ''
            )
339

340
        tr0_out, tr1_out, pid0, pid1 = self._run_cluster(
341 342
            model_file, required_envs
        )
343 344
        input1 = create_test_data(shape=(10, 1000), dtype=dtype, seed=pid0)
        input2 = create_test_data(shape=(10, 1000), dtype=dtype, seed=pid1)
345 346 347 348
        # cast bfloat16 to float32 for numeric comparison
        if dtype == "bfloat16":
            input1 = input1.astype("float32")
            input2 = input2.astype("float32")
349 350 351 352
        if col_type == "allgather":
            need_result = np.vstack((input1, input2))
            tr_out0 = np.vstack((tr0_out[0], tr0_out[1]))
            tr_out1 = np.vstack((tr1_out[0], tr1_out[1]))
353 354
            np.testing.assert_allclose(tr_out0, need_result, rtol=1e-05)
            np.testing.assert_allclose(tr_out1, need_result, rtol=1e-05)
355
        elif col_type == "allgather_object":
356 357 358
            need_result = [input1, input2]
            self.assertEqual(need_result, tr0_out)
            self.assertEqual(need_result, tr1_out)
359 360
        elif col_type == "broadcast":
            need_result = input2
361 362
            np.testing.assert_allclose(tr0_out[0], need_result, rtol=1e-05)
            np.testing.assert_allclose(tr1_out[0], need_result, rtol=1e-05)
363 364 365 366
        elif col_type == "broadcast_object_list":
            need_result = [input2]
            self.assertEqual(need_result, tr0_out)
            self.assertEqual(need_result, tr1_out)
367
        elif col_type == "reduce":
TaoTao Li's avatar
TaoTao Li 已提交
368 369 370 371 372 373 374 375
            if reduce_type == dist.ReduceOp.SUM:
                need_result = input1 + input2
            elif reduce_type == dist.ReduceOp.MAX:
                need_result = np.amax([input1, input2], 0)
            elif reduce_type == dist.ReduceOp.MIN:
                need_result = np.amin([input1, input2], 0)
            elif reduce_type == dist.ReduceOp.PROD:
                need_result = np.prod([input1, input2], 0)
376 377 378 379 380 381 382
            # bfloat16 precision loss comes from truncating the last 16 bits of float32,
            # which sums (\sum_{i=-23}^{-8}2^{i}) to about 0.0078
            if dtype == "bfloat16":
                rtol = 8e-03
            else:
                rtol = 1e-05
            np.testing.assert_allclose(tr0_out[0], need_result, rtol=rtol)
383 384
        elif col_type == "scatter":
            need_result = input2
385 386
            need_result1 = need_result[0 : need_result.shape[0] // 2]
            need_result2 = need_result[need_result.shape[0] // 2 :]
387 388
            np.testing.assert_allclose(tr0_out[0], need_result1, rtol=1e-05)
            np.testing.assert_allclose(tr1_out[0], need_result2, rtol=1e-05)
389 390 391 392 393 394
        elif col_type == "scatter_object_list":
            need_result = input2
            need_result1 = [need_result[0 : len(need_result) // 2]]
            need_result2 = [need_result[len(need_result) // 2 :]]
            self.assertEqual(need_result1, tr0_out)
            self.assertEqual(need_result2, tr1_out)
395 396
        elif col_type == "reduce_scatter":
            need_result = input1 + input2
397 398
            need_result1 = need_result[0 : need_result.shape[0] // 2]
            need_result2 = need_result[need_result.shape[0] // 2 :]
399 400 401 402 403 404
            if dtype == "bfloat16":
                rtol = 8e-03
            else:
                rtol = 1e-05
            np.testing.assert_allclose(tr0_out[0], need_result1, rtol=rtol)
            np.testing.assert_allclose(tr1_out[0], need_result2, rtol=rtol)
405
        elif col_type == "allreduce":
TaoTao Li's avatar
TaoTao Li 已提交
406 407 408 409 410 411 412 413
            if reduce_type == dist.ReduceOp.SUM:
                need_result = input1 + input2
            elif reduce_type == dist.ReduceOp.MAX:
                need_result = np.amax([input1, input2], 0)
            elif reduce_type == dist.ReduceOp.MIN:
                need_result = np.amin([input1, input2], 0)
            elif reduce_type == dist.ReduceOp.PROD:
                need_result = np.prod([input1, input2], 0)
414 415 416 417 418 419
            if dtype == "bfloat16":
                rtol = 8e-03
                atol = 8e-03
            else:
                rtol = 1e-05
                atol = 1e-05
420 421 422 423 424 425
            np.testing.assert_allclose(
                tr0_out[0], need_result, rtol=rtol, atol=atol
            )
            np.testing.assert_allclose(
                tr1_out[0], need_result, rtol=rtol, atol=atol
            )
426 427 428
        elif col_type == "parallel_embedding":
            result_data = tr0_out[0]
            np.random.seed(2020)
429
            need_result = np.random.rand(12, 8)
430 431 432
            for i in range(result_data.shape[0]):
                for j in range(result_data.shape[1]):
                    data = result_data[i][j]
433
                    np.testing.assert_allclose(
434 435
                        tr0_out[1][i][j], need_result[data], atol=1e-08
                    )
436 437 438 439 440
        elif col_type == "row_parallel_linear":
            result_data = tr0_out[0]
            np.random.seed(2020)
            weight = np.random.rand(1000, 16)
            need_result = np.matmul(input1, weight)
441 442 443
            np.testing.assert_allclose(
                result_data, need_result, rtol=1e-05, atol=1e-05
            )
444 445 446 447 448
        elif col_type == "column_parallel_linear":
            result_data = tr0_out[0]
            np.random.seed(2020)
            weight = np.random.rand(1000, 16)
            need_result = np.matmul(input1, weight)
449 450 451
            np.testing.assert_allclose(
                result_data, need_result, rtol=1e-05, atol=1e-05
            )
L
lilong12 已提交
452
        elif col_type == "alltoall":
453 454 455 456 457 458 459 460 461 462 463 464
            need_result1 = np.vstack(
                (
                    input1[0 : input1.shape[0] // 2, :],
                    input2[0 : input2.shape[0] // 2, :],
                )
            )
            need_result2 = np.vstack(
                (
                    input1[input1.shape[0] // 2 :, :],
                    input2[input2.shape[0] // 2 :, :],
                )
            )
L
lilong12 已提交
465 466
            tr0_out = np.vstack(tr0_out)
            tr1_out = np.vstack(tr1_out)
467 468 469 470 471 472
            np.testing.assert_allclose(
                tr0_out, need_result1, rtol=1e-05, atol=1e-05
            )
            np.testing.assert_allclose(
                tr1_out, need_result2, rtol=1e-05, atol=1e-05
            )
L
lilong12 已提交
473 474
        elif col_type == "sendrecv":
            result_data = tr1_out[0]
475 476 477
            np.testing.assert_allclose(
                input1, result_data, rtol=1e-05, atol=1e-05
            )
478 479 480 481 482 483 484 485
        elif col_type == "global_gather":
            in_feat = 2
            n_expert = 2
            world_size = 2
            tot_expert = n_expert * world_size

            np.random.seed(pid0)
            local_expert_count1 = np.random.randint(
486 487
                1, 4, size=tot_expert
            ).astype("int")
488 489 490 491 492 493 494
            expert_ptr1 = np.ones(tot_expert, dtype=np.int32)
            expert_ptr1[0] = 0
            for i in range(1, tot_expert):
                expert_ptr1[i] = expert_ptr1[i - 1] + local_expert_count1[i - 1]

            np.random.seed(pid1)
            local_expert_count2 = np.random.randint(
495 496
                1, 4, size=tot_expert
            ).astype("int")
497 498 499 500 501 502 503 504 505 506 507 508 509 510
            expert_ptr2 = np.ones(tot_expert, dtype=np.int32)
            expert_ptr2[0] = 0
            for i in range(1, tot_expert):
                expert_ptr2[i] = expert_ptr2[i - 1] + local_expert_count2[i - 1]

            global_expert_count1 = np.zeros(tot_expert).astype("int")
            global_expert_count2 = np.zeros(tot_expert).astype("int")
            global_expert_count1[0:n_expert] = local_expert_count1[0:n_expert]
            global_expert_count1[n_expert:] = local_expert_count2[0:n_expert]
            global_expert_count2[0:n_expert] = local_expert_count1[n_expert:]
            global_expert_count2[n_expert:] = local_expert_count2[n_expert:]

            np.random.seed(pid0)
            fwd_expert_count = sum(global_expert_count1).astype("int")
511 512 513
            local_input_buf1 = np.random.rand(fwd_expert_count, in_feat).astype(
                "float32"
            )
514 515
            np.random.seed(pid1)
            fwd_expert_count = sum(global_expert_count2).astype("int")
516 517 518
            local_input_buf2 = np.random.rand(fwd_expert_count, in_feat).astype(
                "float32"
            )
519 520 521 522 523 524 525 526 527
            output1 = [[], [], [], []]
            output2 = [[], [], [], []]
            send_ptr1 = 0
            send_ptr2 = 0

            for i in range(n_expert):
                for j in range(world_size):
                    idx = j * n_expert + i
                    if j == 0:
528 529 530 531 532 533
                        output1_part1 = local_input_buf1[
                            send_ptr1 : send_ptr1 + global_expert_count1[idx], :
                        ]
                        output1_part2 = local_input_buf2[
                            send_ptr2 : send_ptr2 + global_expert_count2[idx], :
                        ]
534 535 536
                        output1[i].extend(output1_part1)
                        output1[i + n_expert].extend(output1_part2)
                    else:
537 538 539 540 541 542
                        output2_part1 = local_input_buf1[
                            send_ptr1 : send_ptr1 + global_expert_count1[idx]
                        ]
                        output2_part2 = local_input_buf2[
                            send_ptr2 : send_ptr2 + global_expert_count2[idx]
                        ]
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
                        output2[i].extend(output2_part1)
                        output2[i + n_expert].extend(output2_part2)
                    send_ptr1 = send_ptr1 + global_expert_count1[idx]
                    send_ptr2 = send_ptr2 + global_expert_count2[idx]
            result1 = []
            result2 = []
            for i in range(tot_expert):
                for arr in output1[i]:
                    if arr == []:
                        continue
                    result1.append(arr)
            for i in range(tot_expert):
                for arr in output2[i]:
                    if arr == []:
                        continue
                    result2.append(arr)
            if result1 == []:
                output1 = np.array([])
            else:
562
                output1 = np.concatenate(result1, axis=0).reshape(
563 564
                    sum(local_expert_count1), in_feat
                )
565 566 567
            if result2 == []:
                output2 = np.array([])
            else:
568
                output2 = np.concatenate(result2, axis=0).reshape(
569 570
                    sum(local_expert_count2), in_feat
                )
571 572 573 574 575 576 577

            if tr0_out[0] is None or tr0_out[0].shape[0] == 0:
                tr0_out[0] = np.array([])

            if tr1_out[0] is None or tr1_out[0].shape[0] == 0:
                tr1_out[0] = np.array([])

578 579 580 581 582 583
            np.testing.assert_allclose(
                tr0_out[0], output1, rtol=1e-05, atol=1e-05
            )
            np.testing.assert_allclose(
                tr1_out[0], output2, rtol=1e-05, atol=1e-05
            )
584
            if static_mode == 0:
585 586 587 588 589 590
                np.testing.assert_allclose(
                    tr0_out[1], 2 * local_input_buf1, rtol=1e-05, atol=1e-05
                )
                np.testing.assert_allclose(
                    tr1_out[1], 2 * local_input_buf2, rtol=1e-05, atol=1e-05
                )
591 592 593 594 595

        elif col_type == "global_scatter":
            np.random.seed(pid0)
            local_expert_count1 = np.random.randint(1, 4, size=4).astype("int")
            fwd_expert_count = sum(local_expert_count1)
596 597 598
            local_input_buf1 = np.random.rand(fwd_expert_count, 2).astype(
                "float32"
            )
599 600 601 602 603 604 605
            expert_ptr1 = np.ones(4, dtype=np.int32)
            expert_ptr1[0] = 0
            for i in range(1, 4):
                expert_ptr1[i] = expert_ptr1[i - 1] + local_expert_count1[i - 1]
            np.random.seed(pid1)
            local_expert_count2 = np.random.randint(1, 4, size=4).astype("int")
            fwd_expert_count = sum(local_expert_count2)
606 607 608
            local_input_buf2 = np.random.rand(fwd_expert_count, 2).astype(
                "float32"
            )
609 610 611 612 613 614 615 616 617 618 619 620
            expert_ptr2 = np.ones(4, dtype=np.int32)
            expert_ptr2[0] = 0
            for i in range(1, 4):
                expert_ptr2[i] = expert_ptr2[i - 1] + local_expert_count2[i - 1]

            output1 = []
            output2 = []
            for i in range(2):
                for j in range(2):
                    idx = j * 2 + i
                    if j == 0:
                        # send data to 0 card
621 622 623 624 625 626 627 628 629 630 631 632
                        output1.append(
                            local_input_buf1[
                                expert_ptr1[idx] : expert_ptr1[idx]
                                + local_expert_count1[idx]
                            ]
                        )
                        output1.append(
                            local_input_buf2[
                                expert_ptr2[idx] : expert_ptr2[idx]
                                + local_expert_count2[idx]
                            ]
                        )
633
                    else:
634 635 636 637 638 639 640 641 642 643 644 645
                        output2.append(
                            local_input_buf1[
                                expert_ptr1[idx] : expert_ptr1[idx]
                                + local_expert_count1[idx]
                            ]
                        )
                        output2.append(
                            local_input_buf2[
                                expert_ptr2[idx] : expert_ptr2[idx]
                                + local_expert_count2[idx]
                            ]
                        )
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
            if output1 == []:
                output1 = np.array([])
            else:
                output1 = np.concatenate(output1)
            if output2 == []:
                output2 = np.array([])
            else:
                output2 = np.concatenate(output2)

            if tr0_out[0] is None or tr0_out[0].shape[0] == 0:
                tr0_out[0] = np.array([])

            if tr1_out[0] is None or tr1_out[0].shape[0] == 0:
                tr1_out[0] = np.array([])

661 662 663 664 665 666
            np.testing.assert_allclose(
                tr0_out[0], output1, rtol=1e-05, atol=1e-05
            )
            np.testing.assert_allclose(
                tr1_out[0], output2, rtol=1e-05, atol=1e-05
            )
667
            if static_mode == 0:
668 669 670 671 672 673
                np.testing.assert_allclose(
                    tr0_out[1], 2 * local_input_buf1, rtol=1e-05, atol=1e-05
                )
                np.testing.assert_allclose(
                    tr1_out[1], 2 * local_input_buf2, rtol=1e-05, atol=1e-05
                )
674 675
        else:
            pass