1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
| # Copyright (c) Microsoft Corporation. All rights reserved.
| # Licensed under the MIT License.
| import unittest
|
| import numpy as np
| from mpi4py import MPI
| from onnx import TensorProto, helper
| from parameterized import parameterized
|
| import onnxruntime as ort
|
|
| class ORTBertPretrainTest(unittest.TestCase):
| @staticmethod
| def _create_model_with_opsets(
| graph_def,
| ):
| opset_imports = [
| helper.make_operatorsetid("", 18),
| helper.make_operatorsetid(".com.microsoft", 1),
| ]
| return helper.make_model(
| graph_def,
| producer_name="ORTBertPretrainTest in onnxruntime_test_collective.py",
| opset_imports=opset_imports,
| )
|
| def _create_allreduce_ut_model(self, shape, elem_type: TensorProto.DataType = TensorProto.FLOAT):
| X = helper.make_tensor_value_info("X", elem_type, shape) # noqa: N806
| Y = helper.make_tensor_value_info("Y", elem_type, shape) # noqa: N806
| node_def = helper.make_node("AllReduce", ["X"], ["Y"], domain="com.microsoft")
| graph_def = helper.make_graph(
| [node_def],
| "",
| [X],
| [Y],
| )
| return ORTBertPretrainTest._create_model_with_opsets(graph_def)
|
| def _get_rank_size(self):
| comm = MPI.COMM_WORLD
| return comm.Get_rank(), comm.Get_size()
|
| def _create_allgather_ut_model(
| self,
| shape,
| axis=None,
| # Element type for AllGather's input and output.
| elem_type: TensorProto.DataType = TensorProto.FLOAT,
| # Element type for Model's input and output.
| communication_elem_type: TensorProto.DataType = TensorProto.FLOAT,
| group_size=None,
| ):
| X = helper.make_tensor_value_info("X", elem_type, shape) # noqa: N806
| if group_size is None:
| _, group_size = self._get_rank_size()
| effective_axis = 1 if axis is None else axis
| output_shape = [
| size * group_size if axis_index == effective_axis else size for axis_index, size in enumerate(shape)
| ]
| Y = helper.make_tensor_value_info("Y", elem_type, output_shape) # noqa: N806
|
| def make_allgather_node(input_name, output_name):
| attributes = {"domain": "com.microsoft", "group_size": group_size}
| if axis is not None:
| attributes["axis"] = axis
| return helper.make_node("AllGather", [input_name], [output_name], **attributes)
|
| if elem_type != communication_elem_type:
| # With elem_type and external_element_type, we use the pattern
| # model input type -> Cast -> elem_type -> AllGather -> elem_type -> Cast -> model output type
| # so that we can test boolean tensors and other special types.
| node_defs = [
| helper.make_node("Cast", ["X"], ["X_casted"], to=communication_elem_type),
| make_allgather_node("X_casted", "Y_casted"),
| helper.make_node("Cast", ["Y_casted"], ["Y"], to=elem_type),
| ]
| else:
| # When elem_type == external_element_type, the pattern
| # model input type -> Cast -> elem_type -> AllGather -> elem_type -> Cast -> model output type
| # is reduced to
| # model input type -> AllGather -> model output type
| node_defs = [
| make_allgather_node("X", "Y"),
| ]
| graph_def = helper.make_graph(
| node_defs,
| "",
| [X],
| [Y],
| )
| return ORTBertPretrainTest._create_model_with_opsets(graph_def)
|
| def _create_alltoall_ut_model(
| self,
| shape,
| elem_type: TensorProto.DataType = TensorProto.FLOAT,
| communication_elem_type: TensorProto.DataType = TensorProto.FLOAT,
| ):
| X = helper.make_tensor_value_info("X", elem_type, shape) # noqa: N806
| Y = helper.make_tensor_value_info("Y", elem_type, shape) # noqa: N806
| _, size = self._get_rank_size()
| # Explanation is in comments for model creation in _create_allgather_ut_model.
| # Basically, ORT Python API doesn't support bool tensor yet, so we need to feed int64
| # tensor and cast it to bool before running communication op.
| if elem_type != communication_elem_type:
| node_defs = [
| helper.make_node("Cast", ["X"], ["X_casted"], to=communication_elem_type),
| helper.make_node(
| "AllToAll",
| ["X_casted"],
| ["Y_casted"],
| domain="com.microsoft",
| group_size=size,
| ),
| helper.make_node("Cast", ["Y_casted"], ["Y"], to=elem_type),
| ]
| else:
| node_defs = [
| helper.make_node("AllToAll", ["X"], ["Y"], domain="com.microsoft", group_size=size),
| ]
| graph_def = helper.make_graph(
| node_defs,
| "",
| [X],
| [Y],
| )
| return ORTBertPretrainTest._create_model_with_opsets(graph_def)
|
| def _create_alltoall_ut_model_for_boolean_tensor(
| self,
| shape,
| # Tuple or list of bool values; e.g., [True, False] if
| # shape is (2,) or [[True, False], [False, True]] if
| # shape is (2, 2).
| # It's input of AllToAll.
| value,
| ):
| Y = helper.make_tensor_value_info("Y", TensorProto.BOOL, shape) # noqa: N806
| _, size = self._get_rank_size()
| # Explanation is in comments for model creation in _create_allgather_ut_model.
| # Basically, ORT Python API doesn't support bool tensor yet, so we need to feed int64
| # tensor and cast it to bool before running communication op.
| x_const_value = helper.make_tensor("condition", TensorProto.BOOL, shape, value)
| node_defs = [
| helper.make_node(
| "Constant",
| [],
| ["X"],
| value=x_const_value,
| ),
| helper.make_node(
| "AllToAll",
| ["X"],
| ["Y"],
| domain="com.microsoft",
| group_size=size,
| ),
| ]
| graph_def = helper.make_graph(
| node_defs,
| "",
| [],
| [Y],
| )
| return ORTBertPretrainTest._create_model_with_opsets(graph_def)
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| @parameterized.expand(
| [
| (np.float32, TensorProto.FLOAT),
| ]
| )
| def test_all_reduce(self, np_elem_type, elem_type):
| model = self._create_allreduce_ut_model((128, 128), elem_type)
| rank, size = self._get_rank_size()
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| # Input for size == 4
| # For rank == 0:
| # Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| # Output: [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]]
| #
| # For rank == 1:
| # Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| # Output: [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]]
| #
| # For rank == 2:
| # Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| # Output: [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]]
| #
| # For rank == 3:
| # Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| # Output: [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]]
|
| input = np.ones((128, 128), dtype=np_elem_type)
| outputs = ort_sess.run(None, {"X": input})
|
| np.testing.assert_allclose(
| outputs[0], size * input, err_msg=f"{rank}: AllGather ({np_elem_type}, {elem_type}): results mismatch"
| )
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| @parameterized.expand(
| [
| (np.float32, TensorProto.FLOAT, TensorProto.FLOAT),
| ]
| )
| def test_all_gather(self, np_elem_type, elem_type, communication_elem_type):
| model = self._create_allgather_ut_model((128, 128), 0, elem_type, communication_elem_type)
| rank, size = self._get_rank_size()
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| # Input for size == 2
| # For rank == 0:
| # Input: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
| # Output: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
| # [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| #
| # For rank == 1:
| # Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| # Output: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
| # [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
|
| input = np.ones((128, 128), dtype=np.float32) * rank
| outputs = ort_sess.run(None, {"X": input})
|
| expected_output = np.zeros((128, 128), dtype=np_elem_type)
| for _ in range(size - 1):
| expected_output = np.concatenate((expected_output, np.ones((128, 128), dtype=np_elem_type) * (_ + 1)))
|
| np.testing.assert_allclose(
| outputs[0],
| expected_output,
| err_msg=f"{rank}: AllGather (axis0) ({np_elem_type}, {elem_type}, {communication_elem_type}): results mismatch",
| )
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| def test_all_gather_bool(self):
| model = self._create_allgather_ut_model((4,), 0, TensorProto.INT64, TensorProto.INT64)
| rank, _ = self._get_rank_size()
|
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| x = np.array([True, True, False, False]).astype(np.int64)
| y = ort_sess.run(None, {"X": x})[0]
|
| y_expected = np.array(
| [True, True, False, False] * 4,
| ).astype(np.int64)
|
| np.testing.assert_allclose(y, y_expected, err_msg=f"{rank}: AllGather (bool): results mismatch")
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| def test_all_gather_axis1(self):
| model = self._create_allgather_ut_model((128, 128), 1)
| rank, size = self._get_rank_size()
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| input = np.ones((128, 128), dtype=np.float32) * rank
| outputs = ort_sess.run(None, {"X": input})
|
| expected_output = np.zeros((128, 128), dtype=np.float32)
| for _ in range(size - 1):
| expected_output = np.concatenate((expected_output, np.ones((128, 128), dtype=np.float32) * (_ + 1)), axis=1)
|
| np.testing.assert_allclose(outputs[0], expected_output, err_msg=f"{rank}: AllGather (axis1): results mismatch")
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| def test_all_gather_default_axis(self):
| model = self._create_allgather_ut_model((8, 8))
| all_gather_node = next(node for node in model.graph.node if node.op_type == "AllGather")
| self.assertNotIn("axis", {attribute.name for attribute in all_gather_node.attribute})
|
| rank, size = self._get_rank_size()
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| input = np.full((8, 8), rank, dtype=np.float32)
| output = ort_sess.run(None, {"X": input})[0]
| expected_output = np.concatenate([np.full_like(input, peer_rank) for peer_rank in range(size)], axis=1)
| np.testing.assert_allclose(
| output, expected_output, err_msg=f"{rank}: AllGather (default axis): results mismatch"
| )
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| def test_all_gather_group_size_mismatch(self):
| rank, size = self._get_rank_size()
| model = self._create_allgather_ut_model((1,), 0, group_size=size + 1)
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| with self.assertRaisesRegex(RuntimeError, "group_size must match the NCCL communicator size"):
| ort_sess.run(None, {"X": np.array([rank], dtype=np.float32)})
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| def test_all_gather_invalid_axis_unknown_rank(self):
| rank, size = self._get_rank_size()
| input_value_info = helper.make_tensor_value_info("X", TensorProto.FLOAT, None)
| output_value_info = helper.make_tensor_value_info("Y", TensorProto.FLOAT, None)
| node = helper.make_node(
| "AllGather",
| ["X"],
| ["Y"],
| domain="com.microsoft",
| axis=2,
| group_size=size,
| )
| graph = helper.make_graph([node], "", [input_value_info], [output_value_info])
| model = self._create_model_with_opsets(graph)
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| with self.assertRaisesRegex(RuntimeError, r"axis must be in the range \[0, 2\)"):
| ort_sess.run(None, {"X": np.ones((2, 2), dtype=np.float32)})
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| @parameterized.expand(
| [
| (np.float32, TensorProto.FLOAT, TensorProto.FLOAT),
| (np.int64, TensorProto.INT64, TensorProto.INT64),
| (np.int64, TensorProto.INT64, TensorProto.BOOL),
| ]
| )
| def test_all_to_all(self, np_elem_type, elem_type, communication_elem_type):
| model = self._create_alltoall_ut_model(
| (8, 8), elem_type=elem_type, communication_elem_type=communication_elem_type
| )
| rank, size = self._get_rank_size()
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| # Casting to Boolean needs to be handled as a special case because only absoluate zero equates
| # to False and everything else to True. Post casting, however, the original input can never be
| # receovered when going in the opposite direction. The end results are always going to be in the
| # set [0, 1].
|
| input = np.ones((8, 8), dtype=np_elem_type) * rank
|
| if communication_elem_type == TensorProto.BOOL:
| # Input for size == 4
| # For rank == 0:
| # Input: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| #
| # For rank == 1:
| # Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| #
| # For rank == 2:
| # Input: [[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| #
| # For rank == 3:
| # Input: [[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
|
| expected_output = np.concatenate(
| (
| np.zeros((8 // size, 8), dtype=np_elem_type),
| np.ones((8 - (8 // size), 8), dtype=np_elem_type),
| )
| )
| else:
| # Input for size == 4
| # For rank == 0:
| # Input: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
| #
| # For rank == 1:
| # Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
| #
| # For rank == 2:
| # Input: [[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
| #
| # For rank == 3:
| # Input: [[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3]]
| # Output: [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
|
| expected_output = np.zeros((8 // size, 8), dtype=np_elem_type)
| for _ in range(size - 1):
| expected_output = np.concatenate(
| (expected_output, np.ones((8 // size, 8), dtype=np_elem_type) * (_ + 1))
| )
|
| outputs = ort_sess.run(None, {"X": input})
|
| np.testing.assert_allclose(
| outputs[0],
| expected_output,
| err_msg=f"{rank}: AllToAll ({np_elem_type}, {elem_type}, {communication_elem_type}): results mismatch",
| )
|
| @unittest.skipIf(not ort.has_collective_ops(), reason="onnx not compiled with mpi support")
| def test_all_to_all_bool(self):
| rank, _ = self._get_rank_size()
|
| # Input for size == 2
| # For rank == 0:
| # Input: [True, True, True, True]
| # Output: [True, True, False, False]
| #
| # For rank == 1:
| # Input: [False, False, False, False]
| # Output: [True, True, False, False]
|
| if rank == 0:
| x = [True, True, True, True]
| else:
| x = [False, False, False, False]
|
| model = self._create_alltoall_ut_model_for_boolean_tensor((4,), x)
|
| ort_sess = ort.InferenceSession(
| model.SerializeToString(),
| providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
| provider_options=[{"device_id": str(rank)}, {}],
| )
|
| y = ort_sess.run(None, {})
|
| y_expected = np.array(
| [True, False, False, False],
| ).astype(np.int64)
|
| np.testing.assert_allclose(y[0], y_expected, err_msg=f"{rank}: AllToAll (bool): results mismatch")
|
|
| if __name__ == "__main__":
| unittest.main(module=__name__, buffer=True)
|
|