Download kernels/sequential/L1/embedding.py from Alexsssu/fastkernels-b200-codex-vanilla-20260923: direct link, hf CLI and curl.
- Browser
- Download file 2.25 kB
-
https://huggingface.co/datasets/Alexsssu/fastkernels-b200-codex-vanilla-20260923/resolve/main/kernels/sequential/L1/embedding.py
- Command line
-
hf download hf://datasets/Alexsssu/fastkernels-b200-codex-vanilla-20260923/kernels/sequential/L1/embedding.py
-
curl -L -o embedding.py https://huggingface.co/datasets/Alexsssu/fastkernels-b200-codex-vanilla-20260923/resolve/main/kernels/sequential/L1/embedding.py
2.25 kB
| """Low-overhead embedding lookup.""" | |
| import torch | |
| import torch.nn as nn | |
| import triton | |
| import triton.language as tl | |
| def _embedding_chunk_kernel(weight, input_ids, output, | |
| embedding_dim: tl.constexpr, | |
| block_dim: tl.constexpr, | |
| chunks: tl.constexpr): | |
| program = tl.program_id(0) | |
| row = program // chunks | |
| col = (program - row * chunks) * block_dim + tl.arange(0, block_dim) | |
| index = tl.load(input_ids + row) | |
| mask = col < embedding_dim | |
| values = tl.load(weight + index * embedding_dim + col, mask=mask) | |
| tl.store(output + row * embedding_dim + col, values, mask=mask) | |
| def _embedding_64_kernel(weight, input_ids, output, num_rows: tl.constexpr): | |
| rows = tl.program_id(0) * 64 + tl.arange(0, 64) | |
| cols = tl.arange(0, 64) | |
| row_mask = rows < num_rows | |
| indices = tl.load(input_ids + rows, mask=row_mask)[:, None] | |
| values = tl.load(weight + indices * 64 + cols[None, :], | |
| mask=row_mask[:, None]) | |
| tl.store(output + rows[:, None] * 64 + cols[None, :], values, | |
| mask=row_mask[:, None]) | |
| class Embedding(nn.Module): | |
| def __init__(self, num_embeddings: int, embedding_dim: int, | |
| padding_idx: int | None = None): | |
| super().__init__() | |
| self.emb = nn.Embedding(num_embeddings, embedding_dim, | |
| padding_idx=padding_idx) | |
| self.embedding_dim = embedding_dim | |
| def forward(self, input_ids): | |
| output = torch.empty((*input_ids.shape, self.embedding_dim), | |
| device=input_ids.device, dtype=self.emb.weight.dtype) | |
| num_rows = input_ids.numel() | |
| if self.embedding_dim == 64: | |
| _embedding_64_kernel[(triton.cdiv(num_rows, 64),)]( | |
| self.emb.weight, input_ids, output, num_rows, num_warps=4) | |
| else: | |
| block_dim = min(2048, triton.next_power_of_2(self.embedding_dim)) | |
| chunks = triton.cdiv(self.embedding_dim, block_dim) | |
| _embedding_chunk_kernel[(num_rows * chunks,)]( | |
| self.emb.weight, input_ids, output, self.embedding_dim, | |
| block_dim, chunks, num_warps=4) | |
| return output | |