dist_attribute.py 20.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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 copy
16

17
from paddle.fluid.framework import Variable
18

19 20 21
from .process_mesh import ProcessMesh

_g_tensor_dist_attr_field_keys = [
22 23 24 25
    "process_mesh",
    "dims_mapping",
    "shard_sizes",
    "device_placement",
26 27
]

28
_g_op_dist_attr_field_keys = [
29 30 31 32
    "process_mesh",
    "impl_type",
    "impl_idx",
    "is_recompute",
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

_g_op_input_suffix = "@input"

_g_op_output_suffix = "@output"


def get_tensor_dist_attr_field_keys():
    global _g_tensor_dist_attr_field_keys
    return _g_tensor_dist_attr_field_keys


def get_op_dist_attr_field_keys():
    global _g_op_dist_attr_field_keys
    return _g_op_dist_attr_field_keys


def append_op_input_suffix(name):
    global _g_op_input_suffix
    return name + _g_op_input_suffix


def append_op_output_suffix(name):
    global _g_op_output_suffix
    return name + _g_op_output_suffix


class TensorDistributedAttribute:
    def __init__(self):
62
        # The process mesh of distributed operator attribute must is the same as
63 64 65 66 67 68 69 70 71 72 73 74 75 76
        # the process meshes of all input and output distributed attributed
        self._process_mesh = None
        self._dims_mapping = None
        self._shard_sizes = None
        self._device_placement = None
        self._is_annotated = {}

    @property
    def process_mesh(self):
        return self._process_mesh

    @process_mesh.setter
    def process_mesh(self, process_mesh):
        if process_mesh is not None:
77 78 79
            assert isinstance(
                process_mesh, (list, ProcessMesh)
            ), "The type of process_mesh must be list or ProcessMesh."
80 81 82 83 84 85 86 87 88 89 90
            if isinstance(process_mesh, list):
                process_mesh = ProcessMesh(process_mesh)
            self._process_mesh = copy.deepcopy(process_mesh)

    @property
    def dims_mapping(self):
        return self._dims_mapping

    @dims_mapping.setter
    def dims_mapping(self, dims_mapping):
        if dims_mapping is not None:
91 92 93 94 95 96 97 98 99
            assert isinstance(
                dims_mapping, list
            ), "The type of dims_mapping must be list."
            assert all(
                isinstance(x, int) for x in dims_mapping
            ), "All elements of dims_mapping must be integer"
            assert all(
                x >= -1 for x in dims_mapping
            ), "All elements of dims_mapping must be greater than or equal to -1."
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
            self._dims_mapping = copy.deepcopy(dims_mapping)

    @property
    def shard_sizes(self):
        return self._shard_sizes

    @shard_sizes.setter
    def shard_sizes(self, shard_sizes):
        if shard_sizes is not None:
            self._shard_sizes = copy.deepcopy(shard_sizes)

    @property
    def device_placement(self):
        return self._device_placement

    @device_placement.setter
    def device_placement(self, device_placement):
        if device_placement is not None:
            self._device_placement = copy.deepcopy(device_placement)

    def init(self, dist_attr):
        if dist_attr is None:
            return
123
        assert isinstance(
124
            dist_attr, TensorDistributedAttribute
125
        ), "The type of dist_attr must be dict or TensorDistributedAttribute."
126 127 128 129 130 131 132
        for key in get_tensor_dist_attr_field_keys():
            field_property = TensorDistributedAttribute.__dict__.get(key, None)
            if field_property:
                field_property.fset(self, field_property.fget(dist_attr))
            else:
                assert False, "No setter for {} in args {}.".format(
                    key, dist_attr
133
                )
134
        self._is_annotated = copy.deepcopy(dist_attr._is_annotated)
135

136
    def reset(self, skip_dist_attr_field_names=None):
137 138 139 140
        if skip_dist_attr_field_names is None or (
            skip_dist_attr_field_names is not None
            and "process_mesh" not in skip_dist_attr_field_names
        ):
141
            self._process_mesh = None
142 143 144 145
        if skip_dist_attr_field_names is None or (
            skip_dist_attr_field_names is not None
            and "dims_mapping" not in skip_dist_attr_field_names
        ):
146 147 148
            for i, _ in enumerate(self._dims_mapping):
                self._dims_mapping[i] = -1
        self._is_annotated = {}
149

150 151 152
    def is_annotated(self, dist_attr_field_name):
        return self._is_annotated.get(dist_attr_field_name, False)

153 154 155 156
    # def mark_annotated_all(self):
    #     for key in get_tensor_dist_attr_field_keys():
    #         self.mark_annotated(key)

157 158 159
    def mark_annotated(self, dist_attr_field_name):
        self._is_annotated[dist_attr_field_name] = True

160 161 162
    # def unmark_annotated(self, dist_attr_field_name):
    #     self._is_annotated[dist_attr_field_name] = False

163 164 165
    def mark_annotated_as(self, dist_attr):
        if dist_attr is None:
            return
166 167 168
        assert isinstance(
            dist_attr, (dict, TensorDistributedAttribute)
        ), "The type of dist_attr must be dict or TensorDistributedAttribute."
169 170 171 172 173 174 175 176 177 178
        if isinstance(dist_attr, dict):
            for key in dist_attr.keys():
                if key in get_tensor_dist_attr_field_keys():
                    self.mark_annotated(key)
        elif isinstance(dist_attr, TensorDistributedAttribute):
            self._is_annotated = copy.deepcopy(dist_attr._is_annotated)

    def clear_annotated(self):
        self._is_annotated.clear()

179 180 181 182 183 184 185 186 187 188 189
    def __eq__(self, other):
        if not isinstance(other, TensorDistributedAttribute):
            return False
        if self.process_mesh != other.process_mesh:
            return False
        if self.dims_mapping != other.dims_mapping:
            return False
        if self._is_annotated != other._is_annotated:
            return False
        return True

190 191 192 193 194 195
    def __str__(self):
        str = "\n\ttensor_dist_attr = {"
        if self.is_annotated("process_mesh"):
            annotated_str = "annotated"
        else:
            annotated_str = "non-annotated"
196 197 198
        str += "\n\t\tprocess_mesh ({}): {},".format(
            annotated_str, self.process_mesh
        )
199 200 201 202 203

        if self.is_annotated("dims_mapping"):
            annotated_str = "annotated"
        else:
            annotated_str = "non-annotated"
204 205 206
        str += "\n\t\tdims_mapping ({}): {}".format(
            annotated_str, self.dims_mapping
        )
207 208 209 210 211 212 213
        str += "\n\t}"
        return str


class OperatorDistributedAttribute:
    def __init__(self):
        self._process_mesh = None
214
        self._op_type = None
215 216 217 218 219
        self._impl_type = None
        self._impl_idx = None
        self._inputs_dist_attrs = {}
        self._outputs_dist_attrs = {}
        self._is_annotated = {}
220
        self._is_recompute = False
221 222 223 224 225 226 227 228

    @property
    def process_mesh(self):
        return self._process_mesh

    @process_mesh.setter
    def process_mesh(self, process_mesh):
        if process_mesh is not None:
229 230
            assert isinstance(
                process_mesh, (list, ProcessMesh)
231 232 233
            ), "The type of process_mesh must be list or ProcessMesh, but receive {}".format(
                type(process_mesh)
            )
234 235 236
            if isinstance(process_mesh, list):
                process_mesh = ProcessMesh(process_mesh)
            self._process_mesh = copy.deepcopy(process_mesh)
237
            # In while op, the proess mesh is not shared by all inputs and outputs
238 239
            if self._op_type == "while":
                return None
240 241 242 243 244
            for dist_attr in self._inputs_dist_attrs.values():
                dist_attr.process_mesh = process_mesh
            for dist_attr in self._outputs_dist_attrs.values():
                dist_attr.process_mesh = process_mesh

245 246 247 248 249 250 251 252 253
    @property
    def op_type(self):
        return self._op_type

    @op_type.setter
    def op_type(self, op_type):
        if op_type is not None:
            self._op_type = op_type

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    @property
    def impl_type(self):
        return self._impl_type

    @impl_type.setter
    def impl_type(self, impl_type):
        if impl_type is not None:
            self._impl_type = impl_type

    @property
    def impl_idx(self):
        return self._impl_idx

    @impl_idx.setter
    def impl_idx(self, impl_idx):
        if impl_idx is not None:
            self._impl_idx = impl_idx

272 273 274 275 276 277 278 279 280
    @property
    def is_recompute(self):
        return self._is_recompute

    @is_recompute.setter
    def is_recompute(self, is_recompute):
        assert isinstance(is_recompute, bool)
        self._is_recompute = is_recompute

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    @property
    def inputs_dist_attrs(self):
        return self._inputs_dist_attrs

    @property
    def outputs_dist_attrs(self):
        return self._outputs_dist_attrs

    def get_input_dist_attr(self, name):
        return self._inputs_dist_attrs.get(name, None)

    def set_input_dist_attr(self, name, dist_attr):
        dist_attr_object = TensorDistributedAttribute()
        dist_attr_object.init(dist_attr)
        self._inputs_dist_attrs[name] = dist_attr_object

297 298
    def del_input_dist_attr(self, name):
        del self._inputs_dist_attrs[name]
299

300 301 302 303 304 305 306 307
    def get_output_dist_attr(self, name):
        return self._outputs_dist_attrs.get(name, None)

    def set_output_dist_attr(self, name, dist_attr):
        dist_attr_object = TensorDistributedAttribute()
        dist_attr_object.init(dist_attr)
        self._outputs_dist_attrs[name] = dist_attr_object

308 309
    def del_output_dist_attr(self, name):
        del self._outputs_dist_attrs[name]
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
    def get_input_dims_mapping(self, name):
        input_dist_attr = self.get_input_dist_attr(name)
        if input_dist_attr:
            dims_mapping = input_dist_attr.dims_mapping
        else:
            dims_mapping = None
        return dims_mapping

    def set_input_dims_mapping(self, name, dims_mapping):
        input_dist_attr = self.get_input_dist_attr(name)
        if input_dist_attr:
            input_dist_attr.dims_mapping = dims_mapping
        else:
            dist_attr = TensorDistributedAttribute()
            dist_attr.dims_mapping = dims_mapping
            self._inputs_dist_attrs[name] = dist_attr

    def get_output_dims_mapping(self, name):
        output_dist_attr = self.get_output_dist_attr(name)
        if output_dist_attr:
            dims_mapping = output_dist_attr.dims_mapping
        else:
            dims_mapping = None
        return dims_mapping

    def set_output_dims_mapping(self, name, dims_mapping):
        output_dist_attr = self.get_output_dist_attr(name)
        if output_dist_attr:
            output_dist_attr.dims_mapping = dims_mapping
        else:
            dist_attr = TensorDistributedAttribute()
            dist_attr.dims_mapping = dims_mapping
            self._outputs_dist_attrs[name] = dist_attr

    def init(self, dist_attr):
        if dist_attr is None:
            return
348 349 350
        assert isinstance(
            dist_attr, (dict, OperatorDistributedAttribute)
        ), "The type of dist_attr must be dict or OperatorDistributedAttribute."
351 352 353 354 355 356 357 358 359 360 361
        if isinstance(dist_attr, dict):
            for key, value in dist_attr.items():
                if isinstance(key, Variable):
                    tensor_dist_attr = TensorDistributedAttribute()
                    tensor_dist_attr.init(value)
                    if dist_attr.get(append_op_input_suffix(key.name), False):
                        self.set_input_dist_attr(key.name, tensor_dist_attr)
                    if dist_attr.get(append_op_output_suffix(key.name), False):
                        self.set_output_dist_attr(key.name, tensor_dist_attr)
                else:
                    if key in get_op_dist_attr_field_keys():
362 363 364
                        field_property = (
                            OperatorDistributedAttribute.__dict__.get(key, None)
                        )
365 366 367 368
                        if field_property:
                            field_property.fset(self, value)
                        else:
                            assert False, "No setter for {} in args {}.".format(
369 370
                                key, dist_attr
                            )
371
        elif isinstance(dist_attr, OperatorDistributedAttribute):
372 373 374 375
            for (
                tensor_name,
                tensor_dist_attr,
            ) in dist_attr.inputs_dist_attrs.items():
376
                self.set_input_dist_attr(
377 378 379 380 381 382
                    tensor_name, dist_attr.get_input_dist_attr(tensor_name)
                )
            for (
                tensor_name,
                tensor_dist_attr,
            ) in dist_attr.outputs_dist_attrs.items():
383
                self.set_output_dist_attr(
384 385
                    tensor_name, dist_attr.get_output_dist_attr(tensor_name)
                )
386 387
            self._is_annotated = copy.deepcopy(dist_attr._is_annotated)
            for key in get_op_dist_attr_field_keys():
388
                field_property = OperatorDistributedAttribute.__dict__.get(
389 390
                    key, None
                )
391 392 393 394
                if field_property:
                    field_property.fset(self, field_property.fget(dist_attr))
                else:
                    assert False, "No setter for {} in args {}.".format(
395 396
                        key, dist_attr
                    )
397
        # Make sure proscess_meshes in dist op be same
398 399
        if self.op_type == "while":
            return None
400 401 402 403 404 405 406 407 408 409 410 411
        process_meshes = []
        process_meshes.append(self.process_mesh)
        for tensor_dist_attr in self.inputs_dist_attrs.values():
            process_meshes.append(tensor_dist_attr.process_mesh)
        for tensor_dist_attr in self.outputs_dist_attrs.values():
            process_meshes.append(tensor_dist_attr.process_mesh)
        shared_process_mesh = None
        for process_mesh in process_meshes:
            if process_mesh is not None:
                if shared_process_mesh is None:
                    shared_process_mesh = process_mesh
                else:
412 413 414
                    assert (
                        process_mesh == shared_process_mesh
                    ), "ProcessMeshes in DistributedOperator must be the same."
415 416
        self.process_mesh = shared_process_mesh

417 418 419 420 421
    def reset(self, skip_dist_attr_field_names=None):
        for tensor_dist_attr in self.inputs_dist_attrs.values():
            tensor_dist_attr.reset(skip_dist_attr_field_names)
        for tensor_dist_attr in self.outputs_dist_attrs.values():
            tensor_dist_attr.reset(skip_dist_attr_field_names)
422 423 424 425
        if skip_dist_attr_field_names is None or (
            skip_dist_attr_field_names is not None
            and "process_mesh" not in skip_dist_attr_field_names
        ):
426 427 428 429
            self._process_mesh = None
        self.impl_type = "default"
        self.impl_idx = 0
        self._is_annotated = {}
430

431 432 433
    def is_annotated(self, attr_name):
        return self._is_annotated.get(attr_name, False)

434 435 436 437
    # def mark_annotated_all(self):
    #     for key in get_op_dist_attr_field_keys():
    #         self.mark_annotated(key)

438 439 440 441 442 443 444 445 446 447 448 449 450 451
    def mark_annotated(self, attr_name):
        if attr_name == "process_mesh":
            # Make sure proscess_mesh be annotated consistently
            self._is_annotated[attr_name] = True
            for tensor_dist_attr in self.inputs_dist_attrs.values():
                tensor_dist_attr.mark_annotated(attr_name)
            for tensor_dist_attr in self.outputs_dist_attrs.values():
                tensor_dist_attr.mark_annotated(attr_name)
        else:
            self._is_annotated[attr_name] = True

    def mark_annotated_as(self, dist_attr):
        if dist_attr is None:
            return
452 453 454
        assert isinstance(
            dist_attr, (dict, OperatorDistributedAttribute)
        ), "The type of dist_attr must be dict or OperatorDistributedAttribute."
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        if isinstance(dist_attr, dict):
            for key, value in dist_attr.items():
                if isinstance(key, Variable):
                    input_dist_attr = self.get_input_dist_attr(key.name)
                    if input_dist_attr is not None:
                        input_dist_attr.mark_annotated_as(value)
                    output_dist_attr = self.get_output_dist_attr(key.name)
                    if output_dist_attr is not None:
                        output_dist_attr.mark_annotated_as(value)
                else:
                    if key in get_op_dist_attr_field_keys():
                        self.mark_annotated(key)
            process_mesh_annotated = False
            if self.is_annotated("process_mesh"):
                process_mesh_annotated = True
            for tensor_dist_attr in self.inputs_dist_attrs.values():
                if tensor_dist_attr.is_annotated("process_mesh"):
                    process_mesh_annotated = True
            for tensor_dist_attr in self.outputs_dist_attrs.values():
                if tensor_dist_attr.is_annotated("process_mesh"):
                    process_mesh_annotated = True
            if process_mesh_annotated:
                self.mark_annotated("process_mesh")
        elif isinstance(dist_attr, OperatorDistributedAttribute):
            process_mesh_annotated = False
            self._is_annotated = copy.deepcopy(dist_attr._is_annotated)
            if self.is_annotated("process_mesh"):
                process_mesh_annotated = True
483 484 485 486
            for (
                tensor_name,
                tensor_dist_attr,
            ) in dist_attr.inputs_dist_attrs.items():
487 488 489 490 491
                input_dist_attr = self.get_input_dist_attr(tensor_name)
                if input_dist_attr is not None:
                    input_dist_attr.mark_annotated_as(tensor_dist_attr)
                    if input_dist_attr.is_annotated("process_mesh"):
                        process_mesh_annotated = True
492 493 494 495
            for (
                tensor_name,
                tensor_dist_attr,
            ) in dist_attr.outputs_dist_attrs.items():
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
                output_dist_attr = self.get_output_dist_attr(tensor_name)
                if output_dist_attr is not None:
                    output_dist_attr.mark_annotated_as(tensor_dist_attr)
                    if output_dist_attr.is_annotated("process_mesh"):
                        process_mesh_annotated = True
            if process_mesh_annotated:
                self.mark_annotated("process_mesh")

    def clear_annotated(self):
        self._is_annotated.clear()
        for tensor_dist_attr in self.inputs_dist_attrs.values():
            tensor_dist_attr.clear_annotated()
        for tensor_dist_attr in self.outputs_dist_attrs.values():
            tensor_dist_attr.clear_annotated()

    def is_annotated_input_dims_mapping(self, name):
        input_dist_attr = self.get_input_dist_attr(name)
        if input_dist_attr:
            return input_dist_attr.is_annotated("dims_mapping")
        else:
            return False

    def is_annotated_output_dims_mapping(self, name):
        output_dist_attr = self.get_output_dist_attr(name)
        if output_dist_attr:
            return output_dist_attr.is_annotated("dims_mapping")
        else:
            return False

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    def __eq__(self, other):
        if not isinstance(other, OperatorDistributedAttribute):
            return False
        if self.process_mesh != other.process_mesh:
            return False
        if self.op_type != other.op_type:
            return False
        if self.impl_type != other.impl_type:
            return False
        if self.impl_idx != other.impl_idx:
            return False
        if self._is_annotated != other._is_annotated:
            return False
        if self._is_recompute != other._is_recompute:
            return False
        if self.inputs_dist_attrs != other.inputs_dist_attrs:
            return False
        if self.outputs_dist_attrs != other.outputs_dist_attrs:
            return False
        return True

546 547 548 549 550 551
    def __str__(self):
        str = "\n\top_dist_attr = {"
        if self.is_annotated("process_mesh"):
            annotated_str = "annotated"
        else:
            annotated_str = "non-annotated"
552 553 554
        str += "\n\t\tprocess_mesh ({}): {},".format(
            annotated_str, self.process_mesh
        )
555 556

        for arg_name, tensor_dist_attr in self.inputs_dist_attrs.items():
557
            str += "\n\t\t{}'s (input): {},".format(arg_name, tensor_dist_attr)
558 559

        for arg_name, tensor_dist_attr in self.outputs_dist_attrs.items():
560
            str += "\n\t\t{}'s (output): {},".format(arg_name, tensor_dist_attr)
561 562 563 564 565

        str += "\n\t\timpl type: {}, ".format(self._impl_type)
        str += "impl idx: {}".format(self._impl_idx)
        str += "\n\t}"
        return str