Alexsssu's picture
Ship the generated kernels themselves (233 files, both regimes) (part 2)
3087568 verified
Raw History Blame Contribute Delete
1.95 kB
"""Primitive tensor manipulation ops.
L1 ops wrapping standard tensor utilities for use by L2+ composites.
"""
from __future__ import annotations
import torch
import torch.nn as nn
import torch.nn.functional as F
import triton
import triton.language as tl
@triton.jit
def _pad_16_kernel(
x,
out,
input_elements: tl.constexpr,
output_elements: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
values = tl.load(x + offsets, mask=offsets < input_elements, other=0)
tl.store(out + offsets, values, mask=offsets < output_elements)
class Pad(nn.Module):
"""Functional padding op."""
def forward(
self, x: torch.Tensor, pad: tuple[int, ...], value: float = 0.0,
) -> torch.Tensor:
if value != 0.0 or tuple(pad) not in ((0, 16), (0, 0, 0, 16)):
return F.pad(x, pad, value=value)
if len(pad) == 2:
output_shape = (*x.shape[:-1], 384)
else:
output_shape = (*x.shape[:-2], 384, x.shape[-1])
out = x.new_empty(output_shape)
output_elements = out.numel()
_pad_16_kernel[(triton.cdiv(output_elements, 1024),)](
x, out, x.numel(), output_elements, BLOCK_SIZE=1024,
num_warps=8,
)
return out
class OneHot(nn.Module):
"""Functional one-hot encoding op."""
def forward(self, x: torch.Tensor, num_classes: int) -> torch.Tensor:
return F.one_hot(x, num_classes)
class Cat(nn.Module):
"""Tensor concatenation op."""
def __init__(self, dim: int = 0):
super().__init__()
self.dim = dim
def forward(self, tensors: list[torch.Tensor] | tuple[torch.Tensor, ...]) -> torch.Tensor:
return torch.cat(tensors, dim=self.dim)
class Exp(nn.Module):
"""Elementwise exponential op."""
def forward(self, x: torch.Tensor) -> torch.Tensor:
return torch.exp(x)