File size: 5,482 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 | """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
|