"""Reference-EQUIVALENT submission for `dist-tp-embedding-allreduce` — validation only, NOT shipped. Two implementations, selected by EMB_MODE ("sparse" | "dense"), so the cost of all-reducing a mostly-zero activation can be measured with everything else held fixed: dense : mask out-of-range ids to zero and exchange the whole (T, H) activation, then add -> 2*T*H*2 link sparse : both ranks derive the owned-position sets from the REPLICATED ids with no communication, exchange only the compact blocks of owned rows, and scatter into place -> T*H*2 link Neither uses a torch.distributed data collective or a pre-packaged fused collective. Transport is a shared MAPPED HOST buffer (mmap of /dev/shm + cudaHostRegister PORTABLE|MAPPED) with sequence-counter flags. """ import mmap import os import torch MAX_BYTES = 1 << 29 # 512 MiB per slot MODE = os.environ.get("EMB_MODE", "sparse") _S = {} def _map(path, nbytes, ctx, register): if ctx.rank == 0: with open(path, "wb") as f: f.truncate(nbytes) ctx.barrier() f = open(path, "r+b") mm = mmap.mmap(f.fileno(), nbytes) t = torch.frombuffer(mm, dtype=torch.uint8) if register: err = torch.cuda.cudart().cudaHostRegister(t.data_ptr(), nbytes, 3) assert int(err) == 0, f"cudaHostRegister failed: {err}" ctx.barrier() if ctx.rank == 0: os.unlink(path) return f, mm, t def _setup(ctx): if "data" in _S: return tag = os.environ.get("MASTER_PORT", "0") _S["data"] = _map(f"/dev/shm/emb_data_{tag}", ctx.world_size * MAX_BYTES, ctx, True) _S["flag"] = _map(f"/dev/shm/emb_flag_{tag}", 4096, ctx, False) _S["flags"] = _S["flag"][2].view(torch.int64) _S["flags"].zero_() _S["seq"] = 0 ctx.barrier() def _wait(flags, i, seq): while int(flags[i]) < seq: pass def tp_embedding_allreduce(ids, weight, ctx): _setup(ctx) Vl, H = weight.shape T = ids.numel() W, r = ctx.world_size, ctx.rank peer = 1 - r lo = r * Vl flags = _S["flags"] _S["seq"] += 1 seq = _S["seq"] raw = _S["data"][2].view(torch.bfloat16).view(W, -1) if MODE == "dense": local_ids = ids - lo inside = (local_ids >= 0) & (local_ids < Vl) rows = weight[local_ids.clamp(0, Vl - 1)] rows = torch.where(inside.unsqueeze(-1), rows, torch.zeros((), dtype=rows.dtype, device=rows.device)) slot = raw[:, :T * H].view(W, T, H) slot[r].copy_(rows, non_blocking=True) torch.cuda.synchronize() flags[r] = seq _wait(flags, peer, seq) buf = torch.empty(T, H, dtype=weight.dtype, device=weight.device) buf.copy_(slot[peer], non_blocking=True) out = rows + buf # exactly one side is non-zero per row torch.cuda.synchronize() else: owner = torch.div(ids, Vl, rounding_mode="floor") # replicated -> both ranks agree, no comms pos_mine = (owner == r).nonzero(as_tuple=True)[0] pos_peer = (owner == peer).nonzero(as_tuple=True)[0] n = pos_mine.numel() block = weight[ids[pos_mine] - lo] # (n, H) compact, only rows I own slot = raw[:, :T * H].view(W, T, H) if n: slot[r][:n].copy_(block, non_blocking=True) torch.cuda.synchronize() flags[r] = seq _wait(flags, peer, seq) out = torch.empty(T, H, dtype=weight.dtype, device=weight.device) if n: out[pos_mine] = block m = pos_peer.numel() if m: buf = torch.empty(m, H, dtype=weight.dtype, device=weight.device) buf.copy_(slot[peer][:m], non_blocking=True) out[pos_peer] = buf torch.cuda.synchronize() flags[W + r] = seq _wait(flags, W + peer, seq) return out.to(torch.bfloat16)