mirror of
https://github.com/lightseekorg/tokenspeed.git
synced 2026-12-04 10:26:50 +08:00
perf(comm): barrier-free lamport all-gather on the MNNVL workspace (#2258)
Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
This commit is contained in:
@@ -512,6 +512,10 @@ class AutoBackend(CommBackend):
|
||||
and tensor.dim() == 2
|
||||
and dim in (-1, tensor.dim() - 1)
|
||||
):
|
||||
# Small rows ride the all-reduce workspace's barrier-free exchange.
|
||||
gathered = self._trtllm_ar.lamport_all_gather(tensor, group)
|
||||
if gathered is not None:
|
||||
return gathered
|
||||
return self._rsag.all_gather(tensor, group, dim)
|
||||
return self._nccl.all_gather(tensor, group, dim)
|
||||
|
||||
|
||||
@@ -192,6 +192,20 @@ class TrtllmAllReduceBackend(CommBackend):
|
||||
|
||||
return self._fallback.all_reduce(tensor, group, op=op)
|
||||
|
||||
def lamport_all_gather(
|
||||
self, tensor: torch.Tensor, group: Group
|
||||
) -> torch.Tensor | None:
|
||||
"""All-gather along the last dim through the armed mnnvl workspace;
|
||||
None when it does not serve the call."""
|
||||
res = self._resources.get(group)
|
||||
if res is None:
|
||||
return None
|
||||
from tokenspeed_kernel.ops.communication.trtllm import (
|
||||
trtllm_workspace_all_gather,
|
||||
)
|
||||
|
||||
return trtllm_workspace_all_gather(tensor, res["device_group"])
|
||||
|
||||
# ---- Delegate everything else to fallback ----
|
||||
|
||||
def all_gather(
|
||||
|
||||
@@ -594,6 +594,17 @@ def test_auto_routes_keep_the_performance_defaults(routing, monkeypatch):
|
||||
assert routing.route(Collective.TOKEN_REDUCE_SCATTER, ROWS, GROUP) is Route.MULTIMEM
|
||||
|
||||
|
||||
def test_all_gather_takes_the_workspace_exchange_where_it_serves(routing, monkeypatch):
|
||||
_switches(monkeypatch, force=False, invariant=False)
|
||||
gathered = torch.empty(4, 32, dtype=torch.bfloat16)
|
||||
routing._trtllm_ar.lamport_all_gather.return_value = gathered
|
||||
assert routing.all_gather(ROWS, GROUP, -1) is gathered
|
||||
routing._rsag.all_gather.assert_not_called()
|
||||
routing._trtllm_ar.lamport_all_gather.return_value = None
|
||||
assert routing.all_gather(ROWS, GROUP, -1) is routing._rsag.all_gather.return_value
|
||||
routing._rsag.all_gather.assert_called_once_with(ROWS, GROUP, -1)
|
||||
|
||||
|
||||
def test_route_never_reads_the_row_count(routing, monkeypatch):
|
||||
# A site's route must not move with the batch; only the capacity check
|
||||
# inside the multimem all-reduce sees the rows, and it refuses rather
|
||||
|
||||
@@ -39,6 +39,7 @@ class TestAutoBackendTopology:
|
||||
backend._iris = Mock()
|
||||
backend._trtllm_ar = Mock()
|
||||
backend._trtllm_ar.has_trtllm_ar.return_value = False
|
||||
backend._trtllm_ar.lamport_all_gather.return_value = None
|
||||
# A host-spread group's rsag routing keys on the fabric probe, so pin
|
||||
# both the probe and the local device count the tests assume.
|
||||
monkeypatch.setattr(torch.cuda, "device_count", lambda: 4)
|
||||
|
||||
@@ -25,7 +25,7 @@ from ctypes import c_void_p
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from tokenspeed_kernel.ops.quantization import quantize_fp8
|
||||
from tokenspeed_kernel.platform import current_platform
|
||||
from tokenspeed_kernel.platform import current_platform, pdl_enabled
|
||||
from tokenspeed_kernel.registry import ErrorClass, error_fn, register_kernel
|
||||
from tokenspeed_kernel.signature import format_signatures
|
||||
|
||||
@@ -83,6 +83,7 @@ __all__ = [
|
||||
"reducescatter_residual_rmsnorm",
|
||||
"trtllm_allreduce_fusion",
|
||||
"trtllm_create_ipc_workspace_for_all_reduce_fusion",
|
||||
"trtllm_workspace_all_gather",
|
||||
"trtllm_workspace_allreduce",
|
||||
"group_spans_nodes",
|
||||
"armed_workspace_hidden_dim",
|
||||
@@ -103,6 +104,7 @@ trtllm_reduce_scatter = error_fn
|
||||
MNNVL_TWOSHOT_MAX_TOKEN = 0
|
||||
allgather_dual_rmsnorm = error_fn
|
||||
allreduce_residual_rmsnorm = error_fn
|
||||
trtllm_workspace_all_gather = error_fn
|
||||
trtllm_workspace_allreduce = error_fn
|
||||
armed_workspace_hidden_dim = error_fn
|
||||
ensure_workspace_initialized = error_fn
|
||||
@@ -129,6 +131,7 @@ if current_platform().is_nvidia:
|
||||
trtllm_create_ipc_workspace_for_all_reduce_fusion,
|
||||
trtllm_create_mnnvl_workspace_for_all_reduce_fusion,
|
||||
trtllm_destroy_ipc_workspace_for_all_reduce_fusion,
|
||||
trtllm_mnnvl_allgather,
|
||||
trtllm_reducescatter_fusion,
|
||||
)
|
||||
|
||||
@@ -765,6 +768,30 @@ if current_platform().is_nvidia:
|
||||
)
|
||||
return allreduce_out.view(input_tensor.shape)
|
||||
|
||||
def trtllm_workspace_all_gather(
|
||||
input_tensor: torch.Tensor,
|
||||
group: dist.ProcessGroup,
|
||||
) -> torch.Tensor | None:
|
||||
"""All-gather of 16-bit rows along the last dim through the group's
|
||||
mnnvl workspace: one lamport exchange, no barrier.
|
||||
|
||||
Args:
|
||||
input_tensor: ``[T, W]`` rows of this rank.
|
||||
group: process group whose armed workspace to use.
|
||||
|
||||
Returns:
|
||||
``[T, world * W]`` (rank-major columns, bit for bit), or None when
|
||||
no mnnvl workspace serves the shape.
|
||||
"""
|
||||
manager = _manager_for_group(group)
|
||||
mnnvl = manager.mnnvl_workspace
|
||||
if mnnvl is None or input_tensor.dim() != 2:
|
||||
return None
|
||||
gathered = trtllm_mnnvl_allgather(input_tensor, mnnvl, pdl_enabled())
|
||||
if gathered is not None:
|
||||
_mark_captured(manager, mnnvl)
|
||||
return gathered
|
||||
|
||||
def allreduce_residual_rmsnorm(
|
||||
input_tensor: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
|
||||
+81
@@ -78,6 +78,7 @@
|
||||
// fragile: it breaks if a non-owner is ever allowed to skip the B poll
|
||||
// (e.g. an "output not needed here" fast path), or if an owner publishes
|
||||
// B before all NRanks A slots have landed.
|
||||
// * All-gather: slots carry each 16-bit value as 0x10000 | value, never the sentinel.
|
||||
|
||||
#pragma once
|
||||
|
||||
@@ -699,6 +700,86 @@ cudaError_t mnnvl_allreduce_fusion_op(AllReduceFusionParams<T> const& params,
|
||||
return cudaErrorInvalidValue;
|
||||
}
|
||||
|
||||
// One-shot all-gather of [num_tokens, width] 16-bit rows: one CTA per token, four values per thread.
|
||||
template <int NRanks>
|
||||
__global__ void __launch_bounds__(1024)
|
||||
mnnvl_allgather_kernel_oneshot(uint16_t const* __restrict__ in, uint16_t* __restrict__ out,
|
||||
int width, int rank, MnnvlCommArgs comm) {
|
||||
int const token = blockIdx.x;
|
||||
int const col = threadIdx.x * 4;
|
||||
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
|
||||
cudaGridDependencySynchronize();
|
||||
#endif
|
||||
MnnvlLamportFlags flags(comm.buffer_flags);
|
||||
uint32_t* stage_mcast = reinterpret_cast<uint32_t*>(flags.current_buf(comm.multicast_ptr));
|
||||
uint32_t const* stage_local =
|
||||
reinterpret_cast<uint32_t const*>(flags.current_buf(comm.buffer_ptr_local));
|
||||
uint2 const v =
|
||||
*reinterpret_cast<uint2 const*>(in + static_cast<size_t>(token) * width + col);
|
||||
#if (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900))
|
||||
cudaTriggerProgrammaticLaunchCompletion();
|
||||
#endif
|
||||
*reinterpret_cast<uint4*>(stage_mcast +
|
||||
(static_cast<size_t>(token) * NRanks + rank) * width + col) =
|
||||
make_uint4(0x10000u | (v.x & 0xffffu), 0x10000u | (v.x >> 16), 0x10000u | (v.y & 0xffffu),
|
||||
0x10000u | (v.y >> 16));
|
||||
flags.cta_arrive();
|
||||
flags.clear_dirty(comm.buffer_ptr_local);
|
||||
|
||||
uint4 words[NRanks];
|
||||
bool done = false;
|
||||
while (!done) {
|
||||
done = true;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < NRanks; ++r) {
|
||||
uint32_t const* src = stage_local + (static_cast<size_t>(token) * NRanks + r) * width + col;
|
||||
asm volatile("ld.volatile.global.v4.u32 {%0, %1, %2, %3}, [%4];"
|
||||
: "=r"(words[r].x), "=r"(words[r].y), "=r"(words[r].z), "=r"(words[r].w)
|
||||
: "l"(src));
|
||||
done &= words[r].x != 0x80000000u && words[r].y != 0x80000000u &&
|
||||
words[r].z != 0x80000000u && words[r].w != 0x80000000u;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < NRanks; ++r) {
|
||||
*reinterpret_cast<uint2*>(out + (static_cast<size_t>(token) * NRanks + r) * width + col) =
|
||||
make_uint2((words[r].x & 0xffffu) | (words[r].y << 16),
|
||||
(words[r].z & 0xffffu) | (words[r].w << 16));
|
||||
}
|
||||
flags.wait_and_update(
|
||||
static_cast<uint32_t>(static_cast<size_t>(gridDim.x) * NRanks * width * sizeof(uint32_t)));
|
||||
}
|
||||
|
||||
inline cudaError_t mnnvl_allgather_op(uint16_t const* in, uint16_t* out, int num_tokens, int width,
|
||||
int nranks, int rank, MnnvlCommArgs const& comm,
|
||||
bool launch_with_pdl, cudaStream_t stream) {
|
||||
cudaLaunchConfig_t cfg;
|
||||
cudaLaunchAttribute attrs[1];
|
||||
cfg.gridDim = dim3(num_tokens, 1, 1);
|
||||
cfg.blockDim = dim3(width / 4, 1, 1);
|
||||
cfg.dynamicSmemBytes = 0;
|
||||
cfg.stream = stream;
|
||||
attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
|
||||
attrs[0].val.programmaticStreamSerializationAllowed = launch_with_pdl ? 1 : 0;
|
||||
cfg.attrs = attrs;
|
||||
cfg.numAttrs = 1;
|
||||
auto launch = [&](auto kernel) {
|
||||
return cudaLaunchKernelEx(&cfg, kernel, in, out, width, rank, comm);
|
||||
};
|
||||
switch (nranks) {
|
||||
case 2:
|
||||
return launch(mnnvl_allgather_kernel_oneshot<2>);
|
||||
case 4:
|
||||
return launch(mnnvl_allgather_kernel_oneshot<4>);
|
||||
case 8:
|
||||
return launch(mnnvl_allgather_kernel_oneshot<8>);
|
||||
case 16:
|
||||
return launch(mnnvl_allgather_kernel_oneshot<16>);
|
||||
default:
|
||||
return cudaErrorInvalidValue;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace trtllm_mnnvl_allreduce_fusion
|
||||
|
||||
} // namespace flashinfer
|
||||
|
||||
Vendored
+24
@@ -130,4 +130,28 @@ void trtllm_mnnvl_allreduce_fusion(
|
||||
});
|
||||
}
|
||||
|
||||
// Gathers every rank's 16-bit rows rank-major on the trtllm_mnnvl_allreduce_fusion rotation.
|
||||
void trtllm_mnnvl_allgather(TensorView input, TensorView output, int64_t world_size,
|
||||
int64_t world_rank, int64_t multicast_ptr, int64_t buffer_ptr_local,
|
||||
TensorView buffer_flags, bool launch_with_pdl) {
|
||||
cudaSetDevice(input.device().device_id);
|
||||
// trtllm_mnnvl_allgather (Python) checks the rows against the workspace and allocates output.
|
||||
int64_t const num_tokens = input.size(0), width = input.size(1);
|
||||
TVM_FFI_ICHECK(input.dtype().bits == 16 && width % 128 == 0 && width <= 4096)
|
||||
<< "all-gather takes 16-bit rows of a width that is a multiple of 128, <= 4096";
|
||||
|
||||
MnnvlCommArgs comm;
|
||||
comm.multicast_ptr = reinterpret_cast<void*>(multicast_ptr);
|
||||
comm.buffer_ptr_local = reinterpret_cast<void*>(buffer_ptr_local);
|
||||
comm.peer_ptrs = nullptr;
|
||||
comm.buffer_flags = reinterpret_cast<uint32_t*>(buffer_flags.data_ptr());
|
||||
auto status = mnnvl_allgather_op(
|
||||
static_cast<uint16_t const*>(input.data_ptr()), static_cast<uint16_t*>(output.data_ptr()),
|
||||
static_cast<int>(num_tokens), static_cast<int>(width), static_cast<int>(world_size),
|
||||
static_cast<int>(world_rank), comm, launch_with_pdl, get_stream(input.device()));
|
||||
TVM_FFI_ICHECK(status == cudaSuccess)
|
||||
<< "mnnvl_allgather_op failed with error code " << cudaGetErrorString(status);
|
||||
}
|
||||
|
||||
TVM_FFI_DLL_EXPORT_TYPED_FUNC(trtllm_mnnvl_allreduce_fusion, trtllm_mnnvl_allreduce_fusion);
|
||||
TVM_FFI_DLL_EXPORT_TYPED_FUNC(trtllm_mnnvl_allgather, trtllm_mnnvl_allgather);
|
||||
|
||||
@@ -288,6 +288,9 @@ MNNVL_PREFER_IPC_BYTES = int(
|
||||
os.environ.get("TOKENSPEED_MNNVL_PREFER_IPC_BYTES", 12 * 1024 * 1024)
|
||||
)
|
||||
|
||||
# Per-rank bytes where lamport stops beating multimem (4 GB300s: 0.45x at 4 KB, 0.97x at 768 KB).
|
||||
MNNVL_ALLGATHER_MAX_BYTES = 768 * 1024
|
||||
|
||||
_MNNVL_SUPPORTED_PATTERNS = frozenset(
|
||||
{
|
||||
AllReduceFusionPattern.kAllReduce,
|
||||
@@ -539,6 +542,50 @@ def trtllm_create_mnnvl_workspace_for_all_reduce_fusion(
|
||||
)
|
||||
|
||||
|
||||
def trtllm_mnnvl_allgather(
|
||||
allgather_in: torch.Tensor,
|
||||
workspace: MnnvlAllReduceFusionWorkspace,
|
||||
launch_with_pdl: bool,
|
||||
) -> Optional[torch.Tensor]:
|
||||
"""One-shot all-gather on the all-reduce workspace, bit for bit.
|
||||
|
||||
Args:
|
||||
allgather_in: ``[T, W]`` 16-bit rows of this rank.
|
||||
workspace: The group's workspace.
|
||||
launch_with_pdl: Launch with programmatic dependent launch.
|
||||
|
||||
Returns:
|
||||
``[T, world * W]`` with rank ``r``'s rows in columns ``r * W``, or None
|
||||
when the workspace does not serve the rows.
|
||||
"""
|
||||
token_num, width = allgather_in.shape
|
||||
# Refuse only on what every rank shares: a rank-local refusal strands its peers.
|
||||
if not (
|
||||
allgather_in.dtype.itemsize == 2
|
||||
and 0 < token_num
|
||||
and 0 < width <= 4096
|
||||
and width % 128 == 0
|
||||
and token_num * width * 2 <= MNNVL_ALLGATHER_MAX_BYTES
|
||||
# Each 16-bit value travels as a 32-bit word.
|
||||
and token_num * workspace.tp_size * width * 4 <= workspace.buffer_size_bytes
|
||||
):
|
||||
return None
|
||||
if allgather_in.stride() != (width, 1) or allgather_in.data_ptr() % 16:
|
||||
allgather_in = allgather_in.clone(memory_format=torch.contiguous_format)
|
||||
out = allgather_in.new_empty((token_num, workspace.tp_size * width))
|
||||
_load_trtllm_comm_module().trtllm_mnnvl_allgather(
|
||||
allgather_in,
|
||||
out,
|
||||
workspace.tp_size,
|
||||
workspace.tp_rank,
|
||||
workspace.multicast_ptr,
|
||||
workspace.local_ptr,
|
||||
workspace.buffer_flags,
|
||||
launch_with_pdl,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AllReduce fusion
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -617,3 +617,210 @@ def _rsag_body(comm, sub, grank, dev):
|
||||
# Refusals must not mutate the armed workspace.
|
||||
assert manager.initialized and manager.use_fp32_lamport is True
|
||||
assert manager.workspace_tensor is ws_before
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"token_num,width", [(1, 640), (16, 1280), (32, 640), (4, 4096)]
|
||||
)
|
||||
def test_lamport_all_gather_moves_every_bit(token_num, width):
|
||||
"""The barrier-free all-gather returns NCCL's gather bit for bit, also for
|
||||
-0.0, NaN payloads, raw integer lanes and a lane pair whose raw packing is
|
||||
the 32-bit sentinel; with a fresh payload every call, between one-shot and
|
||||
two-shot all-reduces on the same rotation that stay correct, after a wider
|
||||
gather, and under CUDA-graph replay."""
|
||||
from tokenspeed_kernel.thirdparty.cuda.trtllm import (
|
||||
AllReduceFusionPattern,
|
||||
trtllm_allreduce_fusion,
|
||||
trtllm_mnnvl_allgather,
|
||||
)
|
||||
|
||||
ws = _skip_unless_mnnvl()
|
||||
rank, world, dev, mnnvl = ws["rank"], ws["world"], ws["dev"], ws["mnnvl"]
|
||||
gen = torch.Generator(device=dev).manual_seed(6_000 + rank)
|
||||
shape = (token_num, width)
|
||||
|
||||
def payload():
|
||||
bits = torch.randint(-(2**15), 2**15, shape, generator=gen, device=dev).short()
|
||||
bits[:, :8] = -0x8000 # -0.0 and the 16-bit lamport sentinel
|
||||
bits[:, 8:16] = 0x7FC1 # a NaN payload
|
||||
# Packed raw, this pair would be the 32-bit sentinel.
|
||||
bits[:, 16:18] = torch.tensor([0, -0x8000], dtype=torch.int16, device=dev)
|
||||
rows = bits.view(torch.bfloat16)
|
||||
# NCCL has no int16; its bf16 all-gather is a plain copy.
|
||||
want = torch.empty(world, token_num, width, dtype=torch.bfloat16, device=dev)
|
||||
dist.all_gather_into_tensor(want, rows)
|
||||
return rows, want.view(torch.int16).permute(1, 0, 2).reshape(token_num, -1)
|
||||
|
||||
x = torch.empty(shape, dtype=torch.bfloat16, device=dev)
|
||||
first = torch.empty(1, width, dtype=torch.bfloat16, device=dev)
|
||||
ar_in = torch.randn(token_num, H, device=dev, dtype=torch.bfloat16) * 0.1
|
||||
ar_out = torch.empty_like(ar_in)
|
||||
ar_kw = dict(pattern_code=AllReduceFusionPattern.kAllReduce, allreduce_out=ar_out)
|
||||
twoshot_in = torch.randn(8, H, device=dev, dtype=torch.bfloat16) * 0.1
|
||||
twoshot_out = torch.empty_like(twoshot_in)
|
||||
ar_want, twoshot_want = ar_in.float(), twoshot_in.float()
|
||||
dist.all_reduce(ar_want)
|
||||
dist.all_reduce(twoshot_want)
|
||||
|
||||
def gather():
|
||||
out = trtllm_mnnvl_allgather(x, mnnvl, launch_with_pdl=True)
|
||||
_run_ar(mnnvl, ar_in, ar_out, ar_kw, token_num, H)
|
||||
row = trtllm_mnnvl_allgather(first, mnnvl, launch_with_pdl=True)
|
||||
trtllm_allreduce_fusion(
|
||||
allreduce_in=twoshot_in,
|
||||
world_size=world,
|
||||
world_rank=rank,
|
||||
token_num=8,
|
||||
hidden_dim=H,
|
||||
workspace_ptrs=mnnvl,
|
||||
launch_with_pdl=True,
|
||||
trigger_completion_at_end=True,
|
||||
fp32_acc=False,
|
||||
use_oneshot=False,
|
||||
pattern_code=AllReduceFusionPattern.kAllReduce,
|
||||
allreduce_out=twoshot_out,
|
||||
)
|
||||
return out, row
|
||||
|
||||
def step(run):
|
||||
rows, want = payload()
|
||||
x.copy_(rows)
|
||||
first.copy_(rows[:1])
|
||||
out, row = run()
|
||||
torch.cuda.synchronize()
|
||||
assert torch.equal(out.view(torch.int16), want)
|
||||
assert torch.equal(row.view(torch.int16), want[:1])
|
||||
torch.testing.assert_close(ar_out.float(), ar_want, atol=3e-2, rtol=3e-2)
|
||||
torch.testing.assert_close(
|
||||
twoshot_out.float(), twoshot_want, atol=3e-2, rtol=3e-2
|
||||
)
|
||||
|
||||
for _ in range(3): # every buffer of the rotation, between all-reduces
|
||||
step(gather)
|
||||
dist.barrier()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
captured = gather()
|
||||
|
||||
def replay():
|
||||
graph.replay()
|
||||
return captured
|
||||
|
||||
for _ in range(3):
|
||||
step(replay)
|
||||
dist.barrier()
|
||||
|
||||
|
||||
def test_lamport_all_gather_refuses_by_shape_and_copies_odd_layouts():
|
||||
"""Refusals depend only on dtype and shape, which every rank shares; a
|
||||
strided or misaligned view is copied rather than refused, since a
|
||||
rank-local refusal would strand the peers in the exchange."""
|
||||
from tokenspeed_kernel.thirdparty.cuda.trtllm import (
|
||||
MNNVL_ALLGATHER_MAX_BYTES,
|
||||
trtllm_mnnvl_allgather,
|
||||
)
|
||||
|
||||
ws = _skip_unless_mnnvl()
|
||||
rank, world, dev, mnnvl = ws["rank"], ws["world"], ws["dev"], ws["mnnvl"]
|
||||
torch.manual_seed(7_000 + rank)
|
||||
flat = torch.randn(4 * 1280 + 8, device=dev).bfloat16()
|
||||
strided = flat[: 4 * 1280].view(4, 1280)[:, ::2]
|
||||
misaligned = flat[1 : 1 + 4 * 640].view(4, 640)
|
||||
assert misaligned.data_ptr() % 16 != 0
|
||||
for rows in (strided, misaligned):
|
||||
keep = rows.clone()
|
||||
want = torch.empty(world, 4, 640, dtype=torch.bfloat16, device=dev)
|
||||
dist.all_gather_into_tensor(want, rows.contiguous())
|
||||
got = trtllm_mnnvl_allgather(rows, mnnvl, launch_with_pdl=True)
|
||||
torch.cuda.synchronize()
|
||||
assert got is not None
|
||||
assert torch.equal(got, want.permute(1, 0, 2).reshape(4, world * 640))
|
||||
assert torch.equal(rows, keep)
|
||||
too_many = MNNVL_ALLGATHER_MAX_BYTES // (4096 * 2) + 1
|
||||
for shape, dtype in (
|
||||
((4, 640), torch.float32),
|
||||
((4, 600), torch.bfloat16),
|
||||
((4, 4224), torch.bfloat16),
|
||||
((too_many, 4096), torch.bfloat16),
|
||||
((0, 640), torch.bfloat16),
|
||||
):
|
||||
refused = torch.zeros(shape, dtype=dtype, device=dev)
|
||||
assert trtllm_mnnvl_allgather(refused, mnnvl, launch_with_pdl=True) is None
|
||||
dist.barrier()
|
||||
|
||||
|
||||
def test_lamport_all_gather_advances_the_rotation_and_clears_behind():
|
||||
"""Each gather takes the next buffer, records its widened extent and
|
||||
returns the buffer the previous call dirtied to the sentinel, whatever the
|
||||
widths on either side."""
|
||||
from tokenspeed_kernel.thirdparty.cuda.trtllm import trtllm_mnnvl_allgather
|
||||
|
||||
ws = _skip_unless_mnnvl()
|
||||
rank, world, dev, mnnvl = ws["rank"], ws["world"], ws["dev"], ws["mnnvl"]
|
||||
handle = mnnvl._refs[1]
|
||||
local = handle.get_buffer(rank, (handle.buffer_size // 4,), torch.int32)
|
||||
words_per_buffer = mnnvl.buffer_size_bytes // 4
|
||||
for token_num, width in ((4, 4096), (1, 640), (16, 1280), (2, 4096)):
|
||||
torch.cuda.synchronize()
|
||||
dist.barrier()
|
||||
before = mnnvl.buffer_flags.tolist()
|
||||
x = torch.randn(token_num, width, device=dev).bfloat16()
|
||||
assert trtllm_mnnvl_allgather(x, mnnvl, launch_with_pdl=False) is not None
|
||||
torch.cuda.synchronize()
|
||||
dist.barrier()
|
||||
after = mnnvl.buffer_flags.tolist()
|
||||
extent = token_num * world * width * 4
|
||||
assert after[:5] == [(before[0] + 1) % 3, before[0], before[2], 1, extent]
|
||||
if before[3] == 1:
|
||||
start = before[1] * words_per_buffer
|
||||
behind = local[start : start + before[4] // 4]
|
||||
assert torch.all(behind == -(2**31))
|
||||
|
||||
|
||||
def test_workspace_all_gather_freezes_the_workspace_only_when_served():
|
||||
"""Capturing a served gather through the backend-facing entry point
|
||||
freezes the workspace against growth; capturing a refused one does not."""
|
||||
from tokenspeed_kernel.ops.communication import trtllm as comm
|
||||
from tokenspeed_kernel.ops.communication.trtllm import (
|
||||
ensure_workspace_initialized,
|
||||
trtllm_workspace_all_gather,
|
||||
)
|
||||
|
||||
rank, dev = _setup()
|
||||
try:
|
||||
armed = ensure_workspace_initialized(
|
||||
rank=rank, group=dist.group.WORLD, max_token_num=2048, hidden_dim=H
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
pytest.skip(f"trtllm fusion workspace unavailable: {exc}")
|
||||
manager = comm._manager_for_group(dist.group.WORLD)
|
||||
if not armed or manager.mnnvl_workspace is None:
|
||||
pytest.skip("no mnnvl workspace on this fabric")
|
||||
world = dist.get_world_size()
|
||||
consumed_before = manager.graph_consumed
|
||||
manager.graph_consumed = False
|
||||
torch.manual_seed(8_000 + rank)
|
||||
x = torch.randn(4, 640, device=dev).bfloat16()
|
||||
refused = torch.randn(4, 640, device=dev)
|
||||
want = torch.empty(world, 4, 640, dtype=torch.bfloat16, device=dev)
|
||||
dist.all_gather_into_tensor(want, x)
|
||||
try:
|
||||
trtllm_workspace_all_gather(x, dist.group.WORLD)
|
||||
torch.cuda.synchronize()
|
||||
assert not manager.graph_consumed
|
||||
# The refused capture holds one ordinary kernel so the graph is not empty.
|
||||
with torch.cuda.graph(torch.cuda.CUDAGraph()):
|
||||
refused.mul_(2)
|
||||
assert trtllm_workspace_all_gather(refused, dist.group.WORLD) is None
|
||||
assert not manager.graph_consumed
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
got = trtllm_workspace_all_gather(x, dist.group.WORLD)
|
||||
assert got is not None and manager.graph_consumed
|
||||
dist.barrier()
|
||||
graph.replay()
|
||||
torch.cuda.synchronize()
|
||||
assert torch.equal(got, want.permute(1, 0, 2).reshape(4, world * 640))
|
||||
finally:
|
||||
manager.graph_consumed = consumed_before
|
||||
dist.barrier()
|
||||
|
||||
Reference in New Issue
Block a user