MCPcopy Create free account
hub / github.com/deepspeedai/DeepSpeed / reduceGrad

Method reduceGrad

csrc/includes/deepcompile.h:503–553  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

501 }
502
503 virtual at::Tensor reduceGrad(at::Tensor grad_tensor, long ds_id)
504 {
505 int world_size = process_group_->getSize();
506 const DSParam& param = param_registry_->getParam(ds_id);
507 const auto expected_grad_dtype = param.getExpectedGradDtype();
508 // Match PyTorch's leaf grad accumulation dtype before bucket selection:
509 // https://docs.pytorch.org/docs/main/generated/torch.sparse.semi_structured.SparseSemiStructuredTensorCUSPARSELT.html#torch.sparse.semi_structured.SparseSemiStructuredTensorCUSPARSELT.grad_dtype
510 if (expected_grad_dtype.has_value() &&
511 grad_tensor.scalar_type() != expected_grad_dtype.value()) {
512 grad_tensor = grad_tensor.to(expected_grad_dtype.value());
513 }
514 const auto scalar_type = grad_tensor.scalar_type();
515 std::shared_ptr<ReduceBucket> reduce_bucket = reduce_buckets_->getBuffer(scalar_type);
516
517 auto comp_stream = at::cuda::getCurrentCUDAStream();
518
519 if (reduce_bucket->shouldFlush(grad_tensor.numel())) {
520 int rank = process_group_->getRank();
521
522 flushReduceBucket(scalar_type);
523
524 // reduce_bucket is swapped in flushReduceBucket if double buffering is enabled
525 reduce_bucket = reduce_buckets_->getBuffer(scalar_type);
526 }
527
528 if (grad_tensor.numel() > reduce_bucket->getSize()) {
529 // extend buckets
530 at::cuda::stream_synchronize(rs_stream_);
531 reduce_bucket->reserve(grad_tensor.numel());
532 }
533
534 at::Tensor reduce_in_buffer = reduce_bucket->allocate(grad_tensor.numel());
535
536 // This ensures the order of reduce_scatter -> copy
537 // Without this block, copy may start while reduce_scatter is still running
538 reduce_buckets_->getEvent(scalar_type)->block(comp_stream);
539 auto copy_src = grad_tensor.contiguous().view({-1}).detach();
540 // keep references to copy src
541 reduce_tasks_[scalar_type].emplace_back(ds_id, copy_src, reduce_in_buffer);
542
543 // computation must be done before copy
544 rs_comp_done_events_[ds_id]->record(comp_stream);
545 rs_comp_done_events_[ds_id]->block(copy_stream_);
546 {
547 at::cuda::CUDAStreamGuard guard(copy_stream_);
548 reduce_in_buffer.copy_(copy_src, true);
549 rs_copy_done_events_[ds_id]->record(copy_stream_);
550 }
551
552 return at::Tensor();
553 }
554
555 bool hasParam(long ds_id) const { return hasKey(has_acc_grad_, ds_id); }
556

Callers

nothing calls this directly

Calls 14

getCurrentCUDAStreamFunction · 0.85
getSizeMethod · 0.80
getExpectedGradDtypeMethod · 0.80
has_valueMethod · 0.80
shouldFlushMethod · 0.80
getEventMethod · 0.80
contiguousMethod · 0.80
toMethod · 0.45
getBufferMethod · 0.45
numelMethod · 0.45
reserveMethod · 0.45
allocateMethod · 0.45

Tested by

no test coverage detected