12 if (!heads || !dim || dim > SIZE_MAX / heads || !tokens || tokens > capacity ||
13 position > SIZE_MAX - tokens || (!circular && position > capacity - tokens) ||
14 !isfinite(key_clip) || key_clip <= 0.f || !isfinite(epsilon) || epsilon <= 0.f)
16 size_t width = heads * dim, active, cache;
19 active > key_elements || active > value_elements ||
20 cache > k_cache_elements || cache > v_cache_elements)
return -2;
31 for (
size_t t = 0; t < tokens; ++t) {
32 const size_t row = circular ? (position + t) % capacity : position + t;
33 for (
size_t h = 0; h < heads; ++h) {
34 const size_t src = (t * heads + h) * dim;
35 const size_t dst = (h * capacity + row) * dim;
36 double key_sq = 0.0, value_sq = 0.0;
37 for (
size_t d = 0; d < dim; ++d) {
38 const volatile double ks = (double)key[src + d] * key[src + d];
39 const volatile double vs = (double)value[src + d] * value[src + d];
43 const double key_scale = fmin(1.0, key_clip / (sqrt(key_sq) + epsilon));
44 const double value_scale = 1.0 / sqrt(value_sq / (
double)dim + epsilon);
45 for (
size_t d = 0; d < dim; ++d) {
46 k_cache[dst + d] = (float)(key[src + d] * key_scale);
47 v_cache[dst + d] = (float)(value[src + d] * value_scale);
int ck_kv_cache_l2_rms_append_ring_checked_f32(const float *key, size_t key_elements, const float *value, size_t value_elements, float *k_cache, size_t k_cache_elements, float *v_cache, size_t v_cache_elements, size_t tokens, size_t heads, size_t dim, size_t capacity, size_t position, float key_clip, float epsilon)
int ck_kv_cache_l2_rms_append_checked_f32(const float *key, size_t key_elements, const float *value, size_t value_elements, float *k_cache, size_t k_cache_elements, float *v_cache, size_t v_cache_elements, size_t tokens, size_t heads, size_t dim, size_t capacity, size_t position, float key_clip, float epsilon)
static int kv_cache_l2_rms_append(const float *key, size_t key_elements, const float *value, size_t value_elements, float *k_cache, size_t k_cache_elements, float *v_cache, size_t v_cache_elements, size_t tokens, size_t heads, size_t dim, size_t capacity, size_t position, float key_clip, float epsilon, int circular)