Download kernels/sequential/L2/parallel_embedding.py from Alexsssu/fastkernels-b200-codex-vanilla-20260923: direct link, hf CLI and curl.
- Browser
- Download file 8.78 kB
-
https://huggingface.co/datasets/Alexsssu/fastkernels-b200-codex-vanilla-20260923/resolve/main/kernels/sequential/L2/parallel_embedding.py
- Command line
-
hf download hf://datasets/Alexsssu/fastkernels-b200-codex-vanilla-20260923/kernels/sequential/L2/parallel_embedding.py
-
curl -L -o parallel_embedding.py https://huggingface.co/datasets/Alexsssu/fastkernels-b200-codex-vanilla-20260923/resolve/main/kernels/sequential/L2/parallel_embedding.py
8.78 kB
| """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 | |
| 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) | |
| 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) | |