Files
leleka/crates/cuda-driver/src/offline_mtp_kernel.cu
T

142 lines
6.5 KiB
Plaintext

// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
// ggml/src/ggml-cuda/{norm.cu,common.cuh,unary.cu}.
//
// MIT License
// Copyright (c) 2023-2026 The ggml authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Fixed MTP input candidates; not an independent native oracle.
// Original native_qsa.cu SHA256:
// a9f47aa583e656757e4b81830143e05cac1a8266fb22cee085663732d5c6948a
// Original verify_kernels.cu SHA256:
// bccc7b510609524f2d45f07690de5e47800a302820a3dceeae2a3c2486a9d24b
// Original caller: core/mtp.cpp SHA256:
// 71d8a93f6edc18916a5df9954cba372833f3cfd4efd952e2aedaed089a8d3fb4
// Fixed pointer-only ABI, aligned F32 whole allocations, disjoint outputs:
// embedding norm 2560 values, grid1/block1024;
// hidden norm WHOLE 10240 values, grid1/block1024 (not four norms);
// h[i] + e[i % 2560] broadcast 10240 values, grid40/block256.
// Packed gamma already contains 1+w; do not add another one.
// Original successful operation/reduction order and literal epsilon1e-6.
// Failure-only qNaN marks malformed/nonfinite intermediate candidates; the
// private producer must validate all outputs before atomic publication.
// Offline: nvcc --ptx -std=c++17 -O3 -arch=sm_120 --use_fast_math
// --ftz=true --fmad=true offline_mtp_kernel.cu -o PRIVATE_OUTPUT
// Cargo does not compile this source; no Toolkit serving dependency.
// Source/assembly success alone does not admit any production operation.
#include <cuda_runtime.h>
#include <stddef.h>
#include <stdint.h>
namespace {
// Native receives n_cols and epsilon as runtime kernel parameters. Retain the
// fixed norm values through volatile loads so lowering cannot replace the
// native hardware reciprocal with a folded literal. No caller controls these.
// CUDA const+volatile lowers to ld.global.nc here; volatile alone retains the
// actual ld.volatile.global fence. Private globals are never written by any
// entry, exported through the safe driver, or selected by a caller.
__device__ volatile int embedding_columns = 2560;
__device__ volatile float embedding_epsilon = 1.0e-6f;
__device__ volatile int hidden_columns = 10240;
__device__ volatile float hidden_epsilon = 1.0e-6f;
__device__ __forceinline__ float failure() {
return __uint_as_float(0x7fc00000u);
}
__device__ __forceinline__ bool finite(float value) {
return (__float_as_uint(value) & 0x7f800000u) != 0x7f800000u;
}
__device__ __forceinline__ float warp_sum(float value) {
#pragma unroll
for (int offset = 16; offset; offset >>= 1)
value += __shfl_xor_sync(0xffffffffu, value, offset, 32);
return value;
}
template<size_t Columns>
__device__ __forceinline__ void norm(const float* input,
const float* __restrict__ gamma,
float* output) {
const int tid = threadIdx.x;
float partial = 0.0f;
__shared__ float sums[32];
__shared__ int bad;
if (tid == 0) bad = 0;
__syncthreads();
for (size_t col = tid; col < Columns; col += 1024) {
const float x = input[col];
if (!finite(x) || !finite(gamma[col])) atomicOr(&bad, 1);
// Keep the original expression so the pinned compiler preserves its
// multiply/add contraction. Positive square overflow is also visible
// in partial; no reciprocal can hide it later.
partial += x * x;
}
if (!finite(partial)) atomicOr(&bad, 1);
partial = warp_sum(partial);
const int lane = tid % 32;
if (lane == 0) sums[tid / 32] = partial;
__syncthreads();
partial = lane < 32 ? sums[lane] : 0.0f;
partial = warp_sum(partial);
const float columns = float(Columns == 2560 ? embedding_columns : hidden_columns);
const float epsilon = Columns == 2560 ? embedding_epsilon : hidden_epsilon;
float reciprocal;
asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(reciprocal) : "f"(columns));
// The unchanged original div+add lowers to MUFU.RCP + FFMA.FTZ.
// Observing mean for failure checks otherwise inhibits this fusion.
const float mean = partial / columns;
const float denominator = fmaf(partial, reciprocal, epsilon);
const float scale = rsqrtf(denominator);
if (!finite(partial) || !finite(mean) || !finite(denominator) ||
denominator <= 0.0f || !finite(scale)) atomicOr(&bad, 1);
__syncthreads();
for (size_t col = tid; col < Columns; col += 1024) {
const float scaled = scale * input[col];
const float candidate = scaled * gamma[col];
output[col] = bad || !finite(scaled) || !finite(candidate)
? failure() : candidate;
}
}
} // namespace
extern "C" __global__ __launch_bounds__(1024)
void leleka_mtp_embedding_norm_f32(const float* input,
const float* __restrict__ gamma,
float* output) {
norm<2560>(input, gamma, output);
}
extern "C" __global__ __launch_bounds__(1024)
void leleka_mtp_hidden_norm_f32(const float* input,
const float* __restrict__ gamma,
float* output) {
norm<10240>(input, gamma, output);
}
extern "C" __global__ __launch_bounds__(256)
void leleka_mtp_broadcast_f32(const float* __restrict__ hidden,
const float* __restrict__ embedding,
float* __restrict__ output) {
const int64_t i = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (i >= 10240) return;
const float h = hidden[i], e = embedding[i % 2560];
const float candidate = h + e;
output[i] = !finite(h) || !finite(e) || !finite(candidate)
? failure() : candidate;
}