MCPcopy Create free account
hub / github.com/modelscope/modelscope / DistributedDataParallel

Class DistributedDataParallel

modelscope/utils/nlp/distributed.py:44–113  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

42
43
44class DistributedDataParallel(Module):
45
46 def __init__(self, module):
47 super(DistributedDataParallel, self).__init__()
48 self.warn_on_half = True if dist._backend == dist.dist_backend.GLOO else False
49
50 self.module = module
51 self.data_parallel_group = mpu.get_data_parallel_group()
52 src_rank = mpu.get_tensor_model_parallel_rank()
53 for p in self.module.parameters():
54 if torch.is_tensor(p):
55 dist.broadcast(p, src_rank, group=self.data_parallel_group)
56
57 def allreduce_params(reduce_after=True,
58 no_scale=False,
59 fp32_allreduce=False):
60 if (self.needs_reduction):
61 self.needs_reduction = False
62 buckets = {}
63 for name, param in self.module.named_parameters():
64 if param.requires_grad and param.grad is not None:
65 tp = (param.data.type())
66 if tp not in buckets:
67 buckets[tp] = []
68 buckets[tp].append(param)
69 if self.warn_on_half:
70 if torch.cuda.HalfTensor in buckets:
71 print(
72 'WARNING: gloo dist backend for half parameters may be extremely slow.',
73 'It is recommended to use the NCCL backend in this case.'
74 )
75 self.warn_on_half = False
76 for tp in buckets:
77 bucket = buckets[tp]
78 grads = [param.grad.data for param in bucket]
79 coalesced = _flatten_dense_tensors(grads)
80 if fp32_allreduce:
81 coalesced = coalesced.float()
82 if not no_scale and not reduce_after:
83 coalesced /= dist.get_world_size(
84 group=self.data_parallel_group)
85 dist.all_reduce(coalesced, group=self.data_parallel_group)
86 torch.cuda.synchronize()
87 if not no_scale and reduce_after:
88 coalesced /= dist.get_world_size(
89 group=self.data_parallel_group)
90 for buf, synced in zip(
91 grads, _unflatten_dense_tensors(coalesced, grads)):
92 buf.copy_(synced)
93
94 self.hook_handles = []
95 self.hooks = []
96 for param in list(self.module.parameters()):
97
98 def allreduce_hook(*unused):
99 Variable._execution_engine.queue_callback(allreduce_params)
100
101 self.allreduce_params = allreduce_params

Callers 2

test_funcFunction · 0.90
__init__Method · 0.50

Calls

no outgoing calls

Tested by 1

test_funcFunction · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…