File size: 11,610 Bytes
0ec7a7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAException.h>
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <math_constants.h>

namespace {
// OpenThai 2.2 has 16 query heads, 8 KV heads, and 64 features per head.
constexpr int dim = 64;
constexpr int tile = 256;
constexpr int warps = 8;
constexpr int kv_heads = 8;
constexpr int groups = 2;
constexpr int partial_stride = dim + 2;

__device__ float warp_sum(float value) {
    #pragma unroll
    for (int delta = 16; delta > 0; delta >>= 1)
        value += __shfl_xor_sync(0xffffffff, value, delta);
    return value;
}

__device__ float warp_max(float value) {
    #pragma unroll
    for (int delta = 16; delta > 0; delta >>= 1)
        value = fmaxf(value, __shfl_xor_sync(0xffffffff, value, delta));
    return value;
}

__device__ float2 as_float2(float2 value) { return value; }
__device__ float2 as_float2(__half2 value) { return __half22float2(value); }

__device__ void store(float2& slot, float2 value) { slot = value; }
__device__ void store(__half2& slot, float2 value) { slot = __float22half2_rn(value); }

template <typename Cache>
__global__ void append_kv(Cache* keys, Cache* values, const float2* key,
                         const float2* value, const int64_t* position, int capacity) {
    const int slot = (threadIdx.x / 32 * capacity + *position) * 32 + threadIdx.x % 32;
    store(keys[slot], key[threadIdx.x]);
    store(values[slot], value[threadIdx.x]);
}

// Each block reads a tile once for both query heads and emits unnormalized
// values, the maximum logit, and the softmax denominator for each head.
template <typename Cache>
__global__ void attention_tiles(const float2* __restrict__ queries,
                                const Cache* __restrict__ keys,
                                const Cache* __restrict__ values,
                                const int64_t* position, float* partials, int capacity) {
    const int head = blockIdx.y;
    const int start = blockIdx.x * tile;
    const int count = min(tile, static_cast<int>(*position) + 1 - start);
    if (count <= 0) return;

    const int lane = threadIdx.x % 32;
    const int warp = threadIdx.x / 32;
    const float2 q0 = queries[(head * groups) * 32 + lane];
    const float2 q1 = queries[(head * groups + 1) * 32 + lane];
    const Cache* key = keys + (head * capacity + start) * 32 + lane;
    const Cache* value = values + (head * capacity + start) * 32 + lane;
    __shared__ float scores[groups][tile];
    __shared__ float2 sums[groups][warps][32];
    float* partial = partials + (head * gridDim.x + blockIdx.x) * groups * partial_stride;

    for (int i = warp; i < count; i += warps) {
        const float2 k = as_float2(key[i * 32]);
        const float score0 = warp_sum(fmaf(q0.x, k.x, q0.y * k.y)) * 0.125f;
        const float score1 = warp_sum(fmaf(q1.x, k.x, q1.y * k.y)) * 0.125f;
        if (lane == 0) {
            scores[0][i] = score0;
            scores[1][i] = score1;
        }
    }
    __syncthreads();

    if (warp < groups) {
        float high = -CUDART_INF_F;
        for (int i = lane; i < count; i += 32)
            high = fmaxf(high, scores[warp][i]);
        high = warp_max(high);
        float norm = 0.0f;
        for (int i = lane; i < count; i += 32) {
            const float probability = __expf(scores[warp][i] - high);
            scores[warp][i] = probability;
            norm += probability;
        }
        norm = warp_sum(norm);
        if (lane == 0) {
            partial[warp * partial_stride + dim] = high;
            partial[warp * partial_stride + dim + 1] = norm;
        }
    }
    __syncthreads();

    float2 acc0 = {0.0f, 0.0f};
    float2 acc1 = {0.0f, 0.0f};
    for (int i = warp; i < count; i += warps) {
        const float2 v = as_float2(value[i * 32]);
        const float s0 = scores[0][i];
        const float s1 = scores[1][i];
        acc0.x = fmaf(s0, v.x, acc0.x);
        acc0.y = fmaf(s0, v.y, acc0.y);
        acc1.x = fmaf(s1, v.x, acc1.x);
        acc1.y = fmaf(s1, v.y, acc1.y);
    }
    sums[0][warp][lane] = acc0;
    sums[1][warp][lane] = acc1;
    __syncthreads();
    if (warp < groups) {
        float2 accumulator = {0.0f, 0.0f};
        for (int i = 0; i < warps; ++i) {
            accumulator.x += sums[warp][i][lane].x;
            accumulator.y += sums[warp][i][lane].y;
        }
        reinterpret_cast<float2*>(partial + warp * partial_stride)[lane] = accumulator;
    }
}

// Rescale each partial by its maximum before summing across tiles.
__global__ void attention_merge(const float* partials, const int64_t* position,
                                float2* output, int max_tiles) {
    const int kv_head = blockIdx.x / groups;
    const int group = blockIdx.x % groups;
    const int active = static_cast<int>(*position) / tile + 1;
    const float* partial = partials + (kv_head * max_tiles * groups + group) * partial_stride;
    constexpr int stride = groups * partial_stride;
    const int lane = threadIdx.x % 32;
    const int warp = threadIdx.x / 32;
    __shared__ float weights[16384 / tile];
    __shared__ float2 sums[4][32];

    if (warp == 0) {
        float high = -CUDART_INF_F;
        for (int i = lane; i < active; i += 32)
            high = fmaxf(high, partial[i * stride + dim]);
        high = warp_max(high);
        float norm = 0.0f;
        for (int i = lane; i < active; i += 32) {
            const float weight = __expf(partial[i * stride + dim] - high);
            weights[i] = weight;
            norm = fmaf(weight, partial[i * stride + dim + 1], norm);
        }
        const float inv = 1.0f / warp_sum(norm);
        for (int i = lane; i < active; i += 32)
            weights[i] *= inv;
    }
    __syncthreads();

    float2 accumulator = {0.0f, 0.0f};
    const float2* vectors = reinterpret_cast<const float2*>(partial);
    for (int i = warp; i < active; i += 4) {
        const float2 v = vectors[i * (stride / 2) + lane];
        accumulator.x = fmaf(weights[i], v.x, accumulator.x);
        accumulator.y = fmaf(weights[i], v.y, accumulator.y);
    }
    sums[warp][lane] = accumulator;
    __syncthreads();
    if (warp == 0) {
        for (int i = 1; i < 4; ++i) {
            accumulator.x += sums[i][lane].x;
            accumulator.y += sums[i][lane].y;
        }
        output[blockIdx.x * 32 + lane] = accumulator;
    }
}

template <typename Cache>
void launch_attention(const float2* query, const float2* key, const float2* value,
                      Cache* keys, Cache* values, const int64_t* position, float2* output,
                      float* partials, int capacity, int tiles, cudaStream_t stream) {
    append_kv<<<1, kv_heads * 32, 0, stream>>>(keys, values, key, value, position, capacity);
    attention_tiles<<<dim3(tiles, kv_heads), 32 * warps, 0, stream>>>(
        query, keys, values, position, partials, capacity);
    attention_merge<<<kv_heads * groups, 128, 0, stream>>>(partials, position, output, tiles);
}

template <int group_size>
__global__ void vectorized_matvec(const float4* __restrict__ x,
                                  const int* __restrict__ weights,
                                  const float* __restrict__ scales,
                                  const float* __restrict__ bias,
                                  float* __restrict__ output,
                                  int in_features, int out_features) {
    const int lane = threadIdx.x % 32;
    const int row = blockIdx.x * warps + threadIdx.x / 32;
    if (row >= out_features) return;

    const int packed_size = in_features / 4;
    const int* weight = weights + static_cast<int64_t>(row) * packed_size;
    const float* scale = scales + static_cast<int64_t>(row) * (in_features / group_size);
    float sum = 0.0f;
    for (int i = lane; i < packed_size; i += 32) {
        const int w = weight[i];
        const float4 v = x[i];
        const float w0 = static_cast<int>(static_cast<unsigned>(w) << 24) >> 24;
        const float w1 = static_cast<int>(static_cast<unsigned>(w) << 16) >> 24;
        const float w2 = static_cast<int>(static_cast<unsigned>(w) << 8) >> 24;
        const float w3 = w >> 24;
        const float dot = fmaf(w3, v.w, fmaf(w2, v.z, fmaf(w1, v.y, w0 * v.x)));
        sum = fmaf(dot, scale[i / (group_size / 4)], sum);
    }
    sum = warp_sum(sum);
    if (lane == 0) {
        output[row] = bias == nullptr ? sum : sum + bias[row];
    }
}
} // namespace

at::Tensor decode_attention(const at::Tensor& query, const at::Tensor& key,
                            const at::Tensor& value, const at::Tensor& keys,
                            const at::Tensor& values, const at::Tensor& position) {
    const int capacity = keys.size(-2);
    TORCH_CHECK(capacity > 0 && capacity <= 16384, "invalid decode cache capacity");
    TORCH_CHECK(query.numel() == kv_heads * groups * dim &&
                key.numel() == kv_heads * dim && value.numel() == kv_heads * dim,
                "expected OpenThai 2.2 attention geometry");
    TORCH_CHECK(keys.numel() == kv_heads * capacity * dim && keys.sizes() == values.sizes(),
                "expected one page of OpenThai 2.2 KV cache");

    const int tiles = (capacity + tile - 1) / tile;
    auto partials = at::empty({kv_heads, tiles, groups, partial_stride}, query.options());
    auto output = at::empty({1, 1, kv_heads * groups * dim}, query.options());
    auto stream = at::cuda::getCurrentCUDAStream();
    const auto q = reinterpret_cast<const float2*>(query.data_ptr<float>());
    const auto k = reinterpret_cast<const float2*>(key.data_ptr<float>());
    const auto v = reinterpret_cast<const float2*>(value.data_ptr<float>());
    const auto pos = position.data_ptr<int64_t>();
    const auto dst = reinterpret_cast<float2*>(output.data_ptr<float>());
    const auto scratch = partials.data_ptr<float>();

    if (keys.scalar_type() == at::kHalf) {
        launch_attention(q, k, v, reinterpret_cast<__half2*>(keys.data_ptr<at::Half>()),
                         reinterpret_cast<__half2*>(values.data_ptr<at::Half>()), pos, dst,
                         scratch, capacity, tiles, stream);
    } else {
        launch_attention(q, k, v, reinterpret_cast<float2*>(keys.data_ptr<float>()),
                         reinterpret_cast<float2*>(values.data_ptr<float>()), pos, dst,
                         scratch, capacity, tiles, stream);
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}

at::Tensor vectorized_gemv(const at::Tensor& x, const at::Tensor& weight,
                          const at::Tensor& scale, const at::Tensor& bias) {
    const int n = weight.size(0);
    const int k = weight.size(1);
    auto output = at::empty({n}, x.options());
    auto stream = at::cuda::getCurrentCUDAStream();
    const auto input = reinterpret_cast<const float4*>(x.data_ptr<float>());
    const auto quantized = reinterpret_cast<const int*>(weight.data_ptr<int8_t>());
    const auto scales = scale.data_ptr<float>();
    const auto bias_data = bias.numel() ? bias.data_ptr<float>() : nullptr;
    const auto dest = output.data_ptr<float>();
    const int blocks = (n + warps - 1) / warps;
    if (scale.size(1) == k / 16) {
        vectorized_matvec<16><<<blocks, 32 * warps, 0, stream>>>(
            input, quantized, scales, bias_data, dest, k, n);
    } else {
        TORCH_CHECK(scale.size(1) == k / 32, "expected 16- or 32-element weight groups");
        vectorized_matvec<32><<<blocks, 32 * warps, 0, stream>>>(
            input, quantized, scales, bias_data, dest, k, n);
    }
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return output;
}