CUDApp
CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.
Brought by drakestapleton
CUDApp / tests / gpu_attn_any_ref.h
| 1 | /* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ |
| 2 | #ifndef GPU_ATTN_ANY_REF_H |
| 3 | #define GPU_ATTN_ANY_REF_H |
| 4 | #include <math.h> |
| 5 | #include <stdint.h> |
| 6 | #include <stdlib.h> |
| 7 | #include <string.h> |
| 8 | /* Independent materialized-score softmax. No online recurrence, IR or production helpers. */ |
| 9 | static double aa_input(const void *p, size_t i, unsigned dtype) { |
| 10 | if (!dtype) return ((const float *)p)[i]; |
| 11 | if (dtype==2) { |
| 12 | unsigned h=((const uint16_t *)p)[i], e=(h>>10)&31u, f=h&1023u; |
| 13 | double value=e==31?(f?NAN:INFINITY):ldexp(e?1024.0+f:f,e?(int)e-25:-24); |
| 14 | return copysign(value,(h&32768u)?-1.0:1.0); |
| 15 | } |
| 16 | uint32_t u = (uint32_t)((const uint16_t *)p)[i] << 16; |
| 17 | float f; memcpy(&f, &u, sizeof f); return f; |
| 18 | } |
| 19 | static void aa_reference(const OmegaGpuAttnAnyShape *s, const void *q, const void *k, |
| 20 | const void *v, double *o, int wrong_mask) { |
| 21 | double *score = malloc((size_t)s->seq_kv * sizeof *score); |
| 22 | if (!score) abort(); |
| 23 | for (uint32_t h = 0; h < s->q_heads; ++h) { |
| 24 | uint32_t kh = h / (s->q_heads / s->kv_heads); |
| 25 | for (uint32_t i = 0; i < s->seq_q; ++i) { |
| 26 | uint32_t n = s->seq_kv; |
| 27 | if (s->causal && !wrong_mask && n > i + 1) n = i + 1; |
| 28 | double top = -INFINITY, sum = 0; |
| 29 | for (uint32_t j = 0; j < n; ++j) { |
| 30 | double dot = 0; |
| 31 | for (uint32_t d = 0; d < s->head_dim; ++d) |
| 32 | dot += aa_input(q, ((size_t)h*s->seq_q+i)*s->head_dim+d, s->dtype) * |
| 33 | aa_input(k, ((size_t)kh*s->seq_kv+j)*s->head_dim+d, s->dtype); |
| 34 | score[j] = dot * (double)s->scale; |
| 35 | if (score[j] > top) top = score[j]; |
| 36 | } |
| 37 | for (uint32_t j = 0; j < n; ++j) { score[j] = exp(score[j]-top); sum += score[j]; } |
| 38 | for (uint32_t d = 0; d < s->head_dim; ++d) { |
| 39 | double a = 0; |
| 40 | for (uint32_t j = 0; j < n; ++j) |
| 41 | a += score[j] * aa_input(v, ((size_t)kh*s->seq_kv+j)*s->head_dim+d, s->dtype); |
| 42 | o[((size_t)h*s->seq_q+i)*s->head_dim+d] = a / sum; |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | free(score); |
| 47 | } |
| 48 | /* Wolfram derivation and finite-input envelope in om/attn-any/README.md. Absolute error, |V|<=1. */ |
| 49 | #define AA_TOL 0.0009765625 |
| 50 | static int aa_equal(const float *a, const double *b, size_t n) { |
| 51 | for (size_t i = 0; i < n; ++i) |
| 52 | if (!(fabs((double)a[i]-b[i]) <= AA_TOL)) return 0; |
| 53 | return 1; |
| 54 | } |
| 55 | #endif |