Commit 08dc1cea9 for llama.cpp
commit 08dc1cea9e96f2f6fab5ba0dcb29d5f2b802090d
Author: Xuan-Son Nguyen <son@huggingface.co>
Date: Wed Dec 2 01:53:54 2026 +0100
llama : refactor decision model api (#33305)
* non-overlap version
* wip
* drop ggml_prec_set
diff --git a/common/common.cpp b/common/common.cpp
index da7657d13..9ea6b51ee 100644
--- a/common/common.cpp
+++ b/common/common.cpp
@@ -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);
}
}
diff --git a/common/common.h b/common/common.h
index 1d8d57d71..e5f4fb2af 100644
--- a/common/common.h
+++ b/common/common.h
@@ -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
};
diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp
index 3391cb49e..b13a81a97 100644
--- a/src/llama-batch.cpp
+++ b/src/llama-batch.cpp
@@ -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].span = span;
+ return true;
+}
+
+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_order = order;
+ span_types[span] = type;
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_attn_scope(int32_t idx, int32_t scope) {
+ if (idx < 0 || idx >= (int32_t) tokens.size() || scope < 0) {
return false;
}
- tokens[idx].decision_group = group;
+ 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_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_decision_group(llama_batch_ext * batch, int32_t idx, int32_t group) {
- return batch->set_decision_group(idx, group);
+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
diff --git a/src/llama-batch.h b/src/llama-batch.h
index e6f4be6a2..f46bb65df 100644
--- a/src/llama-batch.h
+++ b/src/llama-batch.h
@@ -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>;
diff --git a/src/llama-context.cpp b/src/llama-context.cpp
index 88cc05630..f6af3ac99 100644
--- a/src/llama-context.cpp
+++ b/src/llama-context.cpp
@@ -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);
}
diff --git a/src/llama-context.h b/src/llama-context.h
index 3e3921c7d..e7ababe51 100644
--- a/src/llama-context.h
+++ b/src/llama-context.h
@@ -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;
diff --git a/src/llama-ext.h b/src/llama-ext.h
index a77b2f409..2dbe9fa2d 100644
--- a/src/llama-ext.h
+++ b/src/llama-ext.h
@@ -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
+// 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);
+
+// role of a span, read by a decision head (clef, vllm-decision2)
// 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
+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
};
-// 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);
+LLAMA_API bool llama_batch_ext_set_pool_span_type(struct llama_batch_ext * batch, int32_t span, enum llama_pool_span_type type);
-// 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);
+// 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);
diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp
index 948a02ce7..f1bef630d 100644
--- a/src/llama-graph.cpp
+++ b/src/llama-graph.cpp
@@ -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);
}
diff --git a/src/llama-graph.h b/src/llama-graph.h
index a9e155012..4406399cc 100644
--- a/src/llama-graph.h
+++ b/src/llama-graph.h
@@ -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;
diff --git a/src/llama-kv-cache-dsv4.cpp b/src/llama-kv-cache-dsv4.cpp
index 9c0a9b22d..8a8e6a424 100644
--- a/src/llama-kv-cache-dsv4.cpp
+++ b/src/llama-kv-cache-dsv4.cpp
@@ -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,
};
diff --git a/src/models/clef.cpp b/src/models/clef.cpp
index 137561476..01d1589dc 100644
--- a/src/models/clef.cpp
+++ b/src/models/clef.cpp
@@ -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;
+ const auto spans = llama_ubatch_get_spans(ubatch);
+
// TODO: support multiple sequences
- bool ok = ubatch.decision_order != nullptr && ubatch.token != nullptr && ubatch.n_seqs_unq == 1;
-
- 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 });
+ 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;
}
diff --git a/src/models/models.h b/src/models/models.h
index e4bd4eb58..a8d427570 100644
--- a/src/models/models.h
+++ b/src/models/models.h
@@ -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:
diff --git a/src/models/vllm-decision2.cpp b/src/models/vllm-decision2.cpp
index a140a5297..f59db149e 100644
--- a/src/models/vllm-decision2.cpp
+++ b/src/models/vllm-decision2.cpp
@@ -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]
diff --git a/tests/test-batch-alloc.cpp b/tests/test-batch-alloc.cpp
index 49e2b0755..89ede6a82 100644
--- a/tests/test-batch-alloc.cpp
+++ b/tests/test-batch-alloc.cpp
@@ -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);
diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp
index 063eb897a..ad46ef9bc 100644
--- a/tools/server/server-context.cpp
+++ b/tools/server/server-context.cpp
@@ -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;
}
diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp
index 0db4d53c0..bfe4b4ab7 100644
--- a/tools/server/server-decision.cpp
+++ b/tools/server/server-decision.cpp
@@ -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;
}
}
diff --git a/tools/server/server-task.h b/tools/server/server-task.h
index 234cd36e1..865b4c94c 100644
--- a/tools/server/server-task.h
+++ b/tools/server/server-task.h
@@ -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;
}