File size: 8,783 Bytes
3087568 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | """TP-aware embedding and LM head (L2 operators)."""
from __future__ import annotations
import torch
import torch.distributed as dist
import torch.nn as nn
import triton
import triton.language as tl
from ....infra.context import get_context
from ....infra.tp import _tp_size, _tp_rank
from ..L1.linear import Matmul
from ..L1.embedding import Embedding
from ..L1.allreduce import AllReduce
@triton.autotune(
configs=[
triton.Config({"BLOCK": 256}, num_warps=4, num_stages=1),
triton.Config({"BLOCK": 512}, num_warps=4, num_stages=1),
triton.Config({"BLOCK": 1024}, num_warps=4, num_stages=1),
triton.Config({"BLOCK": 1024}, num_warps=8, num_stages=1),
triton.Config({"BLOCK": 2048}, num_warps=4, num_stages=1),
triton.Config({"BLOCK": 2048}, num_warps=8, num_stages=1),
triton.Config({"BLOCK": 4096}, num_warps=8, num_stages=1),
],
key=["num_rows", "embedding_dim"],
)
@triton.jit
def _embedding_kernel(weight, input_ids, output, num_rows: tl.constexpr,
embedding_dim: tl.constexpr, BLOCK: tl.constexpr):
chunk = tl.program_id(0)
chunks_per_row = tl.cdiv(embedding_dim, BLOCK)
row = chunk // chunks_per_row
col = (chunk % chunks_per_row) * BLOCK + tl.arange(0, BLOCK)
index = tl.load(input_ids + row)
mask = col < embedding_dim
value = tl.load(weight + index * embedding_dim + col, mask=mask)
tl.store(output + row * embedding_dim + col, value, mask=mask)
@triton.autotune(
configs=[
triton.Config({"BM": 16, "BN": 128, "BK": 64}, num_warps=4,
num_stages=3),
triton.Config({"BM": 16, "BN": 256, "BK": 64}, num_warps=8,
num_stages=3),
triton.Config({"BM": 32, "BN": 128, "BK": 64}, num_warps=4,
num_stages=3),
triton.Config({"BM": 32, "BN": 256, "BK": 64}, num_warps=8,
num_stages=3),
triton.Config({"BM": 64, "BN": 128, "BK": 64}, num_warps=4,
num_stages=2),
triton.Config({"BM": 64, "BN": 128, "BK": 64}, num_warps=4,
num_stages=3),
triton.Config({"BM": 64, "BN": 128, "BK": 64}, num_warps=4,
num_stages=4),
triton.Config({"BM": 64, "BN": 128, "BK": 64}, num_warps=8,
num_stages=3),
triton.Config({"BM": 64, "BN": 128, "BK": 64}, num_warps=4,
num_stages=3, num_ctas=2),
triton.Config({"BM": 64, "BN": 128, "BK": 128}, num_warps=4,
num_stages=3),
triton.Config({"BM": 64, "BN": 256, "BK": 64}, num_warps=8,
num_stages=3),
],
key=["M", "N", "K"],
)
@triton.jit
def _lm_head_kernel(x, weight, output, M: tl.constexpr, N: tl.constexpr,
K: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr,
BK: tl.constexpr):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
rows = pid_m * BM + tl.arange(0, BM)
cols = pid_n * BN + tl.arange(0, BN)
inner = tl.arange(0, BK)
x_ptrs = x + rows[:, None] * K + inner[None, :]
w_ptrs = weight + cols[:, None] * K + inner[None, :]
accumulator = tl.zeros((BM, BN), dtype=tl.float32)
for offset in range(0, K, BK):
a = tl.load(x_ptrs, mask=(rows[:, None] < M) &
(inner[None, :] + offset < K), other=0.0)
b = tl.load(w_ptrs, mask=(cols[:, None] < N) &
(inner[None, :] + offset < K), other=0.0)
accumulator += tl.dot(a, tl.trans(b))
x_ptrs += BK
w_ptrs += BK
out_ptrs = output + rows[:, None] * N + cols[None, :]
tl.store(out_ptrs, accumulator,
mask=(rows[:, None] < M) & (cols[None, :] < N))
class VocabParallelEmbedding(nn.Module):
def __init__(self, num_embeddings: int, embedding_dim: int,
params_dtype: torch.dtype | None = None,
org_num_embeddings: int | None = None,
padding_size: int = 64):
super().__init__()
tp, rank = _tp_size(), _tp_rank()
assert num_embeddings % tp == 0
self.num_embeddings = num_embeddings
self.org_vocab_size = org_num_embeddings or num_embeddings
self.padding_size = padding_size
self.embedding_dim = embedding_dim
self.per_partition = num_embeddings // tp
self.vocab_start = self.per_partition * rank
self.vocab_end = self.vocab_start + self.per_partition
self.tp_size = tp
if params_dtype is None:
params_dtype = torch.get_default_dtype()
self.embedding_op = Embedding(self.per_partition, embedding_dim)
self.embedding_op.emb.weight.weight_loader = self._weight_loader
self.allreduce = AllReduce()
def _weight_loader(self, param, loaded_weight):
tp, rank = _tp_size(), _tp_rank()
shard = param.data.size(0)
param.data.copy_(loaded_weight.narrow(0, rank * shard, shard))
def forward(self, x):
if self.tp_size == 1:
y = torch.empty((*x.shape, self.embedding_dim), device=x.device,
dtype=self.embedding_op.emb.weight.dtype)
grid = lambda meta: (
x.numel() * triton.cdiv(self.embedding_dim, meta["BLOCK"]),
)
_embedding_kernel[grid](
self.embedding_op.emb.weight, x, y, x.numel(),
self.embedding_dim,
)
return y
if self.tp_size > 1:
mask = (x >= self.vocab_start) & (x < self.vocab_end)
x = mask * (x - self.vocab_start)
y = self.embedding_op(x)
if self.tp_size > 1:
y = mask.unsqueeze(-1) * y
y = self.allreduce(y)
return y
class ParallelLMHead(VocabParallelEmbedding):
def __init__(self, num_embeddings: int, embedding_dim: int,
bias: bool = False,
params_dtype: torch.dtype | None = None,
org_num_embeddings: int | None = None,
padding_size: int = 64):
super().__init__(num_embeddings, embedding_dim,
params_dtype=params_dtype,
org_num_embeddings=org_num_embeddings,
padding_size=padding_size)
self.linear_op = Matmul()
def project(self, x):
"""Linear projection only (no gather). Used inside CUDA graph."""
ctx = get_context()
if ctx.is_mixed:
x = x[ctx.logit_indices].contiguous()
elif ctx.is_prefill:
last_indices = ctx.cu_seqlens_q[1:] - 1
x = x[last_indices].contiguous()
if x.ndim == 2 and 1 < x.shape[0] <= 64:
m, k = x.shape
n = self.per_partition
output = torch.empty((m, n), device=x.device, dtype=x.dtype)
grid = lambda meta: (
triton.cdiv(m, meta["BM"]),
triton.cdiv(n, meta["BN"]),
)
_lm_head_kernel[grid](
x, self.embedding_op.emb.weight, output, m, n, k,
)
return output
return self.linear_op(x, self.embedding_op.emb.weight)
def gather_logits(self, logits):
"""Gather partial logits from all ranks. Used outside CUDA graph."""
if self.tp_size > 1:
all_logits = [torch.empty_like(logits) for _ in range(self.tp_size)] if _tp_rank() == 0 else None
dist.gather(logits, all_logits, 0)
logits = torch.cat(all_logits, -1) if _tp_rank() == 0 else logits
return logits
def gather_greedy(self, logits):
"""Fast path for greedy: local argmax + small allgather.
Instead of gathering full vocab logits (~31MB/rank), gather only
the (max_val, max_idx) per sequence (~2KB/rank).
Returns token IDs directly on rank 0, None on other ranks.
"""
if self.tp_size <= 1:
return None
rank = _tp_rank()
local_max_vals, local_max_idxs = logits.max(dim=-1)
local_max_idxs = local_max_idxs + self.vocab_start
info = torch.stack([local_max_vals, local_max_idxs.float()], dim=-1)
gathered = [torch.empty_like(info) for _ in range(self.tp_size)]
dist.all_gather(gathered, info)
if rank == 0:
all_info = torch.stack(gathered, dim=0)
all_vals = all_info[:, :, 0]
all_idxs = all_info[:, :, 1].long()
best_rank = all_vals.argmax(dim=0)
bs = logits.size(0)
token_ids = all_idxs[best_rank, torch.arange(bs, device=logits.device)]
return token_ids
return None
def forward(self, x):
logits = self.project(x)
return self.gather_logits(logits)
|