Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions deepspeed/module_inject/auto_ep_comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@

from __future__ import annotations

import contextlib
import itertools
import os
import weakref

import torch
Expand Down Expand Up @@ -352,11 +354,12 @@ def combine_with_weight_grad_async(self, rows: torch.Tensor, handle, weight_grad

The current stream does not wait for it, so work queued next runs while the combine is in flight.
"""
combined, combined_weights, event = self.buffer.combine(rows,
handle=handle,
topk_weights=weight_grads,
num_sms=self.num_sms,
async_with_compute_stream=True)
with _event_holds_async_tensors():
combined, combined_weights, event = self.buffer.combine(rows,
handle=handle,
topk_weights=weight_grads,
num_sms=self.num_sms,
async_with_compute_stream=True)
return combined, combined_weights, event

def combine(self, rows: torch.Tensor, handle) -> torch.Tensor:
Expand Down Expand Up @@ -394,6 +397,31 @@ def destroy(self) -> None:
self.buffer.destroy()


# DeepEP's V2 buffers read this on every asynchronous call (DeepEP csrc/elastic/buffer.hpp).
_DEEPEP_AVOID_RECORD_STREAM = "EP_AVOID_RECORD_STREAM"


@contextlib.contextmanager
def _event_holds_async_tensors():
"""Make DeepEP keep an asynchronous call's tensors in its returned event instead of recording them on streams.

By default DeepEP calls ``record_stream`` on every tensor of an asynchronous call, for the compute stream and for
its own stream. The caching allocator then cannot reuse their blocks until DeepEP's stream has passed that point,
which the host, queueing the backward ahead of the GPU, does not wait for. The unusable blocks accumulate until an
allocation fails and the allocator synchronizes and empties its cache, once per combine. Kept in the event, the
tensors are released when the caller drops the event after waiting on it, and their blocks are reusable at once.
"""
previous = os.environ.get(_DEEPEP_AVOID_RECORD_STREAM)
os.environ[_DEEPEP_AVOID_RECORD_STREAM] = "1"
try:
yield
finally:
if previous is None:
del os.environ[_DEEPEP_AVOID_RECORD_STREAM]
else:
os.environ[_DEEPEP_AVOID_RECORD_STREAM] = previous


def run_with_sm_carveout(num_sms: int, compute):
"""Run ``compute`` with ``num_sms`` SMs withheld from the GEMMs it launches.

Expand Down
24 changes: 24 additions & 0 deletions tests/unit/module_inject/test_auto_ep_comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,8 @@ def dispatch(self, tokens, *, topk_idx=None, topk_weights=None, handle=None, do_
def combine(self, rows, *, handle, topk_weights=None, async_with_compute_stream=False, **kwargs):
test, log = self.test, self.log
log.append("combine_async" if async_with_compute_stream else "combine")
if async_with_compute_stream:
test.async_combine_settings.append(os.environ.get("EP_AVOID_RECORD_STREAM"))
combined = rows.new_zeros(test.TOKENS, rows.shape[1]).index_add(0, handle.token_of_row, rows)
combined_weights = None
if topk_weights is not None:
Expand All @@ -863,6 +865,7 @@ def setUp(self):
except (AttributeError, RuntimeError, NotImplementedError):
self.skipTest("this PyTorch build has no CPU torch._grouped_mm")
torch.manual_seed(0)
self.async_combine_settings = []
self.routing = torch.randint(0, self.EXPERTS - 1, (self.TOKENS, self.TOP_K)) # one expert stays empty
self.inputs = torch.randn(self.TOKENS, self.HIDDEN)
self.gate = torch.randn(self.HIDDEN, self.TOP_K)
Expand Down Expand Up @@ -943,6 +946,27 @@ def test_overlap_matches_the_serial_backward_bitwise(self):
self.assertEqual(log[-3:], ["combine_async", "weight_grads_with_12_sms_withheld", "wait"])
self.assertEqual(serial_log, ["combine", "combine"])

def test_async_combine_keeps_its_tensors_in_the_event(self):
# Unless EP_AVOID_RECORD_STREAM is set, DeepEP records an asynchronous call's tensors on both streams, and the
# allocator cannot reuse their blocks until DeepEP's stream catches up. Under non-reentrant checkpointing that
# ran the overlapped backward out of cached memory on every combine. The setting must be on for the call and
# must leave the user's own value, set or not, as it was.
saved = os.environ.pop("EP_AVOID_RECORD_STREAM", None)
try:
for user_value in (None, "0"):
with self.subTest(user_value=user_value):
if user_value is not None:
os.environ["EP_AVOID_RECORD_STREAM"] = user_value
self.async_combine_settings.clear()
self.run_route(True, "fused", "non_reentrant")
self.assertTrue(self.async_combine_settings)
self.assertEqual(set(self.async_combine_settings), {"1"})
self.assertEqual(os.environ.get("EP_AVOID_RECORD_STREAM"), user_value)
finally:
os.environ.pop("EP_AVOID_RECORD_STREAM", None)
if saved is not None:
os.environ["EP_AVOID_RECORD_STREAM"] = saved

def test_the_sm_carveout_is_restored(self):
torch._C._set_sm_carveout_experimental(None)
seen = []
Expand Down
6 changes: 4 additions & 2 deletions tests/unit/v1/moe/test_autoep_deepep_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,9 @@ def test_fused_row_weighting_handles_empty_experts_and_skewed_routing(self, scor
@pytest.mark.parametrize("gate_up_impl", ["separate", "fused"])
@pytest.mark.parametrize("skewed_routing", [False, True])
@pytest.mark.parametrize("zero_stage", [1, 2])
def test_overlapped_weight_gradients_match_the_serial_backward(self, gate_up_impl, skewed_routing, zero_stage):
@pytest.mark.parametrize("reentrant", [True, False], ids=["reentrant", "non-reentrant"])
def test_overlapped_weight_gradients_match_the_serial_backward(self, gate_up_impl, skewed_routing, zero_stage,
reentrant):
"""overlap_weight_grad changes when the experts' weight gradients are computed, not their values.

The two runs dispatch separately, so DeepEP's arrival order can differ between them and change summation
Expand All @@ -696,7 +698,7 @@ def test_overlapped_weight_gradients_match_the_serial_backward(self, gate_up_imp
common = dict(skewed_routing=skewed_routing,
zero_stage=zero_stage,
activation_checkpointing=True,
reentrant_checkpointing=True,
reentrant_checkpointing=reentrant,
gate_up_impl=gate_up_impl,
use_grouped_mm=True,
disable_triton_grouped_mm=True)
Expand Down
Loading