mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-12-01 23:27:39 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02227e87ae | ||
|
|
94f17f659f | ||
|
|
08dc1cea9e |
+4
-1
@@ -1,7 +1,10 @@
|
||||
set(TARGET llama-app)
|
||||
|
||||
add_executable(${TARGET} llama.cpp download.cpp)
|
||||
set_target_properties(${TARGET} PROPERTIES OUTPUT_NAME llama)
|
||||
set_target_properties(${TARGET} PROPERTIES
|
||||
OUTPUT_NAME llama
|
||||
PDB_NAME ${TARGET}
|
||||
)
|
||||
|
||||
target_link_libraries(${TARGET} PRIVATE
|
||||
llama-server-impl
|
||||
|
||||
+4
-4
@@ -2338,11 +2338,11 @@ llama_batch_ext * common_batch::get_sub_batch(int32_t off, int32_t n) {
|
||||
if (t.state_row >= 0 && !llama_batch_ext_set_embd_state_row(res, idx, t.state_row)) {
|
||||
GGML_ABORT("%s: failed to set the state row of the entry at index %d\n", __func__, i);
|
||||
}
|
||||
if (t.decision_order != 0) {
|
||||
llama_batch_ext_set_decision_order(res, idx, (llama_decision_order) t.decision_order);
|
||||
if (t.span != 0 && !(llama_batch_ext_set_pool_span(res, idx, t.span) && llama_batch_ext_set_pool_span_type(res, t.span, (llama_pool_span_type) t.span_type))) {
|
||||
GGML_ABORT("%s: failed to set the span of the entry at index %d\n", __func__, i);
|
||||
}
|
||||
if (t.decision_group != 0 && !llama_batch_ext_set_decision_group(res, idx, t.decision_group)) {
|
||||
GGML_ABORT("%s: failed to set the decision group of the entry at index %d\n", __func__, i);
|
||||
if (t.attn_scope != 0 && !llama_batch_ext_set_attn_scope(res, idx, t.attn_scope)) {
|
||||
GGML_ABORT("%s: failed to set the attention scope of the entry at index %d\n", __func__, i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1123,8 +1123,9 @@ struct common_batch {
|
||||
llama_embd embd; // non-owning view of the data passed to add_embd()/set_embd(), data == NULL if none
|
||||
llama_embd state; // non-owning view of the data passed to set_embd_state(), data == NULL if none
|
||||
std::vector<llama_seq_id> seq_ids_extra; // see add_seq()
|
||||
int32_t decision_order = 0; // see llama_batch_ext_set_decision_order()
|
||||
int32_t decision_group = 0; // see llama_batch_ext_set_decision_group()
|
||||
int32_t span = 0; // see llama_batch_ext_set_pool_span()
|
||||
int32_t span_type = 0; // see llama_batch_ext_set_pool_span_type()
|
||||
int32_t attn_scope = 0; // see llama_batch_ext_set_attn_scope()
|
||||
int32_t embd_row = -1; // see add_embd_row(), -1 if none
|
||||
int32_t state_row = -1; // see set_embd_state_row(), -1 if none
|
||||
};
|
||||
|
||||
@@ -317,6 +317,8 @@ Currently supported values: `auto`, `q8`, `q4`.
|
||||
|
||||
NVFP4 and MXFP4 layers marked as W4A16 request 8-bit activations, so on Blackwell those layers run through the W4A8 path instead of the native W4A4 path. Set `q4` to keep the native W4A4 path for faster prompt processing at the cost of accuracy, or `q8` to use the W4A8 path for every layer, `auto` uses per-tensor prec metadata (this is the same behavior as when the environment variable is not set).
|
||||
|
||||
For dense NVFP4 layers with batches of up to 24 tokens on Blackwell GPUs with compute capability 12.x (RTX 50xx, RTX PRO Blackwell, DGX Spark), the few-row MMQ path uses W4A8 at every batch size, so that the precision of a decode batch does not depend on how many sequences or draft tokens it holds. With `q4` it uses W4A4 from 6 tokens (DGX Spark: 8 tokens). MoE experts and the dense layers that the few-row MMQ path does not support keep MMVQ (W4A8) up to 8 tokens and MMQ above.
|
||||
|
||||
### Unified Memory
|
||||
|
||||
The environment variable `GGML_CUDA_ENABLE_UNIFIED_MEMORY=1` can be used to enable unified memory in Linux. This allows swapping to system RAM instead of crashing when the GPU VRAM is exhausted. In Windows this setting is available in the NVIDIA control panel as `System Memory Fallback`.
|
||||
|
||||
@@ -175,7 +175,7 @@ bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) {
|
||||
}
|
||||
|
||||
// do not fuse the matmuls that few-row MMQ takes in ggml_cuda_mul_mat_id
|
||||
if (tensor->op == GGML_OP_MUL_MAT_ID && ggml_cuda_should_use_mmq_few(src0, src1, tensor->src[2], cc)) {
|
||||
if (tensor->op == GGML_OP_MUL_MAT_ID && ggml_cuda_should_use_mmq_few(src0, src1, tensor->src[2], tensor, cc)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -295,7 +295,7 @@ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_t
|
||||
const int64_t nchannels = is_id ? x_up->ne[2] : y->ne[2]*y->ne[3];
|
||||
const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(x_up->type, cc) : ggml_cuda_should_use_mmvq(x_up->type, cc, ncols);
|
||||
// do not fuse the matmuls that few-row MMQ takes in ggml_cuda_mul_mat; for MUL_MAT_ID the fused MMQ keeps the expert gate and up
|
||||
if (!is_id && ggml_cuda_should_use_mmq_few(x_up, y, nullptr, cc)) {
|
||||
if (!is_id && ggml_cuda_should_use_mmq_few(x_up, y, nullptr, up, cc)) {
|
||||
return false;
|
||||
}
|
||||
if (use_mmvq || !ggml_cuda_should_use_mmq(x_up->type, cc, ncols, /*n_experts =*/ is_id ? x_up->ne[2] : 0)) {
|
||||
|
||||
@@ -2267,15 +2267,15 @@ static bool ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor
|
||||
return false;
|
||||
}
|
||||
// from a per-type number of src1 columns up to 24, few-row MMQ is faster than MMVQ and MMQ
|
||||
const bool use_mmq_few = ggml_cuda_should_use_mmq_few(src0, src1, nullptr, cc);
|
||||
const bool use_mmq_few = ggml_cuda_should_use_mmq_few(src0, src1, nullptr, dst, cc);
|
||||
if (!use_mmq_few && ggml_cuda_should_use_mmvq(src0->type, cc, ne11)) {
|
||||
const bool fold = scale_fold && ggml_cuda_should_fuse_mul_mat_vec_q(dst);
|
||||
ggml_cuda_mul_mat_vec_q(ctx, src0, src1, nullptr, dst, fold ? &fusion : nullptr);
|
||||
return fold;
|
||||
}
|
||||
if (use_mmq_few) {
|
||||
ggml_cuda_mul_mat_q_few(ctx, src0, src1, nullptr, dst);
|
||||
return false;
|
||||
ggml_cuda_mul_mat_q_few(ctx, src0, src1, nullptr, dst, scale_fold ? &fusion : nullptr);
|
||||
return scale_fold;
|
||||
}
|
||||
if (ggml_cuda_should_use_mmq(src0->type, cc, ne11, /*n_experts =*/ 0)) {
|
||||
ggml_cuda_mul_mat_q(ctx, src0, src1, nullptr, dst, scale_fold ? &fusion : nullptr);
|
||||
@@ -2313,7 +2313,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c
|
||||
}
|
||||
}
|
||||
|
||||
if (ggml_cuda_should_use_mmq_few(src0, src1, dst->src[2], cc)) {
|
||||
if (ggml_cuda_should_use_mmq_few(src0, src1, dst->src[2], dst, cc)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2355,7 +2355,7 @@ static bool ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
|
||||
// [TAG_MUL_MAT_ID_CUDA_GRAPHS]
|
||||
if ((src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16) && dst->type == GGML_TYPE_F32) {
|
||||
// up to 24 tokens few-row MMQ is faster than MMQ, on DGX Spark also faster than MMVQ
|
||||
const bool use_mmq_few = ggml_cuda_should_use_mmq_few(src0, src1, ids, cc);
|
||||
const bool use_mmq_few = ggml_cuda_should_use_mmq_few(src0, src1, ids, dst, cc);
|
||||
|
||||
static_assert(MMVQ_MAX_BATCH_SIZE == MMVF_MAX_BATCH_SIZE);
|
||||
if (!use_mmq_few && ne2 <= MMVQ_MAX_BATCH_SIZE) {
|
||||
|
||||
+256
-63
@@ -12,7 +12,7 @@
|
||||
|
||||
using namespace ggml_cuda_mma;
|
||||
|
||||
// Few-row MMQ: int8 MMA mat-mul for 2-24 src1 columns. A CUDA block has 16 src0 rows (32 for 2 column groups on large matrices).
|
||||
// Few-row MMQ: int8 MMA mat-mul for 2-24 src1 columns (block scaled FP4 MMA for NVFP4 with 4-bit src1). A CUDA block has 16 src0 rows (32 for 2 column groups on large matrices, not with 4-bit src1).
|
||||
// Its warps split K in units of 256 values and copy raw src0 rows into their own cp.async ring, src1 is quantized to the MMA fragment layout.
|
||||
// MUL_MAT_ID: one column group per expert and CUDA block, for short rows the warps split the rows instead of K (64 rows per block).
|
||||
|
||||
@@ -36,6 +36,7 @@ static constexpr __host__ __device__ int mmq_few_unit_size(const ggml_type type)
|
||||
case GGML_TYPE_IQ3_S: return mmq_few_unit_size_of<GGML_TYPE_IQ3_S>();
|
||||
case GGML_TYPE_IQ4_NL: return mmq_few_unit_size_of<GGML_TYPE_IQ4_NL>();
|
||||
case GGML_TYPE_IQ4_XS: return mmq_few_unit_size_of<GGML_TYPE_IQ4_XS>();
|
||||
case GGML_TYPE_NVFP4: return mmq_few_unit_size_of<GGML_TYPE_NVFP4>();
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
@@ -46,8 +47,9 @@ static constexpr __host__ __device__ mmq_q8_1_ds_layout mmq_few_ds_layout(const
|
||||
}
|
||||
|
||||
// Units of 256 values per ring stage: 1 for Q6_K, 3 column groups (fewer free registers) and 32-row tiles (2 blocks per SM), else 2.
|
||||
static constexpr __host__ __device__ int mmq_few_nunits_stage(const ggml_type type, const int ncg, const int nmt) {
|
||||
return type == GGML_TYPE_Q6_K || ncg > 2 || nmt > 1 ? 1 : 2;
|
||||
// fp4: NVFP4 with 4-bit src1, which has enough free registers for 2 units with 3 column groups.
|
||||
static constexpr __host__ __device__ int mmq_few_nunits_stage(const ggml_type type, const int ncg, const int nmt, const bool fp4) {
|
||||
return type == GGML_TYPE_Q6_K || (ncg > 2 && !fp4) || nmt > 1 ? 1 : 2;
|
||||
}
|
||||
|
||||
// A third ring stage only makes Q6_K faster, the other types get slower on large matrices.
|
||||
@@ -72,14 +74,19 @@ static constexpr __host__ __device__ int mmq_few_sram_stride(const ggml_type typ
|
||||
return mmq_few_unaligned(type, nunits_stage) && nchunks % 2 == 0 ? 16*(nchunks + 1) : 16*nchunks;
|
||||
}
|
||||
|
||||
static constexpr __host__ __device__ int mmq_few_nbytes_shared(const ggml_type type, const int ncg, const int nmt) {
|
||||
return MMQ_FEW_NWARPS*mmq_few_nstages(type)*nmt*MMQ_FEW_NROWS*mmq_few_sram_stride(type, mmq_few_nunits_stage(type, ncg, nmt));
|
||||
static constexpr __host__ __device__ int mmq_few_nbytes_shared(const ggml_type type, const int ncg, const int nmt, const bool fp4) {
|
||||
return MMQ_FEW_NWARPS*mmq_few_nstages(type)*nmt*MMQ_FEW_NROWS*mmq_few_sram_stride(type, mmq_few_nunits_stage(type, ncg, nmt, fp4));
|
||||
}
|
||||
|
||||
// With Q6_K and Q8_0 two CUDA blocks with 32-row tiles would not fit into an SM.
|
||||
static constexpr __host__ __device__ bool mmq_few_tall_supported(const ggml_type type) {
|
||||
return type == GGML_TYPE_Q3_K || type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K ||
|
||||
type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_IQ4_XS;
|
||||
type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_IQ4_XS || type == GGML_TYPE_NVFP4;
|
||||
}
|
||||
|
||||
// The MUL_MAT_ID src1 quantizer keeps the natural value order, the NVFP4 decoder needs the nvfp4 order (see quantize_mmq_few_q8_1).
|
||||
static constexpr __host__ __device__ bool mmq_few_id_supported(const ggml_type type) {
|
||||
return type != GGML_TYPE_NVFP4;
|
||||
}
|
||||
|
||||
// MUL_MAT_ID with fewer than 2 units of 256 values per warp: the warps split the rows, each warp has its own 16 rows.
|
||||
@@ -106,6 +113,18 @@ static __device__ __forceinline__ void mmq_few_load_y(mmq_few_y_frag & yf, const
|
||||
}
|
||||
}
|
||||
|
||||
// The src1 fragments of a lane for NVFP4 with 4-bit src1, see MMQ_FEW_FP4_INT4: the B fragments of the 4 blocks of 64 values and the scales of column g.
|
||||
struct mmq_few_y_fp4 {
|
||||
int4 qs[2];
|
||||
int4 sc;
|
||||
};
|
||||
|
||||
static __device__ __forceinline__ void mmq_few_load_y(mmq_few_y_fp4 & yf, const int4 * y) {
|
||||
yf.qs[0] = y[threadIdx.x];
|
||||
yf.qs[1] = y[WARP_SIZE + threadIdx.x];
|
||||
yf.sc = y[2*WARP_SIZE + threadIdx.x/4];
|
||||
}
|
||||
|
||||
static __device__ __forceinline__ int2 mmq_few_get_b(const mmq_few_y_frag & yf, const int s) {
|
||||
const int4 q = yf.qs[s/2];
|
||||
return s % 2 == 0 ? make_int2(q.x, q.y) : make_int2(q.z, q.w);
|
||||
@@ -169,12 +188,11 @@ static __device__ __forceinline__ void mmq_few_mma_add(
|
||||
}
|
||||
}
|
||||
|
||||
// Same with one k=16 MMA per half of sub-block s, the int8 scales of the halves are bytes 0 and 1 of sc[r].
|
||||
template <ggml_type type, int ncg>
|
||||
// Same with one k=16 MMA per half of sub-block s, sc_lo and sc_hi are the scales of the halves (int, or float for NVFP4).
|
||||
template <ggml_type type, int ncg, typename scale_t>
|
||||
static __device__ __forceinline__ void mmq_few_mma_k16_add(
|
||||
const int (&lo)[2], const int (&hi)[2], const int (&sc)[2], const mmq_few_y_frag (&yf)[ncg], const int s, float (&sum_d)[ncg][4]) {
|
||||
const int sc_lo[2] = {(int8_t) sc[0], (int8_t) sc[1]};
|
||||
const int sc_hi[2] = {(int8_t) (sc[0] >> 8), (int8_t) (sc[1] >> 8)};
|
||||
const int (&lo)[2], const int (&hi)[2], const scale_t (&sc_lo)[2], const scale_t (&sc_hi)[2], const mmq_few_y_frag (&yf)[ncg], const int s,
|
||||
float (&sum_d)[ncg][4]) {
|
||||
#pragma unroll
|
||||
for (int c = 0; c < ncg; ++c) {
|
||||
const int2 b = mmq_few_get_b(yf[c], s);
|
||||
@@ -189,6 +207,15 @@ static __device__ __forceinline__ void mmq_few_mma_k16_add(
|
||||
}
|
||||
}
|
||||
|
||||
// The int8 scales of the halves are bytes 0 and 1 of sc[r].
|
||||
template <ggml_type type, int ncg>
|
||||
static __device__ __forceinline__ void mmq_few_mma_k16_add(
|
||||
const int (&lo)[2], const int (&hi)[2], const int (&sc)[2], const mmq_few_y_frag (&yf)[ncg], const int s, float (&sum_d)[ncg][4]) {
|
||||
const int sc_lo[2] = {(int8_t) sc[0], (int8_t) sc[1]};
|
||||
const int sc_hi[2] = {(int8_t) (sc[0] >> 8), (int8_t) (sc[1] >> 8)};
|
||||
mmq_few_mma_k16_add<type>(lo, hi, sc_lo, sc_hi, yf, s, sum_d);
|
||||
}
|
||||
|
||||
template <int ncg>
|
||||
static __device__ __forceinline__ void mmq_few_add_scaled(float (&sum)[ncg][4], const float (&d)[2], const float (&sum_d)[ncg][4]) {
|
||||
#pragma unroll
|
||||
@@ -470,6 +497,90 @@ static __device__ __forceinline__ void mmq_few_vec_dot_iq3_s(const char * const
|
||||
mmq_few_add_scaled(sum, d, sum_d);
|
||||
}
|
||||
|
||||
// The doubled E2M1 values of the 4 nibbles in the low 16 bits of q as int8, like get_int_from_table_16.
|
||||
static __device__ __forceinline__ int mmq_few_e2m1_x4(const int q) {
|
||||
const uint32_t * table32 = (const uint32_t *) kvalues_fp4;
|
||||
const uint32_t low = __byte_perm(table32[0], table32[1], q);
|
||||
const uint32_t high = __byte_perm(table32[2], table32[3], q);
|
||||
return __byte_perm(low, high, 0x3210 | ((q & 0x8888) >> 1));
|
||||
}
|
||||
|
||||
// NVFP4 has a UE4M3 scale per 16 values: one k=16 MMA per half of a sub-block, the E2M1 values are converted to int8 with a table.
|
||||
// Byte i of 16 values holds the values i and i + 8. Lane t takes the bytes 2t and 2t + 1, so src1 has the values 2t, 2t + 8, 2t + 1, 2t + 9 in this order (nvfp4_order in quantize.cu).
|
||||
template <int ncg>
|
||||
static __device__ __forceinline__ void mmq_few_vec_dot_nvfp4(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) {
|
||||
const int t = threadIdx.x % 4;
|
||||
|
||||
#pragma unroll
|
||||
for (int ib = 0; ib < QK_K/QK_NVFP4; ++ib) {
|
||||
int q[2][4];
|
||||
float sc[2][4];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < 2; ++r) {
|
||||
const block_nvfp4 * bx = (const block_nvfp4 *) x[r] + ib;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < QK_NVFP4/QK_NVFP4_SUB; ++j) {
|
||||
q[r][j] = mmq_few_e2m1_x4(*(const uint16_t *) (bx->qs + 8*j + 2*t));
|
||||
}
|
||||
// The 4 UE4M3 scales, not halved like in ggml_cuda_ue4m3_to_fp32 (the write-back halves). As there, the NaN codes 0x7F and 0xFF give 0.
|
||||
#ifdef FP8_AVAILABLE
|
||||
// 2 scales per conversion
|
||||
uint32_t d4 = get_int_b4(bx->d, 0);
|
||||
const uint32_t nan = ((d4 & 0x7F7F7F7F) + 0x01010101) & 0x80808080; // 0x80 in the bytes 0x7F and 0xFF
|
||||
d4 &= ~(nan | (nan - (nan >> 7))); // these bytes to 0
|
||||
const float2 s01 = __half22float2(__half2(__nv_cvt_fp8x2_to_halfraw2((__nv_fp8x2_storage_t) (d4 & 0xFFFF), __NV_E4M3)));
|
||||
const float2 s23 = __half22float2(__half2(__nv_cvt_fp8x2_to_halfraw2((__nv_fp8x2_storage_t) (d4 >> 16), __NV_E4M3)));
|
||||
sc[r][0] = s01.x;
|
||||
sc[r][1] = s01.y;
|
||||
sc[r][2] = s23.x;
|
||||
sc[r][3] = s23.y;
|
||||
#else
|
||||
#pragma unroll
|
||||
for (int j = 0; j < QK_NVFP4/QK_NVFP4_SUB; ++j) {
|
||||
sc[r][j] = 2.0f*ggml_cuda_ue4m3_to_fp32(bx->d[j]);
|
||||
}
|
||||
#endif // FP8_AVAILABLE
|
||||
}
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const int lo[2] = {q[0][2*h + 0], q[1][2*h + 0]};
|
||||
const int hi[2] = {q[0][2*h + 1], q[1][2*h + 1]};
|
||||
const float sc_lo[2] = {sc[0][2*h + 0], sc[1][2*h + 0]};
|
||||
const float sc_hi[2] = {sc[0][2*h + 1], sc[1][2*h + 1]};
|
||||
mmq_few_mma_k16_add<GGML_TYPE_NVFP4>(lo, hi, sc_lo, sc_hi, yf, 2*ib + h, sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NVFP4 with 4-bit src1: one block scaled FP4 m16n8k64 MMA per block of 64 values, the 32 bit words of src0 and src1 are the MMA fragments.
|
||||
// Lanes with t % 2 == 0 give the scales of row g, lanes with t % 2 == 1 those of row g + 8, see mma_block_scaled_fp4.
|
||||
template <int ncg>
|
||||
static __device__ __forceinline__ void mmq_few_vec_dot_nvfp4_fp4(const char * const (&x)[2], const mmq_few_y_fp4 (&yf)[ncg], float (&sum)[ncg][4]) {
|
||||
const int t = threadIdx.x % 4;
|
||||
const char * x_sc = t % 2 == 0 ? x[0] : x[1]; // x[t % 2] would put x into local memory
|
||||
|
||||
#pragma unroll
|
||||
for (int ib = 0; ib < QK_K/QK_NVFP4; ++ib) {
|
||||
const block_nvfp4 * bx0 = (const block_nvfp4 *) x[0] + ib;
|
||||
const block_nvfp4 * bx1 = (const block_nvfp4 *) x[1] + ib;
|
||||
tile<16, 8, int> A;
|
||||
A.x[0] = get_int_b4(bx0->qs, t);
|
||||
A.x[1] = get_int_b4(bx1->qs, t);
|
||||
A.x[2] = get_int_b4(bx0->qs, t + 4);
|
||||
A.x[3] = get_int_b4(bx1->qs, t + 4);
|
||||
const uint32_t scale_A = get_int_b4(((const block_nvfp4 *) x_sc + ib)->d, 0);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < ncg; ++c) {
|
||||
const int * qs = (const int *) &yf[c].qs[ib/2];
|
||||
tile<8, 8, int> B;
|
||||
B.x[0] = qs[2*(ib % 2) + 0];
|
||||
B.x[1] = qs[2*(ib % 2) + 1];
|
||||
const uint32_t scale_B = ((const int *) &yf[c].sc)[ib];
|
||||
mma_block_scaled_fp4<GGML_TYPE_NVFP4>(*(tile<16, 8, float> *) sum[c], A, B, scale_A, scale_B);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <ggml_type type, int ncg>
|
||||
static __device__ __forceinline__ void mmq_few_vec_dot(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) {
|
||||
if constexpr (type == GGML_TYPE_Q8_0 || type == GGML_TYPE_IQ4_NL) {
|
||||
@@ -484,6 +595,8 @@ static __device__ __forceinline__ void mmq_few_vec_dot(const char * const (&x)[2
|
||||
mmq_few_vec_dot_iq3_s<ncg>(x, yf, sum);
|
||||
} else if constexpr (type == GGML_TYPE_IQ4_XS) {
|
||||
mmq_few_vec_dot_iq4_xs<ncg>(x, yf, sum);
|
||||
} else if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
mmq_few_vec_dot_nvfp4<ncg>(x, yf, sum);
|
||||
} else {
|
||||
static_assert(type == GGML_TYPE_COUNT, "unsupported type");
|
||||
}
|
||||
@@ -492,10 +605,11 @@ static __device__ __forceinline__ void mmq_few_vec_dot(const char * const (&x)[2
|
||||
#endif // defined(CP_ASYNC_AVAILABLE)
|
||||
|
||||
// has_ids: MUL_MAT_ID, blockIdx.y is a pair of quantize_mmq_few_id_q8_1, its expert is the src0 channel and dst dims 1 and 2 are slot and token.
|
||||
template <ggml_type type, int ncg, int nmt, bool has_ids>
|
||||
// fp4: NVFP4 src0 with 4-bit src1, which has a scale per column in y_scale. x_scale is an optional scale of all of src0.
|
||||
template <ggml_type type, int ncg, int nmt, bool has_ids, bool fp4>
|
||||
__launch_bounds__(MMQ_FEW_NWARPS*ggml_cuda_get_physical_warp_size(), 1)
|
||||
static __global__ void mul_mat_q_few(
|
||||
const char * x, const int4 * y_ptr, float * dst,
|
||||
const char * x, const int4 * y_ptr, const float * y_scale, const float * x_scale, float * dst,
|
||||
const int nunits, const int nrows_x, const int ncols_dst, const int64_t stride_row_x, const int stride_col_dst,
|
||||
const int channel_ratio, const int64_t stride_channel_x, const int stride_channel_dst,
|
||||
const int sample_ratio, const int64_t stride_sample_x, const int stride_sample_dst, const bool x_is_constant, const int * pairs) {
|
||||
@@ -504,10 +618,14 @@ static __global__ void mul_mat_q_few(
|
||||
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
|
||||
static_assert(warp_size == WARP_SIZE, "unsupported warp size");
|
||||
static_assert(!has_ids || (ncg == 1 && nmt == 1), "unsupported MUL_MAT_ID config");
|
||||
static_assert(!fp4 || (type == GGML_TYPE_NVFP4 && !has_ids), "4-bit src1 is only supported for NVFP4 MUL_MAT");
|
||||
|
||||
using y_frag_t = std::conditional_t<fp4, mmq_few_y_fp4, mmq_few_y_frag>;
|
||||
constexpr int y_int4 = fp4 ? MMQ_FEW_FP4_INT4 : MMQ_FEW_Q8_1_INT4;
|
||||
|
||||
constexpr int unit_size = mmq_few_unit_size(type);
|
||||
constexpr int nrows = nmt*MMQ_FEW_NROWS;
|
||||
constexpr int nunits_stage = mmq_few_nunits_stage(type, ncg, nmt);
|
||||
constexpr int nunits_stage = mmq_few_nunits_stage(type, ncg, nmt, fp4);
|
||||
constexpr int nstages = mmq_few_nstages(type);
|
||||
constexpr bool unaligned = mmq_few_unaligned(type, nunits_stage);
|
||||
constexpr int nchunks = mmq_few_nchunks(type, nunits_stage);
|
||||
@@ -543,7 +661,7 @@ static __global__ void mul_mat_q_few(
|
||||
x += int64_t(sample_dst/sample_ratio)*stride_sample_x + int64_t(channel_dst/channel_ratio)*stride_channel_x;
|
||||
dst += int64_t(sample_dst)*stride_sample_dst + int64_t(channel_dst)*stride_channel_dst;
|
||||
}
|
||||
const int4 * GGML_CUDA_RESTRICT y = y_ptr + (int64_t(sample_dst)*nchannels + channel_dst)*nunits*ncg*MMQ_FEW_Q8_1_INT4;
|
||||
const int4 * GGML_CUDA_RESTRICT y = y_ptr + (int64_t(sample_dst)*nchannels + channel_dst)*nunits*ncg*y_int4;
|
||||
|
||||
// No bounds check for the units, the gate makes nunits a multiple of nunits_stage.
|
||||
// The extra bytes of unaligned data are inside the allocation, which ggml aligns and pads to 128 bytes.
|
||||
@@ -613,15 +731,15 @@ static __global__ void mul_mat_q_few(
|
||||
ggml_cuda_pdl_sync();
|
||||
}
|
||||
|
||||
auto load_y = [&](mmq_few_y_frag (&yf)[ncg], const int iu) {
|
||||
auto load_y = [&](y_frag_t (&yf)[ncg], const int iu) {
|
||||
#pragma unroll
|
||||
for (int c = 0; c < ncg; ++c) {
|
||||
mmq_few_load_y(yf[c], y + (int64_t(iu)*ncg + c)*MMQ_FEW_Q8_1_INT4);
|
||||
mmq_few_load_y(yf[c], y + (int64_t(iu)*ncg + c)*y_int4);
|
||||
}
|
||||
};
|
||||
|
||||
// The next src1 fragments are loaded right after the MMAs that use the current ones, an earlier load is slower.
|
||||
mmq_few_y_frag yf[nunits_stage][ncg];
|
||||
y_frag_t yf[nunits_stage][ncg];
|
||||
if (iu_begin < nunits) {
|
||||
#pragma unroll
|
||||
for (int k = 0; k < nunits_stage; ++k) {
|
||||
@@ -653,7 +771,11 @@ static __global__ void mul_mat_q_few(
|
||||
xs + (MMQ_FEW_NROWS*m + threadIdx.x/4 + 0)*sram_stride + (off_row[2*m + 0] + off_stage) % 16 + k*unit_size,
|
||||
xs + (MMQ_FEW_NROWS*m + threadIdx.x/4 + 8)*sram_stride + (off_row[2*m + 1] + off_stage) % 16 + k*unit_size,
|
||||
};
|
||||
mmq_few_vec_dot<type, ncg>(xr, yf[k], sum[m]);
|
||||
if constexpr (fp4) {
|
||||
mmq_few_vec_dot_nvfp4_fp4<ncg>(xr, yf[k], sum[m]);
|
||||
} else {
|
||||
mmq_few_vec_dot<type, ncg>(xr, yf[k], sum[m]);
|
||||
}
|
||||
}
|
||||
if (has_next) {
|
||||
load_y(yf[k], iu0 + iu_step + k);
|
||||
@@ -692,6 +814,14 @@ static __global__ void mul_mat_q_few(
|
||||
}
|
||||
}
|
||||
|
||||
[[maybe_unused]] float scale_x = 1.0f;
|
||||
if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
scale_x = (fp4 ? 1.0f : 0.5f)*(x_scale ? *x_scale : 1.0f); // 8-bit src1: halved here, as the decoder halves neither the UE4M3 scales nor the doubled E2M1 values
|
||||
if constexpr (fp4) {
|
||||
y_scale += (int64_t(sample_dst)*nchannels + channel_dst)*ncg*MMQ_FEW_NCOLS;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int m = 0; m < nmt; ++m) {
|
||||
#pragma unroll
|
||||
@@ -704,6 +834,8 @@ static __global__ void mul_mat_q_few(
|
||||
if constexpr (has_ids) {
|
||||
const int e = pair[2 + j]; // token*n_expert_used + slot
|
||||
dst[int64_t(e / ncols_dst)*stride_channel_dst + int64_t(e % ncols_dst)*stride_col_dst + i] = sum[m][c][l];
|
||||
} else if constexpr (type == GGML_TYPE_NVFP4) {
|
||||
dst[int64_t(j)*stride_col_dst + i] = (fp4 ? y_scale[j]*scale_x : scale_x)*sum[m][c][l];
|
||||
} else {
|
||||
dst[int64_t(j)*stride_col_dst + i] = sum[m][c][l];
|
||||
}
|
||||
@@ -712,7 +844,7 @@ static __global__ void mul_mat_q_few(
|
||||
}
|
||||
}
|
||||
#else
|
||||
GGML_UNUSED_VARS(x, y_ptr, dst, nunits, nrows_x, ncols_dst, stride_row_x, stride_col_dst,
|
||||
GGML_UNUSED_VARS(x, y_ptr, y_scale, x_scale, dst, nunits, nrows_x, ncols_dst, stride_row_x, stride_col_dst,
|
||||
channel_ratio, stride_channel_x, stride_channel_dst,
|
||||
sample_ratio, stride_sample_x, stride_sample_dst, x_is_constant, pairs);
|
||||
NO_DEVICE_CODE;
|
||||
@@ -1074,17 +1206,17 @@ static bool mmq_few_is_constant(const ggml_tensor * src0) {
|
||||
}
|
||||
|
||||
// MUL_MAT_ID: grid y is the pairs, the kernel takes the expert from the pair and does not use the channel and sample ratios.
|
||||
template <ggml_type type, int ncg, int nmt, bool has_ids = false>
|
||||
template <ggml_type type, int ncg, int nmt, bool has_ids = false, bool fp4 = false>
|
||||
static void launch_mul_mat_q_few(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
|
||||
const int4 * src1_q, cudaStream_t stream, const int * pairs = nullptr, const int npairs_max = 0) {
|
||||
const int4 * src1_q, const float * y_scale, const float * x_scale, cudaStream_t stream, const int * pairs = nullptr, const int npairs_max = 0) {
|
||||
GGML_TENSOR_BINARY_OP_LOCALS;
|
||||
|
||||
const int nunits = ne00 / QK_K;
|
||||
GGML_ASSERT(nunits % mmq_few_nunits_stage(type, ncg, nmt) == 0);
|
||||
GGML_ASSERT(nunits % mmq_few_nunits_stage(type, ncg, nmt, fp4) == 0);
|
||||
|
||||
const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
|
||||
const int nbytes_shared = mmq_few_nbytes_shared(type, ncg, nmt);
|
||||
CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_few<type, ncg, nmt, has_ids>), nbytes_shared);
|
||||
const int nbytes_shared = mmq_few_nbytes_shared(type, ncg, nmt, fp4);
|
||||
CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_few<type, ncg, nmt, has_ids, fp4>), nbytes_shared);
|
||||
|
||||
const bool x_is_constant = mmq_few_is_constant(src0);
|
||||
|
||||
@@ -1092,8 +1224,8 @@ static void launch_mul_mat_q_few(const ggml_tensor * src0, const ggml_tensor * s
|
||||
const dim3 block_nums((ne01 + nrows_blk - 1) / nrows_blk, has_ids ? npairs_max : ne12, ne13);
|
||||
const dim3 block_dims(warp_size, MMQ_FEW_NWARPS, 1);
|
||||
const ggml_cuda_kernel_launch_params params(block_nums, block_dims, nbytes_shared, stream);
|
||||
ggml_cuda_kernel_launch(mul_mat_q_few<type, ncg, nmt, has_ids>, params,
|
||||
(const char *) src0->data, src1_q, (float *) dst->data,
|
||||
ggml_cuda_kernel_launch(mul_mat_q_few<type, ncg, nmt, has_ids, fp4>, params,
|
||||
(const char *) src0->data, src1_q, y_scale, x_scale, (float *) dst->data,
|
||||
nunits, (int) ne01, (int) ne1, (int64_t) nb01, (int) (nb1/sizeof(float)),
|
||||
(int) (ne12/ne02), (int64_t) nb02, (int) (nb2/sizeof(float)),
|
||||
(int) (ne13/ne03), (int64_t) nb03, (int) (nb3/sizeof(float)), x_is_constant, pairs);
|
||||
@@ -1104,39 +1236,44 @@ static int mmq_few_ncg(const int64_t ncols) {
|
||||
}
|
||||
|
||||
// With 2 column groups, 32-row tiles halve the src1 loads per src0 byte. With 3 column groups they spill registers.
|
||||
static int mmq_few_nmt(const ggml_type type, const int ncg, const int64_t nrows_x) {
|
||||
// With 4-bit src1 (fp4) there are few src1 loads per unit and the 32-row tiles are slower.
|
||||
static int mmq_few_nmt(const ggml_type type, const int ncg, const int64_t nrows_x, const bool fp4) {
|
||||
const int nsm = ggml_cuda_info().devices[ggml_cuda_get_device()].nsm;
|
||||
return mmq_few_tall_supported(type) && ncg == 2 && nrows_x >= int64_t(nsm)*2*MMQ_FEW_NROWS ? 2 : 1;
|
||||
return mmq_few_tall_supported(type) && !fp4 && ncg == 2 && nrows_x >= int64_t(nsm)*2*MMQ_FEW_NROWS ? 2 : 1;
|
||||
}
|
||||
|
||||
template <ggml_type type>
|
||||
template <ggml_type type, bool fp4>
|
||||
static void launch_mul_mat_q_few_tall(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
|
||||
const int4 * src1_q, cudaStream_t stream) {
|
||||
if constexpr (mmq_few_tall_supported(type)) {
|
||||
if (mmq_few_nmt(type, 2, src0->ne[1]) == 2) {
|
||||
launch_mul_mat_q_few<type, 2, 2>(src0, src1, dst, src1_q, stream);
|
||||
const int4 * src1_q, const float * y_scale, const float * x_scale, cudaStream_t stream) {
|
||||
if constexpr (mmq_few_tall_supported(type) && !fp4) {
|
||||
if (mmq_few_nmt(type, 2, src0->ne[1], fp4) == 2) {
|
||||
launch_mul_mat_q_few<type, 2, 2, false, fp4>(src0, src1, dst, src1_q, y_scale, x_scale, stream);
|
||||
return;
|
||||
}
|
||||
}
|
||||
launch_mul_mat_q_few<type, 2, 1>(src0, src1, dst, src1_q, stream);
|
||||
launch_mul_mat_q_few<type, 2, 1, false, fp4>(src0, src1, dst, src1_q, y_scale, x_scale, stream);
|
||||
}
|
||||
|
||||
template <ggml_type type>
|
||||
template <ggml_type type, bool fp4 = false>
|
||||
static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
|
||||
const int4 * src1_q, const int * pairs, const int npairs_max, const int ncg, cudaStream_t stream) {
|
||||
const int4 * src1_q, const float * y_scale, const float * x_scale, const int * pairs, const int npairs_max, const int ncg, cudaStream_t stream) {
|
||||
if (pairs) {
|
||||
launch_mul_mat_q_few<type, 1, 1, true>(src0, src1, dst, src1_q, stream, pairs, npairs_max);
|
||||
if constexpr (mmq_few_id_supported(type)) {
|
||||
launch_mul_mat_q_few<type, 1, 1, true>(src0, src1, dst, src1_q, y_scale, x_scale, stream, pairs, npairs_max);
|
||||
} else {
|
||||
GGML_ABORT("fatal error"); // see ggml_cuda_mmq_few_min_ncols
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch (ncg) {
|
||||
case 1:
|
||||
launch_mul_mat_q_few<type, 1, 1>(src0, src1, dst, src1_q, stream);
|
||||
launch_mul_mat_q_few<type, 1, 1, false, fp4>(src0, src1, dst, src1_q, y_scale, x_scale, stream);
|
||||
break;
|
||||
case 2:
|
||||
launch_mul_mat_q_few_tall<type>(src0, src1, dst, src1_q, stream);
|
||||
launch_mul_mat_q_few_tall<type, fp4>(src0, src1, dst, src1_q, y_scale, x_scale, stream);
|
||||
break;
|
||||
case 3:
|
||||
launch_mul_mat_q_few<type, 3, 1>(src0, src1, dst, src1_q, stream);
|
||||
launch_mul_mat_q_few<type, 3, 1, false, fp4>(src0, src1, dst, src1_q, y_scale, x_scale, stream);
|
||||
break;
|
||||
default:
|
||||
GGML_ABORT("fatal error");
|
||||
@@ -1235,7 +1372,18 @@ static void ggml_cuda_mul_mat_q_few_wmma(ggml_backend_cuda_context & ctx, const
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
|
||||
// NVFP4: whether src1 is 4-bit (the native FP4 MMA) or 8-bit.
|
||||
// 8-bit unless 4-bit is requested (GGML_CUDA_MMQ_PREC=q4 or by the graph): few-row batches are decode batches (one or more sequences,
|
||||
// draft tokens), whose precision should not depend on how many tokens are in the batch. 4-bit src1 changes the results much more.
|
||||
static bool mmq_few_use_fp4(const ggml_type type, const ggml_prec prec_requested, const int cc) {
|
||||
if (type != GGML_TYPE_NVFP4) {
|
||||
return false;
|
||||
}
|
||||
return ggml_cuda_mmq_get_prec_src1(type, prec_requested == GGML_PREC_UNDEFINED ? GGML_PREC_Q8 : prec_requested, cc) == GGML_PREC_Q4;
|
||||
}
|
||||
|
||||
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
|
||||
const ggml_cuda_mm_fusion_args_host * fusion) {
|
||||
GGML_TENSOR_BINARY_OP_LOCALS;
|
||||
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
|
||||
@@ -1246,15 +1394,36 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
|
||||
GGML_ASSERT(ne00 % QK_K == 0);
|
||||
|
||||
if (mmq_few_use_wmma(ggml_cuda_info().devices[ctx.device].cc)) {
|
||||
GGML_ASSERT(!ids);
|
||||
GGML_ASSERT(!ids && !fusion);
|
||||
ggml_cuda_mul_mat_q_few_wmma(ctx, src0, src1, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
// fusion: only the scale of an NVFP4 src0
|
||||
const ggml_tensor * x_scale = fusion ? fusion->x_scale : nullptr;
|
||||
GGML_ASSERT(!fusion || (!ids && src0->type == GGML_TYPE_NVFP4 && !fusion->x_bias && !fusion->gate && !fusion->gate_bias && !fusion->gate_scale &&
|
||||
!fusion->shared_up && !fusion->shared_gate && !fusion->shared_dst));
|
||||
GGML_ASSERT(!x_scale || (x_scale->type == GGML_TYPE_F32 && ggml_nelements(x_scale) == 1));
|
||||
const float * x_scale_d = x_scale ? (const float *) x_scale->data : nullptr;
|
||||
|
||||
cudaStream_t stream = ctx.stream();
|
||||
|
||||
const int nunits = ne00 / QK_K;
|
||||
const int ncg = ids ? 1 : mmq_few_ncg(ne11);
|
||||
const int cc = ggml_cuda_info().devices[ctx.device].cc;
|
||||
const bool fp4 = !ids && mmq_few_use_fp4(src0->type, fusion ? fusion->prec_src1 : ggml_prec_get_src(dst, 1), cc);
|
||||
|
||||
if (fp4) {
|
||||
GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS);
|
||||
GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0);
|
||||
|
||||
ggml_cuda_pool_alloc<int4> src1_q(ctx.pool(), int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_FP4_INT4);
|
||||
ggml_cuda_pool_alloc<float> y_scale(ctx.pool(), int64_t(ne12)*ne13*ncg*MMQ_FEW_NCOLS);
|
||||
quantize_mmq_few_nvfp4_cuda(src1->data, src1->type, src1_q.get(), y_scale.get(), ne10, nb11/nb10, nb12/nb10, nb13/nb10,
|
||||
ne11, ne12, ne13, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_NVFP4, true>(src0, src1, dst, src1_q.get(), y_scale.get(), x_scale_d, nullptr, 0, ncg, stream);
|
||||
return;
|
||||
}
|
||||
|
||||
ggml_cuda_pool_alloc<int> pairs(ctx.pool());
|
||||
ggml_cuda_pool_alloc<int4> src1_q(ctx.pool());
|
||||
@@ -1280,34 +1449,37 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
|
||||
GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0);
|
||||
|
||||
src1_q.alloc(int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_Q8_1_INT4);
|
||||
quantize_mmq_few_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/nb10, nb12/nb10, nb13/nb10,
|
||||
ne11, ne12, ne13, stream);
|
||||
quantize_mmq_few_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), src0->type == GGML_TYPE_NVFP4,
|
||||
ne10, nb11/nb10, nb12/nb10, nb13/nb10, ne11, ne12, ne13, stream);
|
||||
}
|
||||
|
||||
switch (src0->type) {
|
||||
case GGML_TYPE_Q8_0:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q8_0>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q8_0>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_Q3_K:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q3_K>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q3_K>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_Q4_K:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q4_K>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q4_K>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_Q5_K:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q5_K>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q5_K>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_Q6_K:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q6_K>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_Q6_K>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_IQ3_S:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_IQ3_S>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_IQ3_S>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_IQ4_NL:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_IQ4_NL>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_IQ4_NL>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_IQ4_XS:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_IQ4_XS>(src0, src1, dst, src1_q.get(), pairs.get(), npairs_max, ncg, stream);
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_IQ4_XS>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
case GGML_TYPE_NVFP4:
|
||||
launch_mul_mat_q_few_switch_ncg<GGML_TYPE_NVFP4>(src0, src1, dst, src1_q.get(), nullptr, x_scale_d, pairs.get(), npairs_max, ncg, stream);
|
||||
break;
|
||||
default:
|
||||
GGML_ABORT("unsupported type for few-row MMQ");
|
||||
@@ -1315,7 +1487,8 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
|
||||
}
|
||||
|
||||
// Min. number of src1 columns (MUL_MAT_ID: tokens) for the few-row MMQ, 0 if it is not used for this type, GPU and row length.
|
||||
static int ggml_cuda_mmq_few_min_ncols(const ggml_type type, const int cc, const int64_t ne00, const bool has_ids) {
|
||||
// fp4: NVFP4 with 4-bit src1 (only when requested, see mmq_few_use_fp4).
|
||||
static int ggml_cuda_mmq_few_min_ncols(const ggml_type type, const int cc, const int64_t ne00, const bool has_ids, const bool fp4) {
|
||||
#ifdef GGML_CUDA_FORCE_CUBLAS
|
||||
return 0;
|
||||
#endif // GGML_CUDA_FORCE_CUBLAS
|
||||
@@ -1336,6 +1509,19 @@ static int ggml_cuda_mmq_few_min_ncols(const ggml_type type, const int cc, const
|
||||
if (mmq_few_unit_size(type) == 0 || (!has_ids && ne00 < 8*QK_K)) {
|
||||
return 0;
|
||||
}
|
||||
if (has_ids && !mmq_few_id_supported(type)) {
|
||||
return 0;
|
||||
}
|
||||
// NVFP4: only on Blackwell (cc 12.x), tuned on RTX 5090 and DGX Spark
|
||||
if (type == GGML_TYPE_NVFP4) {
|
||||
if (!blackwell_mma_available(cc)) {
|
||||
return 0;
|
||||
}
|
||||
if (cc == GGML_CUDA_CC_GB10) {
|
||||
return fp4 ? 8 : 9; // 8-bit src1 only gains from 9 columns
|
||||
}
|
||||
return fp4 ? 6 : 7;
|
||||
}
|
||||
if (cc == GGML_CUDA_CC_GB10) { // tuned on DGX Spark GB10, also for MUL_MAT_ID
|
||||
return type == GGML_TYPE_IQ4_XS || type == GGML_TYPE_IQ4_NL ? 8 : 2;
|
||||
}
|
||||
@@ -1355,9 +1541,15 @@ static int ggml_cuda_mmq_few_min_ncols(const ggml_type type, const int cc, const
|
||||
}
|
||||
}
|
||||
|
||||
bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const int cc) {
|
||||
const int64_t ncols = ids ? ids->ne[1] : src1->ne[1];
|
||||
const int min_ncols = ggml_cuda_mmq_few_min_ncols(src0->type, cc, src0->ne[0], ids != nullptr);
|
||||
bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const ggml_tensor * dst, const int cc) {
|
||||
const int64_t ncols = ids ? ids->ne[1] : src1->ne[1];
|
||||
const ggml_prec prec_requested = ggml_prec_get_src(dst, 1);
|
||||
// NVFP4: src1 precisions that MMQ does not take (e.g. F16 without GGML_CUDA_MMQ_PREC) stay with MMVQ and MMQ, like without few-row
|
||||
if (src0->type == GGML_TYPE_NVFP4 && !ggml_cuda_mmq_prec_src1_supported(prec_requested)) {
|
||||
return false;
|
||||
}
|
||||
const bool fp4 = !ids && mmq_few_use_fp4(src0->type, prec_requested, cc);
|
||||
const int min_ncols = ggml_cuda_mmq_few_min_ncols(src0->type, cc, src0->ne[0], ids != nullptr, fp4);
|
||||
if (min_ncols == 0 || ncols < min_ncols || ncols > MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS) {
|
||||
return false;
|
||||
}
|
||||
@@ -1375,8 +1567,8 @@ bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor *
|
||||
}
|
||||
// the row must hold a whole number of ring stages of the launched kernel
|
||||
const int ncg = ids ? 1 : mmq_few_ncg(ncols);
|
||||
const int nmt = ids ? 1 : mmq_few_nmt(src0->type, ncg, src0->ne[1]);
|
||||
const int nunits_stage = mmq_few_nunits_stage(src0->type, ncg, nmt);
|
||||
const int nmt = ids ? 1 : mmq_few_nmt(src0->type, ncg, src0->ne[1], fp4);
|
||||
const int nunits_stage = mmq_few_nunits_stage(src0->type, ncg, nmt, fp4);
|
||||
if (src0->ne[0] % (nunits_stage*QK_K) != 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -1387,13 +1579,14 @@ bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor *
|
||||
|
||||
#else // !defined(GGML_USE_MUSA)
|
||||
|
||||
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
|
||||
GGML_UNUSED_VARS(ctx, src0, src1, ids, dst);
|
||||
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
|
||||
const ggml_cuda_mm_fusion_args_host * fusion) {
|
||||
GGML_UNUSED_VARS(ctx, src0, src1, ids, dst, fusion);
|
||||
GGML_ABORT("few-row MMQ is not supported on MUSA");
|
||||
}
|
||||
|
||||
bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const int cc) {
|
||||
GGML_UNUSED_VARS(src0, src1, ids, cc);
|
||||
bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const ggml_tensor * dst, const int cc) {
|
||||
GGML_UNUSED_VARS(src0, src1, ids, dst, cc);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
#include "common.cuh"
|
||||
|
||||
// ids != nullptr: MUL_MAT_ID
|
||||
bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, int cc);
|
||||
// ids != nullptr: MUL_MAT_ID. dst is the MUL_MAT or MUL_MAT_ID node, it holds the src1 precision requested by the graph.
|
||||
bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, const ggml_tensor * dst, int cc);
|
||||
|
||||
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst);
|
||||
// fusion: only the scalar weight scale of an NVFP4 src0 (x_scale) and the requested src1 precision of the MUL_MAT, applied in the write-back.
|
||||
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
|
||||
const ggml_cuda_mm_fusion_args_host * fusion = nullptr);
|
||||
|
||||
@@ -112,18 +112,24 @@ static ggml_prec ggml_cuda_mmq_get_prec_env() {
|
||||
return GGML_PREC_UNDEFINED;
|
||||
}
|
||||
|
||||
// GGML_CUDA_MMQ_PREC if set, else the src1 precision requested by the graph
|
||||
static ggml_prec ggml_cuda_mmq_get_prec(const ggml_prec prec_requested) {
|
||||
static const ggml_prec prec_env = ggml_cuda_mmq_get_prec_env();
|
||||
return prec_env != GGML_PREC_UNDEFINED ? prec_env : prec_requested;
|
||||
}
|
||||
|
||||
bool ggml_cuda_mmq_prec_src1_supported(const ggml_prec prec_requested) {
|
||||
const ggml_prec prec = ggml_cuda_mmq_get_prec(prec_requested);
|
||||
return prec == GGML_PREC_UNDEFINED || prec == GGML_PREC_Q8 || prec == GGML_PREC_Q4;
|
||||
}
|
||||
|
||||
// src1 is quantized to Q8_1 unless the FP4 types can use 4-bit activations, in which case they
|
||||
// default to the native W4A4 instructions on Blackwell.
|
||||
static ggml_prec ggml_cuda_mmq_get_prec_src1(const ggml_type type, const ggml_prec prec_requested, const int cc) {
|
||||
static const ggml_prec prec_env = ggml_cuda_mmq_get_prec_env();
|
||||
|
||||
ggml_prec prec = prec_env;
|
||||
if (prec == GGML_PREC_UNDEFINED) {
|
||||
prec = prec_requested;
|
||||
}
|
||||
ggml_prec ggml_cuda_mmq_get_prec_src1(const ggml_type type, const ggml_prec prec_requested, const int cc) {
|
||||
GGML_ASSERT(ggml_cuda_mmq_prec_src1_supported(prec_requested));
|
||||
const ggml_prec prec = ggml_cuda_mmq_get_prec(prec_requested);
|
||||
|
||||
// Q4 only for the FP4 types on Blackwell
|
||||
GGML_ASSERT(prec == GGML_PREC_UNDEFINED || prec == GGML_PREC_Q8 || prec == GGML_PREC_Q4);
|
||||
const bool can_use_q4 = (type == GGML_TYPE_NVFP4 || type == GGML_TYPE_MXFP4) && blackwell_mma_available(cc);
|
||||
if (prec == GGML_PREC_Q8 || !can_use_q4) {
|
||||
return GGML_PREC_Q8;
|
||||
|
||||
@@ -1727,5 +1727,12 @@ void ggml_cuda_mul_mat_q(
|
||||
|
||||
bool ggml_cuda_should_use_mmq(enum ggml_type type, int cc, int64_t ne11, int64_t n_experts);
|
||||
|
||||
// The src1 precision of MMQ: GGML_PREC_Q4 for MXFP4 and NVFP4 on Blackwell unless the precision is GGML_PREC_Q8, else GGML_PREC_Q8.
|
||||
// GGML_CUDA_MMQ_PREC, if set, replaces prec_requested. prec_requested must pass ggml_cuda_mmq_prec_src1_supported (asserted).
|
||||
ggml_prec ggml_cuda_mmq_get_prec_src1(ggml_type type, ggml_prec prec_requested, int cc);
|
||||
|
||||
// Whether MMQ takes this src1 precision request: UNDEFINED, Q8 or Q4 after the GGML_CUDA_MMQ_PREC override.
|
||||
bool ggml_cuda_mmq_prec_src1_supported(ggml_prec prec_requested);
|
||||
|
||||
// prec_requested: the src1 precision requested by the fused MUL_MATs.
|
||||
bool ggml_cuda_mmq_fusion_is_efficient(ggml_type type, ggml_prec prec_requested, int64_t nrows_x, int64_t ncols, int64_t nchannels, int device);
|
||||
|
||||
+274
-117
@@ -16,6 +16,18 @@ static __device__ __forceinline__ float4 quantize_load4(const src_t * x, const i
|
||||
}
|
||||
}
|
||||
|
||||
// 2 consecutive values of x as float2, x is aligned to 2 values
|
||||
template <typename src_t>
|
||||
static __device__ __forceinline__ float2 quantize_load2(const src_t * x) {
|
||||
if constexpr (std::is_same_v<src_t, nv_bfloat16>) {
|
||||
__align__(4) nv_bfloat162 v;
|
||||
ggml_cuda_memcpy_1<sizeof(v)>(&v, x);
|
||||
return ggml_cuda_cast<float2>(v);
|
||||
} else {
|
||||
return *(const float2 *) x;
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(BLACKWELL_MMA_AVAILABLE)
|
||||
// this maps to 256-bit loads in PTX on supported devices,
|
||||
// and otherwise falls back to 2 128-bit loads
|
||||
@@ -42,10 +54,14 @@ static __device__ __forceinline__ decltype(auto) quantize_load8(const src_t * x)
|
||||
}
|
||||
|
||||
#if CUDART_VERSION >= 12080
|
||||
static __device__ __forceinline__ float nvfp4_native_scale_error(
|
||||
const float vals[QK_NVFP4_SUB], const float inv_col_scale, const float inv_scale, const float scale) {
|
||||
const float scale_dequant = 2.0f * scale;
|
||||
float err = 0.0f;
|
||||
// The squared errors of the 16 values (times inv_col_scale) for each of the n scales. The n sums do not depend on each other, so they run in parallel.
|
||||
template <int n>
|
||||
static __device__ __forceinline__ void nvfp4_native_scale_error(
|
||||
const float vals[QK_NVFP4_SUB], const float inv_col_scale, const float (&inv_scale)[n], const float (&scale)[n], float (&err)[n]) {
|
||||
#pragma unroll
|
||||
for (int c = 0; c < n; ++c) {
|
||||
err[c] = 0.0f;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; k += 4) {
|
||||
@@ -54,30 +70,33 @@ static __device__ __forceinline__ float nvfp4_native_scale_error(
|
||||
const float v2 = vals[k + 2] * inv_col_scale;
|
||||
const float v3 = vals[k + 3] * inv_col_scale;
|
||||
|
||||
const __nv_fp4x4_e2m1 q(make_float4(v0 * inv_scale, v1 * inv_scale, v2 * inv_scale, v3 * inv_scale));
|
||||
const __nv_fp4x4_storage_t q_storage = q.__x;
|
||||
const __nv_fp4x2_storage_t q_lo = static_cast<__nv_fp4x2_storage_t>(q_storage);
|
||||
const __nv_fp4x2_storage_t q_hi = static_cast<__nv_fp4x2_storage_t>(q_storage >> 8U);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < n; ++c) {
|
||||
const float scale_dequant = 2.0f * scale[c];
|
||||
|
||||
const __half2_raw hraw2_lo = __nv_cvt_fp4x2_to_halfraw2(q_lo, __NV_E2M1);
|
||||
const __half2_raw hraw2_hi = __nv_cvt_fp4x2_to_halfraw2(q_hi, __NV_E2M1);
|
||||
const __half2 h2_lo = static_cast<__half2>(hraw2_lo);
|
||||
const __half2 h2_hi = static_cast<__half2>(hraw2_hi);
|
||||
const float2 dq_lo = __half22float2(h2_lo);
|
||||
const float2 dq_hi = __half22float2(h2_hi);
|
||||
const __nv_fp4x4_e2m1 q(make_float4(v0 * inv_scale[c], v1 * inv_scale[c], v2 * inv_scale[c], v3 * inv_scale[c]));
|
||||
const __nv_fp4x4_storage_t q_storage = q.__x;
|
||||
const __nv_fp4x2_storage_t q_lo = static_cast<__nv_fp4x2_storage_t>(q_storage);
|
||||
const __nv_fp4x2_storage_t q_hi = static_cast<__nv_fp4x2_storage_t>(q_storage >> 8U);
|
||||
|
||||
const float err0 = fabsf(v0) - fabsf(dq_lo.x) * scale_dequant;
|
||||
const float err1 = fabsf(v1) - fabsf(dq_lo.y) * scale_dequant;
|
||||
const float err2 = fabsf(v2) - fabsf(dq_hi.x) * scale_dequant;
|
||||
const float err3 = fabsf(v3) - fabsf(dq_hi.y) * scale_dequant;
|
||||
const __half2_raw hraw2_lo = __nv_cvt_fp4x2_to_halfraw2(q_lo, __NV_E2M1);
|
||||
const __half2_raw hraw2_hi = __nv_cvt_fp4x2_to_halfraw2(q_hi, __NV_E2M1);
|
||||
const __half2 h2_lo = static_cast<__half2>(hraw2_lo);
|
||||
const __half2 h2_hi = static_cast<__half2>(hraw2_hi);
|
||||
const float2 dq_lo = __half22float2(h2_lo);
|
||||
const float2 dq_hi = __half22float2(h2_hi);
|
||||
|
||||
err = fmaf(err0, err0, err);
|
||||
err = fmaf(err1, err1, err);
|
||||
err = fmaf(err2, err2, err);
|
||||
err = fmaf(err3, err3, err);
|
||||
const float err0 = fabsf(v0) - fabsf(dq_lo.x) * scale_dequant;
|
||||
const float err1 = fabsf(v1) - fabsf(dq_lo.y) * scale_dequant;
|
||||
const float err2 = fabsf(v2) - fabsf(dq_hi.x) * scale_dequant;
|
||||
const float err3 = fabsf(v3) - fabsf(dq_hi.y) * scale_dequant;
|
||||
|
||||
err[c] = fmaf(err0, err0, err[c]);
|
||||
err[c] = fmaf(err1, err1, err[c]);
|
||||
err[c] = fmaf(err2, err2, err[c]);
|
||||
err[c] = fmaf(err3, err3, err[c]);
|
||||
}
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
#endif // CUDART_VERSION >= 12080
|
||||
#endif // defined(BLACKWELL_MMA_AVAILABLE)
|
||||
@@ -156,6 +175,119 @@ __device__ __forceinline__ uint8_t compute_e8m0_scale(float amax) {
|
||||
return static_cast<uint8_t>(biased);
|
||||
}
|
||||
|
||||
#if defined(BLACKWELL_MMA_AVAILABLE)
|
||||
// Quantizes 16 values divided by col_scale to E2M1 with the UE4M3 scale of the lowest squared error of 5 candidates, returns the scale code.
|
||||
// q0 and q1 get the 8 bytes of block_nvfp4: byte i holds the values i and i + 8 in its low and high nibble.
|
||||
static __device__ __forceinline__ uint8_t quantize_nvfp4_subblock(
|
||||
const float (&vals)[QK_NVFP4_SUB], const float col_scale, uint32_t & q0, uint32_t & q1) {
|
||||
const float inv_col_scale = col_scale > 0.0f ? 1.0f / col_scale : 0.0f;
|
||||
q0 = 0;
|
||||
q1 = 0;
|
||||
|
||||
float amax_sub = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
|
||||
amax_sub = fmaxf(amax_sub, fabsf(vals[k] * inv_col_scale));
|
||||
}
|
||||
|
||||
static constexpr int test_offsets[5] = { 0, -1, 1, -2, 2 };
|
||||
const int first_fp8_code = (int) ggml_cuda_fp32_to_ue4m3(amax_sub / 6.0f);
|
||||
|
||||
uint8_t fp8_code = (uint8_t) first_fp8_code;
|
||||
float subblock_scale = ggml_cuda_ue4m3_to_fp32(fp8_code);
|
||||
#if CUDART_VERSION >= 12080
|
||||
// the errors of all candidates at once, then compared in order; codes out of range are skipped
|
||||
bool valid[5];
|
||||
float test_scale[5];
|
||||
float test_inv_scale[5];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
const int test_code = first_fp8_code + test_offsets[i];
|
||||
valid[i] = i == 0 || (test_code >= 0 && test_code <= 0x7e);
|
||||
test_scale[i] = ggml_cuda_ue4m3_to_fp32((uint8_t) (valid[i] ? test_code : first_fp8_code));
|
||||
test_inv_scale[i] = test_scale[i] > 0.0f ? 0.5f / test_scale[i] : 0.0f;
|
||||
}
|
||||
float err[5];
|
||||
nvfp4_native_scale_error(vals, inv_col_scale, test_inv_scale, test_scale, err);
|
||||
|
||||
float best_err = err[0];
|
||||
#pragma unroll
|
||||
for (int i = 1; i < 5; ++i) {
|
||||
if (valid[i] && err[i] < best_err) {
|
||||
best_err = err[i];
|
||||
fp8_code = (uint8_t) (first_fp8_code + test_offsets[i]);
|
||||
subblock_scale = test_scale[i];
|
||||
}
|
||||
}
|
||||
#else
|
||||
float inv_scale_err = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
|
||||
float best_err = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
|
||||
const float v = vals[k] * inv_col_scale;
|
||||
const uint8_t q = ggml_cuda_float_to_fp4_e2m1(v, inv_scale_err);
|
||||
const float err_diff = fabsf(v) - fabsf(kvalues_fp4[q & 0x7]) * subblock_scale;
|
||||
best_err = fmaf(err_diff, err_diff, best_err);
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 1; i < 5; ++i) {
|
||||
const int test_code = first_fp8_code + test_offsets[i];
|
||||
if (test_code < 0 || test_code > 0x7e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const float test_scale = ggml_cuda_ue4m3_to_fp32((uint8_t) test_code);
|
||||
const float test_inv_scale = test_scale > 0.0f ? 0.5f / test_scale : 0.0f;
|
||||
float cur_err = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
|
||||
const float v = vals[k] * inv_col_scale;
|
||||
const uint8_t q = ggml_cuda_float_to_fp4_e2m1(v, test_inv_scale);
|
||||
const float err_diff = fabsf(v) - fabsf(kvalues_fp4[q & 0x7]) * test_scale;
|
||||
cur_err = fmaf(err_diff, err_diff, cur_err);
|
||||
}
|
||||
|
||||
if (cur_err < best_err) {
|
||||
best_err = cur_err;
|
||||
fp8_code = (uint8_t) test_code;
|
||||
subblock_scale = test_scale;
|
||||
}
|
||||
}
|
||||
#endif // CUDART_VERSION >= 12080
|
||||
#if CUDART_VERSION >= 12080
|
||||
const float inv_scale = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
|
||||
const float s = inv_col_scale * inv_scale;
|
||||
|
||||
__nv_fp4x4_e2m1 q0_lo(make_float4(vals[0] * s, vals[8] * s, vals[1] * s, vals[9] * s));
|
||||
__nv_fp4x4_e2m1 q0_hi(make_float4(vals[2] * s, vals[10] * s, vals[3] * s, vals[11] * s));
|
||||
__nv_fp4x4_e2m1 q1_lo(make_float4(vals[4] * s, vals[12] * s, vals[5] * s, vals[13] * s));
|
||||
__nv_fp4x4_e2m1 q1_hi(make_float4(vals[6] * s, vals[14] * s, vals[7] * s, vals[15] * s));
|
||||
|
||||
const char2 q0_lo_c = *reinterpret_cast<char2 *>(&q0_lo);
|
||||
const char2 q0_hi_c = *reinterpret_cast<char2 *>(&q0_hi);
|
||||
const char2 q1_lo_c = *reinterpret_cast<char2 *>(&q1_lo);
|
||||
const char2 q1_hi_c = *reinterpret_cast<char2 *>(&q1_hi);
|
||||
|
||||
q0 = uint32_t(uint8_t(q0_lo_c.x)) | (uint32_t(uint8_t(q0_lo_c.y)) << 8) |
|
||||
(uint32_t(uint8_t(q0_hi_c.x)) << 16) | (uint32_t(uint8_t(q0_hi_c.y)) << 24);
|
||||
q1 = uint32_t(uint8_t(q1_lo_c.x)) | (uint32_t(uint8_t(q1_lo_c.y)) << 8) |
|
||||
(uint32_t(uint8_t(q1_hi_c.x)) << 16) | (uint32_t(uint8_t(q1_hi_c.y)) << 24);
|
||||
#else
|
||||
const float inv_scale = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB / 4; ++k) {
|
||||
q0 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 0] * inv_col_scale, inv_scale)) << (8 * k);
|
||||
q0 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 8] * inv_col_scale, inv_scale)) << (8 * k + 4);
|
||||
q1 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 4] * inv_col_scale, inv_scale)) << (8 * k);
|
||||
q1 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 12] * inv_col_scale, inv_scale)) << (8 * k + 4);
|
||||
}
|
||||
#endif // CUDART_VERSION >= 12080
|
||||
|
||||
return fp8_code;
|
||||
}
|
||||
#endif // defined(BLACKWELL_MMA_AVAILABLE)
|
||||
|
||||
// scatter: grid over tokens, quantize once, write to all the token's compact rows
|
||||
template <typename src_t, bool scatter, bool use_aligned_float8>
|
||||
static __global__ void quantize_mmq_nvfp4(
|
||||
@@ -232,7 +364,6 @@ static __global__ void quantize_mmq_nvfp4(
|
||||
const int sub = (i0_base % QK_FP4_MMQ) / QK_NVFP4_SUB;
|
||||
|
||||
const float row_scale = warp_amax[0];
|
||||
const float inv_col_scale = row_scale > 0.0f ? 1.0f / row_scale : 0.0f;
|
||||
|
||||
float vals[QK_NVFP4_SUB];
|
||||
if constexpr (use_aligned_float8) {
|
||||
@@ -251,90 +382,9 @@ static __global__ void quantize_mmq_nvfp4(
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t q0 = 0;
|
||||
uint32_t q1 = 0;
|
||||
|
||||
float amax_sub = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
|
||||
amax_sub = fmaxf(amax_sub, fabsf(vals[k] * inv_col_scale));
|
||||
}
|
||||
|
||||
static constexpr int test_offsets[5] = { 0, -1, 1, -2, 2 };
|
||||
const int first_fp8_code = (int) ggml_cuda_fp32_to_ue4m3(amax_sub / 6.0f);
|
||||
|
||||
uint8_t fp8_code = (uint8_t) first_fp8_code;
|
||||
float subblock_scale = ggml_cuda_ue4m3_to_fp32(fp8_code);
|
||||
float inv_scale_err = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
|
||||
#if CUDART_VERSION >= 12080
|
||||
float best_err = nvfp4_native_scale_error(vals, inv_col_scale, inv_scale_err, subblock_scale);
|
||||
#else
|
||||
float best_err = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
|
||||
const float v = vals[k] * inv_col_scale;
|
||||
const uint8_t q = ggml_cuda_float_to_fp4_e2m1(v, inv_scale_err);
|
||||
const float err_diff = fabsf(v) - fabsf(kvalues_fp4[q & 0x7]) * subblock_scale;
|
||||
best_err = fmaf(err_diff, err_diff, best_err);
|
||||
}
|
||||
#endif // CUDART_VERSION >= 12080
|
||||
|
||||
#pragma unroll
|
||||
for (int i = 1; i < 5; ++i) {
|
||||
const int test_code = first_fp8_code + test_offsets[i];
|
||||
if (test_code < 0 || test_code > 0x7e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const float test_scale = ggml_cuda_ue4m3_to_fp32((uint8_t) test_code);
|
||||
const float test_inv_scale = test_scale > 0.0f ? 0.5f / test_scale : 0.0f;
|
||||
#if CUDART_VERSION >= 12080
|
||||
const float cur_err = nvfp4_native_scale_error(vals, inv_col_scale, test_inv_scale, test_scale);
|
||||
#else
|
||||
float cur_err = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
|
||||
const float v = vals[k] * inv_col_scale;
|
||||
const uint8_t q = ggml_cuda_float_to_fp4_e2m1(v, test_inv_scale);
|
||||
const float err_diff = fabsf(v) - fabsf(kvalues_fp4[q & 0x7]) * test_scale;
|
||||
cur_err = fmaf(err_diff, err_diff, cur_err);
|
||||
}
|
||||
#endif // CUDART_VERSION >= 12080
|
||||
|
||||
if (cur_err < best_err) {
|
||||
best_err = cur_err;
|
||||
fp8_code = (uint8_t) test_code;
|
||||
subblock_scale = test_scale;
|
||||
}
|
||||
}
|
||||
#if CUDART_VERSION >= 12080
|
||||
const float inv_scale = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
|
||||
const float s = inv_col_scale * inv_scale;
|
||||
|
||||
__nv_fp4x4_e2m1 q0_lo(make_float4(vals[0] * s, vals[8] * s, vals[1] * s, vals[9] * s));
|
||||
__nv_fp4x4_e2m1 q0_hi(make_float4(vals[2] * s, vals[10] * s, vals[3] * s, vals[11] * s));
|
||||
__nv_fp4x4_e2m1 q1_lo(make_float4(vals[4] * s, vals[12] * s, vals[5] * s, vals[13] * s));
|
||||
__nv_fp4x4_e2m1 q1_hi(make_float4(vals[6] * s, vals[14] * s, vals[7] * s, vals[15] * s));
|
||||
|
||||
const char2 q0_lo_c = *reinterpret_cast<char2 *>(&q0_lo);
|
||||
const char2 q0_hi_c = *reinterpret_cast<char2 *>(&q0_hi);
|
||||
const char2 q1_lo_c = *reinterpret_cast<char2 *>(&q1_lo);
|
||||
const char2 q1_hi_c = *reinterpret_cast<char2 *>(&q1_hi);
|
||||
|
||||
q0 = uint32_t(uint8_t(q0_lo_c.x)) | (uint32_t(uint8_t(q0_lo_c.y)) << 8) |
|
||||
(uint32_t(uint8_t(q0_hi_c.x)) << 16) | (uint32_t(uint8_t(q0_hi_c.y)) << 24);
|
||||
q1 = uint32_t(uint8_t(q1_lo_c.x)) | (uint32_t(uint8_t(q1_lo_c.y)) << 8) |
|
||||
(uint32_t(uint8_t(q1_hi_c.x)) << 16) | (uint32_t(uint8_t(q1_hi_c.y)) << 24);
|
||||
#else
|
||||
const float inv_scale = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB / 4; ++k) {
|
||||
q0 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 0] * inv_col_scale, inv_scale)) << (8 * k);
|
||||
q0 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 8] * inv_col_scale, inv_scale)) << (8 * k + 4);
|
||||
q1 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 4] * inv_col_scale, inv_scale)) << (8 * k);
|
||||
q1 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 12] * inv_col_scale, inv_scale)) << (8 * k + 4);
|
||||
}
|
||||
#endif // CUDART_VERSION >= 12080
|
||||
uint32_t q0;
|
||||
uint32_t q1;
|
||||
const uint8_t fp8_code = quantize_nvfp4_subblock(vals, row_scale, q0, q1);
|
||||
|
||||
if constexpr (scatter) {
|
||||
#pragma unroll
|
||||
@@ -711,7 +761,8 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i
|
||||
}
|
||||
|
||||
// Each thread quantizes 4 values of one column, see quantize.cuh for the layouts.
|
||||
template <typename src_t, mmq_q8_1_ds_layout ds_layout, bool wmma>
|
||||
// nvfp4_order: the 4 values of a thread are 2m, 2m + 8, 2m + 1, 2m + 9 of 16 values, the values of 2 bytes of block_nvfp4.
|
||||
template <typename src_t, mmq_q8_1_ds_layout ds_layout, bool wmma, bool nvfp4_order>
|
||||
static __global__ void quantize_mmq_few_q8_1(
|
||||
const src_t * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int ne1, const int ne2) {
|
||||
@@ -727,7 +778,19 @@ static __global__ void quantize_mmq_few_q8_1(
|
||||
|
||||
const int64_t i2 = blockIdx.z % ne2;
|
||||
const int64_t i3 = blockIdx.z / ne2;
|
||||
const float4 xi = (int) blockIdx.x < ne1 ? quantize_load4(x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0, 0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
static_assert(!(wmma && nvfp4_order), "the WMMA layout has no nvfp4 order");
|
||||
float4 xi = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
if ((int) blockIdx.x < ne1) {
|
||||
const src_t * xc = x + i3*s03 + i2*s02 + blockIdx.x*s01;
|
||||
if constexpr (nvfp4_order) {
|
||||
const int64_t i16 = i0 - i0 % 16 + 2*((i0 % 16)/4);
|
||||
const float2 lo = quantize_load2(xc + i16);
|
||||
const float2 hi = quantize_load2(xc + i16 + 8);
|
||||
xi = make_float4(lo.x, hi.x, lo.y, hi.y);
|
||||
} else {
|
||||
xi = quantize_load4(xc + i0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (wmma) {
|
||||
const int m = blockIdx.x % MMQ_FEW_WMMA_NCOLS; // column in group
|
||||
@@ -833,21 +896,29 @@ static __global__ void quantize_mmq_few_id_q8_1(
|
||||
|
||||
template <bool wmma, typename src_t>
|
||||
static void quantize_mmq_few_q8_1_launch(
|
||||
const src_t * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const src_t * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const bool nvfp4_order, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne00 % QK_K == 0);
|
||||
GGML_ASSERT(!nvfp4_order || (ds_layout == MMQ_Q8_1_DS_LAYOUT_D4 && !wmma));
|
||||
|
||||
const int64_t block_num_y = (ne00 + 4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ - 1) / (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ);
|
||||
const dim3 num_blocks(GGML_PAD(ne1, wmma ? MMQ_FEW_WMMA_NCOLS : MMQ_FEW_NCOLS), block_num_y, ne2*ne3);
|
||||
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
|
||||
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
|
||||
if constexpr (!wmma) {
|
||||
if (nvfp4_order) {
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, false, true>, launch_params,
|
||||
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
|
||||
return;
|
||||
}
|
||||
}
|
||||
switch (ds_layout) {
|
||||
case MMQ_Q8_1_DS_LAYOUT_D4:
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, wmma>, launch_params,
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, wmma, false>, launch_params,
|
||||
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
|
||||
break;
|
||||
case MMQ_Q8_1_DS_LAYOUT_DS4:
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, wmma>, launch_params,
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, wmma, false>, launch_params,
|
||||
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
|
||||
break;
|
||||
default:
|
||||
@@ -855,11 +926,97 @@ static void quantize_mmq_few_q8_1_launch(
|
||||
}
|
||||
}
|
||||
|
||||
// Each thread quantizes one sub-block of 16 values like quantize_mmq_nvfp4, columns beyond ne1 are zero.
|
||||
// A CUDA block takes a chunk of the sub-blocks of one column, so each CUDA block first reads the whole column for the column scale.
|
||||
template <typename src_t>
|
||||
static __global__ void quantize_mmq_few_nvfp4(
|
||||
const src_t * x_ptr, void * vy_ptr, float * y_scale_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int ne1, const int ne2) {
|
||||
#if defined(BLACKWELL_MMA_AVAILABLE)
|
||||
ggml_cuda_pdl_lc();
|
||||
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
int * GGML_CUDA_RESTRICT vy = (int *) vy_ptr;
|
||||
float * GGML_CUDA_RESTRICT y_scale = y_scale_ptr;
|
||||
|
||||
const int col = blockIdx.x;
|
||||
const int64_t i2 = blockIdx.z % ne2;
|
||||
const int64_t i3 = blockIdx.z / ne2;
|
||||
const src_t * x_row = x + i3*s03 + i2*s02 + int64_t(col)*s01;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
|
||||
float amax = 0.0f;
|
||||
if (col < ne1) {
|
||||
for (int64_t i0 = 4*threadIdx.x; i0 < ne00; i0 += 4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ) {
|
||||
const float4 v = quantize_load4(x_row + i0, 0);
|
||||
amax = fmaxf(amax, fmaxf(fmaxf(fabsf(v.x), fabsf(v.y)), fmaxf(fabsf(v.z), fabsf(v.w))));
|
||||
}
|
||||
}
|
||||
__shared__ float amax_warp[CUDA_QUANTIZE_BLOCK_SIZE_MMQ/WARP_SIZE];
|
||||
amax = block_reduce<block_reduce_method::MAX, CUDA_QUANTIZE_BLOCK_SIZE_MMQ>(amax, amax_warp);
|
||||
|
||||
const float col_scale = amax / (6.0f * 448.0f);
|
||||
if (blockIdx.y == 0 && threadIdx.x == 0) {
|
||||
y_scale[blockIdx.z*gridDim.x + col] = col_scale;
|
||||
}
|
||||
|
||||
const int64_t isb = int64_t(blockIdx.y)*CUDA_QUANTIZE_BLOCK_SIZE_MMQ + threadIdx.x;
|
||||
if (isb >= ne00/QK_NVFP4_SUB) {
|
||||
return;
|
||||
}
|
||||
|
||||
float vals[QK_NVFP4_SUB] = {0.0f};
|
||||
if (col < ne1) {
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; k += 4) {
|
||||
const float4 v = quantize_load4(x_row + isb*QK_NVFP4_SUB + k, 0);
|
||||
vals[k + 0] = v.x;
|
||||
vals[k + 1] = v.y;
|
||||
vals[k + 2] = v.z;
|
||||
vals[k + 3] = v.w;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t q[2];
|
||||
const uint8_t code = quantize_nvfp4_subblock(vals, col_scale, q[0], q[1]);
|
||||
|
||||
const int64_t kb = isb / (QK_NVFP4/QK_NVFP4_SUB); // block of 64 values
|
||||
const int sub = isb % (QK_NVFP4/QK_NVFP4_SUB);
|
||||
const int ib = kb % (QK_K/QK_NVFP4); // block in the unit of 256 values
|
||||
const int g = col % MMQ_FEW_NCOLS;
|
||||
int * yg = vy + 4*(((blockIdx.z*(ne00/QK_K) + kb/(QK_K/QK_NVFP4))*(gridDim.x/MMQ_FEW_NCOLS) + col/MMQ_FEW_NCOLS)*MMQ_FEW_FP4_INT4);
|
||||
#pragma unroll
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const int i = 2*sub + h; // int of the block
|
||||
yg[4*((ib/2)*WARP_SIZE + 4*g + i % 4) + 2*(ib % 2) + i/4] = q[h];
|
||||
}
|
||||
((uint8_t *) (yg + 4*(2*WARP_SIZE + g) + ib))[sub] = code;
|
||||
#else
|
||||
GGML_UNUSED_VARS(x_ptr, vy_ptr, y_scale_ptr, ne00, s01, s02, s03, ne1, ne2);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // defined(BLACKWELL_MMA_AVAILABLE)
|
||||
}
|
||||
|
||||
void quantize_mmq_few_nvfp4_cuda(
|
||||
const void * x, const ggml_type type_src1, void * vy, float * y_scale, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne00 % QK_K == 0);
|
||||
|
||||
const int64_t nsub = ne00 / QK_NVFP4_SUB;
|
||||
const dim3 num_blocks(GGML_PAD(ne1, MMQ_FEW_NCOLS), (nsub + CUDA_QUANTIZE_BLOCK_SIZE_MMQ - 1) / CUDA_QUANTIZE_BLOCK_SIZE_MMQ, ne2*ne3);
|
||||
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
|
||||
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
using src_t = std::remove_cv_t<std::remove_pointer_t<decltype(x_t)>>;
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_nvfp4<src_t>, launch_params, x_t, vy, y_scale, ne00, s01, s02, s03, (int) ne1, (int) ne2);
|
||||
});
|
||||
}
|
||||
|
||||
void quantize_mmq_few_q8_1_cuda(
|
||||
const void * x, const ggml_type type_src1, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const void * x, const ggml_type type_src1, void * vy, const mmq_q8_1_ds_layout ds_layout, const bool nvfp4_order, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_mmq_few_q8_1_launch<false>(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
|
||||
quantize_mmq_few_q8_1_launch<false>(x_t, vy, ds_layout, nvfp4_order, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -867,7 +1024,7 @@ void quantize_mmq_few_wmma_q8_1_cuda(
|
||||
const void * x, const ggml_type type_src1, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_mmq_few_q8_1_launch<true>(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
|
||||
quantize_mmq_few_q8_1_launch<true>(x_t, vy, ds_layout, /*nvfp4_order =*/ false, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -30,8 +30,21 @@ void quantize_mmq_q8_1_cuda(
|
||||
static constexpr int MMQ_FEW_NCOLS = 8; // src1 columns per column group
|
||||
static constexpr int MMQ_FEW_Q8_1_INT4 = 4*WARP_SIZE + 4*4; // int4 per 256 values and column group
|
||||
|
||||
// nvfp4_order: the value order of block_nvfp4 within 16 values, see quantize_mmq_few_q8_1.
|
||||
void quantize_mmq_few_q8_1_cuda(
|
||||
const void * x, ggml_type type_src1, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
|
||||
const void * x, ggml_type type_src1, void * vy, mmq_q8_1_ds_layout ds_layout, bool nvfp4_order, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
|
||||
int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
|
||||
|
||||
// src1 of the few-row MMQ for NVFP4 src0 with 4-bit src1 (Blackwell), quantized like quantize_mmq_nvfp4: a float scale per column, E2M1 values with a UE4M3 scale per 16 values.
|
||||
// A 64 value block has the block_nvfp4 layout: 8 ints of packed values and an int of 4 scales. The values of int i are k = 8i .. 8i + 7 of the m16n8k64 MMA.
|
||||
// Per channel, 256 values and column group:
|
||||
// qs: int4[2][32], [h][lane] holds the B fragments of the blocks 2h and 2h+1 of lane (g, t): ints t and t + 4 of column g.
|
||||
// sc: int4[8], [g] holds the scales of the 4 blocks of column g.
|
||||
// The column scales are a float array per channel, ne1 padded to a multiple of MMQ_FEW_NCOLS.
|
||||
static constexpr int MMQ_FEW_FP4_INT4 = 2*WARP_SIZE + MMQ_FEW_NCOLS; // int4 per 256 values and column group
|
||||
|
||||
void quantize_mmq_few_nvfp4_cuda(
|
||||
const void * x, ggml_type type_src1, void * vy, float * y_scale, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
|
||||
int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
|
||||
|
||||
// MUL_MAT_ID: a pair is an expert and one column group of up to MMQ_FEW_NCOLS of its (token, slot) entries. The src1 of pair p is channel p above, its columns past the entries are not written.
|
||||
|
||||
+107
-30
@@ -12,6 +12,27 @@
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
|
||||
std::vector<llama_ubatch_span> llama_ubatch_get_spans(const llama_ubatch & ubatch) {
|
||||
std::vector<llama_ubatch_span> res;
|
||||
if (ubatch.span == nullptr) {
|
||||
return res;
|
||||
}
|
||||
|
||||
const int32_t n_tokens = ubatch.n_tokens;
|
||||
for (int32_t i = 0; i < n_tokens;) {
|
||||
int32_t end = i + 1;
|
||||
while (end < n_tokens && ubatch.span[end] == ubatch.span[i]) {
|
||||
end++;
|
||||
}
|
||||
if (ubatch.span[i] != 0) {
|
||||
res.push_back({ ubatch.span[i], ubatch.span_type[i], i, end });
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
llama_batch_allocr::llama_batch_allocr(uint32_t n_pos_per_embd, bool allow_mixed) : n_pos_per_embd(n_pos_per_embd), allow_mixed(allow_mixed) {
|
||||
const char * LLAMA_BATCH_DEBUG = getenv("LLAMA_BATCH_DEBUG");
|
||||
debug = LLAMA_BATCH_DEBUG ? atoi(LLAMA_BATCH_DEBUG) : 0;
|
||||
@@ -255,16 +276,44 @@ bool llama_batch_allocr::init(
|
||||
|
||||
// kept empty if no entry has one
|
||||
for (int32_t i = 0; i < n_tok; ++i) {
|
||||
if (batch_inp.tokens[i].decision_order != 0) {
|
||||
decision_order.resize(n_tok, 0);
|
||||
decision_order[i] = batch_inp.tokens[i].decision_order;
|
||||
const auto & tok = batch_inp.tokens[i];
|
||||
if (tok.span != 0) {
|
||||
span.resize(n_tok, 0);
|
||||
span_type.resize(n_tok, LLAMA_POOL_SPAN_TYPE_DEFAULT);
|
||||
span[i] = tok.span;
|
||||
const auto it = batch_inp.span_types.find(tok.span);
|
||||
if (it != batch_inp.span_types.end()) {
|
||||
span_type[i] = it->second;
|
||||
}
|
||||
}
|
||||
if (batch_inp.tokens[i].decision_group != 0) {
|
||||
decision_group.resize(n_tok, 0);
|
||||
decision_group[i] = batch_inp.tokens[i].decision_group;
|
||||
if (tok.attn_scope != 0) {
|
||||
attn_scope.resize(n_tok, 0);
|
||||
attn_scope[i] = tok.attn_scope;
|
||||
}
|
||||
}
|
||||
|
||||
// a span is one run of entries in one sequence
|
||||
if (!span.empty()) {
|
||||
std::unordered_set<int32_t> seen;
|
||||
for (int32_t i = 0; i < n_tok; ++i) {
|
||||
if (span[i] == 0) {
|
||||
continue;
|
||||
}
|
||||
if (i > 0 && span[i - 1] == span[i]) {
|
||||
if (batch_inp.tokens[i].seq_ids != batch_inp.tokens[i - 1].seq_ids) {
|
||||
LLAMA_LOG_ERROR("%s: the entries of span %d are not in the same sequence\n", __func__, span[i]);
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!seen.insert(span[i]).second) {
|
||||
LLAMA_LOG_ERROR("%s: the entries of span %d are not next to each other\n", __func__, span[i]);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
n_spans = seen.size();
|
||||
}
|
||||
|
||||
//
|
||||
// set up the internal llama_batch to point to our owned arrays
|
||||
//
|
||||
@@ -356,8 +405,9 @@ bool llama_batch_allocr::init(
|
||||
/*.seq_idx =*/ this->seq_idx.data(),
|
||||
/*.output =*/ batch.logits,
|
||||
/*.type =*/ is_embd_vec.empty() ? nullptr : is_embd_vec.data(),
|
||||
/*.decision_order =*/ decision_order.empty() ? nullptr : decision_order.data(),
|
||||
/*.decision_group =*/ decision_group.empty() ? nullptr : decision_group.data(),
|
||||
/*.span =*/ span.empty() ? nullptr : span.data(),
|
||||
/*.span_type =*/ span_type.empty() ? nullptr : span_type.data(),
|
||||
/*.attn_scope =*/ attn_scope.empty() ? nullptr : attn_scope.data(),
|
||||
/*.data =*/ {},
|
||||
};
|
||||
|
||||
@@ -583,8 +633,9 @@ llama_ubatch llama_batch_allocr::ubatch_reserve(uint32_t n_seq_tokens, uint32_t
|
||||
/*.seq_idx =*/ udata->seq_idx.data(),
|
||||
/*.output =*/ udata->output.data(),
|
||||
/*.type =*/ nullptr,
|
||||
/*.decision_order =*/ nullptr,
|
||||
/*.decision_group =*/ nullptr,
|
||||
/*.span =*/ nullptr,
|
||||
/*.span_type =*/ nullptr,
|
||||
/*.attn_scope =*/ nullptr,
|
||||
/*.data =*/ std::move(udata),
|
||||
};
|
||||
|
||||
@@ -607,6 +658,14 @@ uint32_t llama_batch_allocr::get_n_used() const {
|
||||
return n_used;
|
||||
}
|
||||
|
||||
bool llama_batch_allocr::has_spans() const {
|
||||
return !span.empty();
|
||||
}
|
||||
|
||||
uint32_t llama_batch_allocr::get_n_spans() const {
|
||||
return n_spans;
|
||||
}
|
||||
|
||||
std::vector<int32_t> & llama_batch_allocr::get_out_ids() {
|
||||
return out_ids;
|
||||
}
|
||||
@@ -892,8 +951,10 @@ void llama_batch_allocr::clear() {
|
||||
seq_id .clear();
|
||||
seq_id_unq .clear();
|
||||
output .clear();
|
||||
decision_order.clear();
|
||||
decision_group.clear();
|
||||
span .clear();
|
||||
n_spans = 0;
|
||||
span_type .clear();
|
||||
attn_scope .clear();
|
||||
|
||||
for (auto & cur : seq_pos) {
|
||||
cur.clear();
|
||||
@@ -949,8 +1010,9 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector<int32_t> & idxs, u
|
||||
udata->seq_idx .resize(LLAMA_MAX_SEQ, -1);
|
||||
udata->output .resize(n_tokens);
|
||||
udata->type .resize(mixed ? n_tokens : 0);
|
||||
udata->decision_order.resize(decision_order.empty() ? 0 : n_tokens);
|
||||
udata->decision_group.resize(decision_group.empty() ? 0 : n_tokens);
|
||||
udata->span .resize(span.empty() ? 0 : n_tokens);
|
||||
udata->span_type .resize(span.empty() ? 0 : n_tokens);
|
||||
udata->attn_scope.resize(attn_scope.empty() ? 0 : n_tokens);
|
||||
|
||||
udata->batch_idxs = idxs;
|
||||
udata->seq_id_data.reserve(n_tokens);
|
||||
@@ -989,11 +1051,12 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector<int32_t> & idxs, u
|
||||
udata->n_seq_id[i] = batch.n_seq_id[idxs[i]];
|
||||
udata->output[i] = batch.logits[idxs[i]];
|
||||
|
||||
if (!decision_order.empty()) {
|
||||
udata->decision_order[i] = decision_order[idxs[i]];
|
||||
if (!span.empty()) {
|
||||
udata->span[i] = span[idxs[i]];
|
||||
udata->span_type[i] = span_type[idxs[i]];
|
||||
}
|
||||
if (!decision_group.empty()) {
|
||||
udata->decision_group[i] = decision_group[idxs[i]];
|
||||
if (!attn_scope.empty()) {
|
||||
udata->attn_scope[i] = attn_scope[idxs[i]];
|
||||
}
|
||||
|
||||
for (int s = 0; s < udata->n_seq_id[i]; ++s) {
|
||||
@@ -1040,8 +1103,9 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector<int32_t> & idxs, u
|
||||
/*.seq_idx =*/ udata->seq_idx.data(),
|
||||
/*.output =*/ udata->output.data(),
|
||||
/*.type =*/ mixed ? udata->type.data() : nullptr,
|
||||
/*.decision_order =*/ udata->decision_order.empty() ? nullptr : udata->decision_order.data(),
|
||||
/*.decision_group =*/ udata->decision_group.empty() ? nullptr : udata->decision_group.data(),
|
||||
/*.span =*/ udata->span.empty() ? nullptr : udata->span.data(),
|
||||
/*.span_type =*/ udata->span_type.empty() ? nullptr : udata->span_type.data(),
|
||||
/*.attn_scope =*/ udata->attn_scope.empty() ? nullptr : udata->attn_scope.data(),
|
||||
/*.data =*/ std::move(udata),
|
||||
};
|
||||
|
||||
@@ -1261,6 +1325,7 @@ void llama_batch_ext::clear() {
|
||||
tokens.clear();
|
||||
embd .clear();
|
||||
state .clear();
|
||||
span_types.clear();
|
||||
n_embd = 0;
|
||||
}
|
||||
|
||||
@@ -1438,19 +1503,27 @@ bool llama_batch_ext::set_output(int32_t idx, bool output_last) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool llama_batch_ext::set_decision_order(int32_t idx, int32_t order) {
|
||||
if (idx < 0 || idx >= (int32_t) tokens.size()) {
|
||||
bool llama_batch_ext::set_span(int32_t idx, int32_t span) {
|
||||
if (idx < 0 || idx >= (int32_t) tokens.size() || span < 0) {
|
||||
return false;
|
||||
}
|
||||
tokens[idx].decision_order = order;
|
||||
tokens[idx].span = span;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool llama_batch_ext::set_decision_group(int32_t idx, int32_t group) {
|
||||
if (idx < 0 || idx >= (int32_t) tokens.size() || group < 0) {
|
||||
bool llama_batch_ext::set_span_type(int32_t span, int32_t type) {
|
||||
if (span <= 0 || type < LLAMA_POOL_SPAN_TYPE_DEFAULT || type > LLAMA_POOL_SPAN_TYPE_DECISION_OPTION) {
|
||||
return false;
|
||||
}
|
||||
tokens[idx].decision_group = group;
|
||||
span_types[span] = type;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool llama_batch_ext::set_attn_scope(int32_t idx, int32_t scope) {
|
||||
if (idx < 0 || idx >= (int32_t) tokens.size() || scope < 0) {
|
||||
return false;
|
||||
}
|
||||
tokens[idx].attn_scope = scope;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1533,12 +1606,16 @@ bool llama_batch_ext_set_output_logits(llama_batch_ext * batch, int32_t idx, boo
|
||||
return batch->set_output(idx, value);
|
||||
}
|
||||
|
||||
bool llama_batch_ext_set_decision_order(llama_batch_ext * batch, int32_t idx, llama_decision_order order) {
|
||||
return batch->set_decision_order(idx, order);
|
||||
bool llama_batch_ext_set_pool_span(llama_batch_ext * batch, int32_t idx, int32_t span) {
|
||||
return batch->set_span(idx, span);
|
||||
}
|
||||
|
||||
bool llama_batch_ext_set_decision_group(llama_batch_ext * batch, int32_t idx, int32_t group) {
|
||||
return batch->set_decision_group(idx, group);
|
||||
bool llama_batch_ext_set_pool_span_type(llama_batch_ext * batch, int32_t span, llama_pool_span_type type) {
|
||||
return batch->set_span_type(span, type);
|
||||
}
|
||||
|
||||
bool llama_batch_ext_set_attn_scope(llama_batch_ext * batch, int32_t idx, int32_t scope) {
|
||||
return batch->set_attn_scope(idx, scope);
|
||||
}
|
||||
|
||||
// llama_batch_compat
|
||||
|
||||
+30
-10
@@ -60,8 +60,9 @@ struct llama_ubatch {
|
||||
int32_t * seq_idx; // [LLAMA_MAX_SEQ] | - | seq_idx
|
||||
int8_t * output; // [n_tokens] | i | -
|
||||
int8_t * type; // [n_tokens] | i | - (mixed ubatch only, 0 - token, 1 - embd)
|
||||
int32_t * decision_order; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_decision_order()
|
||||
int32_t * decision_group; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_decision_group()
|
||||
int32_t * span; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_pool_span()
|
||||
int32_t * span_type; // [n_tokens], NULL if no entry has a span
|
||||
int32_t * attn_scope; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_attn_scope()
|
||||
|
||||
struct data_t {
|
||||
std::vector<llama_token> token;
|
||||
@@ -77,8 +78,9 @@ struct llama_ubatch {
|
||||
std::vector<int8_t> output;
|
||||
std::vector<int8_t> type;
|
||||
std::vector<int32_t> batch_idxs; // original batch index for each token
|
||||
std::vector<int32_t> decision_order;
|
||||
std::vector<int32_t> decision_group;
|
||||
std::vector<int32_t> span;
|
||||
std::vector<int32_t> span_type;
|
||||
std::vector<int32_t> attn_scope;
|
||||
|
||||
std::vector<llama_seq_id> seq_id_data;
|
||||
};
|
||||
@@ -87,6 +89,17 @@ struct llama_ubatch {
|
||||
std::shared_ptr<data_t> data;
|
||||
};
|
||||
|
||||
// a span of a ubatch, see llama_batch_ext_set_pool_span()
|
||||
struct llama_ubatch_span {
|
||||
int32_t id;
|
||||
int32_t type; // see llama_pool_span_type
|
||||
int32_t start; // [start, end) in ubatch token indices
|
||||
int32_t end;
|
||||
};
|
||||
|
||||
// the spans of the ubatch, in the order of their first token
|
||||
std::vector<llama_ubatch_span> llama_ubatch_get_spans(const llama_ubatch & ubatch);
|
||||
|
||||
// crash if a mixed ubatch reaches code that expects only tokens or only embd
|
||||
#define ASSERT_EMBD_OR_TOKEN(ubatch) GGML_ASSERT(!(ubatch).is_mixed() && "mixed token/embd ubatch is not supported here")
|
||||
|
||||
@@ -122,14 +135,15 @@ struct llama_batch_ext {
|
||||
int32_t embd_row = -1; // row of ctx_other's layer input device buffer used as embd, -1 if none
|
||||
int32_t state_row = -1; // row of ctx_state_src's h_nextn device buffer used as state, -1 if none
|
||||
bool output = false; // TODO: have dedicated output flags
|
||||
int32_t decision_order = 0; // see llama_batch_ext_set_decision_order()
|
||||
int32_t decision_group = 0; // see llama_batch_ext_set_decision_group()
|
||||
int32_t span = 0; // see llama_batch_ext_set_pool_span()
|
||||
int32_t attn_scope = 0; // see llama_batch_ext_set_attn_scope()
|
||||
std::unordered_set<llama_seq_id> seq_ids;
|
||||
std::array<llama_pos, GGML_MROPE_SECTIONS> pos = {0, 0, 0, 0};
|
||||
};
|
||||
std::vector<token> tokens;
|
||||
std::vector<float> embd;
|
||||
std::vector<float> state;
|
||||
std::unordered_map<int32_t, int32_t> span_types; // span id -> llama_pool_span_type, default if missing
|
||||
|
||||
llama_batch_ext(llama_context * ctx);
|
||||
|
||||
@@ -157,8 +171,9 @@ struct llama_batch_ext {
|
||||
bool set_token_state_row(int32_t idx, int32_t row);
|
||||
bool set_token_pos(int32_t idx, const llama_pos * pos_in);
|
||||
bool set_output(int32_t idx, bool output_last);
|
||||
bool set_decision_order(int32_t idx, int32_t order);
|
||||
bool set_decision_group(int32_t idx, int32_t group);
|
||||
bool set_span(int32_t idx, int32_t span);
|
||||
bool set_span_type(int32_t span, int32_t type);
|
||||
bool set_attn_scope(int32_t idx, int32_t scope);
|
||||
};
|
||||
|
||||
// a helper for sanitizing, fulfilling and splitting a batch
|
||||
@@ -178,6 +193,9 @@ public:
|
||||
uint32_t get_n_outputs() const;
|
||||
uint32_t get_n_used() const;
|
||||
|
||||
bool has_spans() const;
|
||||
uint32_t get_n_spans() const;
|
||||
|
||||
// the array of output indices in the order they were encountered during the ubatch splitting
|
||||
std::vector<int32_t> & get_out_ids();
|
||||
|
||||
@@ -244,8 +262,10 @@ private:
|
||||
std::vector<llama_seq_id> seq_id_unq;
|
||||
std::vector<int32_t> seq_idx;
|
||||
std::vector<int8_t> output;
|
||||
std::vector<int32_t> decision_order; // empty if no entry has one
|
||||
std::vector<int32_t> decision_group; // empty if no entry has one
|
||||
std::vector<int32_t> span; // empty if no entry has one
|
||||
uint32_t n_spans = 0;
|
||||
std::vector<int32_t> span_type; // empty if no entry has a span
|
||||
std::vector<int32_t> attn_scope; // empty if no entry has one
|
||||
|
||||
using pos_set_t = std::set<llama_pos>;
|
||||
using seq_cpl_t = std::vector<bool>;
|
||||
|
||||
+61
-4
@@ -1168,6 +1168,30 @@ float * llama_context::get_embeddings_seq(llama_seq_id seq_id) {
|
||||
return it->second.data();
|
||||
}
|
||||
|
||||
float * llama_context::get_embeddings_span(int32_t span) {
|
||||
auto it = embd_span.find(span);
|
||||
if (it == embd_span.end()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return it->second.data();
|
||||
}
|
||||
|
||||
void llama_context::output_embd_spans(const llama_ubatch & ubatch, ggml_tensor * t_embd_span) {
|
||||
ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd_span);
|
||||
GGML_ASSERT(backend_embd != nullptr);
|
||||
|
||||
const auto spans = llama_ubatch_get_spans(ubatch);
|
||||
GGML_ASSERT((int64_t) spans.size() <= t_embd_span->ne[1]);
|
||||
|
||||
const size_t n_row = t_embd_span->ne[0];
|
||||
for (size_t s = 0; s < spans.size(); ++s) {
|
||||
auto & out = embd_span[spans[s].id];
|
||||
out.resize(n_row);
|
||||
ggml_backend_tensor_get_async(backend_embd, t_embd_span, out.data(), s*n_row*sizeof(float), n_row*sizeof(float));
|
||||
}
|
||||
}
|
||||
|
||||
float * llama_context::get_embeddings_nextn() {
|
||||
output_reorder();
|
||||
|
||||
@@ -1892,6 +1916,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (llm_graph_pools_spans(cparams) && balloc->get_n_spans() > LLAMA_MAX_POOL_SPANS) {
|
||||
LLAMA_LOG_ERROR("%s: too many spans to pool, n_spans = %u > %d\n", __func__, balloc->get_n_spans(), LLAMA_MAX_POOL_SPANS);
|
||||
return -1;
|
||||
}
|
||||
|
||||
const uint32_t n_tokens = balloc->get_n_tokens();
|
||||
|
||||
// [TAG_NO_CACHE_PAD]
|
||||
@@ -1907,10 +1936,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) {
|
||||
|
||||
// TODO: this clear of the buffer can easily be forgotten - need something better
|
||||
// sync first so any in-flight async copies into embd_seq complete before it is freed
|
||||
if (!embd_seq.empty()) {
|
||||
if (!embd_seq.empty() || !embd_span.empty()) {
|
||||
synchronize();
|
||||
}
|
||||
embd_seq.clear();
|
||||
embd_span.clear();
|
||||
|
||||
if (t_compute_start_us == 0) {
|
||||
t_compute_start_us = ggml_time_us();
|
||||
@@ -1960,6 +1990,8 @@ int llama_context::encode(const llama_batch_ext & batch_inp) {
|
||||
auto * t_embd = res->get_embd_pooled() ? res->get_embd_pooled() : res->get_embd();
|
||||
auto * t_h_nextn = cparams.embeddings_nextn ? res->get_h_nextn() : nullptr;
|
||||
|
||||
auto * t_embd_span = ubatch.span ? res->get_embd_span() : nullptr;
|
||||
|
||||
// extract logits
|
||||
if (logits.data && t_logits) {
|
||||
ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
|
||||
@@ -1970,7 +2002,9 @@ int llama_context::encode(const llama_batch_ext & batch_inp) {
|
||||
}
|
||||
|
||||
// extract embeddings
|
||||
if (embd.data && t_embd) {
|
||||
if (embd.data && t_embd_span) {
|
||||
output_embd_spans(ubatch, t_embd_span);
|
||||
} else if (embd.data && t_embd) {
|
||||
ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
|
||||
GGML_ASSERT(backend_embd != nullptr);
|
||||
|
||||
@@ -2204,14 +2238,27 @@ int llama_context::decode(const llama_batch_ext & batch_inp) {
|
||||
|
||||
GGML_ASSERT(n_tokens_all <= cparams.n_batch);
|
||||
|
||||
if (llm_graph_pools_spans(cparams) && balloc->get_n_spans() > LLAMA_MAX_POOL_SPANS) {
|
||||
LLAMA_LOG_ERROR("%s: too many spans to pool, n_spans = %u > %d\n", __func__, balloc->get_n_spans(), LLAMA_MAX_POOL_SPANS);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// a span cannot be split over two ubatches
|
||||
if (output_all && balloc->has_spans() && n_tokens_all > cparams.n_ubatch) {
|
||||
LLAMA_LOG_ERROR("%s: a batch with spans is read in one pass, n_tokens = %u > n_ubatch = %u, increase n_ubatch (-ub)\n",
|
||||
__func__, n_tokens_all, cparams.n_ubatch);
|
||||
return -1;
|
||||
}
|
||||
|
||||
GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
|
||||
|
||||
// TODO: this clear of the buffer can easily be forgotten - need something better
|
||||
// sync first so any in-flight async copies into embd_seq complete before it is freed
|
||||
if (!embd_seq.empty()) {
|
||||
if (!embd_seq.empty() || !embd_span.empty()) {
|
||||
synchronize();
|
||||
}
|
||||
embd_seq.clear();
|
||||
embd_span.clear();
|
||||
|
||||
if (t_compute_start_us == 0) {
|
||||
t_compute_start_us = ggml_time_us();
|
||||
@@ -2388,6 +2435,8 @@ int llama_context::decode(const llama_batch_ext & batch_inp) {
|
||||
t_embd = res->get_embd_pooled();
|
||||
}
|
||||
|
||||
auto * t_embd_span = cparams.embeddings && ubatch.span ? res->get_embd_span() : nullptr;
|
||||
|
||||
// extract logits
|
||||
if (logits.data && t_logits && n_outputs > 0 && needs_raw_logits(ubatch, sampling.samplers)) {
|
||||
ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
|
||||
@@ -2404,7 +2453,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) {
|
||||
}
|
||||
|
||||
// extract embeddings
|
||||
if (embd.data && t_embd && n_outputs > 0) {
|
||||
if (embd.data && t_embd_span) {
|
||||
output_embd_spans(ubatch, t_embd_span);
|
||||
} else if (embd.data && t_embd && n_outputs > 0) {
|
||||
ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
|
||||
GGML_ASSERT(backend_embd != nullptr);
|
||||
|
||||
@@ -4692,6 +4743,12 @@ float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) {
|
||||
return ctx->get_embeddings_seq(seq_id);
|
||||
}
|
||||
|
||||
float * llama_get_embeddings_pool_span(llama_context * ctx, int32_t span) {
|
||||
ctx->synchronize();
|
||||
|
||||
return ctx->get_embeddings_span(span);
|
||||
}
|
||||
|
||||
void llama_set_embeddings_nextn(llama_context * ctx, bool value, bool masked) {
|
||||
ctx->set_embeddings_nextn(value, masked);
|
||||
}
|
||||
|
||||
@@ -87,6 +87,7 @@ struct llama_context {
|
||||
float * get_embeddings();
|
||||
float * get_embeddings_ith(int32_t i);
|
||||
float * get_embeddings_seq(llama_seq_id seq_id);
|
||||
float * get_embeddings_span(int32_t span);
|
||||
|
||||
float * get_embeddings_nextn();
|
||||
float * get_embeddings_nextn_ith(int32_t i);
|
||||
@@ -251,6 +252,9 @@ private:
|
||||
|
||||
void output_reorder();
|
||||
|
||||
// copy t_embd_span rows to embd_span, see llama_ubatch_get_spans()
|
||||
void output_embd_spans(const llama_ubatch & ubatch, ggml_tensor * t_embd_span);
|
||||
|
||||
// map the output row index `i` to batch index
|
||||
int64_t output_resolve_row(int32_t i) const;
|
||||
|
||||
@@ -386,6 +390,9 @@ private:
|
||||
// populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
|
||||
std::map<llama_seq_id, std::vector<float>> embd_seq;
|
||||
|
||||
// span embeddings output, see llama_get_embeddings_pool_span()
|
||||
std::map<int32_t, std::vector<float>> embd_span;
|
||||
|
||||
// reuse the batch_allocr to avoid unnecessary memory allocations
|
||||
std::unique_ptr<llama_batch_allocr> balloc;
|
||||
|
||||
|
||||
+27
-16
@@ -125,23 +125,34 @@ LLAMA_API std::vector<ggml_backend_buffer_t> llama_memory_get_buffers(const llam
|
||||
// Useful for testing purposes.
|
||||
LLAMA_API void llama_model_set_attn_rot(struct llama_model * model, bool value);
|
||||
|
||||
// Marks the entries that a decision head (clef, vllm-decision2) reads, the default is 0
|
||||
// See https://github.com/ggml-org/llama.cpp/pull/29831 for details
|
||||
// A run of entries with the same value is one span, spans must be separated by entries with value 0
|
||||
// An option belongs to the last question before it
|
||||
enum llama_decision_order {
|
||||
LLAMA_DECISION_ORDER_NONE = 0, // not read by the head
|
||||
LLAMA_DECISION_ORDER_QUESTION_NOUL = 1, // text of a question
|
||||
LLAMA_DECISION_ORDER_QUESTION_CHOICE = 2,
|
||||
LLAMA_DECISION_ORDER_QUESTION_SCORE = 3,
|
||||
LLAMA_DECISION_ORDER_OPTION = 4, // text of an option
|
||||
};
|
||||
// The embeddings output has one value per entry: row i is the score of option i
|
||||
LLAMA_API bool llama_batch_ext_set_decision_order(struct llama_batch_ext * batch, int32_t idx, enum llama_decision_order order);
|
||||
// span id of an entry, 0 (default) = no span
|
||||
// a span is one run of entries in one sequence, a batch with spans must fit in one ubatch
|
||||
// with mean, cls or last pooling, each span is pooled instead of each sequence
|
||||
// note: spans cannot overlap
|
||||
// to pool overlapping or disjoint ranges, cut them into spans, then join the results:
|
||||
// mean = sum(n_tokens(span) * mean(span)) / sum(n_tokens(span)), before normalization
|
||||
// cls / last = result of the first / last span
|
||||
LLAMA_API bool llama_batch_ext_set_pool_span(struct llama_batch_ext * batch, int32_t idx, int32_t span);
|
||||
|
||||
// Questions packed after a shared state in one sequence, contexts without memory only
|
||||
// 0 (default) is the state, k > 0 the k-th question; full attention layers hide other questions from a question
|
||||
LLAMA_API bool llama_batch_ext_set_decision_group(struct llama_batch_ext * batch, int32_t idx, int32_t group);
|
||||
// role of a span, read by a decision head (clef, vllm-decision2)
|
||||
// See https://github.com/ggml-org/llama.cpp/pull/29831 for details
|
||||
// An option belongs to the last question before it
|
||||
enum llama_pool_span_type {
|
||||
LLAMA_POOL_SPAN_TYPE_DEFAULT = 0, // pooled with the context pooling type
|
||||
LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_NOUL = 1, // text of a question
|
||||
LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_CHOICE = 2,
|
||||
LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_SCORE = 3,
|
||||
LLAMA_POOL_SPAN_TYPE_DECISION_OPTION = 4, // text of an option
|
||||
};
|
||||
LLAMA_API bool llama_batch_ext_set_pool_span_type(struct llama_batch_ext * batch, int32_t span, enum llama_pool_span_type type);
|
||||
|
||||
// result of a span of the last batch, nullptr if none
|
||||
// n_embd_out pooled values, or 1 score for an option span of a decision head
|
||||
LLAMA_API float * llama_get_embeddings_pool_span(struct llama_context * ctx, int32_t span);
|
||||
|
||||
// entries packed after a shared prefix in one sequence, contexts without memory only
|
||||
// 0 (default) is seen by all, scope k > 0 is hidden from other scopes in full attn layers
|
||||
LLAMA_API bool llama_batch_ext_set_attn_scope(struct llama_batch_ext * batch, int32_t idx, int32_t scope);
|
||||
|
||||
// Label of option i of a decision model ("<arch>.decision.labels"), nullptr past the last one
|
||||
LLAMA_API const char * llama_model_decision_label(const struct llama_model * model, uint32_t i);
|
||||
|
||||
+64
-13
@@ -431,6 +431,21 @@ bool llm_graph_input_moe_ids::can_reuse(const llm_graph_params & params) {
|
||||
return res;
|
||||
}
|
||||
|
||||
bool llm_graph_pools_spans(const llama_cparams & cparams) {
|
||||
return cparams.embeddings && (
|
||||
cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN ||
|
||||
cparams.pooling_type == LLAMA_POOLING_TYPE_CLS ||
|
||||
cparams.pooling_type == LLAMA_POOLING_TYPE_LAST);
|
||||
}
|
||||
|
||||
int64_t llm_graph_n_pooled(const llama_cparams & cparams, const llama_ubatch & ubatch) {
|
||||
return llm_graph_pools_spans(cparams) ? std::max<int64_t>(LLAMA_MAX_POOL_SPANS, cparams.n_seq_max) : ubatch.n_seqs_unq;
|
||||
}
|
||||
|
||||
std::vector<llama_ubatch_span> llm_graph_pooling_spans(const llama_cparams & cparams, const llama_ubatch & ubatch) {
|
||||
return llm_graph_pools_spans(cparams) ? llama_ubatch_get_spans(ubatch) : std::vector<llama_ubatch_span>();
|
||||
}
|
||||
|
||||
void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) {
|
||||
if (cparams.embeddings &&
|
||||
(cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN ||
|
||||
@@ -444,7 +459,19 @@ void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) {
|
||||
GGML_ASSERT(ggml_backend_buffer_is_host(mean->buffer));
|
||||
|
||||
float * data = (float *) mean->data;
|
||||
memset(mean->data, 0, n_tokens*n_seqs_unq*ggml_element_size(mean));
|
||||
|
||||
memset(mean->data, 0, ggml_nbytes(mean));
|
||||
|
||||
const auto spans = llm_graph_pooling_spans(cparams, *ubatch);
|
||||
if (!spans.empty()) {
|
||||
GGML_ASSERT((int64_t) spans.size() <= mean->ne[1]);
|
||||
for (size_t s = 0; s < spans.size(); ++s) {
|
||||
for (int32_t i = spans[s].start; i < spans[s].end; ++i) {
|
||||
data[s*n_tokens + i] = 1.0f/float(spans[s].end - spans[s].start);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<uint64_t> sums(n_seqs_unq, 0);
|
||||
for (int i = 0; i < n_tokens; i += n_seq_tokens) {
|
||||
@@ -490,16 +517,26 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) {
|
||||
GGML_ASSERT(ggml_backend_buffer_is_host(cls->buffer));
|
||||
|
||||
uint32_t * data = (uint32_t *) cls->data;
|
||||
memset(cls->data, 0, n_seqs_unq*ggml_element_size(cls));
|
||||
|
||||
std::vector<int> target_pos(n_seqs_unq, -1);
|
||||
std::vector<int> target_row(n_seqs_unq, -1);
|
||||
|
||||
const bool last = (
|
||||
cparams.pooling_type == LLAMA_POOLING_TYPE_LAST ||
|
||||
(cparams.pooling_type == LLAMA_POOLING_TYPE_RANK && cparams.causal_attn)
|
||||
);
|
||||
|
||||
memset(cls->data, 0, ggml_nbytes(cls));
|
||||
|
||||
const auto spans = llm_graph_pooling_spans(cparams, *ubatch);
|
||||
if (!spans.empty()) {
|
||||
GGML_ASSERT((int64_t) spans.size() <= cls->ne[0]);
|
||||
for (size_t s = 0; s < spans.size(); ++s) {
|
||||
data[s] = last ? spans[s].end - 1 : spans[s].start;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<int> target_pos(n_seqs_unq, -1);
|
||||
std::vector<int> target_row(n_seqs_unq, -1);
|
||||
|
||||
for (int i = 0; i < n_tokens; ++i) {
|
||||
const llama_pos pos = ubatch->pos[i];
|
||||
|
||||
@@ -636,28 +673,28 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) {
|
||||
const int64_t n_kv = self_attn_mask.raw->ne[0];
|
||||
const int64_t n_tokens = ubatch->n_tokens;
|
||||
|
||||
const auto fill_mask = [&](auto * data, int64_t ne, int n_swa, llama_swa_type swa_type, bool causal, const int32_t * group) {
|
||||
const auto fill_mask = [&](auto * data, int64_t ne, int n_swa, llama_swa_type swa_type, bool causal, const int32_t * scope) {
|
||||
using T = std::remove_reference_t<decltype(*data)>;
|
||||
std::fill(data, data + ne, llama_cast<T>(-INFINITY));
|
||||
|
||||
for (int i1 = 0; i1 < n_tokens; ++i1) {
|
||||
const llama_seq_id s1 = ubatch->seq_id[i1][0];
|
||||
const llama_pos p1 = ubatch->pos[i1];
|
||||
const int32_t g1 = group ? group[i1] : 0;
|
||||
const int32_t g1 = scope ? scope[i1] : 0;
|
||||
|
||||
const uint64_t idst = i1*n_kv;
|
||||
|
||||
for (int i0 = 0; i0 < n_tokens; ++i0) {
|
||||
const llama_seq_id s0 = ubatch->seq_id[i0][0];
|
||||
const llama_pos p0 = ubatch->pos[i0];
|
||||
const int32_t g0 = group ? group[i0] : 0;
|
||||
const int32_t g0 = scope ? scope[i0] : 0;
|
||||
|
||||
// mask different sequences
|
||||
if (s0 != s1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// mask other questions, see llama_batch_ext_set_decision_group()
|
||||
// mask other scopes, see llama_batch_ext_set_attn_scope()
|
||||
if (g0 != 0 && g1 != 0 && g0 != g1) {
|
||||
continue;
|
||||
}
|
||||
@@ -688,9 +725,9 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) {
|
||||
GGML_ASSERT(self_attn_mask.raw);
|
||||
GGML_ASSERT(ggml_backend_buffer_is_host(self_attn_mask.raw->buffer));
|
||||
if (self_attn_mask.raw->type == GGML_TYPE_F16) {
|
||||
fill_mask((ggml_fp16_t *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->decision_group);
|
||||
fill_mask((ggml_fp16_t *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->attn_scope);
|
||||
} else {
|
||||
fill_mask((float *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->decision_group);
|
||||
fill_mask((float *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->attn_scope);
|
||||
}
|
||||
|
||||
if (hparams.swa_type != LLAMA_SWA_TYPE_NONE) {
|
||||
@@ -1587,6 +1624,7 @@ void llm_graph_result::reset() {
|
||||
t_logits = nullptr;
|
||||
t_embd = nullptr;
|
||||
t_embd_pooled = nullptr;
|
||||
t_embd_span = nullptr;
|
||||
t_h_nextn = nullptr;
|
||||
|
||||
t_layer_inp.resize(LLAMA_MAX_LAYERS + 1);
|
||||
@@ -1639,6 +1677,9 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) {
|
||||
if (t_embd_pooled != nullptr) {
|
||||
ggml_set_output(t_embd_pooled);
|
||||
}
|
||||
if (t_embd_span != nullptr) {
|
||||
ggml_set_output(t_embd_span);
|
||||
}
|
||||
if (t_h_nextn != nullptr) {
|
||||
ggml_set_output(t_h_nextn);
|
||||
}
|
||||
@@ -3019,7 +3060,7 @@ ggml_tensor * llm_graph_context::build_inp_mean() const {
|
||||
|
||||
auto & cur = inp->mean;
|
||||
|
||||
cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, ubatch.n_seqs_unq);
|
||||
cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, llm_graph_n_pooled(cparams, ubatch));
|
||||
ggml_set_input(cur);
|
||||
ggml_set_name(cur, "mean");
|
||||
|
||||
@@ -3033,7 +3074,7 @@ ggml_tensor * llm_graph_context::build_inp_cls() const {
|
||||
|
||||
auto & cur = inp->cls;
|
||||
|
||||
cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_seqs_unq);
|
||||
cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, llm_graph_n_pooled(cparams, ubatch));
|
||||
ggml_set_input(cur);
|
||||
ggml_set_name(cur, "cls");
|
||||
|
||||
@@ -4517,6 +4558,8 @@ void llm_graph_context::build_dense_out(
|
||||
ggml_tensor * cur = res->t_embd_pooled != nullptr ? res->t_embd_pooled : res->t_embd;
|
||||
GGML_ASSERT(cur != nullptr && "missing t_embd_pooled/t_embd");
|
||||
|
||||
const bool is_span = cur == res->t_embd_span;
|
||||
|
||||
if (dense_2) {
|
||||
cur = build_lora_mm(dense_2, cur);
|
||||
}
|
||||
@@ -4528,6 +4571,9 @@ void llm_graph_context::build_dense_out(
|
||||
}
|
||||
cb(cur, "result_embd_pooled", -1);
|
||||
res->t_embd_pooled = cur;
|
||||
if (is_span) {
|
||||
res->t_embd_span = cur;
|
||||
}
|
||||
ggml_build_forward_expand(gf, cur);
|
||||
}
|
||||
|
||||
@@ -4631,6 +4677,11 @@ void llm_graph_context::build_pooling(
|
||||
cb(cur, "result_embd_pooled", -1);
|
||||
res->t_embd_pooled = cur;
|
||||
|
||||
// a model with its own head has set it already
|
||||
if (res->t_embd_span == nullptr && !llm_graph_pooling_spans(cparams, ubatch).empty()) {
|
||||
res->t_embd_span = cur;
|
||||
}
|
||||
|
||||
ggml_build_forward_expand(gf, cur);
|
||||
}
|
||||
|
||||
|
||||
@@ -283,6 +283,18 @@ public:
|
||||
const int64_t n_expert;
|
||||
};
|
||||
|
||||
// max number of spans pooled in one ubatch
|
||||
#define LLAMA_MAX_POOL_SPANS 64
|
||||
|
||||
// true if the context pools spans instead of sequences
|
||||
bool llm_graph_pools_spans(const llama_cparams & cparams);
|
||||
|
||||
// number of pooled rows, fixed when pooling spans to avoid a realloc
|
||||
int64_t llm_graph_n_pooled(const llama_cparams & cparams, const llama_ubatch & ubatch);
|
||||
|
||||
// the spans to pool, empty if pooling per sequence
|
||||
std::vector<llama_ubatch_span> llm_graph_pooling_spans(const llama_cparams & cparams, const llama_ubatch & ubatch);
|
||||
|
||||
class llm_graph_input_mean : public llm_graph_input_i {
|
||||
public:
|
||||
llm_graph_input_mean(const llama_cparams & cparams) : cparams(cparams) {}
|
||||
@@ -1006,6 +1018,7 @@ public:
|
||||
ggml_tensor * get_logits() const { return t_logits; }
|
||||
ggml_tensor * get_embd() const { return t_embd; }
|
||||
ggml_tensor * get_embd_pooled() const { return t_embd_pooled; }
|
||||
ggml_tensor * get_embd_span() const { return t_embd_span; }
|
||||
ggml_tensor * get_h_nextn() const { return t_h_nextn; }
|
||||
|
||||
ggml_tensor * get_layer_inp(int il) const { return t_layer_inp[il]; }
|
||||
@@ -1047,6 +1060,7 @@ public:
|
||||
ggml_tensor * t_logits = nullptr;
|
||||
ggml_tensor * t_embd = nullptr;
|
||||
ggml_tensor * t_embd_pooled = nullptr;
|
||||
ggml_tensor * t_embd_span = nullptr; // [n_embd_out or 1, n_pooled], one row per span
|
||||
ggml_tensor * t_h_nextn = nullptr; // [n_embd, n_outputs] hidden state before final output norm
|
||||
|
||||
std::vector<ggml_tensor *> t_layer_inp;
|
||||
|
||||
@@ -168,8 +168,9 @@ static llama_ubatch dsv4_build_raw_write_ubatch(const llama_ubatch & ubatch) {
|
||||
/*.seq_idx =*/ data->seq_idx.data(),
|
||||
/*.output =*/ data->output.data(),
|
||||
/*.type =*/ nullptr,
|
||||
/*.decision_order =*/ nullptr,
|
||||
/*.decision_group =*/ nullptr,
|
||||
/*.span =*/ nullptr,
|
||||
/*.span_type =*/ nullptr,
|
||||
/*.attn_scope =*/ nullptr,
|
||||
/*.data =*/ data,
|
||||
};
|
||||
|
||||
|
||||
+48
-28
@@ -17,7 +17,7 @@ void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hpar
|
||||
// used by the head
|
||||
ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
|
||||
|
||||
// the output is one score per token, see llama_batch_ext_set_decision_order()
|
||||
// the output is one score per span, see llama_batch_ext_set_pool_span_type()
|
||||
hparams.n_embd_out_impl = 1;
|
||||
}
|
||||
|
||||
@@ -133,50 +133,47 @@ struct clef_spans {
|
||||
};
|
||||
std::vector<question> questions;
|
||||
std::vector<option> options;
|
||||
std::vector<int32_t> span_option; // option index of each span, -1 if not an option
|
||||
bool valid = false;
|
||||
};
|
||||
|
||||
// see llama_batch_ext_set_decision_order()
|
||||
// if the batch has no usable order, returns one empty question with one empty option
|
||||
// see llama_batch_ext_set_pool_span_type()
|
||||
// if no usable spans, return one empty question and one empty option
|
||||
static clef_spans clef_get_spans(const llama_ubatch & ubatch) {
|
||||
clef_spans res;
|
||||
std::vector<bool> has_option;
|
||||
|
||||
// TODO: support multiple sequences
|
||||
bool ok = ubatch.decision_order != nullptr && ubatch.token != nullptr && ubatch.n_seqs_unq == 1;
|
||||
const auto spans = llama_ubatch_get_spans(ubatch);
|
||||
|
||||
const int32_t n_tokens = ubatch.n_tokens;
|
||||
for (int32_t i = 0; ok && i < n_tokens;) {
|
||||
const int32_t order = ubatch.decision_order[i];
|
||||
int32_t end = i + 1;
|
||||
while (end < n_tokens && ubatch.decision_order[end] == order) {
|
||||
end++;
|
||||
}
|
||||
switch (order) {
|
||||
case LLAMA_DECISION_ORDER_NONE:
|
||||
break;
|
||||
case LLAMA_DECISION_ORDER_QUESTION_NOUL:
|
||||
case LLAMA_DECISION_ORDER_QUESTION_CHOICE:
|
||||
case LLAMA_DECISION_ORDER_QUESTION_SCORE:
|
||||
res.questions.push_back({ order - LLAMA_DECISION_ORDER_QUESTION_NOUL, i, end });
|
||||
// TODO: support multiple sequences
|
||||
bool ok = !spans.empty() && ubatch.token != nullptr && ubatch.n_seqs_unq == 1;
|
||||
|
||||
for (size_t i = 0; ok && i < spans.size(); i++) {
|
||||
const auto & span = spans[i];
|
||||
switch (span.type) {
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_NOUL:
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_CHOICE:
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_SCORE:
|
||||
res.questions.push_back({ span.type - LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_NOUL, span.start, span.end });
|
||||
res.span_option.push_back(-1);
|
||||
has_option.push_back(false);
|
||||
break;
|
||||
case LLAMA_DECISION_ORDER_OPTION:
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_OPTION:
|
||||
ok = !res.questions.empty();
|
||||
if (ok) {
|
||||
res.options.push_back({ (int32_t) res.questions.size() - 1, i, end });
|
||||
res.span_option.push_back(res.options.size());
|
||||
res.options.push_back({ (int32_t) res.questions.size() - 1, span.start, span.end });
|
||||
has_option.back() = true;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
ok = false;
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
|
||||
// the head reads the token ids of the spans, they cannot be embeddings
|
||||
for (int32_t i = 0; ok && ubatch.is_mixed() && i < n_tokens; i++) {
|
||||
ok = !ubatch.type[i] || ubatch.decision_order[i] == LLAMA_DECISION_ORDER_NONE;
|
||||
for (int32_t i = 0; ok && ubatch.is_mixed() && i < (int32_t) ubatch.n_tokens; i++) {
|
||||
ok = !ubatch.type[i] || ubatch.span[i] == 0;
|
||||
}
|
||||
|
||||
// each question needs an option
|
||||
@@ -186,6 +183,7 @@ static clef_spans clef_get_spans(const llama_ubatch & ubatch) {
|
||||
res.options.clear();
|
||||
res.questions.push_back({ 0, 0, 0 });
|
||||
res.options.push_back({ 0, 0, 0 });
|
||||
res.span_option.assign(spans.size(), -1);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -209,6 +207,7 @@ public:
|
||||
auto spans = clef_get_spans(*ubatch);
|
||||
const int32_t n_q_used = spans.questions.size();
|
||||
GGML_ASSERT((size_t) n_q_used < n_questions && spans.options.size() <= n_options);
|
||||
GGML_ASSERT(spans.span_option.size() <= (size_t) n_tokens);
|
||||
|
||||
// the padding options belong to the first padding question, the questions do not read the padding questions
|
||||
spans.questions.resize(n_questions, { 0, 0, 0 });
|
||||
@@ -220,10 +219,17 @@ public:
|
||||
}
|
||||
ggml_backend_tensor_set(question_mask, q_mask.data(), 0, ggml_nbytes(question_mask));
|
||||
|
||||
// the scores are NaN if the batch has a decision order that cannot be used
|
||||
const float status_data = spans.valid || ubatch->decision_order == nullptr ? 0.0f : NAN;
|
||||
// scores are NaN if the spans cannot be used
|
||||
const float status_data = spans.valid || ubatch->span == nullptr ? 0.0f : NAN;
|
||||
ggml_backend_tensor_set(status, &status_data, 0, ggml_nbytes(status));
|
||||
|
||||
// row n_options is 0, used by non-option and padding spans
|
||||
std::vector<int32_t> span_option_data(n_tokens, n_options);
|
||||
for (size_t i = 0; i < spans.span_option.size(); i++) {
|
||||
span_option_data[i] = spans.span_option[i] < 0 ? n_options : spans.span_option[i];
|
||||
}
|
||||
ggml_backend_tensor_set(span_option, span_option_data.data(), 0, ggml_nbytes(span_option));
|
||||
|
||||
std::vector<float> pool_q_data(n_tokens * n_questions, 0.0f);
|
||||
std::vector<int32_t> types(n_questions);
|
||||
for (size_t i = 0; i < n_questions; i++) {
|
||||
@@ -268,6 +274,7 @@ public:
|
||||
ggml_tensor * option_mask = nullptr; // F32 [n_options, n_questions], 0 if the option belongs to the question, else -inf
|
||||
ggml_tensor * question_mask = nullptr; // F32 [n_questions, n_questions], -inf for the padding questions
|
||||
ggml_tensor * status = nullptr; // F32 [1], added to the scores: 0, or NaN on invalid input
|
||||
ggml_tensor * span_option = nullptr; // I32 [n_tokens], n_tokens is the max number of spans
|
||||
|
||||
const int64_t n_tokens;
|
||||
const size_t n_questions;
|
||||
@@ -562,6 +569,8 @@ ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor
|
||||
for (ggml_tensor * t : { inp->tokens, inp->pool_q, inp->pool_o, inp->question_type, inp->option_question, inp->option_mask, inp->question_mask, inp->status }) {
|
||||
ggml_set_input(t);
|
||||
}
|
||||
inp->span_option = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
|
||||
ggml_set_input(inp->span_option);
|
||||
|
||||
hidden = build_head_norm(ctx, hidden, hidden_norm);
|
||||
|
||||
@@ -658,10 +667,21 @@ ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor
|
||||
|
||||
ggml_tensor * cur = ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2)));
|
||||
|
||||
// row i of the output is the score of option i
|
||||
// one row per span: the score of an option, 0 for a question
|
||||
{
|
||||
ggml_tensor * span = ggml_pad(ctx0, cur, 0, 1, 0, 0);
|
||||
span = ggml_get_rows(ctx0, span, inp->span_option);
|
||||
span = ggml_add(ctx0, span, inp->status);
|
||||
ctx.cb(span, "result_decision", -1);
|
||||
|
||||
ctx.res->t_embd_span = span;
|
||||
|
||||
ggml_build_forward_expand(ctx.gf, span);
|
||||
}
|
||||
|
||||
// unused without spans, kept so the graph is never empty
|
||||
cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0);
|
||||
cur = ggml_add(ctx0, cur, inp->status);
|
||||
ctx.cb(cur, "result_decision", -1);
|
||||
|
||||
return cur;
|
||||
}
|
||||
|
||||
+2
-1
@@ -3072,7 +3072,8 @@ struct llama_clef_head {
|
||||
static llm_graph_input_attn_no_cache * build_attn_inp_causal(const llm_graph_context & ctx);
|
||||
|
||||
// hidden: [n_embd, n_tokens]
|
||||
// returns [1, n_tokens], row i is the score of option i
|
||||
// set res->t_embd_span to the score of each span, see llama_batch_ext_set_pool_span_type()
|
||||
// returns [1, n_tokens], unused without spans
|
||||
ggml_tensor * build(const llm_graph_context & ctx, ggml_tensor * hidden) const;
|
||||
|
||||
private:
|
||||
|
||||
@@ -10,7 +10,7 @@ void llama_model_vllm_decision2::load_arch_hparams(llama_model_loader & ml) {
|
||||
// used by the head
|
||||
ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
|
||||
|
||||
// the output is one score per token, see llama_batch_ext_set_decision_order()
|
||||
// the output is one score per span, see llama_batch_ext_set_pool_span_type()
|
||||
hparams.n_embd_out_impl = 1;
|
||||
}
|
||||
|
||||
@@ -45,17 +45,19 @@ std::unique_ptr<llm_graph_context> llama_model_vllm_decision2::build_arch_graph(
|
||||
// output rows read by the head: the last token of each option span and the last token of the question span
|
||||
struct decision2_rows {
|
||||
std::vector<int32_t> options;
|
||||
std::vector<int32_t> span_option; // option index of each span, -1 if not an option
|
||||
int32_t query = 0;
|
||||
bool valid = false;
|
||||
};
|
||||
|
||||
// see llama_batch_ext_set_decision_order()
|
||||
// if the batch has no usable order, returns one option at row 0
|
||||
// see llama_batch_ext_set_pool_span_type()
|
||||
// if no usable spans, return one option at row 0
|
||||
static decision2_rows decision2_get_rows(const llama_ubatch & ubatch) {
|
||||
decision2_rows res;
|
||||
|
||||
const int32_t n_tokens = ubatch.n_tokens;
|
||||
bool ok = ubatch.decision_order != nullptr && ubatch.n_seqs_unq == 1;
|
||||
const auto spans = llama_ubatch_get_spans(ubatch);
|
||||
bool ok = !spans.empty() && ubatch.n_seqs_unq == 1;
|
||||
|
||||
// output row of each token, -1 if the token has no output
|
||||
std::vector<int32_t> rows(n_tokens, -1);
|
||||
@@ -66,34 +68,30 @@ static decision2_rows decision2_get_rows(const llama_ubatch & ubatch) {
|
||||
}
|
||||
|
||||
int32_t n_questions = 0;
|
||||
for (int32_t i = 0; ok && i < n_tokens;) {
|
||||
const int32_t order = ubatch.decision_order[i];
|
||||
int32_t end = i + 1;
|
||||
while (end < n_tokens && ubatch.decision_order[end] == order) {
|
||||
end++;
|
||||
}
|
||||
switch (order) {
|
||||
case LLAMA_DECISION_ORDER_NONE:
|
||||
break;
|
||||
case LLAMA_DECISION_ORDER_QUESTION_NOUL:
|
||||
case LLAMA_DECISION_ORDER_QUESTION_CHOICE:
|
||||
case LLAMA_DECISION_ORDER_QUESTION_SCORE:
|
||||
res.query = rows[end - 1];
|
||||
for (const auto & span : spans) {
|
||||
const int32_t row = rows[span.end - 1];
|
||||
switch (span.type) {
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_NOUL:
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_CHOICE:
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_SCORE:
|
||||
res.query = row;
|
||||
res.span_option.push_back(-1);
|
||||
n_questions++;
|
||||
break;
|
||||
case LLAMA_DECISION_ORDER_OPTION:
|
||||
res.options.push_back(rows[end - 1]);
|
||||
case LLAMA_POOL_SPAN_TYPE_DECISION_OPTION:
|
||||
res.span_option.push_back(res.options.size());
|
||||
res.options.push_back(row);
|
||||
break;
|
||||
default:
|
||||
ok = false;
|
||||
}
|
||||
ok = ok && (order == LLAMA_DECISION_ORDER_NONE || rows[end - 1] >= 0);
|
||||
i = end;
|
||||
ok = ok && row >= 0;
|
||||
}
|
||||
|
||||
res.valid = ok && n_questions == 1 && !res.options.empty();
|
||||
if (!res.valid) {
|
||||
res.options.assign(1, 0);
|
||||
res.span_option.assign(spans.size(), -1);
|
||||
res.query = 0;
|
||||
}
|
||||
return res;
|
||||
@@ -101,36 +99,46 @@ static decision2_rows decision2_get_rows(const llama_ubatch & ubatch) {
|
||||
|
||||
// no decision order (e.g. reserve): use the max number of options
|
||||
static size_t decision2_n_options(const llama_ubatch & ubatch, uint32_t n_outputs) {
|
||||
return ubatch.decision_order ? decision2_get_rows(ubatch).options.size() : std::max<uint32_t>(n_outputs, 1);
|
||||
return ubatch.span ? decision2_get_rows(ubatch).options.size() : std::max<uint32_t>(n_outputs, 1);
|
||||
}
|
||||
|
||||
class llama_model_vllm_decision2::input_decision : public llm_graph_input_i {
|
||||
public:
|
||||
input_decision(const llama_ubatch & ubatch, uint32_t n_outputs) : n_options(decision2_n_options(ubatch, n_outputs)) {}
|
||||
input_decision(const llama_ubatch & ubatch, uint32_t n_outputs) :
|
||||
n_tokens(ubatch.n_tokens), n_options(decision2_n_options(ubatch, n_outputs)) {}
|
||||
|
||||
void set_input(const llama_ubatch * ubatch) override {
|
||||
auto rows = decision2_get_rows(*ubatch);
|
||||
GGML_ASSERT(rows.options.size() <= n_options);
|
||||
GGML_ASSERT(rows.options.size() <= n_options && rows.span_option.size() <= (size_t) n_tokens);
|
||||
rows.options.resize(n_options, 0);
|
||||
|
||||
// the scores are NaN if the batch has a decision order that cannot be used
|
||||
const float status_data = rows.valid || ubatch->decision_order == nullptr ? 0.0f : NAN;
|
||||
// scores are NaN if the spans cannot be used
|
||||
const float status_data = rows.valid || ubatch->span == nullptr ? 0.0f : NAN;
|
||||
|
||||
ggml_backend_tensor_set(options, rows.options.data(), 0, ggml_nbytes(options));
|
||||
ggml_backend_tensor_set(query, &rows.query, 0, ggml_nbytes(query));
|
||||
ggml_backend_tensor_set(status, &status_data, 0, ggml_nbytes(status));
|
||||
|
||||
// row n_options is 0, used by non-option and padding spans
|
||||
std::vector<int32_t> span_option_data(n_tokens, n_options);
|
||||
for (size_t i = 0; i < rows.span_option.size(); i++) {
|
||||
span_option_data[i] = rows.span_option[i] < 0 ? n_options : rows.span_option[i];
|
||||
}
|
||||
ggml_backend_tensor_set(span_option, span_option_data.data(), 0, ggml_nbytes(span_option));
|
||||
}
|
||||
|
||||
bool can_reuse(const llm_graph_params & params) override {
|
||||
// the values are computed again in set_input(), only the shapes must match
|
||||
return decision2_n_options(params.ubatch, params.n_outputs) == n_options;
|
||||
return params.ubatch.n_tokens == (uint32_t) n_tokens && decision2_n_options(params.ubatch, params.n_outputs) == n_options;
|
||||
}
|
||||
|
||||
ggml_tensor * options = nullptr; // I32 [n_options]
|
||||
ggml_tensor * query = nullptr; // I32 [1]
|
||||
ggml_tensor * status = nullptr; // F32 [1], added to the scores: 0, or NaN on invalid input
|
||||
ggml_tensor * options = nullptr; // I32 [n_options]
|
||||
ggml_tensor * query = nullptr; // I32 [1]
|
||||
ggml_tensor * status = nullptr; // F32 [1], added to the scores: 0, or NaN on invalid input
|
||||
ggml_tensor * span_option = nullptr; // I32 [n_tokens], n_tokens is the max number of spans
|
||||
|
||||
const size_t n_options;
|
||||
const int64_t n_tokens;
|
||||
const size_t n_options;
|
||||
};
|
||||
|
||||
llama_model_vllm_decision2::graph::graph(const llm_graph_params & params) :
|
||||
@@ -144,10 +152,21 @@ llama_model_vllm_decision2::graph::graph(const llm_graph_params & params) :
|
||||
// the head is always evaluated, so that the graph has the same nodes for every batch
|
||||
cur = build_head(cur, inp_decision);
|
||||
|
||||
// row i of the output is the score of option i
|
||||
// one row per span: the score of an option, 0 for a question
|
||||
{
|
||||
ggml_tensor * span = ggml_pad(ctx0, cur, 0, 1, 0, 0);
|
||||
span = ggml_get_rows(ctx0, span, inp_decision->span_option);
|
||||
span = ggml_add(ctx0, span, inp_decision->status);
|
||||
cb(span, "result_decision", -1);
|
||||
|
||||
res->t_embd_span = span;
|
||||
|
||||
ggml_build_forward_expand(gf, span);
|
||||
}
|
||||
|
||||
// unused without spans, kept so the graph is never empty
|
||||
cur = ggml_pad(ctx0, cur, 0, n_outputs - cur->ne[1], 0, 0);
|
||||
cur = ggml_add(ctx0, cur, inp_decision->status);
|
||||
cb(cur, "result_decision", -1);
|
||||
|
||||
res->t_embd = cur;
|
||||
|
||||
@@ -161,6 +180,8 @@ ggml_tensor * llama_model_vllm_decision2::graph::build_head(ggml_tensor * hidden
|
||||
for (ggml_tensor * t : { inp->options, inp->query, inp->status }) {
|
||||
ggml_set_input(t);
|
||||
}
|
||||
inp->span_option = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, inp->n_tokens);
|
||||
ggml_set_input(inp->span_option);
|
||||
|
||||
ggml_tensor * options = ggml_get_rows(ctx0, hidden, inp->options); // [n_embd, n_options]
|
||||
ggml_tensor * query = ggml_get_rows(ctx0, hidden, inp->query); // [n_embd, 1]
|
||||
|
||||
+143
-9
@@ -6688,25 +6688,28 @@ struct test_mul_mat_hadamard : public test_mul_mat {
|
||||
}
|
||||
};
|
||||
|
||||
// FP4 W4A8 path (GGML_PREC_Q8 on src1 disallows 4-bit activations)
|
||||
// FP4 W4A8 path (GGML_PREC_Q8 on src1 disallows 4-bit activations), or with prec = GGML_PREC_Q4 the W4A4 path requested by the graph
|
||||
struct test_mul_mat_w4a8 : public test_mul_mat {
|
||||
const ggml_prec prec;
|
||||
|
||||
test_mul_mat_w4a8(ggml_type type_a = GGML_TYPE_NVFP4, ggml_type type_b = GGML_TYPE_F32,
|
||||
int64_t m = 32, int64_t n = 32, int64_t k = 256,
|
||||
std::array<int64_t, 2> bs = {1, 1},
|
||||
std::array<int64_t, 2> nr = {1, 1})
|
||||
: test_mul_mat(type_a, type_b, m, n, k, bs, nr) {}
|
||||
std::array<int64_t, 2> nr = {1, 1},
|
||||
ggml_prec prec = GGML_PREC_Q8)
|
||||
: test_mul_mat(type_a, type_b, m, n, k, bs, nr), prec(prec) {}
|
||||
ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override {
|
||||
ggml_tensor * out = test_mul_mat::build_graph(ctx, ctx_weights);
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->op == GGML_OP_MUL_MAT) {
|
||||
ggml_prec_set_src(t, GGML_PREC_Q8, 1);
|
||||
ggml_prec_set_src(t, prec, 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "MUL_MAT_W4A8";
|
||||
return prec == GGML_PREC_Q4 ? "MUL_MAT_W4A4_REQ" : "MUL_MAT_W4A8";
|
||||
}
|
||||
};
|
||||
|
||||
@@ -9327,6 +9330,67 @@ struct test_mul_mat_pos : public test_mul_mat {
|
||||
}
|
||||
};
|
||||
|
||||
// mul_mat with 4-bit src1 requested by the graph (GGML_PREC_Q4): the FP4 W4A4 path also where the default src1 is 8-bit (CUDA few-row MMQ)
|
||||
struct test_mul_mat_src1_q4 : public test_mul_mat {
|
||||
using test_mul_mat::test_mul_mat;
|
||||
|
||||
std::string vars() override {
|
||||
return test_mul_mat::vars() + ",src1_prec=q4";
|
||||
}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override {
|
||||
ggml_tensor * out = test_mul_mat::build_graph(ctx, ctx_weights);
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->op == GGML_OP_MUL_MAT) {
|
||||
ggml_prec_set_src(t, GGML_PREC_Q4, 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
// mul_mat with 4-bit src1 and the src1 rows scaled by 1, 5, ..., 25 (period 7): with a src1 scale per row (FP4 W4A4) the scale of a wrong row changes the result.
|
||||
// Period 7 does not divide the row offsets of other channels and samples for the shapes used here, so a wrong channel or sample also changes it.
|
||||
struct test_mul_mat_rows_scaled : public test_mul_mat_src1_q4 {
|
||||
using test_mul_mat_src1_q4::test_mul_mat_src1_q4;
|
||||
|
||||
std::string vars() override {
|
||||
return test_mul_mat_src1_q4::vars() + ",src1_rows=x1..x25";
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
|
||||
init_tensor_uniform(t);
|
||||
if (std::string(ggml_get_name(t)) != "b") {
|
||||
continue;
|
||||
}
|
||||
GGML_ASSERT(t->type == GGML_TYPE_F32 && ggml_is_contiguous(t));
|
||||
std::vector<float> data(ggml_nelements(t));
|
||||
ggml_backend_tensor_get(t, data.data(), 0, ggml_nbytes(t));
|
||||
for (size_t i = 0; i < data.size(); ++i) {
|
||||
data[i] *= 1.0f + 4.0f*((int64_t) i / t->ne[0] % 7);
|
||||
}
|
||||
ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// mul_mat with the default src1 precision and at most 8 columns: CUDA keeps 8-bit src1 there (MMVQ or few-row MMQ W4A8), so the W4A8 tolerance applies also on Blackwell.
|
||||
// Checks that the default does not switch to 4-bit src1.
|
||||
struct test_mul_mat_8bit_default : public test_mul_mat {
|
||||
using test_mul_mat::test_mul_mat;
|
||||
|
||||
std::string vars() override {
|
||||
return test_mul_mat::vars() + ",src1_prec=default_8bit";
|
||||
}
|
||||
|
||||
double max_nmse_err(ggml_backend_t backend) override {
|
||||
GGML_UNUSED(backend);
|
||||
GGML_ASSERT(n <= 8);
|
||||
return test_mul_mat::max_nmse_err();
|
||||
}
|
||||
};
|
||||
|
||||
enum mul_mat_add_mode {
|
||||
MUL_MAT_ADD_MM_RES, // mm + res
|
||||
MUL_MAT_ADD_RES_MM, // res + mm
|
||||
@@ -9607,6 +9671,27 @@ struct test_mul_mat_fusion_w4a8 : public test_mul_mat_fusion {
|
||||
}
|
||||
};
|
||||
|
||||
// FP4 W4A4 path requested by the graph (GGML_PREC_Q4 on src1), also where the default src1 is 8-bit (CUDA few-row MMQ)
|
||||
struct test_mul_mat_fusion_w4a4_req : public test_mul_mat_fusion {
|
||||
using test_mul_mat_fusion::test_mul_mat_fusion;
|
||||
using test_mul_mat_fusion::build_graph;
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override {
|
||||
ggml_tensor * out = test_mul_mat_fusion::build_graph(ctx, ctx_weights);
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->op == GGML_OP_MUL_MAT || t->op == GGML_OP_MUL_MAT_ID) {
|
||||
ggml_prec_set_src(t, GGML_PREC_Q4, 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "MUL_MAT_FUSION_W4A4_REQ";
|
||||
}
|
||||
};
|
||||
|
||||
// GGML_OP_SUM
|
||||
struct test_sum : public test_case {
|
||||
const ggml_type type;
|
||||
@@ -13802,7 +13887,7 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
}
|
||||
// CUDA few-row MMQ: 1-3 column groups, 32-row tiles (6170 rows), K = 18 units (uneven over the warps) and 9 units (one unit per ring stage)
|
||||
for (ggml_type type_a : {GGML_TYPE_Q8_0, GGML_TYPE_Q3_K, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K,
|
||||
GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) {
|
||||
GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS, GGML_TYPE_NVFP4}) {
|
||||
for (int64_t k : {4608, 2304}) {
|
||||
test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 1000, 8, k, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 6170, 13, k, {1, 1}, {1, 1}));
|
||||
@@ -13828,6 +13913,45 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
// CUDA few-row MMQ for MUL_MAT_ID: strided experts, more than 32 experts
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_F32, 16, 4, true, 72, 13, 2048, 80));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_F32, 128, 8, false, 72, 16, 2048));
|
||||
// CUDA few-row MMQ for NVFP4 (also in the loop above): 8-bit src1 (by default and with GGML_PREC_Q8) from 7 tokens (DGX Spark: 9),
|
||||
// 4-bit src1 only with GGML_PREC_Q4, from 6 tokens (DGX Spark: 8), K = 8 units and not a multiple of 256
|
||||
for (int64_t n : {7, 8, 9, 21, 24}) {
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, n, 4608));
|
||||
if (n <= 8) {
|
||||
test_cases.emplace_back(new test_mul_mat_8bit_default(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, n, 2048, {1, 1}, {1, 1}));
|
||||
} else {
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, n, 2048, {1, 1}, {1, 1}));
|
||||
}
|
||||
}
|
||||
for (int64_t n : {6, 8, 9, 21, 24}) {
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, n, 4608, {1, 1}, {1, 1}, GGML_PREC_Q4));
|
||||
}
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 6170, 13, 4608));
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, 21, 2304));
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, 8, 4160));
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 64, 13, 4608, {3, 2}, {2, 2}));
|
||||
// 4-bit src1 with broadcast: src1 rows of different magnitudes, so a wrong row, channel or sample of the src1 scales changes the result
|
||||
test_cases.emplace_back(new test_mul_mat_rows_scaled(GGML_TYPE_NVFP4, GGML_TYPE_F32, 63, 13, 4608, {3, 2}, {2, 2}));
|
||||
// 8-bit and 4-bit src1 with the weights in a WEIGHTS buffer (with PDL the kernel reads them before the wait)
|
||||
test_cases.emplace_back(new test_mul_mat (GGML_TYPE_NVFP4, GGML_TYPE_F32, 6170, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, true));
|
||||
test_cases.emplace_back(new test_mul_mat_src1_q4(GGML_TYPE_NVFP4, GGML_TYPE_F32, 6170, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, true));
|
||||
// 4-bit and 8-bit src1 with padded and permuted rows of src0 and src1
|
||||
test_cases.emplace_back(new test_mul_mat_src1_q4(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 5120));
|
||||
test_cases.emplace_back(new test_mul_mat_src1_q4(GGML_TYPE_NVFP4, GGML_TYPE_F32, 64, 13, 4608, {2, 3}, {1, 1}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat (GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 5120));
|
||||
test_cases.emplace_back(new test_mul_mat (GGML_TYPE_NVFP4, GGML_TYPE_F32, 64, 13, 4608, {2, 3}, {1, 1}, {0, 2, 1, 3}));
|
||||
// BF16 src1: 8-bit (NVFP4 value order) and 4-bit src1, contiguous and as a permuted view (rows 4*k values apart)
|
||||
for (int64_t n : {8, 13, 24}) {
|
||||
test_cases.emplace_back(new test_mul_mat (GGML_TYPE_NVFP4, GGML_TYPE_BF16, 1000, n, 4608, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat_src1_q4(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 1000, n, 4608, {1, 1}, {1, 1}));
|
||||
}
|
||||
test_cases.emplace_back(new test_mul_mat (GGML_TYPE_NVFP4, GGML_TYPE_BF16, 64, 13, 4608, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat_src1_q4(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 64, 13, 4608, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
// weight scale as a strided view: per tensor (applied in the few-row write-back) and per output channel (a separate pass)
|
||||
for (int scale_gran : {1, 2}) {
|
||||
test_cases.emplace_back(new test_mul_mat (GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, false, scale_gran, true));
|
||||
test_cases.emplace_back(new test_mul_mat_src1_q4(GGML_TYPE_NVFP4, GGML_TYPE_F32, 1000, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, false, scale_gran, true));
|
||||
}
|
||||
|
||||
#if 0
|
||||
{
|
||||
@@ -15412,9 +15536,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 4, false, false, false, true));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false, false, false, true));
|
||||
// Few columns and tiles with a long K: split-K through the stream-k fixup, the scale is applied to the partial sums
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 11, 64, 2048, false, 1, 1, false, false, false, true, { 1, 1 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 11, 64, 2048, false, 1, 1, false, false, false, true, { 1, 1 }));
|
||||
// Few columns (more than few-row MMQ takes) and tiles with a long K: split-K through the stream-k fixup, the scale is applied to the partial sums
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 32, 64, 2048, false, 1, 1, false, false, false, true, { 1, 1 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 32, 64, 2048, false, 1, 1, false, false, false, true, { 1, 1 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false, false, false, true));
|
||||
// The same with experts (~1280 tiles each): 17 tokens with broadcast input (one MMA tile per warp), 2048 tokens without (two, several column tiles per expert).
|
||||
@@ -15431,6 +15555,16 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 9, 128, 2048, false, 1, 1, false, false, true, false, { 1, 1 }));
|
||||
// on DGX Spark also the expert gate and up matmuls at 8 tokens, instead of the fused MMVQ path
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 8, 128, 2048, true, 16, 4, true));
|
||||
// NVFP4 gate and up with weight scales at 8-24 tokens: few-row MMQ, where enabled, takes each matmul with its weight scale
|
||||
for (int64_t m : {8, 13, 24}) {
|
||||
test_cases.emplace_back(new test_mul_mat_fusion (GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, m, 1000, 4096, false, 1, 1, false, false, true, true, { 1, 1 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a8 (GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, m, 1000, 4096, false, 1, 1, false, false, true, true, { 1, 1 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a4_req(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, m, 1000, 4096, false, 1, 1, false, false, true, true, { 1, 1 }));
|
||||
}
|
||||
test_cases.emplace_back(new test_mul_mat_fusion (GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 13, 64, 4096, false, 1, 1, false, false, true, true, { 3, 2 }));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a4_req(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 13, 64, 4096, false, 1, 1, false, false, true, true, { 3, 2 }));
|
||||
// 8-bit src1 with 32-row tiles and the weight scale
|
||||
test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 13, 6170, 4096, false, 1, 1, false, false, false, true, { 1, 1 }));
|
||||
// BF16 input to MUL_MAT_ID: fused gate/up + GLU on MMVF (BF16 experts with more than 512 rows) and on MMQ (broadcast input)
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_BF16, GGML_GLU_OP_SWIGLU, 1, 1024, 256, true, 16, 8, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true, false, true, false, { 4, 2 }, false, GGML_TYPE_BF16));
|
||||
|
||||
@@ -723,6 +723,81 @@ static void test_split(testing & t) {
|
||||
});
|
||||
}
|
||||
|
||||
static void test_spans(testing & t) {
|
||||
llama_vocab vocab;
|
||||
|
||||
t.test("spans_types_and_ranges", [&](testing & t) {
|
||||
batch_builder bb;
|
||||
const int32_t spans[] = { 5, 5, 2, 2, 2, 0, 9 };
|
||||
for (int i = 0; i < 7; ++i) {
|
||||
t.assert_true(bb.b.set_span(bb.add(i, {0}, true), spans[i]));
|
||||
}
|
||||
t.assert_true(bb.b.set_span_type(2, 4));
|
||||
t.assert_true(bb.b.set_attn_scope(6, 3));
|
||||
|
||||
llama_batch_allocr ba(1);
|
||||
t.assert_true(ba.init(bb.b, vocab, false));
|
||||
t.assert_true(ba.has_spans());
|
||||
|
||||
const llama_ubatch ub = ba.split_simple(8);
|
||||
const auto res = llama_ubatch_get_spans(ub);
|
||||
t.assert_equal(3u, (uint32_t) res.size());
|
||||
|
||||
const int32_t expected[3][4] = { { 5, 0, 0, 2 }, { 2, 4, 2, 5 }, { 9, 0, 6, 7 } }; // id, type, start, end
|
||||
for (size_t i = 0; i < res.size(); ++i) {
|
||||
t.assert_equal(expected[i][0], res[i].id);
|
||||
t.assert_equal(expected[i][1], res[i].type);
|
||||
t.assert_equal(expected[i][2], res[i].start);
|
||||
t.assert_equal(expected[i][3], res[i].end);
|
||||
}
|
||||
t.assert_equal(0, ub.attn_scope[0]);
|
||||
t.assert_equal(3, ub.attn_scope[6]);
|
||||
});
|
||||
|
||||
t.test("no_span", [&](testing & t) {
|
||||
batch_builder bb;
|
||||
bb.add(0, {0}, true);
|
||||
|
||||
llama_batch_allocr ba(1);
|
||||
t.assert_true(ba.init(bb.b, vocab, false));
|
||||
t.assert_true(!ba.has_spans());
|
||||
|
||||
const llama_ubatch ub = ba.split_simple(8);
|
||||
t.assert_true(ub.span == nullptr && ub.attn_scope == nullptr);
|
||||
t.assert_true(llama_ubatch_get_spans(ub).empty());
|
||||
});
|
||||
|
||||
t.test("rejects_span_in_two_runs", [&](testing & t) {
|
||||
batch_builder bb;
|
||||
const int32_t spans[] = { 1, 2, 1 };
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
bb.b.set_span(bb.add(i, {0}, true), spans[i]);
|
||||
}
|
||||
|
||||
llama_batch_allocr ba(1);
|
||||
t.assert_true(!ba.init(bb.b, vocab, false));
|
||||
});
|
||||
|
||||
t.test("rejects_span_over_two_sequences", [&](testing & t) {
|
||||
batch_builder bb;
|
||||
bb.b.set_span(bb.add(0, {0}, true), 1);
|
||||
bb.b.set_span(bb.add(0, {1}, true), 1);
|
||||
|
||||
llama_batch_allocr ba(1);
|
||||
t.assert_true(!ba.init(bb.b, vocab, false));
|
||||
});
|
||||
|
||||
t.test("rejects_invalid_args", [&](testing & t) {
|
||||
batch_builder bb;
|
||||
const int32_t idx = bb.add(0, {0}, true);
|
||||
t.assert_true(!bb.b.set_span(idx + 1, 1));
|
||||
t.assert_true(!bb.b.set_span(idx, -1));
|
||||
t.assert_true(!bb.b.set_span_type(0, 0));
|
||||
t.assert_true(!bb.b.set_span_type(1, 5));
|
||||
t.assert_true(!bb.b.set_attn_scope(idx, -1));
|
||||
});
|
||||
}
|
||||
|
||||
static void test_keep_tail(testing & t) {
|
||||
llama_vocab vocab;
|
||||
|
||||
@@ -1200,6 +1275,7 @@ int main(int argc, char ** argv) {
|
||||
t.test("mixed", test_mixed);
|
||||
t.test("compat", test_compat);
|
||||
t.test("split", test_split);
|
||||
t.test("spans", test_spans);
|
||||
t.test("keep_tail", test_keep_tail);
|
||||
t.test("mrope", test_mrope);
|
||||
t.test("mtp_embd_width", test_mtp_embd_width);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
#include "common.h"
|
||||
#include "fit.h"
|
||||
#include "llama.h"
|
||||
#include "../../src/llama-ext.h" // staging API: llama_get_embeddings_pool_span
|
||||
#include "log.h"
|
||||
#include "sampling.h"
|
||||
#include "speculative.h"
|
||||
@@ -158,8 +159,9 @@ struct server_batch {
|
||||
std::array<llama_pos, GGML_MROPE_SECTIONS> pos; // only pos[0] is used for text tokens
|
||||
bool output;
|
||||
bool is_prompt; // for stats tracking
|
||||
int32_t decision_order = 0;
|
||||
int32_t decision_group = 0;
|
||||
int32_t span = 0;
|
||||
int32_t span_type = 0;
|
||||
int32_t attn_scope = 0;
|
||||
int32_t i_embd = -1; // row in embd, -1 if this is a token
|
||||
};
|
||||
std::vector<token> tokens;
|
||||
@@ -235,14 +237,15 @@ struct server_batch {
|
||||
tokens[idx].output = output;
|
||||
}
|
||||
|
||||
void set_decision_order(int32_t idx, int32_t order) {
|
||||
void set_span(int32_t idx, int32_t span, int32_t type) {
|
||||
GGML_ASSERT(idx >= 0 && idx < (int32_t)tokens.size());
|
||||
tokens[idx].decision_order = order;
|
||||
tokens[idx].span = span;
|
||||
tokens[idx].span_type = type;
|
||||
}
|
||||
|
||||
void set_decision_group(int32_t idx, int32_t group) {
|
||||
void set_attn_scope(int32_t idx, int32_t scope) {
|
||||
GGML_ASSERT(idx >= 0 && idx < (int32_t)tokens.size());
|
||||
tokens[idx].decision_group = group;
|
||||
tokens[idx].attn_scope = scope;
|
||||
}
|
||||
|
||||
// render the sub-batch [off, off + n_tokens) into view, index i in view is index off + i here
|
||||
@@ -258,8 +261,9 @@ struct server_batch {
|
||||
} else {
|
||||
view.add(t.token, t.pos[0], t.id_slot, t.output);
|
||||
}
|
||||
view.tokens.back().decision_order = t.decision_order;
|
||||
view.tokens.back().decision_group = t.decision_group;
|
||||
view.tokens.back().span = t.span;
|
||||
view.tokens.back().span_type = t.span_type;
|
||||
view.tokens.back().attn_scope = t.attn_scope;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -541,11 +545,22 @@ struct server_slot {
|
||||
return false;
|
||||
}
|
||||
|
||||
// set the span and attn scope of the last entry from prompt token i
|
||||
void set_batch_decision(server_batch & batch, int32_t i) const {
|
||||
const auto & decision = task->decision;
|
||||
if (!decision.span.empty() && decision.span[i] != 0) {
|
||||
batch.set_span(batch.size() - 1, decision.span[i], decision.span_types[decision.span[i] - 1]);
|
||||
}
|
||||
if (!decision.attn_scope.empty()) {
|
||||
batch.set_attn_scope(batch.size() - 1, decision.attn_scope[i]);
|
||||
}
|
||||
}
|
||||
|
||||
bool can_batch_with(server_slot & other_slot) const {
|
||||
GGML_ASSERT(task);
|
||||
|
||||
// a joint decision head reads the whole batch
|
||||
if (!task->decision.order.empty() || !other_slot.task->decision.order.empty()) {
|
||||
if (!task->decision.span.empty() || !other_slot.task->decision.span.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2544,9 +2559,12 @@ private:
|
||||
return i >= 0 && i < (int32_t) idx.size() ? llama_get_embeddings_ith(slot.ctx_tgt, idx[i]) : nullptr;
|
||||
};
|
||||
|
||||
// joint head (decision model): the scores are the first rows
|
||||
for (int32_t i = 0; i < decision.n_scores; i++) {
|
||||
const float * embd = i < (int32_t) idx.size() ? llama_get_embeddings_ith(slot.ctx_tgt, idx[i]) : nullptr;
|
||||
// joint head (decision model): one score per option span
|
||||
for (size_t i = 0; i < decision.span_types.size(); i++) {
|
||||
if (decision.span_types[i] != LLAMA_POOL_SPAN_TYPE_DECISION_OPTION) {
|
||||
continue;
|
||||
}
|
||||
const float * embd = llama_get_embeddings_pool_span(slot.ctx_tgt, i + 1);
|
||||
if (embd == nullptr) {
|
||||
send_error(slot, "failed to get embeddings", ERROR_TYPE_SERVER);
|
||||
return;
|
||||
@@ -4454,12 +4472,7 @@ private:
|
||||
/* pos = */ slot.prompt.tokens.pos_next(),
|
||||
/* output = */ slot.need_embd(),
|
||||
/* is_prompt = */ true);
|
||||
if (!slot.task->decision.order.empty()) {
|
||||
batch.set_decision_order(batch.size() - 1, slot.task->decision.order[slot.prompt.n_tokens()]);
|
||||
}
|
||||
if (!slot.task->decision.group.empty()) {
|
||||
batch.set_decision_group(batch.size() - 1, slot.task->decision.group[slot.prompt.n_tokens()]);
|
||||
}
|
||||
slot.set_batch_decision(batch, slot.prompt.n_tokens());
|
||||
slot.prompt.tokens.push_back(cur_tok);
|
||||
|
||||
// break at the last user message, or at user messages at least min step past the last checkpoint
|
||||
@@ -4587,12 +4600,7 @@ private:
|
||||
/* output = */ slot.need_embd(),
|
||||
/* is_prompt = */ true);
|
||||
GGML_ASSERT(add_ok);
|
||||
if (!slot.task->decision.order.empty()) {
|
||||
batch.set_decision_order(batch.size() - 1, slot.task->decision.order[cur_token_idx]);
|
||||
}
|
||||
if (!slot.task->decision.group.empty()) {
|
||||
batch.set_decision_group(batch.size() - 1, slot.task->decision.group[cur_token_idx]);
|
||||
}
|
||||
slot.set_batch_decision(batch, cur_token_idx);
|
||||
slot.prompt.tokens.push_back(cur_tok);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#include "server-decision.h"
|
||||
|
||||
#include "../../src/llama-ext.h" // staging API: llama_decision_order
|
||||
#include "../../src/llama-ext.h" // staging API: llama_pool_span_type
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
@@ -1529,15 +1529,15 @@ void server_decision_context::fill_task_set(
|
||||
if (n_first >= task.tokens.size()) {
|
||||
throw std::runtime_error("unexpected layout of the decision prompt");
|
||||
}
|
||||
task.decision.group.assign(task.tokens.size(), 0);
|
||||
std::fill(task.decision.group.end() - n_first, task.decision.group.end(), 1);
|
||||
task.decision.attn_scope.assign(task.tokens.size(), 0);
|
||||
std::fill(task.decision.attn_scope.end() - n_first, task.decision.attn_scope.end(), 1);
|
||||
task.decision.label_pos.assign(task.decision.label_groups.size(), task.tokens.size() - 1);
|
||||
|
||||
for (size_t k = 1; k < questions.size(); k++) {
|
||||
const std::string text = (state.is_null() ? "" : D1_HEADER) + suffix(questions[k]);
|
||||
for (const llama_token token : common_tokenize(vocab, text, false, true)) {
|
||||
task.tokens.push_back(token);
|
||||
task.decision.group.push_back(k + 1);
|
||||
task.decision.attn_scope.push_back(k + 1);
|
||||
}
|
||||
|
||||
std::vector<std::string> texts;
|
||||
@@ -1627,44 +1627,52 @@ void server_decision_context::fill_task_joint(
|
||||
throw invalid;
|
||||
}
|
||||
task.tokens = process_mtmd_prompt(mctx, head, media, init_opt);
|
||||
task.decision.order.resize(task.tokens.size(), LLAMA_DECISION_ORDER_NONE);
|
||||
task.decision.span.resize(task.tokens.size(), 0);
|
||||
}
|
||||
|
||||
size_t i_question = 0;
|
||||
size_t n_scores = 0;
|
||||
for (; i_piece < pieces.size(); i_piece++) {
|
||||
std::string piece = pieces[i_piece];
|
||||
int32_t order = LLAMA_DECISION_ORDER_NONE;
|
||||
int32_t type = LLAMA_POOL_SPAN_TYPE_DEFAULT;
|
||||
if (string_starts_with(piece, CLEF_MARK_QUESTION)) {
|
||||
piece = piece.substr(CLEF_MARK_QUESTION.size());
|
||||
if (i_question >= questions.size()) {
|
||||
throw invalid;
|
||||
}
|
||||
switch (questions[i_question++].type) {
|
||||
case SERVER_DECISION_QUESTION_NOUL: order = LLAMA_DECISION_ORDER_QUESTION_NOUL; break;
|
||||
case SERVER_DECISION_QUESTION_CHOICE: order = LLAMA_DECISION_ORDER_QUESTION_CHOICE; break;
|
||||
case SERVER_DECISION_QUESTION_SCORE: order = LLAMA_DECISION_ORDER_QUESTION_SCORE; break;
|
||||
case SERVER_DECISION_QUESTION_NOUL: type = LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_NOUL; break;
|
||||
case SERVER_DECISION_QUESTION_CHOICE: type = LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_CHOICE; break;
|
||||
case SERVER_DECISION_QUESTION_SCORE: type = LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_SCORE; break;
|
||||
}
|
||||
} else if (string_starts_with(piece, CLEF_MARK_OPTION)) {
|
||||
piece = piece.substr(CLEF_MARK_OPTION.size());
|
||||
order = LLAMA_DECISION_ORDER_OPTION;
|
||||
task.decision.n_scores++;
|
||||
type = LLAMA_POOL_SPAN_TYPE_DECISION_OPTION;
|
||||
n_scores++;
|
||||
}
|
||||
|
||||
const llama_tokens piece_tokens = common_tokenize(vocab, piece, false, true);
|
||||
if (order != LLAMA_DECISION_ORDER_NONE && piece_tokens.empty()) {
|
||||
if (type != LLAMA_POOL_SPAN_TYPE_DEFAULT && piece_tokens.empty()) {
|
||||
throw std::invalid_argument("the instructions and the options of a question must not be empty");
|
||||
}
|
||||
for (const llama_token token : piece_tokens) {
|
||||
task.tokens.push_back(token);
|
||||
}
|
||||
task.decision.order.resize(task.tokens.size(), order);
|
||||
|
||||
// each question and each option is one span
|
||||
int32_t span = 0;
|
||||
if (type != LLAMA_POOL_SPAN_TYPE_DEFAULT) {
|
||||
task.decision.span_types.push_back(type);
|
||||
span = task.decision.span_types.size();
|
||||
}
|
||||
task.decision.span.resize(task.tokens.size(), span);
|
||||
}
|
||||
|
||||
size_t n_options = 0;
|
||||
for (const auto & question : questions) {
|
||||
n_options += question.options.size();
|
||||
}
|
||||
if (i_question != questions.size() || (size_t) task.decision.n_scores != n_options) {
|
||||
if (i_question != questions.size() || n_scores != n_options) {
|
||||
throw invalid;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,21 +226,21 @@ struct server_task {
|
||||
for (const int32_t marker : markers) {
|
||||
pos = pos < 0 ? marker : std::min(pos, marker);
|
||||
}
|
||||
for (size_t i = 0; i < order.size(); i++) {
|
||||
if (order[i] != 0) {
|
||||
for (size_t i = 0; i < span.size(); i++) {
|
||||
if (span[i] != 0) {
|
||||
return pos < 0 ? (int32_t) i : std::min(pos, (int32_t) i);
|
||||
}
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
// for a joint head: one value per prompt token, see llama_batch_ext_set_decision_order()
|
||||
// the scores are the first n_scores rows of the embeddings
|
||||
std::vector<int32_t> order;
|
||||
int32_t n_scores = 0;
|
||||
// joint head: span id of each prompt token, see llama_batch_ext_set_pool_span()
|
||||
std::vector<int32_t> span;
|
||||
// llama_pool_span_type of span k at index k - 1
|
||||
std::vector<int32_t> span_types;
|
||||
|
||||
// one value per prompt token, see llama_batch_ext_set_decision_group()
|
||||
std::vector<int32_t> group;
|
||||
// one value per prompt token, see llama_batch_ext_set_attn_scope()
|
||||
std::vector<int32_t> attn_scope;
|
||||
};
|
||||
decision decision;
|
||||
|
||||
@@ -264,7 +264,7 @@ struct server_task {
|
||||
case SERVER_TASK_TYPE_RERANK:
|
||||
return true;
|
||||
case SERVER_TASK_TYPE_DECISION:
|
||||
return !decision.markers.empty() || !decision.order.empty() || decision.pooled;
|
||||
return !decision.markers.empty() || !decision.span.empty() || decision.pooled;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user