Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
118 commits
Select commit Hold shift + click to select a range
5c46317
server: preemption notices, asynchronous parks and exact concurrency,…
danielhanchen Oct 13, 2026
eb1e4fe
server: preemption reservation for an aged head, rotation of any resi…
danielhanchen Oct 11, 2026
f9e79f8
server: tests for the preemption reservation, rotation, victim choice…
danielhanchen Oct 11, 2026
2457021
server: grow a pinned park buffer only with room for another state le…
danielhanchen Oct 11, 2026
6429b05
server: keep the reservation test off a CUDA decode hang past positio…
danielhanchen Oct 11, 2026
c69f0e6
server: keep the decision start in scope for the prefix reuse bound o…
danielhanchen Oct 13, 2026
83b6ca0
rpc: refuse a paged FLASH_ATTN_EXT at the server
danielhanchen Oct 13, 2026
75dabc1
kv-cache: refuse a negative restored position in exact mode instead o…
danielhanchen Oct 13, 2026
64399f3
tests: a whole-context restore is refused in exact mode through the e…
danielhanchen Oct 13, 2026
1161f59
ggml: publish the event query through the backend registry, not ggml_…
danielhanchen Oct 13, 2026
40cd744
server: do not group decision tasks on a shared prompt in exact mode
danielhanchen Oct 13, 2026
2bf0e4a
context: refuse a whole-context save in exact mode, which cannot be r…
danielhanchen Oct 13, 2026
d0d9828
server: no output for a re-prefill's last token under a backend sampler
danielhanchen Oct 13, 2026
02dcf73
server: document that requests_preempted counts parks still in transfer
danielhanchen Oct 13, 2026
b8f7b90
server: sum the preempt counters of every prompt in a merged OAI resp…
danielhanchen Oct 13, 2026
49e12b9
llama-adapter: condense the exact concurrency lora placement comment
danielhanchen Oct 13, 2026
5bfe43f
llama-context: refuse every host-placed weight outside the input laye…
danielhanchen Oct 13, 2026
eeee4d2
ggml : document the optional page table in src[5] of ggml_flash_attn_ext
danielhanchen Oct 13, 2026
3e94edf
server tests: satisfy ty in the preemption tests
danielhanchen Oct 13, 2026
19bd423
hip: follow the vec kernel's new paged parameter in the VGPR ignore list
danielhanchen Oct 13, 2026
6a42333
server tests: give the overtaken-head test a stream long enough for s…
danielhanchen Oct 13, 2026
419791c
trim and unwrap comments in the preemption change
danielhanchen Oct 13, 2026
d2b16e6
server tests: run the 24k-token rotation regression in the slow suite
danielhanchen Oct 13, 2026
f7cdcb8
server: describe preempt_ram_bytes as all host RAM held for parking
danielhanchen Oct 13, 2026
9fb7fd8
server tests: give the whole-prompt test two different prompts
danielhanchen Oct 13, 2026
24bec04
trim comments in the preemption change
danielhanchen Oct 13, 2026
e8ad1cc
server: keep the non-causal decision check in the prompt validator
danielhanchen Oct 14, 2026
2df2ed0
server: trim started slots before purging idle caches for KV pressure
danielhanchen Oct 14, 2026
c1af185
server tests: a started slot that fits once trimmed parks nobody
danielhanchen Oct 14, 2026
2f25fc9
ggml-cuda: refuse paged FLASH_ATTN_EXT shapes the paged kernel does n…
danielhanchen Oct 14, 2026
491d98c
tests: skip devices without events in test-event-query
danielhanchen Oct 14, 2026
32c6740
tests: build the server helper tests only when the server is built
danielhanchen Oct 14, 2026
8c704c6
tests: cover integrated GPUs in test-exact-buft
danielhanchen Oct 14, 2026
becae25
server: keep a resumed re-prefill's reservation until it is done
danielhanchen Oct 14, 2026
45f0067
server: do not let n_cmpl > 1 requests turn an overflow into an error…
danielhanchen Oct 14, 2026
7432429
server: do not re-size a park state the budget already refused
danielhanchen Oct 14, 2026
0edf9c8
server: do not rotate out a resident for nothing
danielhanchen Oct 14, 2026
54ac4ad
server: land in-flight restores before the last-resort park
danielhanchen Oct 14, 2026
a8eae5b
server: send the preempt record only when the server can park
danielhanchen Oct 14, 2026
ea8b7b9
server: leave a context shift to the decode when nothing can be parked
danielhanchen Oct 14, 2026
295957c
server: do not exempt a slot that has only just started
danielhanchen Oct 14, 2026
1bb7970
server: add --preempt-policy fcfs next to the cost-based victim choice
danielhanchen Oct 14, 2026
9667e05
server: resume a prompt dropped in its prefill only when it fits whole
danielhanchen Oct 14, 2026
d4531b9
server tests: check the policy in use in the fcfs tests
danielhanchen Oct 14, 2026
c2cfc8d
server: stop time-slicing residents that end by themselves
danielhanchen Oct 14, 2026
de33940
server tests: oversubscribed bounded chats are not time-sliced
danielhanchen Oct 14, 2026
317ef28
server tests: run test_preempt_models with two threads
danielhanchen Oct 14, 2026
4bdbeb1
server: resume a parked slot only into room its bounded residents wil…
danielhanchen Oct 14, 2026
8dc178b
Merge the model and backend fixes
danielhanchen Oct 14, 2026
9354766
server: under fcfs, queue a rotated-out slot behind the head it made …
danielhanchen Oct 14, 2026
cafbded
server: rotate a resident that ends by itself only if it would hold t…
danielhanchen Oct 14, 2026
323e93f
server: make fcfs the default preemption policy
danielhanchen Oct 14, 2026
f032338
Merge the fcfs default and rotation fixes
danielhanchen Oct 14, 2026
9b1a6a1
Merge b11612 into the preemption pin
danielhanchen Oct 14, 2026
e3f32b8
server: let --preempt-policy outrank the old LLAMA_SERVER_PREEMPT_POL…
danielhanchen Oct 14, 2026
f643976
llama: emit state runs without allocating, and refuse a decode width …
danielhanchen Oct 14, 2026
37254a7
Trim comments
danielhanchen Oct 14, 2026
2456bf8
server: do not hold an n>1 prompt already on cells behind a parked head
danielhanchen Oct 15, 2026
6e277f5
server: charge the rotation margin on what stays resident after it
danielhanchen Oct 15, 2026
c0e5d8e
llama, server: record the transfer fence only when a transfer is issued
danielhanchen Oct 15, 2026
abf60fd
server: do not park on a cache whose sequences do not share cells
danielhanchen Oct 15, 2026
ce0965c
server tests: warm up before timing a recompute restore
danielhanchen Oct 15, 2026
49b2552
Merge upstream b11641 into server-side preemption
danielhanchen Oct 15, 2026
bc04bd4
server: follow a slot that falls back to synchronous parks in the mar…
danielhanchen Oct 15, 2026
6355265
Merge upstream b11642 into server-side preemption
danielhanchen Oct 15, 2026
d1766cc
server: report the live async state in /props
danielhanchen Oct 15, 2026
3c7e71f
Trim comments in the preemption and exact concurrency tests
danielhanchen Oct 15, 2026
a9f9160
llama : keep branches off 32-byte boundaries on x86
danielhanchen Oct 15, 2026
3ef8b53
llama : shorten the JCC alignment comment
danielhanchen Oct 15, 2026
3a68a5c
spec : keep the per-call LiliCorr bound clear of the walk's loop header
danielhanchen Oct 15, 2026
f57ea1b
server tests: name the repeated --override-kv list apart from upstrea…
danielhanchen Oct 15, 2026
dde3e20
server: never park the oldest under fcfs, and drop a started slot tri…
danielhanchen Oct 18, 2026
51d53d5
server: let fcfs park the oldest when only it can make room for a run…
danielhanchen Oct 18, 2026
fcb5f33
server tests: give the oldest-at-the-window-end case a window long en…
danielhanchen Oct 18, 2026
833fa33
server tests: hold the window-end case until the oldest cannot share …
danielhanchen Oct 18, 2026
de519a4
server tests: run the window-end case on a 4096-cell window
danielhanchen Oct 18, 2026
18b4ec5
ci: re-run the checks on this head
danielhanchen Oct 19, 2026
2772512
server: match upstream's recv_with_timeout deadline hunk verbatim
danielhanchen Oct 21, 2026
b16f414
Merge upstream b11780 into the server-side preemption pin
danielhanchen Oct 21, 2026
baa8e92
Merge upstream b11782 into the server-side preemption pin
danielhanchen Oct 21, 2026
15b4e3b
server: never pick a TTS or realtime transcription slot to park
danielhanchen Oct 21, 2026
18365c1
Merge upstream b11793 into the server-side preemption pin
danielhanchen Oct 21, 2026
27ce31b
server: one parkable check for every victim and rotation selector
danielhanchen Oct 22, 2026
b6be4a0
cuda: claim a paged FLASH_ATTN_EXT only in the shapes the paged kerne…
danielhanchen Oct 22, 2026
88c9cce
llama : refuse a negative position as an invalid batch under exact co…
danielhanchen Oct 22, 2026
8923399
server: never give up a batch holding a realtime transcription's audi…
danielhanchen Oct 22, 2026
5149d08
tests: check both forks in test-rpc-paged-fa, send overflow prompts t…
danielhanchen Oct 22, 2026
2a2d232
ci: leave bench.yml.disabled as upstream has it
danielhanchen Oct 22, 2026
00d60d4
ggml : one mask plane on the paged FLASH_ATTN_EXT path, and no page t…
danielhanchen Oct 22, 2026
df1d0ab
common : sum the exact batch geometry in 64 bits
danielhanchen Oct 22, 2026
4e17297
server: planner accounting fixes for full-context, cache-reuse and de…
danielhanchen Oct 22, 2026
b0e8d2d
llama : exact concurrency needs the backend that carries its kernels,…
danielhanchen Oct 22, 2026
723efaa
server: preemption fixes from review
danielhanchen Oct 22, 2026
514a287
tests: a client that could not start is not an RPC refusal; use a fre…
danielhanchen Oct 22, 2026
ce0b9e4
llama : llama_memory_n_cells_used() reads occupancy from the KV cells
danielhanchen Oct 22, 2026
465da89
server: preemption fixes from review
danielhanchen Oct 22, 2026
46b88cb
common : exact concurrency refuses a draft ubatch other than the targ…
danielhanchen Oct 22, 2026
96de063
tests: tighten the exact-mode and RPC tests
danielhanchen Oct 22, 2026
2ddd0b9
server: the granularity test knob keeps the planner's estimate
danielhanchen Oct 22, 2026
8dd07ec
server tests: wait on observed progress, not on wall-clock deadlines
danielhanchen Oct 22, 2026
fdc26c6
server tests: the zero-budget park test overlaps its generations on a…
danielhanchen Oct 22, 2026
463e1af
server, llama, tests: review fixes (round 9)
danielhanchen Oct 22, 2026
8256bfb
server, llama, tests: review fixes (round 10)
danielhanchen Oct 22, 2026
ac1dbf8
server, llama: review fixes (round 11)
danielhanchen Oct 22, 2026
95ddf1f
server: preemption review fixes (round 12)
danielhanchen Oct 23, 2026
68ea605
server, llama, ggml-cuda, tools: review fixes (round 13)
danielhanchen Oct 23, 2026
c520216
llama, common, tools: review fixes (round 14)
danielhanchen Oct 23, 2026
f815b63
common, tools: flush the log on the exact concurrency refusals
danielhanchen Oct 23, 2026
9226f57
tests: preemption and RPC test robustness (round 15)
danielhanchen Oct 23, 2026
839cacc
tools, server, common: review fixes (round 16)
danielhanchen Oct 23, 2026
ef9fc2b
server tests: bound the sliding-window trim test; print the server lo…
danielhanchen Oct 23, 2026
b867ddc
common/speculative: the shared equal-block bound needs no truncation,…
danielhanchen Oct 23, 2026
a483bb9
exact : refuse self-extend, context shift and passkey position edits,…
danielhanchen Oct 23, 2026
841ba3f
server : tests establish the overlap they depend on, bound the notifi…
danielhanchen Oct 23, 2026
be076be
server : up-front prompt checks keep the order a slot meets them, the…
danielhanchen Oct 23, 2026
32abc8d
server : keep the aLoRA-set check on the server loop, out of the up-f…
danielhanchen Oct 23, 2026
d5b2f1c
exact : the decode tokens figure cannot outgrow a live context's batc…
danielhanchen Oct 23, 2026
c732f0f
Merge upstream b11838 (4231b23dc2c) into the preemption pin
danielhanchen Oct 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions common/arg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1310,6 +1310,12 @@ bool common_params_parse(int argc, char ** argv, common_params & params, llama_e
exit(0);
}
params.lr.init();

if (!common_exact_concurrency_init(ctx_arg.params)) {
common_log_flush(common_log_main()); // the refusal is logged on the logger's thread, and the tool exits next
ctx_arg.params = params_org;
return false;
}
} catch (const std::invalid_argument & ex) {
fprintf(stderr, "%s\n", ex.what());
ctx_arg.params = params_org;
Expand Down Expand Up @@ -1724,6 +1730,38 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
params.cache_ram_explicit = true;
}
).set_env("LLAMA_ARG_CACHE_RAM").set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}));
add_opt(common_arg(
{"--preempt-ram"}, "N",
string_format("with a unified KV cache, park a slot in host RAM instead of failing every slot when the cache fills; "
"N is the maximum host RAM for parked sequences in MiB (default: %d - disabled, -1 - no limit)", params.preempt_ram_mib),
[](common_params & params, int value) {
params.preempt_ram_mib = value;
}
).set_env("LLAMA_ARG_PREEMPT_RAM").set_examples({LLAMA_EXAMPLE_SERVER}));
add_opt(common_arg(
{"--preempt-async"},
{"--no-preempt-async"},
"copy a parked sequence out of and back into the KV cache on a stream of its own: the copy out "
"overlaps with the slots that keep decoding, while a copy back in, and a kv-full retry behind a "
"copy out that has not landed, wait for it (default: enabled, needs a backend that can copy "
"asynchronously, otherwise the copies are synchronous as before)",
[](common_params & params, bool value) {
params.preempt_async = value;
}
).set_env("LLAMA_ARG_PREEMPT_ASYNC").set_examples({LLAMA_EXAMPLE_SERVER}));
add_opt(common_arg(
{"--preempt-policy"}, "{fcfs,cost}",
string_format("which slot is parked when the cache fills: fcfs parks the most recently arrived request and resumes "
"in arrival order; cost parks the slot that frees the room most cheaply and never the largest generating one "
"(default: %s)", COMMON_PREEMPT_POLICY_DEFAULT),
[](common_params & params, const std::string & value) {
if (value != "fcfs" && value != "cost") {
throw std::invalid_argument("invalid value");
}
params.preempt_policy = value;
params.preempt_policy_set = true;
}
).set_env("LLAMA_ARG_PREEMPT_POLICY").set_examples({LLAMA_EXAMPLE_SERVER}));
add_opt(common_arg(
{"-kvu", "--kv-unified"},
{"-no-kvu", "--no-kv-unified"},
Expand Down
210 changes: 210 additions & 0 deletions common/common.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "ggml.h"
#include "ggml-cpp.h"
#include "ggml-backend.h"
#include "gguf.h"

#include "build-info.h"
Expand Down Expand Up @@ -1243,6 +1244,13 @@ common_gguf_info common_get_gguf_info(const std::string & fname) {

common_init_result::common_init_result(common_params & params, bool model_only) :
pimpl(new impl{}) {
// [TAG_EXACT_CONCURRENCY] Checked before any context exists, so none is created outside the explicit bound.
if (!model_only && !common_exact_concurrency_init(params)) {
COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY: refusing to load the model, see the error above\n");
common_log_flush(common_log_main()); // the logger writes on its own thread, and the caller may exit at once
return;
}

auto mparams = common_model_params_to_llama(params);
auto cparams = common_context_params_to_llama(params);

Expand Down Expand Up @@ -1291,6 +1299,12 @@ common_init_result::common_init_result(common_params & params, bool model_only)
return;
}

if (!common_exact_concurrency_model(params, model)) {
COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY: refusing to create a context, see the error above\n");
common_log_flush(common_log_main());
return;
}

const llama_vocab * vocab = llama_model_get_vocab(model);

// these decision models return a score for each token via the embeddings output
Expand Down Expand Up @@ -1376,11 +1390,19 @@ common_init_result::common_init_result(common_params & params, bool model_only)
llama_context * lctx = llama_init_from_model(model, cparams);
if (lctx == NULL) {
COM_ERR("failed to create context with model '%s'\n", params.model.path.c_str());
common_log_flush(common_log_main()); // a refused context (e.g. an exact concurrency check) is reported before the caller exits
return;
}

pimpl->context.reset(lctx);

if (!common_exact_concurrency_context(params, lctx)) {
COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY: refusing to serve this context, see the error above\n");
common_log_flush(common_log_main());
pimpl->context.reset();
return;
}

set_process_priority(params.cpuparams.priority);

pimpl->threadpools.init(lctx, params);
Expand Down Expand Up @@ -1419,6 +1441,194 @@ static void common_batch_set_zero_state(common_batch & batch, const llama_model
}
}

// [TAG_EXACT_CONCURRENCY]
bool common_exact_concurrency() {
static const bool enabled = []() {
const char * val = getenv("LLAMA_EXACT_CONCURRENCY");
return val && atoi(val) != 0;
}();

return enabled;
}

int common_exact_decode_width(const common_params & params) {
const int64_t n_slots = std::max(1, params.n_parallel);

const int64_t n_draft = std::max(0, (int) common_speculative_n_max(&params.speculative));

// the product is handed to a backend as an int; one that overflows is reported, not wrapped
const int64_t n_cols = n_slots*(1 + n_draft);

return n_cols > INT32_MAX ? -1 : (int) n_cols;
}

bool common_exact_batch_geometry(int n_batch, int n_ubatch, int n_decode_width, int * n_batch_min) {
// an unset ubatch is the whole batch, and a ubatch never exceeds it
const int n_ub = std::min(n_batch, n_ubatch <= 0 ? n_batch : n_ubatch);

// summed in 64 bits: a width near INT32_MAX must not wrap into an accepted geometry
const int64_t n_min = int64_t(n_ub) + std::max(0, n_decode_width);

if (n_batch_min) {
*n_batch_min = (int) std::min<int64_t>(n_min, INT32_MAX);
}

return n_min <= INT32_MAX && n_batch >= n_min;
}

// [TAG_EXACT_CONCURRENCY] the refusals that need the loaded model, run before a context exists
bool common_exact_concurrency_model(const common_params & params, const llama_model * model) {
if (!common_exact_concurrency() || params.mmproj.path.empty()) {
return true;
}

// The paged pool places a cell by sequence and position, and M-RoPE gives all tokens of an image one temporal position, so such batches are refused.
const llama_rope_type rope_type = llama_model_rope_type(model);

if (rope_type == LLAMA_ROPE_TYPE_MROPE || rope_type == LLAMA_ROPE_TYPE_IMROPE) {
COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY does not support M-RoPE together with a projector: the tokens of one image share a temporal position and the paged pool would give them one cell\n");
return false;
}

return true;
}

bool common_exact_concurrency_seq_copy_ok(const char * what) {
if (!common_exact_concurrency()) {
return true;
}

COM_ERR("LLAMA_EXACT_CONCURRENCY does not support %s: it copies cells between sequences, and exact concurrency gives each page "
"one owner, so every such copy is refused (llama_memory_seq_cp ignores it) and the tool would run on missing cells\n", what);

// the logger writes on its own thread and the caller exits next: without a flush the line can be lost
common_log_flush(common_log_main());

return false;
}

bool common_exact_concurrency_position_edit_ok(const char * what) {
if (!common_exact_concurrency()) {
return true;
}

COM_ERR("LLAMA_EXACT_CONCURRENCY does not support %s: it moves or rescales the positions of cached cells (llama_memory_seq_add / "
"seq_div), and a cell's page offset is its position, so every such edit is refused and the tool would decode at positions "
"its cells do not have\n", what);

common_log_flush(common_log_main());

return false;
}

bool common_exact_concurrency_init(const common_params & params) {
if (!common_exact_concurrency()) {
return true;
}

// SelfExtend (--grp-attn-n > 1) divides the positions of cached cells as the context fills
if (params.grp_attn_n > 1 && !common_exact_concurrency_position_edit_ok("self-extend (--grp-attn-n > 1)")) {
return false;
}


// DFlash and DSpark turn causal attention off on the draft context, which paged attention needs; refuse here instead of asserting in the graph.
for (const auto type : params.speculative.types) {
if (type == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || type == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) {
COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY does not support --spec-type draft-dflash or draft-dspark: both disable causal attention on the draft, which the paged attention needs\n");
return false;
}
}

// [TAG_EXACT_CONCURRENCY] A draft context splits each batch at its own ubatch size; any other size than the target's moves its splits with what else is in the batch.
const bool has_draft_ctx = params.speculative.has_dft() ||
std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_MTP) != params.speculative.types.end();
const int n_ubatch_tgt = params.n_ubatch <= 0 ? params.n_batch : std::min(params.n_batch, params.n_ubatch);

if (has_draft_ctx && params.speculative.draft.n_ubatch > 0 && params.speculative.draft.n_ubatch != n_ubatch_tgt) {
COM_ERR("LLAMA_EXACT_CONCURRENCY needs the draft context to split a batch where the target does: --spec-draft-n-ubatch %d differs from the target's ubatch of %d; drop it or set it to %d\n",
params.speculative.draft.n_ubatch, n_ubatch_tgt, n_ubatch_tgt);
return false;
}

const int n_cols = common_exact_decode_width(params);

if (n_cols < 0) {
COM_ERR("LLAMA_EXACT_CONCURRENCY: a decode step of %d slots with %d draft tokens each is too wide to report\n",
std::max(1, params.n_parallel), std::max(0, (int) common_speculative_n_max(&params.speculative)));
return false;
}

const char * bound = getenv("GGML_CUDA_BATCH_INVARIANT_MAX_COLS");
if (bound) {
const int max_cols = atoi(bound);
if (max_cols > 0 && max_cols < n_cols) {
COM_ERR("GGML_CUDA_BATCH_INVARIANT_MAX_COLS is %d but LLAMA_EXACT_CONCURRENCY needs at "
"least %d to cover a decode step of %d slots, above which a matmul is left "
"batched and its rows depend on the other rows in the ubatch. Raise it to %d, "
"set it to 0 for no bound, or unset it to let it default to %d.\n",
max_cols, n_cols, std::max(1, params.n_parallel), n_cols, n_cols);
return false;
}
}

// the batch must hold one whole ubatch beside a decode step of every slot, else a shared step changes a prompt's ubatches.
// a causal context clamps the batch to n_ctx; an unset -c is checked later by common_exact_concurrency_context().
const int n_batch_eff = params.n_ctx > 0 ? std::min(params.n_ctx, params.n_batch) : params.n_batch;

int n_batch_min = 0;

if (!common_exact_batch_geometry(n_batch_eff, params.n_ubatch, n_cols, &n_batch_min)) {
COM_ERR("LLAMA_EXACT_CONCURRENCY needs a batch of at least %d tokens for a %d-token ubatch "
"and a decode step of %d slots (%d columns), but the batch is %d: a prefill beside "
"a running slot would be split into shorter ubatches than the same prompt gets alone. "
"Raise -b to %d (and -c to at least that), or lower -ub.\n",
n_batch_min, std::min(n_batch_eff, params.n_ubatch <= 0 ? n_batch_eff : params.n_ubatch),
std::max(1, params.n_parallel), n_cols, n_batch_eff, n_batch_min);
return false;
}

// Tell the batch splitter the width of one sequence's decode step; this also covers callers that decode before creating a context.
if (!llama_set_exact_decode_tokens((uint32_t) (n_cols / std::max(1, params.n_parallel))) ||
!llama_set_exact_decode_width((uint32_t) n_cols)) {
COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY: the decode width could not be reported, see the error above\n");
return false;
}

return true;
}

bool common_exact_concurrency_context(const common_params & params, const llama_context * ctx) {
if (!common_exact_concurrency()) {
return true;
}

const int n_cols = common_exact_decode_width(params);

if (n_cols < 0) {
return false; // already reported by common_exact_concurrency_init()
}

// The context clamps the batch to n_ctx and the ubatch to the batch, and an unset -c comes from the model or the memory fit, so this is the real prefill geometry.
const int n_batch = (int) llama_n_batch(ctx);
const int n_ubatch = (int) llama_n_ubatch(ctx);

int n_batch_min = 0;

if (!common_exact_batch_geometry(n_batch, n_ubatch, n_cols, &n_batch_min)) {
COM_ERR("LLAMA_EXACT_CONCURRENCY needs a batch of at least %d tokens for a %d-token ubatch "
"and a decode step of %d slots (%d columns), but the context was created with a batch "
"of %d: a context of %d tokens clamps it, so a prefill beside a running slot would be "
"split into shorter ubatches than the same prompt gets alone. Raise -c to at least %d "
"(-fitc as well when the context was fitted to device memory), or lower -ub.\n",
n_batch_min, n_ubatch, std::max(1, params.n_parallel), n_cols, n_batch,
(int) llama_n_ctx(ctx), n_batch_min);
return false;
}

return true;
}

common_init_result_ptr common_init_from_params(common_params & params, bool model_only) {
common_init_result_ptr res(new common_init_result(params, model_only));

Expand Down
32 changes: 32 additions & 0 deletions common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@
#define COM_ERR(fmt, ...) LOG_ERR("cmn %12.*s: " fmt, 12, __func__, __VA_ARGS__)
#define COM_CNT(fmt, ...) LOG_CNT("" fmt, __VA_ARGS__)

// --preempt-policy default: "fcfs" (park the newest arrival) or "cost" (park the cheapest slot, the largest exempt)
#define COMMON_PREEMPT_POLICY_DEFAULT "fcfs"

#define die(msg) do { fputs("error: " msg "\n", stderr); exit(1); } while (0)
#define die_fmt(fmt, ...) do { fprintf(stderr, "error: " fmt "\n", __VA_ARGS__); exit(1); } while (0)

Expand Down Expand Up @@ -640,6 +643,10 @@ struct common_params {
int32_t kv_unified_per_slot = 0; // max context per parallel slot; 0 = unset
int32_t checkpoint_min_step = 8192; // minimum spacing between context checkpoints
int32_t cache_ram_mib = 8192; // -1 = no limit, 0 - disable, 1 = 1 MiB, etc.
int32_t preempt_ram_mib = 0; // host RAM for parked (preempted) sequences: 0 = preemption off (the default), -1 = no limit
bool preempt_async = true; // park and restore on a stream of their own, off the decode loop
std::string preempt_policy = COMMON_PREEMPT_POLICY_DEFAULT; // victim choice: "fcfs" or "cost"
bool preempt_policy_set = false; // --preempt-policy or LLAMA_ARG_PREEMPT_POLICY was given
bool cache_ram_explicit = false; // set by --cache-ram, decision models disable the cache otherwise

// llama-connect params
Expand Down Expand Up @@ -1012,6 +1019,31 @@ using common_init_result_ptr = std::unique_ptr<common_init_result>;

common_init_result_ptr common_init_from_params(common_params & params, bool model_only = false);

// [TAG_EXACT_CONCURRENCY] true when LLAMA_EXACT_CONCURRENCY is set for this process
bool common_exact_concurrency();

int common_exact_decode_width(const common_params & params);

// [TAG_EXACT_CONCURRENCY] Whether a batch of this shape holds a whole prompt ubatch beside a decode step of every slot, so prefills split as they would alone; n_batch_min reports the batch size that would
bool common_exact_batch_geometry(int n_batch, int n_ubatch, int n_decode_width, int * n_batch_min = nullptr);

// report that width to the CUDA backend, refusing a smaller explicit GGML_CUDA_BATCH_INVARIANT_MAX_COLS; false if the configuration must not run
bool common_exact_concurrency_init(const common_params & params);

// [TAG_EXACT_CONCURRENCY] Every tool that copies cells between sequences (llama_memory_seq_cp with src != dst) calls this before loading
// a model, for the feature that copies: exact concurrency refuses such copies, so the tool is refused instead (false, logged).
bool common_exact_concurrency_seq_copy_ok(const char * what);

// [TAG_EXACT_CONCURRENCY] As common_exact_concurrency_seq_copy_ok(), for a tool whose feature moves or rescales cached positions
// (llama_memory_seq_add / seq_div: context shift, self-extend): exact concurrency refuses those edits, so the tool is refused.
bool common_exact_concurrency_position_edit_ok(const char * what);

// the same for what only the loaded model tells: false if the model must not be served in exact mode
bool common_exact_concurrency_model(const common_params & params, const struct llama_model * model);

// the same for the geometry the created context settled on, which the context size may have clamped below what -b and -ub asked for
bool common_exact_concurrency_context(const common_params & params, const struct llama_context * ctx);

struct llama_model_params common_model_params_to_llama ( common_params & params);
struct llama_context_params common_context_params_to_llama(const common_params & params);

Expand Down
Loading
Loading