#include #include #include #include #include #include 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 __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 __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(*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(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(*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(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 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<<>>( query, keys, values, position, partials, capacity); attention_merge<<>>(partials, position, output, tiles); } template __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(row) * packed_size; const float* scale = scales + static_cast(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(static_cast(w) << 24) >> 24; const float w1 = static_cast(static_cast(w) << 16) >> 24; const float w2 = static_cast(static_cast(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(query.data_ptr()); const auto k = reinterpret_cast(key.data_ptr()); const auto v = reinterpret_cast(value.data_ptr()); const auto pos = position.data_ptr(); const auto dst = reinterpret_cast(output.data_ptr()); const auto scratch = partials.data_ptr(); if (keys.scalar_type() == at::kHalf) { launch_attention(q, k, v, reinterpret_cast<__half2*>(keys.data_ptr()), reinterpret_cast<__half2*>(values.data_ptr()), pos, dst, scratch, capacity, tiles, stream); } else { launch_attention(q, k, v, reinterpret_cast(keys.data_ptr()), reinterpret_cast(values.data_ptr()), 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(x.data_ptr()); const auto quantized = reinterpret_cast(weight.data_ptr()); const auto scales = scale.data_ptr(); const auto bias_data = bias.numel() ? bias.data_ptr() : nullptr; const auto dest = output.data_ptr(); const int blocks = (n + warps - 1) / warps; if (scale.size(1) == k / 16) { vectorized_matvec<16><<>>( 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><<>>( input, quantized, scales, bias_data, dest, k, n); } C10_CUDA_KERNEL_LAUNCH_CHECK(); return output; }