28#include <cuda_runtime.h>
38 const std::string
v =
s ?
s :
"";
39 if (
v.empty() ||
v ==
"f32")
return kF32;
40 if (
v ==
"f16")
return kF16;
41 if (
v ==
"q8")
return kQ8;
42 if (
v ==
"q4")
return kQ4;
43 throw std::runtime_error(
"EMBER_KV=" +
v +
": expected f32, f16, q8 or q4");
56 if (
f ==
kF32)
return "";
57 if (
head_dim % 4 != 0)
return "head_dim % 4 != 0";
58 if ((
f ==
kQ8 ||
f ==
kQ4) &&
head_dim %
kBlock != 0)
return "head_dim % 32 != 0 (q8 and q4 blocks sit inside a head)";
66 std::memcpy(&
u, &
x, 4);
69 if (
ax >= 0x7f800000u)
return static_cast<uint16_t>(
sign | (
ax > 0x7f800000u ? 0x7e00u : 0x7c00u));
70 if (
ax >= 0x477ff000u)
return static_cast<uint16_t>(
sign | 0x7c00u);
71 if (
ax < 0x38800000u) {
85 if (
rem > 0x1000u || (
rem == 0x1000u && (
r & 1u))) ++
r;
96 const float v =
static_cast<float>(
m) * 5.9604644775390625e-8f;
97 std::memcpy(&
u, &
v, 4);
100 }
else if (
e == 31) {
101 u =
sign | 0x7f800000u | (
m << 13);
103 u =
sign | ((
e + 112u) << 23) | (
m << 13);
106 std::memcpy(&
f, &
u, 4);
117 float q = d != 0.0f ? std::nearbyint(
x[
i] / d) : 0.0f;
118 q = std::fmin(127.0f, std::fmax(-127.0f, q));
121 }
else if (
f ==
kQ4) {
122 float mn =
x[0],
mx =
x[0];
130 float q = d != 0.0f ? std::nearbyint((
x[
i] -
m) / d) : 0.0f;
131 q = std::fmin(15.0f, std::fmax(0.0f, q));
132 x[
i] = std::fma(q, d,
m);
139 if (
f ==
kF32)
return;
158void decode_cuda(
int f,
const float* q,
const void*
Kd,
const void*
Ks,
const void*
Vd,
const void*
Vs,
float*
out,
160 const int*
dpos =
nullptr);
const char * format_name(int f)
void write_cuda(int f, void *Kd, void *Ks, void *Vd, void *Vs, const float *k, const float *v, int T, int row, int start_pos, cudaStream_t st, const int *dpos)
size_t partial_floats(int hq, int hd, int max_len)
void decode_cuda(int f, const float *q, const void *Kd, const void *Ks, const void *Vd, const void *Vs, float *out, int hq, int hkv, int hd, float scale, int max_len, int seq_len, float *part, cudaStream_t st, const int *dpos)
uint16_t f32_to_f16(float x)
size_t data_bytes(int f, size_t row)
void dequant_rows_cuda(int f, const void *Kd, const void *Ks, const void *Vd, const void *Vs, float *K, float *V, int n, int row, cudaStream_t st)
void roundtrip_block(int f, float *x)
std::string shape_error(int f, int head_dim)
size_t scale_bytes(int f, size_t row)
Format parse_format(const char *s)
float f16_to_f32(uint16_t h)
void roundtrip_rows(int f, float *x, size_t rows, size_t row)