Alexsssu's picture
Ship the generated kernels themselves (233 files, both regimes) (part 2)
3087568 verified
Raw History Blame Contribute Delete
5.48 kB
"""CLIP encoder layer: pre-norm attention + MLP with residual connections (L3).
Standard transformer encoder layer used in CLIP text models.
"""
from __future__ import annotations
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import CLIPTextConfig
from torch.utils.cpp_extension import load_inline
from ..L1.layer_norm import LayerNorm
from ..L2.clip_attention import CLIPAttention, _get_cuda_ext as _get_attention_ext
from ..L2.clip_mlp import CLIPMLP
_CUDA_EXT = None
_CPP_SRC = """
void quick_gelu_cuda(torch::Tensor input, torch::Tensor output);
"""
_CUDA_SRC = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void quick_gelu_kernel(
const float4* __restrict__ input,
float4* __restrict__ output
) {
const int index = blockIdx.x * blockDim.x + threadIdx.x;
if (index >= 77 * 3072 / 4)
return;
float4 x = input[index];
x.x = x.x / (1.0f + expf(-1.702f * x.x));
x.y = x.y / (1.0f + expf(-1.702f * x.y));
x.z = x.z / (1.0f + expf(-1.702f * x.z));
x.w = x.w / (1.0f + expf(-1.702f * x.w));
output[index] = x;
}
void quick_gelu_cuda(torch::Tensor input, torch::Tensor output) {
constexpr int count = 77 * 3072 / 4;
quick_gelu_kernel<<<(count + 255) / 256, 256, 0,
at::cuda::getCurrentCUDAStream()>>>(
reinterpret_cast<const float4*>(input.data_ptr<float>()),
reinterpret_cast<float4*>(output.data_ptr<float>()));
}
"""
def _get_cuda_ext():
global _CUDA_EXT
if _CUDA_EXT is None:
_CUDA_EXT = load_inline(
name="fk_clip_encoder_layer_v1",
cpp_sources=_CPP_SRC,
cuda_sources=_CUDA_SRC,
functions=["quick_gelu_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False,
)
return _CUDA_EXT
class CLIPEncoderLayer(nn.Module):
def __init__(self, config: CLIPTextConfig):
super().__init__()
self.self_attn = CLIPAttention(config)
self.layer_norm1 = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.mlp = CLIPMLP(config)
self.layer_norm2 = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self._softmax_cuda = None
self._quick_gelu_cuda = None
def forward(
self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None,
) -> torch.Tensor:
if (
hidden_states.is_cuda
and hidden_states.dtype == torch.float32
and hidden_states.shape == (1, 77, 768)
and attention_mask is not None
):
residual = hidden_states
hidden_states = F.layer_norm(
hidden_states,
(768,),
self.layer_norm1.weight,
self.layer_norm1.bias,
self.layer_norm1.eps,
)
queries = F.linear(
hidden_states,
self.self_attn.q_proj.weight,
self.self_attn.q_proj.bias,
)
keys = F.linear(
hidden_states,
self.self_attn.k_proj.weight,
self.self_attn.k_proj.bias,
)
values = F.linear(
hidden_states,
self.self_attn.v_proj.weight,
self.self_attn.v_proj.bias,
)
queries = queries.view(1, 77, 12, 64).transpose(1, 2)
keys = keys.view(1, 77, 12, 64).transpose(1, 2)
values = values.view(1, 77, 12, 64).transpose(1, 2)
scores = torch.bmm(queries[0], keys[0].transpose(-1, -2))
probabilities = torch.empty_like(scores)
if self._softmax_cuda is None:
self._softmax_cuda = (
_get_attention_ext().clip_masked_softmax_cuda
)
self._quick_gelu_cuda = _get_cuda_ext().quick_gelu_cuda
self._softmax_cuda(scores, attention_mask, probabilities)
attention_output = torch.bmm(probabilities, values[0])
attention_output = attention_output.transpose(0, 1).contiguous()
hidden_states = F.linear(
attention_output.view(1, 77, 768),
self.self_attn.out_proj.weight,
self.self_attn.out_proj.bias,
)
hidden_states.add_(residual)
residual = hidden_states
hidden_states = F.layer_norm(
hidden_states,
(768,),
self.layer_norm2.weight,
self.layer_norm2.bias,
self.layer_norm2.eps,
)
hidden_states = F.linear(
hidden_states, self.mlp.fc1.weight, self.mlp.fc1.bias
)
self._quick_gelu_cuda(hidden_states, hidden_states)
hidden_states = F.linear(
hidden_states, self.mlp.fc2.weight, self.mlp.fc2.bias
)
return hidden_states.add_(residual)
residual = hidden_states
hidden_states = self.layer_norm1(hidden_states)
hidden_states = self.self_attn(hidden_states, attention_mask=attention_mask)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states