|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | + |
| 8 | +import torch.nn as nn |
| 9 | +from torch.distributed.tensor import distribute_tensor, Replicate, Shard |
| 10 | +from torchtitan.distributed.expert_parallel import ExpertTensorParallel, TensorParallel |
| 11 | + |
| 12 | +# implementation of Tensor Parallel for the GroupedExperts in MoE |
| 13 | +class GptossTensorParallel(TensorParallel): |
| 14 | + def _partition_fn(self, name, module, device_mesh): |
| 15 | + module.register_parameter( |
| 16 | + "mlp1_weight", |
| 17 | + nn.Parameter( |
| 18 | + distribute_tensor(module.mlp1_weight, device_mesh, [Shard(1)]) |
| 19 | + ), |
| 20 | + ) # Column-wise sharding |
| 21 | + module.register_parameter( |
| 22 | + "mlp1_bias", |
| 23 | + nn.Parameter(distribute_tensor(module.mlp1_bias, device_mesh, [Shard(1)])), |
| 24 | + ) # Column-wise sharding |
| 25 | + module.register_parameter( |
| 26 | + "mlp2_weight", |
| 27 | + nn.Parameter( |
| 28 | + distribute_tensor(module.mlp2_weight, device_mesh, [Shard(2)]) |
| 29 | + ), |
| 30 | + ) # Row-wise sharding |
| 31 | + module.register_parameter( |
| 32 | + "mlp2_bias", |
| 33 | + nn.Parameter( |
| 34 | + distribute_tensor(module.mlp2_bias, device_mesh, [Replicate()]) |
| 35 | + ), |
| 36 | + ) # Replicate |
| 37 | + |
| 38 | + |
| 39 | +# This class is for dp2ep with TP (without TP we can just use GptossExpertParallel) |
| 40 | +class GptossExpertTensorParallel(ExpertTensorParallel): |
| 41 | + def _partition_fn_2d(self, name, mod, ep_tp_mesh): |
| 42 | + mod.register_parameter( |
| 43 | + "mlp1_weight", |
| 44 | + nn.Parameter( |
| 45 | + distribute_tensor(mod.mlp1_weight, ep_tp_mesh, [Shard(0), Shard(1)]) |
| 46 | + ), |
| 47 | + ) # Column-wise sharding |
| 48 | + mod.register_parameter( |
| 49 | + "mlp1_bias", |
| 50 | + nn.Parameter( |
| 51 | + distribute_tensor(mod.mlp1_bias, ep_tp_mesh, [Shard(0), Shard(1)]) |
| 52 | + ), |
| 53 | + ) # Column-wise sharding |
| 54 | + mod.register_parameter( |
| 55 | + "mlp2_weight", |
| 56 | + nn.Parameter( |
| 57 | + distribute_tensor(mod.mlp2_weight, ep_tp_mesh, [Shard(0), Shard(2)]) |
| 58 | + ), |
| 59 | + ) # Row-wise sharding |
| 60 | + mod.register_parameter( |
| 61 | + "mlp2_bias", |
| 62 | + nn.Parameter( |
| 63 | + distribute_tensor(mod.mlp2_bias, ep_tp_mesh, [Shard(0), Replicate()]) |
| 64 | + ), |
| 65 | + ) # Replicate |
0 commit comments