From 5c46317900392f3763753a69670618868238c976 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 02:42:33 -0700 Subject: [PATCH 001/109] server: preemption notices, asynchronous parks and exact concurrency, on b11577 The change carried by #210, applied to upstream b11577 alone (first carried on b11540 by #260). #210 sat on b10871 with Inkling merged in, so its diff carried an old #25731 and no longer composes with the nightly. --- .github/workflows/bench.yml.disabled | 6 +- common/arg.cpp | 24 + common/common.cpp | 160 ++ common/common.h | 19 + common/speculative.cpp | 11 +- ggml/include/ggml-backend.h | 6 + ggml/include/ggml-cuda.h | 3 + ggml/src/ggml-backend-impl.h | 3 + ggml/src/ggml-backend-meta.cpp | 1 + ggml/src/ggml-backend.cpp | 21 + ggml/src/ggml-blas/ggml-blas.cpp | 1 + ggml/src/ggml-cann/ggml-cann.cpp | 5 + ggml/src/ggml-cpu/ggml-cpu.cpp | 2 + ggml/src/ggml-cuda/common.cuh | 5 + ggml/src/ggml-cuda/fattn-common.cuh | 19 +- ggml/src/ggml-cuda/fattn-vec.cuh | 17 +- ggml/src/ggml-cuda/fattn.cu | 51 + ggml/src/ggml-cuda/ggml-cuda.cu | 338 ++- ggml/src/ggml-cuda/mmvq.cu | 36 +- ggml/src/ggml-cuda/mmvq.cuh | 3 + ggml/src/ggml-cuda/vendors/hip.h | 2 + ggml/src/ggml-cuda/vendors/musa.h | 2 + ggml/src/ggml-et/ggml-et.cpp | 6 + ggml/src/ggml-hexagon/ggml-hexagon.cpp | 4 +- ggml/src/ggml-metal/ggml-metal-device.m | 4 + ggml/src/ggml-metal/ggml-metal.cpp | 1 + ggml/src/ggml-opencl/ggml-opencl.cpp | 5 + ggml/src/ggml-openvino/ggml-openvino.cpp | 5 + ggml/src/ggml-rpc/ggml-rpc.cpp | 6 +- ggml/src/ggml-sycl/ggml-sycl.cpp | 4 +- ggml/src/ggml-virtgpu/ggml-backend-device.cpp | 1 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 5 + ggml/src/ggml-webgpu/ggml-webgpu.cpp | 7 + ggml/src/ggml-zdnn/ggml-zdnn.cpp | 1 + ggml/src/ggml-zendnn/ggml-zendnn.cpp | 1 + include/llama.h | 57 + src/llama-adapter.cpp | 15 + src/llama-batch.cpp | 84 +- src/llama-batch.h | 11 +- src/llama-context.cpp | 875 ++++++- src/llama-context.h | 22 + src/llama-graph.cpp | 30 +- src/llama-graph.h | 4 +- src/llama-impl.cpp | 160 ++ src/llama-impl.h | 15 + src/llama-kv-cache.cpp | 401 ++- src/llama-kv-cache.h | 39 + src/llama-memory-hybrid.cpp | 36 +- src/llama-memory-hybrid.h | 2 + src/llama-memory-recurrent.cpp | 5 +- src/llama-memory.h | 3 + tests/CMakeLists.txt | 21 + tests/test-backend-ops.cpp | 52 + tests/test-exact-buft.cpp | 60 + tests/test-exact-geometry.cpp | 55 + tests/test-exact-pages.cpp | 162 ++ tests/test-server-tokens.cpp | 184 ++ tests/test-state-restore-fragmented.cpp | 14 + tests/test-state-seq-copy.cpp | 144 ++ tools/server/README.md | 21 + tools/server/server-common.cpp | 6 + tools/server/server-common.h | 9 + tools/server/server-context.cpp | 2240 +++++++++++++++-- tools/server/server-queue.cpp | 13 +- tools/server/server-task.cpp | 52 +- tools/server/server-task.h | 24 + tools/server/tests/unit/test_preempt.py | 1094 ++++++++ .../server/tests/unit/test_preempt_notify.py | 298 +++ 68 files changed, 6766 insertions(+), 227 deletions(-) create mode 100644 tests/test-exact-buft.cpp create mode 100644 tests/test-exact-geometry.cpp create mode 100644 tests/test-exact-pages.cpp create mode 100644 tests/test-server-tokens.cpp create mode 100644 tests/test-state-seq-copy.cpp create mode 100644 tools/server/tests/unit/test_preempt.py create mode 100644 tools/server/tests/unit/test_preempt_notify.py diff --git a/.github/workflows/bench.yml.disabled b/.github/workflows/bench.yml.disabled index f2d7e16e981a..5829359ad10e 100644 --- a/.github/workflows/bench.yml.disabled +++ b/.github/workflows/bench.yml.disabled @@ -162,7 +162,7 @@ jobs: tools/server/bench/*.log - name: Commit status - uses: Sibz/github-status-action@v1 + uses: Sibz/github-status-action@faaa4d96fecf273bd762985e0e7f9f933c774918 # v1 with: authToken: ${{secrets.GITHUB_TOKEN}} sha: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} @@ -172,7 +172,7 @@ jobs: state: 'success' - name: Upload benchmark images - uses: devicons/public-upload-to-imgur@v2.2.2 + uses: devicons/public-upload-to-imgur@352cf5f2805c692539a96cfe49a09669e6fca88e # v2.2.2 continue-on-error: true # Important as it looks unstable: 503 id: imgur_step with: @@ -221,7 +221,7 @@ jobs: echo "IMAGE_3=${{ fromJSON(steps.imgur_step.outputs.imgur_urls)[3] }}" >> $GITHUB_ENV - name: Comment PR - uses: mshick/add-pr-comment@v2 + uses: mshick/add-pr-comment@b8f338c590a895d50bcbfa6c5859251edc8952fc # v2 id: comment_pr if: ${{ github.event.pull_request != '' && matrix.pr_comment_enabled == 'true' }} with: diff --git a/common/arg.cpp b/common/arg.cpp index 6bc4a84e20bf..b4ae21e4a9fe 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -1310,6 +1310,11 @@ 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)) { + ctx_arg.params = params_org; + return false; + } } catch (const std::invalid_argument & ex) { fprintf(stderr, "%s\n", ex.what()); ctx_arg.params = params_org; @@ -1723,6 +1728,25 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.cache_ram_mib = value; } ).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( {"-kvu", "--kv-unified"}, {"-no-kvu", "--no-kv-unified"}, diff --git a/common/common.cpp b/common/common.cpp index c5db228329f5..98847dce260d 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1,5 +1,6 @@ #include "ggml.h" #include "ggml-cpp.h" +#include "ggml-backend.h" #include "gguf.h" #include "build-info.h" @@ -1238,6 +1239,12 @@ 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] before any context exists, so one is never created under a figure the explicit bound does not cover + if (!model_only && !common_exact_concurrency_init(params)) { + COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY: refusing to load the model, see the error above\n"); + return; + } + auto mparams = common_model_params_to_llama(params); auto cparams = common_context_params_to_llama(params); @@ -1286,6 +1293,11 @@ 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"); + return; + } + const llama_vocab * vocab = llama_model_get_vocab(model); // these decision models return a score for each token via the embeddings output @@ -1376,6 +1388,12 @@ common_init_result::common_init_result(common_params & params, bool model_only) 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"); + pimpl->context.reset(); + return; + } + set_process_priority(params.cpuparams.priority); pimpl->threadpools.init(lctx, params); @@ -1414,6 +1432,148 @@ 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(¶ms.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); + + const int n_min = n_ub + std::max(0, n_decode_width); + + if (n_batch_min) { + *n_batch_min = n_min; + } + + return 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 from the sequence and the position alone, and M-RoPE gives every token of one image the same temporal position, so the second of them lands on the first one's cell and the batch is refused at the first image + 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_init(const common_params & params) { + if (!common_exact_concurrency()) { + return true; + } + + // DFlash drafting turns causal attention off on its draft context, which the paged attention needs; say so instead of asserting in the graph. DSpark is the same. + 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; + } + } + + 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(¶ms.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; + } + } + + // a prompt is added to a batch in whole ubatches, so a batch that cannot hold one beside a decode step of every slot would leave a prefill shorter ubatches than it gets alone, and the mode would report itself as on while a shared step changed the prompt's arithmetic + // a causal context clamps the batch to the context size, so that is the batch a prefill really gets; an unset -c is only known once the context exists, which common_exact_concurrency_context() checks + 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; + } + + // the batch splitter isolates prompts by width, so tell it how wide one sequence's decode step is; this also covers a caller that decodes 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 the context size and the ubatch to the batch, and an unset -c takes its size from the model or from the fit to device memory, so this is the geometry a prefill really gets + 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)); diff --git a/common/common.h b/common/common.h index b6683fe67100..b4f557115209 100644 --- a/common/common.h +++ b/common/common.h @@ -638,6 +638,8 @@ 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 public_path = ""; // NOLINT std::string api_prefix = ""; // NOLINT @@ -1002,6 +1004,23 @@ using common_init_result_ptr = std::unique_ptr; 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, which a prefill needs to be split into the ubatches it would get 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); + +// 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); diff --git a/common/speculative.cpp b/common/speculative.cpp index c5043a4a83e3..cfac34a5d12d 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -882,7 +882,9 @@ struct common_speculative_impl_draft_eagle3 : public common_speculative_impl { result.push_back(id); - if (params.n_max <= (int) result.size()) { + // the per-call bound comes from the caller's remaining context, so it stops the loop as well as the configured maximum + if ((params.n_max <= (int) result.size()) || + (dp.n_max > 0 && dp.n_max <= (int) result.size())) { drafting[seq_id] = false; n_drafting--; continue; @@ -1259,7 +1261,8 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const int32_t n = (int32_t) dp.pos0; - const int32_t n_draft = params.n_max; + // the caller's remaining context bounds the block as well as the configured maximum: the whole block is decoded before any truncation + const int32_t n_draft = dp.n_max > 0 ? std::min(params.n_max, dp.n_max) : params.n_max; const int32_t n_block_tokens = n_draft + (is_dspark && sample_from_anchor ? 0 : 1); i_block_beg[seq_id] = batch.size(); @@ -1762,7 +1765,9 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { dp.result_q->emplace_back(cur_p->data, cur_p->data + cur_p->size); } - if (params.n_max <= (int) result.size()) { + // the per-call bound comes from the caller's remaining context, so it stops the loop as well as the configured maximum + if ((params.n_max <= (int) result.size()) || + (dp.n_max > 0 && dp.n_max <= (int) result.size())) { drafting[seq_id] = false; n_drafting--; continue; diff --git a/ggml/include/ggml-backend.h b/ggml/include/ggml-backend.h index 7a65d8121b1c..a69226e58a77 100644 --- a/ggml/include/ggml-backend.h +++ b/ggml/include/ggml-backend.h @@ -64,6 +64,8 @@ extern "C" { GGML_API size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor); GGML_API void ggml_backend_buffer_clear (ggml_backend_buffer_t buffer, uint8_t value); GGML_API bool ggml_backend_buffer_is_host (ggml_backend_buffer_t buffer); + // whether the buffer copies a strided set of rows in one call (see ggml_backend_tensor_set_2d); without it the generic path issues one transfer per row + GGML_API bool ggml_backend_buffer_supports_2d (ggml_backend_buffer_t buffer); GGML_API void ggml_backend_buffer_set_usage (ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage); GGML_API enum ggml_backend_buffer_usage ggml_backend_buffer_get_usage (ggml_backend_buffer_t buffer); GGML_API ggml_backend_buffer_type_t ggml_backend_buffer_get_type (ggml_backend_buffer_t buffer); @@ -127,6 +129,8 @@ extern "C" { GGML_API void ggml_backend_event_free(ggml_backend_event_t event); GGML_API void ggml_backend_event_record(ggml_backend_event_t event, ggml_backend_t backend); GGML_API void ggml_backend_event_synchronize(ggml_backend_event_t event); + // non-blocking: true once everything recorded before the event has completed. Backends without a query implementation fall back to a blocking synchronize. + GGML_API bool ggml_backend_event_query(ggml_backend_event_t event); GGML_API void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event); // @@ -192,6 +196,8 @@ extern "C" { GGML_API ggml_backend_buffer_t ggml_backend_dev_buffer_from_host_ptr(ggml_backend_dev_t device, void * ptr, size_t size, size_t max_tensor_size); GGML_API bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_tensor * op); + // whether ggml_backend_event_query() on this device really is non-blocking, rather than falling back to a blocking synchronize + GGML_API bool ggml_backend_dev_supports_event_query(ggml_backend_dev_t device); GGML_API bool ggml_backend_dev_supports_buft(ggml_backend_dev_t device, ggml_backend_buffer_type_t buft); GGML_API bool ggml_backend_dev_offload_op(ggml_backend_dev_t device, const struct ggml_tensor * op); diff --git a/ggml/include/ggml-cuda.h b/ggml/include/ggml-cuda.h index 1cd81eeaebcd..897da6ca5f82 100644 --- a/ggml/include/ggml-cuda.h +++ b/ggml/include/ggml-cuda.h @@ -38,6 +38,9 @@ GGML_BACKEND_API void ggml_backend_cuda_get_device_description(int device, char GGML_BACKEND_API void ggml_backend_cuda_get_device_memory(int device, size_t * free, size_t * total); GGML_BACKEND_API bool ggml_backend_cuda_register_host_buffer(void * buffer, size_t size); + +// [TAG_EXACT_CONCURRENCY] report the widest ubatch a decode step of this process can build, so the column policy covers it; call before the first graph is computed +GGML_BACKEND_API void ggml_backend_cuda_set_exact_decode_width(int n_cols); GGML_BACKEND_API void ggml_backend_cuda_unregister_host_buffer(void * buffer); GGML_BACKEND_API ggml_backend_reg_t ggml_backend_cuda_reg(void); diff --git a/ggml/src/ggml-backend-impl.h b/ggml/src/ggml-backend-impl.h index dc7367dec4fe..121762359397 100644 --- a/ggml/src/ggml-backend-impl.h +++ b/ggml/src/ggml-backend-impl.h @@ -216,6 +216,9 @@ extern "C" { ggml_backend_event_t (*event_new) (ggml_backend_dev_t dev); void (*event_free) (ggml_backend_dev_t dev, ggml_backend_event_t event); void (*event_synchronize) (ggml_backend_dev_t dev, ggml_backend_event_t event); + + // (optional) non-blocking completion test for an event. Kept last: a missing entry is NULL and ggml_backend_event_query() then blocks instead. + bool (*event_query) (ggml_backend_dev_t dev, ggml_backend_event_t event); }; struct ggml_backend_device { diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 86748b689a8a..ea405d56e0c6 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -193,6 +193,7 @@ static const ggml_backend_device_i ggml_backend_meta_device_iface = { /* .event_new = */ nullptr, /* .event_free = */ nullptr, /* .event_synchronize = */ nullptr, + /* .event_query = */ NULL, }; static bool ggml_backend_dev_is_meta(ggml_backend_dev_t dev) { diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index ffbcba3661cf..1cbd01534f0e 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -324,6 +324,10 @@ bool ggml_backend_buffer_is_host(ggml_backend_buffer_t buffer) { return ggml_backend_buft_is_host(ggml_backend_buffer_get_type(buffer)); } +bool ggml_backend_buffer_supports_2d(ggml_backend_buffer_t buffer) { + return buffer->iface.set_tensor_2d != NULL && buffer->iface.get_tensor_2d != NULL; +} + void ggml_backend_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) { GGML_ASSERT(buffer); buffer->usage = usage; @@ -700,6 +704,18 @@ void ggml_backend_event_synchronize(ggml_backend_event_t event) { event->device->iface.event_synchronize(event->device, event); } +bool ggml_backend_event_query(ggml_backend_event_t event) { + GGML_ASSERT(event); + + if (event->device->iface.event_query == NULL) { + // no way to ask: the honest answer is to wait for it and then say yes + ggml_backend_event_synchronize(event); + return true; + } + + return event->device->iface.event_query(event->device, event); +} + void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event) { GGML_ASSERT(backend); GGML_ASSERT(backend->iface.event_wait != NULL); @@ -776,6 +792,11 @@ bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_t return device->iface.supports_op(device, op); } +bool ggml_backend_dev_supports_event_query(ggml_backend_dev_t device) { + GGML_ASSERT(device); + return device->iface.event_query != NULL; +} + bool ggml_backend_dev_supports_buft(ggml_backend_dev_t device, ggml_backend_buffer_type_t buft) { GGML_ASSERT(device); return device->iface.supports_buft(device, buft); diff --git a/ggml/src/ggml-blas/ggml-blas.cpp b/ggml/src/ggml-blas/ggml-blas.cpp index 6feb370bb5e6..8266b994b1b9 100644 --- a/ggml/src/ggml-blas/ggml-blas.cpp +++ b/ggml/src/ggml-blas/ggml-blas.cpp @@ -471,6 +471,7 @@ static const struct ggml_backend_device_i ggml_backend_blas_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; // backend reg interface diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 28e17f3f7cb6..e66b9a12b3ad 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2664,6 +2664,10 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten return true; case GGML_OP_FLASH_ATTN_EXT: { + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + if (op->src[5]) { + return false; + } #ifdef ASCEND_310P // FA not support on 310p device return false; @@ -2956,6 +2960,7 @@ static const ggml_backend_device_i ggml_backend_cann_device_interface = { /* .event_new = */ ggml_backend_cann_device_event_new, /* .event_free = */ ggml_backend_cann_device_event_free, /* .event_synchronize = */ ggml_backend_cann_device_event_synchronize, + /* .event_query = */ NULL, }; // backend reg diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index 81ff5d79fa98..42dfe86291e0 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -481,6 +481,7 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st return ggml_is_contiguous(op->src[0]); case GGML_OP_SSM_SCAN: return ggml_get_op_params_i32(op, 0) == 1 || op->src[3]->ne[0] == 1; + // [TAG_EXACT_CONCURRENCY] note: FLASH_ATTN_EXT with src[5], the page table, is deliberately still accepted: the CPU ignores it, but it is the reference test-backend-ops uses default: return true; } @@ -507,6 +508,7 @@ static const struct ggml_backend_device_i ggml_backend_cpu_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; // CPU backend - backend (reg) diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index 928607c4103b..9e1f3030294d 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -49,6 +49,11 @@ #define GGML_CUDA_CC_PASCAL 600 #define GGML_CUDA_CC_DP4A 610 // minimum compute capability for __dp4a, an intrinsic for byte-wise dot products +// [TAG_BATCH_INVARIANT] 0 = off, 1 = split every batched matmul, 2 = split only where it changes bits +int ggml_cuda_batch_invariant(); +// widest batch the split applies to, 0 = no bound; bounding it gives up prompt-phase invariance only +int ggml_cuda_batch_invariant_max_cols(); + #define GGML_CUDA_CC_VOLTA 700 #define GGML_CUDA_CC_TURING 750 #define GGML_CUDA_CC_AMPERE 800 diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 41d948335ef5..7eaa6454d4db 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -10,6 +10,12 @@ #define HALF_MAX_HALF __float2half(65504.0f/2) // Use neg. of this instead of -INFINITY to initialize KQ max vals to avoid NaN upon subtraction. #define SOFTMAX_FTZ_THRESHOLD -20.0f // Softmax exp. of values smaller than this are flushed to zero to avoid NaNs. +// [TAG_EXACT_CONCURRENCY] the page table of the paged path, which only the ordinary flash +// attention op carries: another op is free to keep a tensor of its own in the same slot +static __forceinline__ const ggml_tensor * ggml_cuda_fattn_pages(const ggml_tensor * dst) { + return dst->op == GGML_OP_FLASH_ATTN_EXT ? dst->src[5] : nullptr; +} + // log(2) = 0.6931, by adding this to the KQ maximum used for the softmax the numerical range representable // by the VKQ accumulators is effectively being shifted up by a factor of 2. // This reduces issues with numerical overflow but also causes larger values to be flushed to zero. @@ -1114,7 +1120,9 @@ void launch_fattn( // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped. // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or // multiple sequences of possibly different lengths. - const bool scan_mask = !use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1); + // [TAG_BATCH_INVARIANT] without this scan the KV loop runs to K->ne[1], which grows with the other sequences; the mask bounds it by the sequence's own extent + const bool batch_invariant_KV_max = ggml_cuda_batch_invariant() != 0; + const bool scan_mask = !use_sparse && !ggml_cuda_fattn_pages(dst) && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || batch_invariant_KV_max); if (scan_mask) { const int64_t s31 = mask->nb[1] / sizeof(half2); const int64_t s33 = mask->nb[3] / sizeof(half2); @@ -1188,6 +1196,13 @@ void launch_fattn( if (ntiles_dst % blocks_num.x != 0) { // Fixup is only needed if the SMs work on fractional tiles. dst_tmp_meta.alloc((size_t(blocks_num.x) * ncols * (2 + DV/2))); } + } else if (ggml_cuda_fattn_pages(dst) || ggml_cuda_batch_invariant()) { + // [TAG_BATCH_INVARIANT] the KV split between blocks, and so the order the partials combine in, follows K->ne[1]: pin it to one block per tile + parallel_blocks = 1; + + blocks_num.x = ntiles_x; + blocks_num.y = parallel_blocks; + blocks_num.z = ntiles_z_gqa*K->ne[2]*Q->ne[3]; } else { // parallel_blocks must not be larger than what the tensor size allows: parallel_blocks = std::min(parallel_blocks, ntiles_KV); @@ -1254,7 +1269,7 @@ void launch_fattn( V_data, mask ? ((const char *) mask->data) : nullptr, sinks ? ((const char *) sinks->data) : nullptr, - KV_max.ptr, + ggml_cuda_fattn_pages(dst) ? (const int *) ggml_cuda_fattn_pages(dst)->data : KV_max.ptr, !stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr, scale, max_bias, m0, m1, n_head_log2, logit_softcap, Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3], diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh index 57a285565913..fc35c0f6358d 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh @@ -16,7 +16,7 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpass-failed" #endif // __clang__ -template // D == head size +template // D == head size __launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) static __global__ void flash_attn_ext_vec( const char * Q_ptr, @@ -247,13 +247,24 @@ static __global__ void flash_attn_ext_vec( #endif // V_DOT2_F32_F16_AVAILABLE } - const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; + // in the paged specialization KV_max carries [count, physical page IDs...] per query; the loop and each warp's recurrence follow logical positions, never physical addresses + static_assert(!paged || ncols == 1, "paged attention has one query per block"); + const int * pages = paged ? KV_max + (sequence*int(ne01.z) + ic0)*(1 + ne11/FATTN_KQ_STRIDE) : nullptr; + const int k_VKQ_max = paged ? pages[0]*FATTN_KQ_STRIDE : (KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11); + const char * K_base = K; + const char * V_base = V; + const half * mask_base = maskh; K += blockIdx.y*nthreads * nb11; V += blockIdx.y*nthreads * nb21; maskh += blockIdx.y*nthreads; for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, - // Increment pointers after each loop: K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { + if constexpr (paged) { + const int physical = pages[1 + k_VKQ_0/FATTN_KQ_STRIDE]*FATTN_KQ_STRIDE + k_VKQ_0%FATTN_KQ_STRIDE; + K = K_base + int64_t(physical)*nb11; + V = V_base + int64_t(physical)*nb21; + maskh = mask_base + physical; + } // Calculate KQ tile and keep track of new maximum KQ values: float KQ_reg[ncols]; // KQ in registers. diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index bb34e01f3667..09ede03fecba 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -634,6 +634,11 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path. const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && K->ne[1] % FATTN_KQ_STRIDE == 0; + // [TAG_BATCH_INVARIANT] every choice below switches on Q->ne[1] or K->ne[1], both of which grow with the other sequences, so pin the kernel a batch of one would use + if (ggml_cuda_batch_invariant() && can_use_vector_kernel && Q->ne[1] == 1) { + return BEST_FATTN_KERNEL_VEC; + } + // If Turing tensor cores are available, use them: if (turing_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) { if (can_use_vector_kernel) { @@ -757,6 +762,52 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d void ggml_cuda_flash_attn_ext(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { ggml_cuda_set_device(ctx.device); + + if (const ggml_tensor * pages = ggml_cuda_fattn_pages(dst)) { + GGML_ASSERT(dst->src[0]->ne[0] == 256 && dst->src[2]->ne[0] == 256); + GGML_ASSERT(dst->src[1]->type == GGML_TYPE_F16 && dst->src[2]->type == GGML_TYPE_F16); + GGML_ASSERT(dst->src[3] && dst->src[0]->ne[3] == 1); + GGML_ASSERT(pages->type == GGML_TYPE_I32 && ggml_is_contiguous(pages)); + GGML_ASSERT(pages->ne[0] == 1 + dst->src[1]->ne[1]/FATTN_KQ_STRIDE); + GGML_ASSERT(pages->ne[1] == dst->src[0]->ne[1]); + float softcap; + memcpy(&softcap, (const float *) dst->op_params + 2, sizeof(softcap)); + GGML_ASSERT(softcap == 0.0f); + fattn_kernel_t kernel = flash_attn_ext_vec<256, 1, GGML_TYPE_F16, GGML_TYPE_F16, false, true>; + launch_fattn<256, 1, 1>(ctx, dst, kernel, 4, 0, 128, false, false, false, /*use_sparse =*/ false); + return; + } + + // [TAG_BATCH_INVARIANT] attend one query row at a time, as a batch of one would + const int fattn_max_cols = ggml_cuda_batch_invariant_max_cols(); + if (ggml_cuda_batch_invariant() && dst->src[0]->ne[1] > 1 && dst->src[0]->ne[3] == 1 && + (fattn_max_cols <= 0 || dst->src[0]->ne[1] <= fattn_max_cols)) { + const ggml_tensor * Q = dst->src[0]; + const ggml_tensor * mask = dst->src[3]; + + for (int64_t i = 0; i < Q->ne[1]; ++i) { + ggml_tensor Q_row = *Q; + Q_row.ne[1] = 1; + Q_row.data = (char *) Q->data + i*Q->nb[1]; + + ggml_tensor mask_row; + ggml_tensor dst_row = *dst; + // ne[2] runs to the end of dst so the F16 K/V scratch behind dst stays in place + dst_row.ne[2] = dst->ne[2] - i; + dst_row.data = (char *) dst->data + i*dst->nb[2]; + dst_row.src[0] = &Q_row; + if (mask) { + mask_row = *mask; + mask_row.ne[1] = 1; + mask_row.data = (char *) mask->data + i*mask->nb[1]; + dst_row.src[3] = &mask_row; + } + + ggml_cuda_flash_attn_ext(ctx, &dst_row); + } + return; + } + switch (ggml_cuda_get_best_fattn_kernel(ggml_cuda_get_device(), dst)) { case BEST_FATTN_KERNEL_NONE: GGML_ABORT("fatal error"); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 957908f65e63..85402c11cd21 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -1795,6 +1795,11 @@ static bool ggml_cuda_should_fuse_mul_mat(const ggml_tensor * ffn_up, } static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor) { + // [TAG_BATCH_INVARIANT] mul_mat+GLU is fused for a single destination column only, so leaving it on would give a solo request a different code path from a batched one + if (ggml_cuda_batch_invariant()) { + return false; + } + ggml_tensor * src0 = tensor->src[0]; ggml_tensor * src1 = tensor->src[1]; const ggml_tensor * dst = tensor; @@ -1823,6 +1828,10 @@ static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor) { } static bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) { + if (ggml_cuda_batch_invariant()) { + return false; + } + ggml_tensor * src0 = tensor->src[0]; ggml_tensor * src1 = tensor->src[1]; const ggml_tensor * dst = tensor; @@ -1903,6 +1912,223 @@ static bool ggml_cuda_match_shared_expert(const ggml_cgraph * graph, int routed_ return true; } +// [TAG_BATCH_INVARIANT] the token count picks the matmul and how its K loop is split, so the same request produces different bits. GGML_CUDA_BATCH_INVARIANT: +// 1 - compute every destination column on its own, exactly as a batch of one would +// 2 - split off only the columns whose batch-of-one configuration differs from the batched one +static bool ggml_cuda_exact_concurrency() { + static const bool exact = []() { + const char * value = getenv("LLAMA_EXACT_CONCURRENCY"); + return value && atoi(value) != 0; + }(); + return exact; +} + +int ggml_cuda_batch_invariant() { + static const int mode = []() { + if (ggml_cuda_exact_concurrency()) { return 2; } + const char * val = getenv("GGML_CUDA_BATCH_INVARIANT"); + return val ? atoi(val) : 0; + }(); + return mode; +} + +// [TAG_EXACT_CONCURRENCY] the widest decode ubatch the caller says it can build, 0 if it never said +static std::atomic g_exact_decode_width{0}; + +void ggml_backend_cuda_set_exact_decode_width(int n_cols) { + // monotonic: the widest figure ever reported stays, whatever order the reports arrive in + int cur = g_exact_decode_width.load(std::memory_order_relaxed); + + while (n_cols > cur && !g_exact_decode_width.compare_exchange_weak(cur, n_cols, std::memory_order_relaxed)) { + } +} + +int ggml_cuda_batch_invariant_max_cols() { + // [TAG_EXACT_CONCURRENCY] prompt ubatches hold one sequence, so a prefill already matches its solo run; an explicit bound always wins + static const int explicit_cols = []() { + const char * val = getenv("GGML_CUDA_BATCH_INVARIANT_MAX_COLS"); + return val ? atoi(val) : -1; + }(); + + if (explicit_cols >= 0) { + return explicit_cols; + } + + if (!ggml_cuda_exact_concurrency()) { + return 0; + } + + const int width = g_exact_decode_width.load(std::memory_order_relaxed); + + return width > 0 ? width : 16; +} + +// [TAG_EXACT_CONCURRENCY] a batch wider than the bound is left batched, so say so once. Only when nothing reported a decode width: with one, wider batches are single-sequence prefills. +static void ggml_cuda_warn_above_exact_bound(const char * op, int64_t ncols, int max_cols) { + if (!ggml_cuda_exact_concurrency()) { + return; + } + + if (g_exact_decode_width.load(std::memory_order_relaxed) > 0) { + return; + } + + static std::atomic_flag warned = ATOMIC_FLAG_INIT; + if (warned.test_and_set(std::memory_order_relaxed)) { + return; + } + + GGML_LOG_WARN("%s: LLAMA_EXACT_CONCURRENCY is set, but this %s is %d columns wide while " + "GGML_CUDA_BATCH_INVARIANT_MAX_COLS is %d, so it is left batched and its result depends " + "on the other columns in the ubatch. Raise the bound, set it to 0 for no bound, or call " + "ggml_backend_cuda_set_exact_decode_width() with the widest decode this process builds. " + "Reported once.\n", __func__, op, (int) ncols, max_cols); +} + +enum ggml_cuda_mm_path { + GGML_CUDA_MM_CUBLAS_UNSUPPORTED, + GGML_CUDA_MM_MMVF, + GGML_CUDA_MM_MMVF_TRANSPOSED, + GGML_CUDA_MM_MMF, + GGML_CUDA_MM_MMVQ, + GGML_CUDA_MM_MMQ, + GGML_CUDA_MM_CUBLAS, +}; + +static ggml_cuda_mm_path ggml_cuda_mul_mat_path( + int cc, int warp_size, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst, int64_t ne11) { + // If src0 is a temporary compute buffer it may have some padding that needs to be cleared for mul_mat_vec_q or mul_mat_q. + // But if src0 is also a view of another tensor then this cannot be done safely because it may overwrite valid tensor data. + // Therefore, in such cases use cuBLAS. + const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE + && ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && src0->view_src; + if (bad_padding_clear || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + return GGML_CUDA_MM_CUBLAS_UNSUPPORTED; + } + if (ggml_cuda_should_use_mmvf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11)) { + // The custom F16 vector kernel can be used over batched cuBLAS GEMM. + // But this is only faster for GPUs without tensor cores or with a thin src0 matrix (particularly KQV in attention) + return GGML_CUDA_MM_MMVF; + } + // A transposed vector can still use MMVQ (i.e. ne01 == 1) + if (src0->ne[1] == 1 && ne11 > MMVF_MAX_BATCH_SIZE && dst->ne[2] == 1 && dst->ne[3] == 1 + && src0->type == GGML_TYPE_F32 + && ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) + && ggml_cuda_should_use_mmvf(src1->type, cc, warp_size, src1->ne, src1->nb, /*ne11 =*/ 1)) { + return GGML_CUDA_MM_MMVF_TRANSPOSED; + } + if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11, /*mul_mat_id =*/ false)) { + return GGML_CUDA_MM_MMF; + } + if (ggml_cuda_should_use_mmvq(src0->type, cc, ne11)) { + return GGML_CUDA_MM_MMVQ; + } + if (ggml_cuda_should_use_mmq(src0->type, cc, ne11, /*n_experts =*/ 0)) { + return GGML_CUDA_MM_MMQ; + } + return GGML_CUDA_MM_CUBLAS; +} + +static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); + +// [TAG_BATCH_INVARIANT] the widest slice of columns that can be recomputed in one launch while every column still sums as a batch of one; always below ncols_dst, so the recursion ends +static int64_t ggml_cuda_mul_mat_invariant_width( + int cc, int warp_size, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst, + ggml_cuda_mm_path path_one, int64_t ncols_dst) { + if (path_one != GGML_CUDA_MM_MMVF && path_one != GGML_CUDA_MM_MMVQ) { + return 1; + } + const int64_t widest = path_one == GGML_CUDA_MM_MMVF ? MMVF_MAX_BATCH_SIZE : MMVQ_MAX_BATCH_SIZE; + for (int64_t w = std::min(ncols_dst - 1, widest); w > 1; --w) { + if (ggml_cuda_mul_mat_path(cc, warp_size, src0, src1, dst, w) != path_one) { + continue; + } + if (path_one == GGML_CUDA_MM_MMVQ && !ggml_cuda_mmvq_matches_single_column(src0->type, cc, w)) { + continue; + } + return w; + } + return 1; +} + +static bool ggml_cuda_mul_mat_split_columns( + ggml_backend_cuda_context & ctx, int cc, int warp_size, + const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + // recurrent output projections broadcast one weight matrix over sequence planes, so normalize each plane before applying the column policy + // every mode owes the caller the batch-of-one column policy, and a plane the policy never sees is left batched + if (ggml_cuda_batch_invariant() && src0->ne[2] == 1 && src0->ne[3] == 1 && + (dst->ne[2] > 1 || dst->ne[3] > 1) && + src1->ne[2] == dst->ne[2] && src1->ne[3] == dst->ne[3]) { + for (int64_t i3 = 0; i3 < dst->ne[3]; ++i3) { + for (int64_t i2 = 0; i2 < dst->ne[2]; ++i2) { + ggml_tensor src_plane = *src1; + ggml_tensor dst_plane = *dst; + src_plane.ne[2] = src_plane.ne[3] = 1; + dst_plane.ne[2] = dst_plane.ne[3] = 1; + src_plane.data = (char *) src1->data + i2*src1->nb[2] + i3*src1->nb[3]; + dst_plane.data = (char *) dst->data + i2*dst->nb[2] + i3*dst->nb[3]; + ggml_cuda_mul_mat(ctx, src0, &src_plane, &dst_plane); + } + } + return true; + } + + const int64_t ncols_dst = dst->ne[1]; + if (ncols_dst <= 1 || src1->ne[1] != ncols_dst) { + return false; + } + if (src1->ne[2] != 1 || src1->ne[3] != 1 || dst->ne[2] != 1 || dst->ne[3] != 1) { + return false; + } + const int max_cols = ggml_cuda_batch_invariant_max_cols(); + if (max_cols > 0 && ncols_dst > max_cols) { + ggml_cuda_warn_above_exact_bound("MUL_MAT", ncols_dst, max_cols); + return false; + } + + // mode 1 recomputes one column at a time; mode 2, which exact concurrency runs under, uses the widest slices that keep the batch-of-one arithmetic + int64_t width = 1; + // F32 weights go one column at a time: the predictor cannot see precision rules another pin adds to the dispatch for them + if (ggml_cuda_batch_invariant() >= 2 && src0->type != GGML_TYPE_F32) { + const ggml_cuda_mm_path path_one = ggml_cuda_mul_mat_path(cc, warp_size, src0, src1, dst, 1); + const ggml_cuda_mm_path path_batched = ggml_cuda_mul_mat_path(cc, warp_size, src0, src1, dst, ncols_dst); + if (path_one == path_batched) { + // same implementation, but it still has to sum in the same order + if (path_batched == GGML_CUDA_MM_MMVF) { + return false; // the block size follows K alone + } + if (path_batched == GGML_CUDA_MM_MMVQ && + ggml_cuda_mmvq_matches_single_column(src0->type, cc, ncols_dst)) { + return false; + } + } + width = ggml_cuda_mul_mat_invariant_width(cc, warp_size, src0, src1, dst, path_one, ncols_dst); + if (width >= ncols_dst) { + width = 1; + } + } + + for (int64_t i = 0; i < ncols_dst; i += width) { + const int64_t n = std::min(width, ncols_dst - i); + + ggml_tensor src1_col = *src1; + ggml_tensor dst_col = *dst; + + src1_col.ne[1] = n; + src1_col.nb[2] = n*src1_col.nb[1]; + src1_col.nb[3] = n*src1_col.nb[1]; + src1_col.data = (char *) src1->data + i*src1->nb[1]; + + dst_col.ne[1] = n; + dst_col.nb[2] = n*dst_col.nb[1]; + dst_col.nb[3] = n*dst_col.nb[1]; + dst_col.data = (char *) dst->data + i*dst->nb[1]; + + ggml_cuda_mul_mat(ctx, src0, &src1_col, &dst_col); + } + return true; +} + static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_TENSOR_BINARY_OP_LOCALS @@ -1910,6 +2136,13 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor return; } + // [TAG_BATCH_INVARIANT] ahead of the dispatch below, which is left as upstream wrote it so other pins that edit it still merge + if (ggml_cuda_batch_invariant() && + ggml_cuda_mul_mat_split_columns(ctx, ggml_cuda_info().devices[ctx.device].cc, + ggml_cuda_info().devices[ctx.device].warp_size, src0, src1, dst)) { + return; + } + // If src0 is a temporary compute buffer it may have some padding that needs to be cleared for mul_mat_vec_q or mul_mat_q. // But if src0 is also a view of another tensor then this cannot be done safely because it may overwrite valid tensor data. // Therefore, in such cases use cuBLAS. @@ -1958,6 +2191,22 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor ggml_cuda_mul_mat_cublas(ctx, src0, src1, dst); } +static bool ggml_cuda_mul_mat_id_splits_tokens(const ggml_tensor * dst) { + if (!ggml_cuda_batch_invariant()) { + return false; + } + const int64_t ntokens = dst->ne[2]; + if (ntokens <= 1) { + return false; + } + const int max_cols = ggml_cuda_batch_invariant_max_cols(); + if (max_cols > 0 && ntokens > max_cols) { + ggml_cuda_warn_above_exact_bound("MUL_MAT_ID", ntokens, max_cols); + return false; + } + return true; +} + // returns true when ggml_cuda_mul_mat_id takes the fallback path that requires stream synchronization // [TAG_MUL_MAT_ID_CUDA_GRAPHS] static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int cc) { @@ -1968,9 +2217,12 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c return true; } - if (dst->ne[2] <= MMVQ_MAX_BATCH_SIZE) { + // [TAG_BATCH_INVARIANT] a split node runs as ntokens single-token calls, so the path that decides whether the stream is synchronized is the single-token one + const int64_t ntokens = ggml_cuda_mul_mat_id_splits_tokens(dst) ? 1 : dst->ne[2]; + + if (ntokens <= MMVQ_MAX_BATCH_SIZE) { if (ggml_is_quantized(src0->type)) { - if (dst->ne[2] <= get_mmvq_mmid_max_batch(src0->type, cc)) { + if (ntokens <= get_mmvq_mmid_max_batch(src0->type, cc)) { return false; } } else if (GGML_CUDA_CC_IS_AMD(cc)) { @@ -1978,9 +2230,13 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c } } - if (ggml_cuda_should_use_mmq(src0->type, cc, src1->ne[2], /*n_experts=*/src0->ne[2])) { + if (ggml_cuda_should_use_mmq(src0->type, cc, ntokens, /*n_experts=*/src0->ne[2])) { return false; } + // a split node that got this far synchronizes: always correct, and leaves upstream's next check as it is + if (ntokens != src1->ne[2]) { + return true; + } if (ggml_cuda_should_use_mmf(src0->type, cc, WARP_SIZE, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { return false; @@ -1989,6 +2245,40 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c return true; } +static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst); + +// [TAG_BATCH_INVARIANT] recompute dst one token at a time: every implementation below groups the ubatch's tokens by the expert they routed to, so shapes depend on the other tokens +static void ggml_cuda_mul_mat_id_split_tokens(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + const ggml_tensor * src1 = dst->src[1]; + const ggml_tensor * ids = dst->src[2]; + + const int64_t ntokens = dst->ne[2]; + + for (int64_t i = 0; i < ntokens; ++i) { + ggml_tensor src1_token = *src1; + ggml_tensor ids_token = *ids; + ggml_tensor dst_token = *dst; + + src1_token.ne[2] = 1; + src1_token.nb[3] = src1_token.nb[2]; + src1_token.data = (char *) src1->data + i*src1->nb[2]; + + ids_token.ne[1] = 1; + ids_token.nb[2] = ids_token.nb[1]; + ids_token.nb[3] = ids_token.nb[1]; + ids_token.data = (char *) ids->data + i*ids->nb[1]; + + dst_token.ne[2] = 1; + dst_token.nb[3] = dst_token.nb[2]; + dst_token.data = (char *) dst->data + i*dst->nb[2]; + + dst_token.src[1] = &src1_token; + dst_token.src[2] = &ids_token; + + ggml_cuda_mul_mat_id(ctx, &dst_token); + } +} + static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * src0 = dst->src[0]; const ggml_tensor * src1 = dst->src[1]; @@ -2001,6 +2291,18 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + // [TAG_BATCH_INVARIANT] + if (ggml_cuda_mul_mat_id_splits_tokens(dst)) { + GGML_ASSERT(ne3 == 1 && src1->ne[3] == 1 && ids->ne[2] == 1 && ids->ne[3] == 1); + // a quantized expert matrix takes the single-token MMVQ path at every token count and can put the tokens on its sample axis in one launch; anything else goes token by token + if (ggml_is_quantized(src0->type) && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst); + return; + } + ggml_cuda_mul_mat_id_split_tokens(ctx, dst); + return; + } + // [TAG_MUL_MAT_ID_CUDA_GRAPHS] if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { static_assert(MMVQ_MAX_BATCH_SIZE == MMVF_MAX_BATCH_SIZE); @@ -3612,7 +3914,9 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph ggml_tensor * node = cgraph->nodes[i]; - if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() && + // [TAG_BATCH_INVARIANT] a fused multi-token launch cannot take the token split, and a solo run must take the batched path's kernels + if (!ggml_cuda_batch_invariant() && + node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() && ggml_cuda_match_shared_expert(cgraph, i, i + 3) && ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) { const int outputs[] = { i + 2, i + 5 }; @@ -3673,8 +3977,10 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } //topk-moe - if (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX || - cgraph->nodes[i]->op == GGML_OP_ARGSORT) { + // [TAG_BATCH_INVARIANT] the routing fusion passes its memory-range check only for a one-token ubatch, so a solo request takes the fused top-k kernel and a batched one the long chain + if (!ggml_cuda_batch_invariant() && + (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX || + cgraph->nodes[i]->op == GGML_OP_ARGSORT)) { ggml_cuda_topk_moe_args args; const bool can_fuse = ggml_cuda_topk_moe_fusion(cgraph, i, args); std::vector ops; @@ -5897,6 +6203,21 @@ static void ggml_backend_cuda_device_event_synchronize(ggml_backend_dev_t dev, g CUDA_CHECK(cudaEventSynchronize((cudaEvent_t)event->context)); } +static bool ggml_backend_cuda_device_event_query(ggml_backend_dev_t dev, ggml_backend_event_t event) { + GGML_UNUSED(dev); + + const cudaError_t err = cudaEventQuery((cudaEvent_t)event->context); + + // not an error, and nothing to clear: cudaEventQuery() returns cudaErrorNotReady without recording it, so collecting one here would consume somebody else's + if (err == cudaErrorNotReady) { + return false; + } + + CUDA_CHECK(err); + + return true; +} + static const ggml_backend_device_i ggml_backend_cuda_device_interface = { /* .get_name = */ ggml_backend_cuda_device_get_name, /* .get_description = */ ggml_backend_cuda_device_get_description, @@ -5913,6 +6234,7 @@ static const ggml_backend_device_i ggml_backend_cuda_device_interface = { /* .event_new = */ ggml_backend_cuda_device_event_new, /* .event_free = */ ggml_backend_cuda_device_event_free, /* .event_synchronize = */ ggml_backend_cuda_device_event_synchronize, + /* .event_query = */ ggml_backend_cuda_device_event_query, }; // backend reg @@ -6005,6 +6327,10 @@ static void * ggml_backend_cuda_reg_get_proc_address(ggml_backend_reg_t reg, con if (strcmp(name, "ggml_backend_comm_allreduce_tensor") == 0) { return (void *)ggml_backend_cuda_comm_allreduce_tensor; } + // [TAG_EXACT_CONCURRENCY] + if (strcmp(name, "ggml_backend_cuda_set_exact_decode_width") == 0) { + return (void *)ggml_backend_cuda_set_exact_decode_width; + } if (strcmp(name, "ggml_backend_register_host_buffer") == 0) { return (void *)ggml_backend_cuda_register_host_buffer; } diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 0714ae3bbd18..0ad0d293b37a 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -596,6 +596,20 @@ static constexpr __host__ __device__ int calc_rows_per_block(int ncols_dst, int return 1; } +// [TAG_BATCH_INVARIANT] +bool ggml_cuda_mmvq_matches_single_column(enum ggml_type type, int cc, int64_t ncols_dst) { + if (ncols_dst < 1 || ncols_dst > MMVQ_MAX_BATCH_SIZE) { + return false; + } + const mmvq_parameter_table_id table_id = get_device_table_id(cc); + if (table_id == MMVQ_PARAMETERS_GB10) { + // There nwarps also depends on the K loop trip count, which the caller does not pass in. + return ncols_dst == 1; + } + // blocks_per_iter, which assigns K blocks to threads, is proportional to nwarps; rows_per_cuda_block only changes which rows a block owns, not the order within a row + return calc_nwarps(type, 1, table_id) == calc_nwarps(type, (int) ncols_dst, table_id); +} + template __launch_bounds__(calc_nwarps(type, ncols_dst, get_device_table_id(), small_k, halve_iters)*ggml_cuda_get_physical_warp_size(), 1) static __global__ void mul_mat_vec_q( @@ -638,9 +652,10 @@ static __global__ void mul_mat_vec_q( uint32_t sample_dst; ggml_cuda_pdl_sync(); - channel_x = shared_expert ? 0 : ncols_dst == 1 && ids ? ids[channel_dst] : fastdiv(channel_dst, channel_ratio); - channel_y = ncols_dst == 1 && ids ? fastmodulo(channel_dst, nchannels_y) : channel_dst; sample_dst = blockIdx.z; + // [TAG_BATCH_INVARIANT] with ids, a sample is a token: every token goes on the z axis of one single-column launch, so each (token, expert slot) block runs the single-token configuration + channel_x = shared_expert ? 0 : ncols_dst == 1 && ids ? ids[sample_dst*ids_stride + channel_dst] : fastdiv(channel_dst, channel_ratio); + channel_y = ncols_dst == 1 && ids ? fastmodulo(channel_dst, nchannels_y) : channel_dst; const uint32_t sample_x = fastdiv(sample_dst, sample_ratio); const uint32_t sample_y = sample_dst; @@ -1451,7 +1466,11 @@ void ggml_cuda_mul_mat_vec_q( GGML_ASSERT( nb0 == ts_dst); GGML_ASSERT(!ids || ids->nb[0] == ggml_type_size(ids->type)); - GGML_ASSERT(!ids || ne12 <= MMVQ_MAX_BATCH_SIZE); + // [TAG_BATCH_INVARIANT] a multi-token MUL_MAT_ID becomes one launch of the single-token configuration with the tokens on the sample axis, so the count is not bounded by the column templates + const bool tokens_as_samples = ids && ne2 > 1 && ggml_cuda_batch_invariant(); + + GGML_ASSERT(!ids || ne12 <= MMVQ_MAX_BATCH_SIZE || tokens_as_samples); + GGML_ASSERT(!tokens_as_samples || !fusion); const float * src1_d = (const float *) src1->data; const int32_t * ids_d = ids ? (const int32_t *) ids->data : nullptr; @@ -1558,6 +1577,17 @@ void ggml_cuda_mul_mat_vec_q( const int64_t ids_stride = ids ? ids->nb[1] / ggml_type_size(ids->type) : 0; + if (tokens_as_samples) { + GGML_ASSERT(ne03 == 1 && ne13 == 1 && ne3 == 1); + // one column, one sample per token: y advances by s12 per token, dst by s2, x not at all + mul_mat_vec_q_switch_type( + src0->data, src0->type, src1_q8_1.get(), ids_d, fusion_local, dst_d, ne00, + ne01, 1, s01, stride_col_y, stride_col_dst, + ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst, + 1, ne2, s03, s12, s2, ids_stride, stream); + return; + } + mul_mat_vec_q_switch_type( src0->data, src0->type, src1_q8_1.get(), ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst, diff --git a/ggml/src/ggml-cuda/mmvq.cuh b/ggml/src/ggml-cuda/mmvq.cuh index 5605bf7a4e60..688c944c1f90 100644 --- a/ggml/src/ggml-cuda/mmvq.cuh +++ b/ggml/src/ggml-cuda/mmvq.cuh @@ -4,6 +4,9 @@ bool ggml_cuda_should_use_mmvq(enum ggml_type type, int cc, int64_t ne11); +// [TAG_BATCH_INVARIANT] true when an MMVQ launch of ncols_dst columns sums each destination element in the same order as a single-column launch, i.e. when nwarps is unchanged +bool ggml_cuda_mmvq_matches_single_column(enum ggml_type type, int cc, int64_t ncols_dst); + // Returns the maximum batch size for which MMVQ should be used for MUL_MAT_ID, // based on the quantization type and GPU architecture (compute capability). int get_mmvq_mmid_max_batch(ggml_type type, int cc); diff --git a/ggml/src/ggml-cuda/vendors/hip.h b/ggml/src/ggml-cuda/vendors/hip.h index da7e3da0b9ca..2a46db718208 100644 --- a/ggml/src/ggml-cuda/vendors/hip.h +++ b/ggml/src/ggml-cuda/vendors/hip.h @@ -58,10 +58,12 @@ #define cudaDeviceSynchronize hipDeviceSynchronize #define cudaError_t hipError_t #define cudaErrorMemoryAllocation hipErrorOutOfMemory +#define cudaErrorNotReady hipErrorNotReady #define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled #define cudaErrorPeerAccessNotEnabled hipErrorPeerAccessNotEnabled #define cudaEventCreateWithFlags hipEventCreateWithFlags #define cudaEventDisableTiming hipEventDisableTiming +#define cudaEventQuery hipEventQuery #define cudaEventRecord hipEventRecord #define cudaEventSynchronize hipEventSynchronize #define cudaEvent_t hipEvent_t diff --git a/ggml/src/ggml-cuda/vendors/musa.h b/ggml/src/ggml-cuda/vendors/musa.h index 22126decfbd8..a645c43bc85c 100644 --- a/ggml/src/ggml-cuda/vendors/musa.h +++ b/ggml/src/ggml-cuda/vendors/musa.h @@ -52,10 +52,12 @@ #define cudaDeviceGetAttribute musaDeviceGetAttribute #define cudaError_t musaError_t #define cudaErrorMemoryAllocation musaErrorMemoryAllocation +#define cudaErrorNotReady musaErrorNotReady #define cudaErrorPeerAccessAlreadyEnabled musaErrorPeerAccessAlreadyEnabled #define cudaErrorPeerAccessNotEnabled musaErrorPeerAccessNotEnabled #define cudaEventCreateWithFlags musaEventCreateWithFlags #define cudaEventDisableTiming musaEventDisableTiming +#define cudaEventQuery musaEventQuery #define cudaEventRecord musaEventRecord #define cudaEventSynchronize musaEventSynchronize #define cudaEvent_t musaEvent_t diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp index 54a6d166dcc3..cb1e39f37fc4 100644 --- a/ggml/src/ggml-et/ggml-et.cpp +++ b/ggml/src/ggml-et/ggml-et.cpp @@ -1268,6 +1268,11 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm (op->src[1]->ne[1] % op->src[4]->ne[1] == 0); break; case GGML_OP_FLASH_ATTN_EXT: + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + if (op->src[5]) { + supported = false; + break; + } if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && @@ -1686,6 +1691,7 @@ static const struct ggml_backend_device_i ggml_backend_et_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; /* diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp index a32ed59190af..a44a93f6f080 100644 --- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp +++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp @@ -9406,7 +9406,8 @@ static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, cons break; case GGML_OP_FLASH_ATTN_EXT: - supp = ggml_hexagon_supported_flash_attn_ext(sess, op); + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + supp = op->src[5] == nullptr && ggml_hexagon_supported_flash_attn_ext(sess, op); break; case GGML_OP_SET_ROWS: @@ -9519,6 +9520,7 @@ static const struct ggml_backend_device_i ggml_backend_hexagon_device_i = { /* .event_new = */ ggml_backend_hexagon_device_event_new, /* .event_free = */ ggml_backend_hexagon_device_event_free, /* .event_synchronize = */ ggml_backend_hexagon_device_event_synchronize, + /* .event_query = */ NULL, }; //** backend registry diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 13aecbdd320a..e36fb942b085 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1724,6 +1724,10 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_OP_ROLL: return ggml_is_contiguous(op->src[0]); case GGML_OP_FLASH_ATTN_EXT: + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads; walking the pool in physical order here would be silently wrong + if (op->src[5] != NULL) { + return false; + } // for new head sizes, add checks here if (op->src[0]->ne[0] != 32 && op->src[0]->ne[0] != 40 && diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 344882e044f3..191051906f80 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -833,6 +833,7 @@ static ggml_backend_device_i ggml_backend_metal_device_i = { /* .event_new = */ ggml_backend_metal_device_event_new, /* .event_free = */ ggml_backend_metal_device_event_free, /* .event_synchronize = */ ggml_backend_metal_device_event_synchronize, + /* .event_query = */ NULL, }; // backend registry diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 2abc0bc583b2..f5b7c68d8f67 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -9395,6 +9395,10 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te case GGML_OP_MEAN: return op->src[0]->type == GGML_TYPE_F32; case GGML_OP_FLASH_ATTN_EXT: { + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + if (op->src[5]) { + return false; + } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (use_fa_bin_kernels_prefill(backend_ctx, op->src[0], op->src[1], op->src[2])) { return true; @@ -13233,6 +13237,7 @@ struct ggml_backend_device_i ggml_backend_opencl_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; } diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 22b2f45e24a6..d539d1d9dd55 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1498,6 +1498,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { break; } case GGML_OP_FLASH_ATTN_EXT: { + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + if (op->src[5]) { + return {false, "FLASH_ATTN_EXT with a page table is CUDA only"}; + } float scale = 1.0f; float max_bias = 0.0f; float logit_softcap = 0.0f; @@ -1922,6 +1926,7 @@ static const struct ggml_backend_device_i ggml_backend_openvino_device_interface /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; namespace { diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index 45fa8a42d28f..da4bb1e593f2 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -2852,7 +2852,10 @@ static ggml_backend_buffer_type_t ggml_backend_rpc_device_get_buffer_type(ggml_b static bool ggml_backend_rpc_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { GGML_UNUSED(dev); - GGML_UNUSED(op); + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads; the remote end is not asked, so it is not claimed here + if (op->op == GGML_OP_FLASH_ATTN_EXT && op->src[5]) { + return false; + } //TODO: call the remote backend and cache the results return true; } @@ -2900,6 +2903,7 @@ static const struct ggml_backend_device_i ggml_backend_rpc_device_i = { /* .event_new = */ ggml_backend_rpc_device_event_new, /* .event_free = */ ggml_backend_rpc_device_event_free, /* .event_synchronize = */ ggml_backend_rpc_device_event_synchronize, + /* .event_query = */ NULL, }; // backend reg interface diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 8557c1160ccd..dcab08dcb210 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7087,7 +7087,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_SOLVE_TRI: return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; case GGML_OP_FLASH_ATTN_EXT: - return ggml_sycl_flash_attn_ext_supported(device, op); + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op); default: return false; } @@ -7193,6 +7194,7 @@ static const ggml_backend_device_i ggml_backend_sycl_device_interface = { /* .event_new = */ ggml_backend_sycl_device_event_new, /* .event_free = */ ggml_backend_sycl_device_event_free, /* .event_synchronize = */ ggml_backend_sycl_device_event_synchronize, + /* .event_query = */ NULL, }; // backend reg diff --git a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp index 987ce9dd110c..13a70c594df6 100644 --- a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp +++ b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp @@ -157,4 +157,5 @@ const ggml_backend_device_i ggml_backend_remoting_device_interface = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 05c63b64e3b6..502e5c6c32db 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -15490,6 +15490,10 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } case GGML_OP_FLASH_ATTN_EXT: { + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + if (op->src[5]) { + return false; + } bool coopmat2 = device->coopmat2; uint32_t HSK = op->src[1]->ne[0]; uint32_t HSV = op->src[2]->ne[0]; @@ -16127,6 +16131,7 @@ static const struct ggml_backend_device_i ggml_backend_vk_device_i = { /* .event_new = */ ggml_backend_vk_device_event_new, /* .event_free = */ ggml_backend_vk_device_event_free, /* .event_synchronize = */ ggml_backend_vk_device_event_synchronize, + /* .event_query = */ NULL, }; static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) { diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 3fbac9675897..b54d02ba3bfd 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -4582,6 +4582,12 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const break; case GGML_OP_FLASH_ATTN_EXT: { + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + if (op->src[5]) { + supports_op = false; + break; + } + // conservative support checks for whether the more resource-intensive shader paths // can be used, to avoid cases where flash_attn is assigned to the CPU later on supports_op = src0->type == GGML_TYPE_F32 && @@ -4836,6 +4842,7 @@ static struct ggml_backend_device_i ggml_backend_webgpu_device_i = { /* .event_new = */ ggml_backend_webgpu_device_event_new, /* .event_free = */ ggml_backend_webgpu_device_event_free, /* .event_synchronize = */ ggml_backend_webgpu_device_event_synchronize, + /* .event_query = */ NULL, }; /* End GGML Backend Device Interface */ diff --git a/ggml/src/ggml-zdnn/ggml-zdnn.cpp b/ggml/src/ggml-zdnn/ggml-zdnn.cpp index 5d1209357ff5..37e9f9aab145 100644 --- a/ggml/src/ggml-zdnn/ggml-zdnn.cpp +++ b/ggml/src/ggml-zdnn/ggml-zdnn.cpp @@ -578,6 +578,7 @@ static ggml_backend_device_i ggml_backend_zdnn_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; // diff --git a/ggml/src/ggml-zendnn/ggml-zendnn.cpp b/ggml/src/ggml-zendnn/ggml-zendnn.cpp index ec7ce233145a..89c6c36a0f19 100644 --- a/ggml/src/ggml-zendnn/ggml-zendnn.cpp +++ b/ggml/src/ggml-zendnn/ggml-zendnn.cpp @@ -781,6 +781,7 @@ static const struct ggml_backend_device_i ggml_backend_zendnn_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, + /* .event_query = */ NULL, }; // backend reg interface diff --git a/include/llama.h b/include/llama.h index 6f76c819f854..505f0bd4a441 100644 --- a/include/llama.h +++ b/include/llama.h @@ -820,6 +820,22 @@ extern "C" { // Check if the memory supports shifting LLAMA_API bool llama_memory_can_shift(llama_memory_t mem); + // [TAG_EXACT_CONCURRENCY] cells the memory allocates in one indivisible block: 1 ordinarily, larger where a mode places cells in blocks + // n contiguous tokens then occupy round_up(n, granularity) cells; a sequence left with holes still holds every block one live cell is in + LLAMA_API uint32_t llama_memory_alloc_granularity(llama_memory_t mem); + + // [TAG_PREEMPT] run the in-place update a seq_add() recorded, which llama_decode() would otherwise run at the start of the next batch + // takes the context because the update is a graph; returns true when one was run + LLAMA_API bool llama_memory_update(struct llama_context * ctx); + + // [TAG_EXACT_CONCURRENCY] the most tokens one sequence contributes to a decode step: 1, or 1 plus the draft length. Never lowered; false when a column bound cannot cover it. + LLAMA_API bool llama_set_exact_decode_tokens(uint32_t n_tokens); + LLAMA_API uint32_t llama_exact_decode_tokens(void); + + // [TAG_EXACT_CONCURRENCY] the widest decode ubatch this process can build, in columns; never lowered, and false when GGML_CUDA_BATCH_INVARIANT_MAX_COLS is below it + LLAMA_API bool llama_set_exact_decode_width(uint32_t n_cols); + LLAMA_API uint32_t llama_exact_decode_width(void); + // // State / sessions // @@ -952,6 +968,47 @@ extern "C" { llama_seq_id dest_seq_id, llama_state_seq_flags flags); + // [TAG_STATE_ASYNC] asynchronous per-sequence state transfer, polled with llama_state_seq_copy_done(). + // Until it completes the caller must not touch the buffer, free the cells read, or decode what is written. + struct llama_state_seq_copy; + + // NULL when the backends cannot copy asynchronously, or cannot say whether a copy has finished without waiting for it; the caller then uses the synchronous calls + // Also NULL for a recurrent or hybrid model: its states move between rows on every decode, so a transfer beside a decode can read another sequence + LLAMA_API struct llama_state_seq_copy * llama_state_seq_copy_init(struct llama_context * ctx); + LLAMA_API void llama_state_seq_copy_free(struct llama_state_seq_copy * cpy); + + // size the transfer's host buffer, keeping no contents; NULL on failure. Grow-only: page-locking is far too slow to redo per transfer, so only llama_state_seq_copy_buf_free() frees it. + LLAMA_API uint8_t * llama_state_seq_copy_buf_resize (struct llama_state_seq_copy * cpy, size_t size); + LLAMA_API uint8_t * llama_state_seq_copy_buf (struct llama_state_seq_copy * cpy); + LLAMA_API size_t llama_state_seq_copy_buf_size (struct llama_state_seq_copy * cpy); + LLAMA_API size_t llama_state_seq_copy_buf_capacity(struct llama_state_seq_copy * cpy); + LLAMA_API void llama_state_seq_copy_buf_free (struct llama_state_seq_copy * cpy); + + // true when the buffer held right now is page-locked. False while no buffer is held: ask llama_state_seq_copy_buf_can_pin() instead. + LLAMA_API bool llama_state_seq_copy_buf_is_pinned(struct llama_state_seq_copy * cpy); + + LLAMA_API bool llama_state_seq_copy_buf_can_pin(struct llama_state_seq_copy * cpy); + + // issue the copies; the bytes covered, 0 on failure. size must be within llama_state_seq_copy_buf_size(), and LLAMA_STATE_SEQ_FLAGS_ON_DEVICE is refused. + LLAMA_API size_t llama_state_seq_copy_get( + struct llama_state_seq_copy * cpy, + size_t size, + llama_seq_id seq_id, + llama_state_seq_flags flags); + + LLAMA_API size_t llama_state_seq_copy_set( + struct llama_state_seq_copy * cpy, + size_t size, + llama_seq_id dest_seq_id, + llama_state_seq_flags flags); + + LLAMA_API size_t llama_state_seq_copy_n_copies(struct llama_state_seq_copy * cpy); + + LLAMA_API int64_t llama_state_seq_copy_sync_us(struct llama_state_seq_copy * cpy); + + LLAMA_API bool llama_state_seq_copy_done(struct llama_state_seq_copy * cpy); + LLAMA_API void llama_state_seq_copy_wait(struct llama_state_seq_copy * cpy); + // // Decoding // diff --git a/src/llama-adapter.cpp b/src/llama-adapter.cpp index 6a7ffd6a61da..e8175539533e 100644 --- a/src/llama-adapter.cpp +++ b/src/llama-adapter.cpp @@ -358,6 +358,21 @@ static void llama_adapter_lora_init_impl(llama_model & model, FILE * file, llama LLAMA_LOG_DEBUG("%s: lora for '%s' -> '%s'\n", __func__, model_tensor->name, ggml_backend_buft_name(buft)); + // [TAG_EXACT_CONCURRENCY] the adapter follows the weight it adapts, so a weight the mode + // leaves on the host puts the adapted matmul there too. token_embd is exempt from the + // context's weight check because get_rows is not offloaded by width, but its adapter is + // applied with a mul_mat, which is: see llm_graph_context::build_inp_embd(). + if (llama_exact_concurrency() && !llama_exact_buft_invariant(buft)) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but the lora for '%s' would sit in a %s " + "buffer, which has no batch-invariant kernels: the adapted matmul's result would " + "depend on how many sequences share the step (move the tensor to the device that " + "holds the layers, for example --override-tensor %s=CUDA0, or serve this adapter " + "without the mode)\n", + __func__, model_tensor->name, ggml_backend_buft_name(buft), model_tensor->name); + + throw std::runtime_error("exact concurrency: a lora weight is not on the CUDA backend"); + } + ggml_context * dev_ctx = ctx_for_buft(buft); // validate tensor shape if (is_token_embd) { diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index 3c4b52008646..26b60fbc986a 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -616,7 +616,54 @@ llama_ubatch llama_batch_allocr::split_simple(uint32_t n_ubatch) { return ubatch_add(idxs, idxs.size(), false); } -llama_ubatch llama_batch_allocr::split_equal(uint32_t n_ubatch, bool sequential, uint32_t n_keep_tail) { +bool llama_batch_allocr::has_shared_tokens() const { + for (int32_t i = 0; i < batch.n_tokens; ++i) { + if (batch.n_seq_id[i] > 1) { + return true; + } + } + + return false; +} + +bool llama_batch_allocr::has_repeated_positions() const { + std::vector n_per_seq(n_seq_max, 0); + + for (int32_t i = 0; i < batch.n_tokens; ++i) { + for (int32_t s = 0; s < batch.n_seq_id[i]; ++s) { + n_per_seq[batch.seq_id[i][s]]++; + } + } + + for (uint32_t s = 0; s < n_seq_max; ++s) { + if (n_per_seq[s] > seq_pos[s].size()) { + return true; + } + } + + return false; +} + +bool llama_batch_allocr::has_seq_wider_than(uint32_t n_tokens) const { + std::vector n_per_seq(n_seq_max, 0); + + for (int32_t i = 0; i < batch.n_tokens; ++i) { + // tokens already placed in an earlier ubatch do not make the rest of the batch a prompt + if (used[i]) { + continue; + } + + for (int32_t s = 0; s < batch.n_seq_id[i]; ++s) { + if (++n_per_seq[batch.seq_id[i][s]] > n_tokens) { + return true; + } + } + } + + return false; +} + +llama_ubatch llama_batch_allocr::split_equal(uint32_t n_ubatch, bool sequential, uint32_t n_keep_tail, uint32_t isolate_seqs_above) { if (sequential && has_cpl) { LLAMA_LOG_ERROR("%s: sequential split is not supported when there are coupled sequences in the input batch (you may need to use the -kvu flag)\n", __func__); @@ -627,6 +674,9 @@ llama_ubatch llama_batch_allocr::split_equal(uint32_t n_ubatch, bool sequential, llama_seq_id last_seq_id = -1; + // [TAG_EXACT_CONCURRENCY] tokens left in the first set taken, when isolating: only sets with the same count join it, so every set in the ubatch finishes in it + uint32_t n_left_first = 0; + // determine the non-overlapping sequence sets participating in this ubatch for (int32_t i = 0; i < batch.n_tokens; ++i) { if (used[i]) { @@ -649,6 +699,38 @@ llama_ubatch llama_batch_allocr::split_equal(uint32_t n_ubatch, bool sequential, } if (add) { + // [TAG_EXACT_CONCURRENCY] a set with more tokens left than a decode step carries is a prompt and gets a ubatch of its own; grouped sets need equal tokens left, or the expansion below changes their sum order + if (isolate_seqs_above > 0) { + uint32_t n_left = 0; + + for (const auto idx : seq_set_map[seq_set[i]]) { + if (!used[idx]) { + ++n_left; + } + } + + if (n_left > isolate_seqs_above) { + if (!cur_seq_set.empty()) { + // let the sets already taken have this ubatch; the prompt gets the next one + break; + } + + cur_seq_set.push_back(seq_set[i]); + + last_seq_id = batch.seq_id[i][0]; + + break; + } + + if (cur_seq_set.empty()) { + n_left_first = n_left; + } else if (n_left != n_left_first) { + continue; + } else if ((cur_seq_set.size() + 1) * n_left_first > n_ubatch) { + break; + } + } + cur_seq_set.push_back(seq_set[i]); last_seq_id = batch.seq_id[i][0]; diff --git a/src/llama-batch.h b/src/llama-batch.h index e1e43979b540..a728a4b057a1 100644 --- a/src/llama-batch.h +++ b/src/llama-batch.h @@ -183,7 +183,16 @@ class llama_batch_allocr { // make ubatches of equal-length sequences sets // if sequential == true, the tokens in the ubatch will have increasing sequential sequence ids // n_keep_tail = minimum trailing tokens of a seq that must land in the same ubatch - llama_ubatch split_equal(uint32_t n_ubatch, bool sequential, uint32_t n_keep_tail); + // isolate_seqs_above = [TAG_EXACT_CONCURRENCY] when > 0, a sequence set with more than this many tokens left is a prompt and gets a ubatch of its own + llama_ubatch split_equal(uint32_t n_ubatch, bool sequential, uint32_t n_keep_tail, uint32_t isolate_seqs_above = 0); + + // [TAG_EXACT_CONCURRENCY] true if some sequence still has more than n_tokens left to place, i.e. what remains of the batch holds a prompt + bool has_seq_wider_than(uint32_t n_tokens) const; + + bool has_shared_tokens() const; + + // [TAG_EXACT_CONCURRENCY] true if a sequence has several tokens at one position, which the paged pool would give one cell + bool has_repeated_positions() const; // sequence-set-wise split - each ubatch contains a single sequence-set // TODO: extend to support multiple _full_ sequences in the ubatch diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 231b34dc28af..81c40c9dbc29 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -14,6 +14,7 @@ #include "llama-sampler.h" #include "llama.h" +#include #include #include #include @@ -117,6 +118,52 @@ static llm_graph_type ctx_type_to_graph_type(llama_context_type ctx_type) { throw std::runtime_error("Unsupported ctx type"); } +// [TAG_EXACT_CONCURRENCY] the caches check where the KV lives; this checks the weights. Every per-layer weight and the output head must sit on a backend with the mode's kernels, else a sequence's own matmuls change with the width of the step it shares. +// token_embd is exempt: it feeds GET_ROWS, a per-row copy that reports a batch size of 0 to the offload test, so it stays put at every width. A tied head is that same tensor and model.output points at it, so the head check covers it; a lora on it runs as MUL_MAT, which llama_adapter_lora_init_impl() refuses on a host buffer. +static void llama_exact_check_weights(const llama_model & model) { + auto host_buft = [](const ggml_tensor * t) -> ggml_backend_buffer_type_t { + if (!t || !t->buffer) { + return nullptr; + } + + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(t->buffer); + + return llama_exact_buft_invariant(buft) ? nullptr : buft; + }; + + auto refuse = [&model](const char * name, ggml_backend_buffer_type_t buft, const char * what) { + const std::string tname = name; + + const char * fix = "pass -ngl to offload every layer, and no --override-tensor that keeps one on the host"; + + if (tname.find("_exps") != std::string::npos) { + fix = "do not pass --cpu-moe or --n-cpu-moe, and no --override-tensor that keeps an expert on the host"; + } else if (model.has_tensor_overrides()) { + fix = "drop the --override-tensor that placed it there, and pass -ngl to offload every layer"; + } + + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but %s %s is in a %s buffer, which has no " + "batch-invariant kernels: its result would depend on how many sequences share the step (%s)\n", + __func__, what, tname.c_str(), ggml_backend_buft_name(buft), fix); + + throw std::runtime_error("exact concurrency: a weight is not on the CUDA backend"); + }; + + for (const auto & [name, t] : model.tensors_by_name) { + if (name.rfind("blk.", 0) != 0) { + continue; + } + + if (auto * buft = host_buft(t)) { + refuse(name.c_str(), buft, "layer weight"); + } + } + + if (auto * buft = host_buft(model.output)) { + refuse(ggml_get_name(model.output), buft, "the output head"); + } +} + struct llm_fused_op_probe { llm_fused_op op; const char * name; @@ -188,6 +235,17 @@ llama_context::llama_context( throw std::runtime_error("n_seq_max must be <= " + std::to_string(LLAMA_MAX_SEQ)); } + // [TAG_EXACT_CONCURRENCY] the widest decode step this context can build, reported so a backend that splits columns covers it; reported at the end of the constructor + if (llama_exact_concurrency()) { + if (!llama_exact_check_n_seq(cparams.n_seq_max)) { + throw std::runtime_error("exact concurrency: the explicit column bound is below this context's decode width"); + } + + if (!hparams.vocab_only) { + llama_exact_check_weights(model); + } + } + cparams.n_rs_seq = params.n_rs_seq; if (cparams.n_rs_seq > 0 && !llm_arch_supports_rs_rollback(model.arch)) { LLAMA_LOG_DEBUG("%s: n_rs_seq=%u requested but model does not support recurrent partial rollback; clamping to 0\n", @@ -482,6 +540,12 @@ llama_context::llama_context( }; memory.reset(model.create_memory(params_mem, cparams)); + + // [TAG_EXACT_CONCURRENCY] the paged attention is causal, so a non-causal context with a cache would assert on its first graph + if (llama_exact_concurrency() && memory && !cparams.causal_attn) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set and this context has a KV cache, so it cannot be created with non-causal attention\n", __func__); + throw std::runtime_error("exact concurrency: non-causal attention is not supported with a KV cache"); + } } // init backends @@ -570,12 +634,24 @@ llama_context::llama_context( sampling.token_ids_full_vocab[i] = i; } } + + // [TAG_EXACT_CONCURRENCY] nothing above can fail now, so publish the width; a refusal here means the bound moved + if (llama_exact_concurrency() && !llama_exact_report_n_seq(cparams.n_seq_max)) { + throw std::runtime_error("exact concurrency: the explicit column bound is below this context's decode width"); + } } llama_context::~llama_context() { // wait for any pending asynchronous copies into the output buffers before they are freed synchronize(); + // a transfer still alive is drained first: synchronize() covers the graph backends, not the copy backend a transfer owns, and its KV buffers are about to go + state_seq_copies_drain(); + + for (auto & it : state_copy_fences) { + ggml_backend_event_free(it.second); + } + // when training, ggml_opt allocates extra buffers through the scheduler, so the sizes no longer match the expectation if (!model.hparams.no_alloc && !opt_ctx) { for (size_t i = 0; i < backend_ptrs.size(); ++i) { @@ -1361,6 +1437,11 @@ void llama_context::set_causal_attn(bool value) { return; } + if (!value && memory && llama_exact_concurrency()) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set and this context has a KV cache, so causal attention cannot be turned off; the change is refused\n", __func__); + return; + } + cparams.causal_attn = value; // no scheduler reserve needed because graph shapes must not depend on causal_attn, a flip only rebuilds the graph @@ -1759,6 +1840,10 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } } + if (!state_copy_fences.empty()) { + state_seq_copy_fence(); + } + return 0; } @@ -1877,6 +1962,12 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -1; } + // [TAG_EXACT_CONCURRENCY] an invalid batch, not a full cache: left to the memory it came back as 1, which callers retry + if (llama_exact_concurrency() && (balloc->has_shared_tokens() || balloc->has_repeated_positions())) { + LLAMA_LOG_ERROR("%s: exact concurrency needs every token at one sequence id and one position of its own\n", __func__); + return -1; + } + const uint32_t n_tokens_all = balloc->get_n_tokens(); const uint32_t n_outputs_all = balloc->get_n_outputs(); @@ -2213,6 +2304,10 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // wait for the computation to finish (automatically done when obtaining the model output) //synchronize(); + if (!state_copy_fences.empty()) { + state_seq_copy_fence(); + } + return 0; } @@ -2896,16 +2991,132 @@ class llama_io_write_dummy : public llama_io_write_i { size_t size_written = 0; }; +// [TAG_STATE_COALESCE] one transfer per run of cells, not one per cell; the restore side asks for one per cell, and the transposed V layout repeats every run once per row +template +static size_t llama_io_run_end(const std::vector & infos, size_t i) { + size_t end = i + 1; + + while (end < infos.size() && + infos[end].tensor == infos[end - 1].tensor && + infos[end].offset == infos[end - 1].offset + infos[end - 1].size && + infos[end].ptr == infos[end - 1].ptr + infos[end - 1].size) { + end++; + } + + return end; +} + +template +static size_t llama_io_run_size(const std::vector & infos, size_t i, size_t end) { + size_t size = 0; + + for (size_t j = i; j < end; ++j) { + size += infos[j].size; + } + + return size; +} + +// [TAG_STATE_COALESCE] a comb of equal runs at a constant stride is one strided copy: sequences sharing a unified cache take their cells in turn +template +static void llama_io_emit(const std::vector & infos, size_t first, size_t last, emit_t emit) { + std::vector> runs; + + for (size_t i = first; i < last; ) { + const size_t end = llama_io_run_end(infos, i); + + runs.emplace_back(i, end); + + i = end; + } + + for (size_t r = 0; r < runs.size(); ) { + const auto & head = infos[runs[r].first]; + + const size_t size = llama_io_run_size(infos, runs[r].first, runs[r].second); + + size_t n_copies = 1; + size_t stride_tensor = 0; + size_t stride_data = 0; + + if (r + 1 < runs.size()) { + const auto & next = infos[runs[r + 1].first]; + + if (next.tensor == head.tensor && next.offset > head.offset && next.ptr > head.ptr && + llama_io_run_size(infos, runs[r + 1].first, runs[r + 1].second) == size) { + stride_tensor = next.offset - head.offset; + stride_data = (size_t) (next.ptr - head.ptr); + + // a strided copy may not have its rows overlap, on either side + if (stride_tensor >= size && stride_data >= size) { + while (r + n_copies < runs.size()) { + const auto & cur = infos[runs[r + n_copies].first]; + + if (cur.tensor != head.tensor || + cur.offset != head.offset + n_copies * stride_tensor || + cur.ptr != head.ptr + n_copies * stride_data || + llama_io_run_size(infos, runs[r + n_copies].first, runs[r + n_copies].second) != size) { + break; + } + + n_copies++; + } + } + } + } + + emit(head.tensor, head.ptr, head.offset, size, n_copies, stride_tensor, stride_data); + + r += n_copies; + } +} + +// a null backend means the caller wants the copy to have happened by the time this returns +static void llama_io_get(ggml_backend_t backend, ggml_tensor * tensor, void * ptr, + size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { + if (n_copies > 1) { + if (backend) { + ggml_backend_tensor_get_2d_async(backend, tensor, ptr, offset, size, n_copies, stride_tensor, stride_data); + } else { + ggml_backend_tensor_get_2d(tensor, ptr, offset, size, n_copies, stride_tensor, stride_data); + } + } else if (backend) { + ggml_backend_tensor_get_async(backend, tensor, ptr, offset, size); + } else { + ggml_backend_tensor_get(tensor, ptr, offset, size); + } +} + +static void llama_io_set(ggml_backend_t backend, ggml_tensor * tensor, const void * ptr, + size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { + if (n_copies > 1) { + if (backend) { + ggml_backend_tensor_set_2d_async(backend, tensor, ptr, offset, size, n_copies, stride_tensor, stride_data); + } else { + ggml_backend_tensor_set_2d(tensor, ptr, offset, size, n_copies, stride_tensor, stride_data); + } + } else if (backend) { + ggml_backend_tensor_set_async(backend, tensor, ptr, offset, size); + } else { + ggml_backend_tensor_set(tensor, ptr, offset, size); + } +} + class llama_io_write_host : public llama_io_write_i { public: llama_io_write_host( uint8_t * p, size_t len) : ptr(p), buf_size(len) {} ~llama_io_write_host() { - // TODO: add backend support to batch tensor_get? or some other way to speed this up - for (const auto & winfo : winfos) { - ggml_backend_tensor_get(winfo.tensor, winfo.ptr, winfo.offset, winfo.size); + if (deferred) { + return; // [TAG_STATE_ASYNC] the derived class posts the copies itself } + + llama_io_emit(winfos, 0, winfos.size(), + [](ggml_tensor * tensor, uint8_t * ptr, size_t offset, size_t size, + size_t n_copies, size_t stride_tensor, size_t stride_data) { + llama_io_get(nullptr, tensor, ptr, offset, size, n_copies, stride_tensor, stride_data); + }); } void write(const void * src, size_t size) override { @@ -2935,10 +3146,8 @@ class llama_io_write_host : public llama_io_write_i { return size_written; } -private: - uint8_t * ptr; - size_t buf_size = 0; - size_t size_written = 0; +protected: + llama_io_write_host(uint8_t * p, size_t len, bool deferred) : ptr(p), buf_size(len), deferred(deferred) {} struct write_info { ggml_tensor * tensor; @@ -2947,6 +3156,12 @@ class llama_io_write_host : public llama_io_write_i { size_t offset; }; std::vector winfos; + +private: + uint8_t * ptr; + size_t buf_size = 0; + size_t size_written = 0; + const bool deferred = false; }; class llama_io_read_host : public llama_io_read_i { @@ -2954,9 +3169,54 @@ class llama_io_read_host : public llama_io_read_i { llama_io_read_host(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {} ~llama_io_read_host() { + if (deferred) { + return; // [TAG_STATE_ASYNC] the derived class posts the copies itself + } + // flush the reads - for (const auto & rinfo : rinfos) { - ggml_backend_tensor_set(rinfo.tensor, rinfo.ptr, rinfo.offset, rinfo.size); + for (size_t i = 0; i < rinfos.size();) { + auto * tensor = rinfos[i].tensor; + size_t end = i + 1; + while (end < rinfos.size() && rinfos[end].tensor == tensor) { + end++; + } + // [TAG_STATE_COALESCE] the restore emits one fragment per cell, but the cost is the number of runs of adjacent cells, so count runs before falling back to staging + const size_t tensor_bytes = ggml_nbytes(tensor); + auto * buffer = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; + + const bool has_2d = ggml_backend_buffer_supports_2d(buffer); + + size_t n_runs = 0; + llama_io_emit(rinfos, i, end, + [&n_runs, has_2d](ggml_tensor *, const uint8_t *, size_t, size_t, size_t n_copies, size_t, size_t) { + n_runs += has_2d ? 1 : n_copies; + }); + if (n_runs >= 64 && tensor_bytes <= 64 * 1024 * 1024 && + !ggml_backend_buffer_is_host(buffer)) { + std::vector staging; + try { + staging.resize(tensor_bytes); + } catch (const std::bad_alloc &) { + } + if (!staging.empty()) { + ggml_backend_tensor_get(tensor, staging.data(), 0, tensor_bytes); + for (size_t j = i; j < end; ++j) { + const auto & rinfo = rinfos[j]; + GGML_ASSERT(rinfo.offset <= tensor_bytes && rinfo.size <= tensor_bytes - rinfo.offset); + memcpy(staging.data() + rinfo.offset, rinfo.ptr, rinfo.size); + } + ggml_backend_tensor_set(tensor, staging.data(), 0, tensor_bytes); + i = end; + continue; + } + } + llama_io_emit(rinfos, i, end, + [](ggml_tensor * tensor, const uint8_t * ptr, size_t offset, size_t size, + size_t n_copies, size_t stride_tensor, size_t stride_data) { + llama_io_set(nullptr, tensor, ptr, offset, size, n_copies, stride_tensor, stride_data); + }); + + i = end; } } @@ -2991,10 +3251,8 @@ class llama_io_read_host : public llama_io_read_i { return size_read; } -private: - const uint8_t * ptr; - size_t buf_size = 0; - size_t size_read = 0; +protected: + llama_io_read_host(const uint8_t * p, size_t len, bool deferred) : ptr(p), buf_size(len), deferred(deferred) {} struct read_info { ggml_tensor * tensor; @@ -3003,6 +3261,12 @@ class llama_io_read_host : public llama_io_read_i { size_t offset; }; std::vector rinfos; + +private: + const uint8_t * ptr; + size_t buf_size = 0; + size_t size_read = 0; + const bool deferred = false; }; class llama_io_write_file : public llama_io_write_i { @@ -3393,6 +3657,273 @@ size_t llama_context::state_set_data(const uint8_t * src, size_t size) { } } +// [TAG_STATE_ASYNC] a sequence state transfer that runs beside the decode instead of in it: the host buffer, one backend per device, each with its own stream, and one event per device +struct llama_state_seq_copy { + llama_context * ctx = nullptr; + + struct dev_copy { + ggml_backend_ptr backend; + ggml_backend_event_t event = nullptr; + bool pending = false; + }; + + std::map devs; + + ggml_backend_buffer_ptr host_buf; + + bool counted = false; // held in the context's count of live transfers + + uint8_t * data = nullptr; + size_t size = 0; // bytes the current transfer covers + size_t capacity = 0; // bytes actually held, kept across transfers + bool pinned = false; + bool can_pin = false; + + size_t n_copies = 0; + int64_t t_sync_us = 0; + + ~llama_state_seq_copy() { + if (counted) { + ctx->state_seq_copy_release(this); + } + + wait(); + + for (auto & it : devs) { + if (it.second.event) { + ggml_backend_event_free(it.second.event); + } + } + } + + // the stream this tensor is copied on, or null when it needs none: a host tensor is a memcpy, and a split buffer fails every backend's async copy assert + ggml_backend_t backend_for(const ggml_tensor * t) { + ggml_backend_buffer_t buf = t->view_src ? t->view_src->buffer : t->buffer; + + if (!buf || ggml_backend_buffer_is_host(buf)) { + return nullptr; + } + + ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(buf); + + ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); + + if (!dev || buft != ggml_backend_dev_buffer_type(dev)) { + return nullptr; + } + + auto it = devs.find(dev); + + if (it == devs.end()) { + return nullptr; + } + + it->second.pending = true; + + return it->second.backend.get(); + } + + void record() { + + for (auto & it : devs) { + if (it.second.pending) { + ggml_backend_event_record(it.second.event, it.second.backend.get()); + } + } + } + + // order the copies behind the compute already queued on each device: the copy stream waits for the context's fence, recorded at the end of every decode + void order_after(const std::map & fences) { + for (auto & it : devs) { + const auto fence = fences.find(it.first); + + if (fence != fences.end()) { + ggml_backend_event_wait(it.second.backend.get(), fence->second); + } + } + } + + // order the context's compute behind the copies just recorded, for a restore only: its copies write KV cells while other sequences read every cell up to n_kv + void order_before(const std::vector & compute) { + for (auto & it : devs) { + if (!it.second.pending) { + continue; + } + + for (const auto & backend : compute) { + if (ggml_backend_get_device(backend.get()) == it.first) { + ggml_backend_event_wait(backend.get(), it.second.event); + } + } + } + } + + bool done() { + bool res = true; + + for (auto & it : devs) { + if (!it.second.pending) { + continue; + } + + if (ggml_backend_event_query(it.second.event)) { + it.second.pending = false; + } else { + res = false; + } + } + + return res; + } + + void wait() { + for (auto & it : devs) { + if (!it.second.pending) { + continue; + } + + ggml_backend_event_synchronize(it.second.event); + + it.second.pending = false; + } + } + + // grow-only: pinning host memory costs about as long as the copy it is for, and a caller parking the same sequence asks for a slightly different size each time + uint8_t * buf_resize(size_t size_new) { + if (size_new <= capacity) { + size = size_new; + + return size_new == 0 ? nullptr : data; + } + + // never move memory a copy could still be reading or writing + wait(); + + host_buf.reset(); + + data = nullptr; + size = 0; + capacity = 0; + pinned = false; + + ggml_backend_buffer_type_t host_buft = host_buffer_type(); + + ggml_backend_buffer_t buf = ggml_backend_buft_alloc_buffer(host_buft, size_new); + + if (!buf) { + return nullptr; + } + + uint8_t * base = (uint8_t *) ggml_backend_buffer_get_base(buf); + + if (!base) { + ggml_backend_buffer_free(buf); + return nullptr; + } + + host_buf.reset(buf); + + data = base; + size = size_new; + capacity = size_new; + // a host buffer type may quietly hand back ordinary memory when pinning is off, so believe the buffer that came back rather than the type + pinned = can_pin && ggml_backend_buffer_get_type(buf) == host_buft; + + return data; + } + + void buf_free() { + wait(); + + host_buf.reset(); + + data = nullptr; + size = 0; + capacity = 0; + pinned = false; + } + + ggml_backend_buffer_type_t host_buffer_type() { + for (auto & it : devs) { + ggml_backend_buffer_type_t buft = ggml_backend_dev_host_buffer_type(it.first); + + if (buft) { + return buft; + } + } + + return ggml_backend_cpu_buffer_type(); + } +}; + +// [TAG_STATE_ASYNC] the buffer walk of llama_io_write_host, with the copies posted on the transfer's stream instead of made here +class llama_io_write_host_async : public llama_io_write_host { +public: + llama_io_write_host_async(uint8_t * p, size_t len, llama_state_seq_copy & cpy) : + llama_io_write_host(p, len, true), cpy(cpy) {} + + // posted from the destructor, and only once serialisation reached the end: a caller told of a partial failure by a zero return is free to reuse the buffer at once + void commit() { + committed = true; + } + + ~llama_io_write_host_async() { + if (!committed) { + return; + } + + llama_io_emit(winfos, 0, winfos.size(), + [this](ggml_tensor * tensor, uint8_t * ptr, size_t offset, size_t size, + size_t n_copies, size_t stride_tensor, size_t stride_data) { + llama_io_get(cpy.backend_for(tensor), tensor, ptr, offset, size, + n_copies, stride_tensor, stride_data); + + cpy.n_copies++; + }); + + cpy.record(); + } + +private: + llama_state_seq_copy & cpy; + + bool committed = false; +}; + +// [TAG_STATE_ASYNC] the read half of the same, without llama_io_read_host's whole-tensor staging: a write-back would undo whatever the sequences sharing the tensor wrote while these copies ran +class llama_io_read_host_async : public llama_io_read_host { +public: + llama_io_read_host_async(const uint8_t * p, size_t len, llama_state_seq_copy & cpy) : + llama_io_read_host(p, len, true), cpy(cpy) {} + + // see llama_io_write_host_async::commit(): a restore that failed part way has dropped the sequence, and copies posted for it would write cells that are no longer its own + void commit() { + committed = true; + } + + ~llama_io_read_host_async() { + if (!committed) { + return; + } + + llama_io_emit(rinfos, 0, rinfos.size(), + [this](ggml_tensor * tensor, const uint8_t * ptr, size_t offset, size_t size, + size_t n_copies, size_t stride_tensor, size_t stride_data) { + llama_io_set(cpy.backend_for(tensor), tensor, ptr, offset, size, + n_copies, stride_tensor, stride_data); + + cpy.n_copies++; + }); + + cpy.record(); + } + +private: + llama_state_seq_copy & cpy; + + bool committed = false; +}; + static constexpr uint32_t io_magic = 0xaf143cd8; size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_flags flags) { @@ -3467,6 +3998,243 @@ size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * sr } } +// [TAG_STATE_ASYNC] + +void llama_context::state_seq_copies_drain() { + for (auto * cpy : state_copies) { + cpy->wait(); + cpy->ctx = nullptr; + cpy->counted = false; + } + + state_copies.clear(); +} + +void llama_context::state_seq_copy_release(llama_state_seq_copy * cpy) { + GGML_ASSERT(state_copies.erase(cpy) == 1); + + if (state_copies.empty()) { + for (auto & it : state_copy_fences) { + ggml_backend_event_free(it.second); + } + + state_copy_fences.clear(); + } +} + +void llama_context::state_seq_copy_fence() { + for (const auto & it : state_copy_fences) { + for (const auto & backend : backends) { + if (ggml_backend_get_device(backend.get()) == it.first) { + ggml_backend_event_record(it.second, backend.get()); + } + } + } +} + +llama_state_seq_copy * llama_context::state_seq_copy_init() { + // [TAG_STATE_ASYNC] a recurrent state keeps no fixed row: find_slot() gathers the live rows together, so a decode beside a transfer moves or overwrites the row the transfer reads. A hybrid carries that half too + if (llm_arch_is_recurrent(model.arch) || llm_arch_is_hybrid(model.arch)) { + LLAMA_LOG_INFO("%s: this model moves sequence states between rows, so they are copied synchronously\n", __func__); + return nullptr; + } + + std::unique_ptr cpy(new llama_state_seq_copy()); + + cpy->ctx = this; + + for (auto & backend : backends) { + ggml_backend_dev_t dev = ggml_backend_get_device(backend.get()); + + if (!dev || cpy->devs.find(dev) != cpy->devs.end()) { + continue; + } + + ggml_backend_dev_props props; + ggml_backend_dev_get_props(dev, &props); + + if (!props.caps.async || !props.caps.events) { + continue; + } + + // a device that advertises events but does not implement event_query makes the first poll wait for the whole copy, so leave it out and let state_seq_copy_init() return NULL + if (!ggml_backend_dev_supports_event_query(dev)) { + static std::atomic warned(false); + + if (!warned.exchange(true)) { + LLAMA_LOG_INFO("%s: %s cannot test an event without waiting for it, so sequence " + "states are copied synchronously\n", __func__, ggml_backend_dev_name(dev)); + } + + continue; + } + + // a backend of its own, not the one the graphs are computed on: that one moves its copies to whichever stream it is using, so a transfer could end up ordered behind a graph + ggml_backend_t backend_cpy = ggml_backend_dev_init(dev, nullptr); + + if (!backend_cpy) { + continue; + } + + ggml_backend_event_t event = ggml_backend_event_new(dev); + + if (!event) { + ggml_backend_free(backend_cpy); + continue; + } + + auto & dc = cpy->devs[dev]; + + dc.backend.reset(backend_cpy); + dc.event = event; + } + + if (cpy->devs.empty()) { + return nullptr; + } + + // the devices above are the ones the graphs run on, not the ones the state lives on: with most layers on the CPU every copy takes the synchronous branch of backend_for() + if (memory) { + bool on_device = false; + + for (const auto & [buft, size] : memory->memory_breakdown()) { + if (size == 0) { + continue; + } + + ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); + + if (ggml_backend_buft_is_host(buft) || !dev || buft != ggml_backend_dev_buffer_type(dev) || + cpy->devs.find(dev) == cpy->devs.end()) { + LLAMA_LOG_INFO("%s: the sequence state is not all in device memory (%s), so it is copied synchronously\n", + __func__, ggml_backend_buft_name(buft)); + return nullptr; + } + + on_device = true; + } + + if (!on_device) { + return nullptr; + } + } + + cpy->can_pin = cpy->host_buffer_type() != ggml_backend_cpu_buffer_type(); + + // one fence per device, shared by every transfer and recorded after every decode; installed only after the checks above, so a refused transfer leaves nothing behind + std::vector fences_new; + + for (const auto & it : cpy->devs) { + if (state_copy_fences.find(it.first) != state_copy_fences.end()) { + continue; + } + + ggml_backend_event_t fence = ggml_backend_event_new(it.first); + + if (!fence) { + for (auto dev : fences_new) { + ggml_backend_event_free(state_copy_fences[dev]); + state_copy_fences.erase(dev); + } + + return nullptr; + } + + state_copy_fences[it.first] = fence; + fences_new.push_back(it.first); + } + + state_seq_copy_fence(); + + state_copies.insert(cpy.get()); + cpy->counted = true; + + return cpy.release(); +} + +size_t llama_context::state_seq_copy_get(llama_state_seq_copy & cpy, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) { + // the library owns this buffer, so the extent can be checked instead of believed: every bounds check validates against it, so an oversized one agrees and the copy overruns + if (!cpy.data || size == 0 || size > cpy.size) { + LLAMA_LOG_ERROR("%s: cannot cover %zu bytes, the transfer's buffer holds %zu\n", __func__, size, cpy.size); + return 0; + } + + // LLAMA_STATE_SEQ_FLAGS_ON_DEVICE has nowhere to leave the data here, and get_size_ext() with that flag reports a metadata-sized state, so the two cannot be paired + if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { + LLAMA_LOG_ERROR("%s: LLAMA_STATE_SEQ_FLAGS_ON_DEVICE is not supported here, the copies go through host memory\n", __func__); + return 0; + } + + const int64_t t_sync = ggml_time_us(); + cpy.order_after(state_copy_fences); + cpy.t_sync_us = ggml_time_us() - t_sync; + + cpy.n_copies = 0; + + llama_io_write_host_async io(cpy.data, size, cpy); + + try { + io.write(&io_magic, sizeof(io_magic)); + io.write(&seq_id, sizeof(seq_id)); + + const size_t n = state_seq_write_data(io, seq_id, flags); + + io.commit(); + + return n; + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what()); + return 0; + } +} + +size_t llama_context::state_seq_copy_set(llama_state_seq_copy & cpy, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) { + if (!cpy.data || size == 0 || size > cpy.size) { + LLAMA_LOG_ERROR("%s: cannot cover %zu bytes, the transfer's buffer holds %zu\n", __func__, size, cpy.size); + return 0; + } + + if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { + LLAMA_LOG_ERROR("%s: LLAMA_STATE_SEQ_FLAGS_ON_DEVICE is not supported here, the copies go through host memory\n", __func__); + return 0; + } + + // the cells this restore was given may still be read, masked, by a graph in flight, so the copy stream waits for the compute stream on the device, see order_after() + const int64_t t_sync = ggml_time_us(); + cpy.order_after(state_copy_fences); + cpy.t_sync_us = ggml_time_us() - t_sync; + + cpy.n_copies = 0; + + size_t n = 0; + + { + llama_io_read_host_async io(cpy.data, size, cpy); + + try { + uint32_t magic_read; + io.read(&magic_read, sizeof(magic_read)); + if (io_magic != magic_read) { + throw std::runtime_error("wrong sequence state magic"); + } + + llama_seq_id seq_id_read; + io.read(&seq_id_read, sizeof(seq_id_read)); + + n = state_seq_read_data(io, seq_id, flags); + + io.commit(); + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what()); + return 0; + } + } + + cpy.order_before(backends); + + return n; +} + bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) { llama_file file(filepath, "rb"); @@ -3622,6 +4390,11 @@ size_t llama_context::state_write_data(llama_io_write_i & io) { } size_t llama_context::state_read_data(llama_io_read_i & io) { + // [TAG_EXACT_CONCURRENCY] a whole-context restore writes cells at their recorded physical index, which the paged pool owns; refused before anything is parsed + if (memory && memory->alloc_granularity() > 1) { + throw std::runtime_error("whole-context restore is not supported with LLAMA_EXACT_CONCURRENCY, restore per sequence"); + } + LLAMA_LOG_DEBUG("%s: reading state\n", __func__); // read model info @@ -4475,6 +5248,22 @@ bool llama_memory_can_shift(llama_memory_t mem) { return mem->get_can_shift(); } +uint32_t llama_memory_alloc_granularity(llama_memory_t mem) { + if (!mem) { + return 1; + } + + return mem->alloc_granularity(); +} + +bool llama_memory_update(llama_context * ctx) { + if (!ctx) { + return false; + } + + return ctx->memory_update(false); +} + // llama state API // deprecated @@ -4570,6 +5359,66 @@ size_t llama_state_seq_set_data_ext(llama_context * ctx, const uint8_t * src, si return ctx->state_seq_set_data(seq_id, src, size, flags); } +llama_state_seq_copy * llama_state_seq_copy_init(llama_context * ctx) { + return ctx->state_seq_copy_init(); +} + +void llama_state_seq_copy_free(llama_state_seq_copy * cpy) { + delete cpy; // waits for anything still in flight +} + +uint8_t * llama_state_seq_copy_buf_resize(llama_state_seq_copy * cpy, size_t size) { + return cpy->buf_resize(size); +} + +uint8_t * llama_state_seq_copy_buf(llama_state_seq_copy * cpy) { + return cpy->data; +} + +size_t llama_state_seq_copy_buf_size(llama_state_seq_copy * cpy) { + return cpy->size; +} + +size_t llama_state_seq_copy_buf_capacity(llama_state_seq_copy * cpy) { + return cpy->capacity; +} + +size_t llama_state_seq_copy_n_copies(llama_state_seq_copy * cpy) { + return cpy->n_copies; +} + +int64_t llama_state_seq_copy_sync_us(llama_state_seq_copy * cpy) { + return cpy->t_sync_us; +} + +void llama_state_seq_copy_buf_free(llama_state_seq_copy * cpy) { + cpy->buf_free(); +} + +bool llama_state_seq_copy_buf_is_pinned(llama_state_seq_copy * cpy) { + return cpy->pinned; +} + +bool llama_state_seq_copy_buf_can_pin(llama_state_seq_copy * cpy) { + return cpy->can_pin; +} + +size_t llama_state_seq_copy_get(llama_state_seq_copy * cpy, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) { + return cpy->ctx->state_seq_copy_get(*cpy, size, seq_id, flags); +} + +size_t llama_state_seq_copy_set(llama_state_seq_copy * cpy, size_t size, llama_seq_id dest_seq_id, llama_state_seq_flags flags) { + return cpy->ctx->state_seq_copy_set(*cpy, size, dest_seq_id, flags); +} + +bool llama_state_seq_copy_done(llama_state_seq_copy * cpy) { + return cpy->done(); +} + +void llama_state_seq_copy_wait(llama_state_seq_copy * cpy) { + cpy->wait(); +} + size_t llama_state_seq_save_file(llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) { ctx->synchronize(); diff --git a/src/llama-context.h b/src/llama-context.h index 277aff71d52e..dd8dabe97cde 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -14,6 +14,7 @@ #include #include +#include #include struct llama_model; @@ -42,6 +43,8 @@ struct llama_memory_buffer { using llama_memory_buffers = std::map; +struct llama_state_seq_copy; + struct llama_context { // init scheduler and compute buffers, reserve worst-case graphs llama_context( @@ -165,6 +168,19 @@ struct llama_context { size_t state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags); size_t state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags); + // [TAG_STATE_ASYNC] the same two transfers, issued on a stream of their own and left running + llama_state_seq_copy * state_seq_copy_init(); + + size_t state_seq_copy_get(llama_state_seq_copy & cpy, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags); + size_t state_seq_copy_set(llama_state_seq_copy & cpy, size_t size, llama_seq_id dest_seq_id, llama_state_seq_flags flags); + + // [TAG_STATE_ASYNC] mark the point the compute streams have reached, for the copies to wait for; recorded after every decode and encode once a transfer exists + void state_seq_copy_fence(); + + void state_seq_copy_release(llama_state_seq_copy * cpy); + + void state_seq_copies_drain(); + bool state_load_file( const char * filepath, llama_token * tokens_out, @@ -391,6 +407,12 @@ struct llama_context { ggml_backend_t backend_cpu = nullptr; std::vector backends; + // [TAG_STATE_ASYNC] one event per device that copies asynchronously, recorded on the compute stream at the end of every decode; see state_seq_copy_fence() + std::map state_copy_fences; + + // transfers alive on this context; the fences go when the last one does, and a context freed with transfers still alive drains them and lets them go first + std::set state_copies; + // training ggml_opt_context_t opt_ctx = nullptr; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index f06b94d15c7b..96b57c4e0094 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -22,11 +22,25 @@ #include #include #include +#include #include #include // dedup helpers +// [TAG_EXACT_CONCURRENCY] the page table is wired into llm_graph_input_attn_kv only, so a V-less layout would attend in physical order with the mode reporting itself on +static void llm_graph_reject_exact_concurrency(const char * layout) { + if (!llama_exact_concurrency()) { + return; + } + + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set, but this model uses the %s attention " + "layout, which carries no page table and would attend in physical cell order\n", + __func__, layout); + + throw std::runtime_error("exact concurrency: unsupported attention layout"); +} + static ggml_tensor * build_attn_inp_kq_mask( ggml_context * ctx, const llama_kv_cache_context * mctx, @@ -523,6 +537,7 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { } void llm_graph_input_attn_kv::set_input(const llama_ubatch * ubatch) { + if (self_pages && self_pages->buffer) { mctx->set_input_pages(self_pages, ubatch); } // the idxs are left unallocated when the KV cache is bypassed during training if (self_k_idxs && self_k_idxs->buffer) { mctx->set_input_k_idxs(self_k_idxs, ubatch); @@ -1147,6 +1162,7 @@ void llm_graph_input_attn_cross::set_input(const llama_ubatch * ubatch) { } void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { + if (inp_attn->self_pages) { mctx->get_attn()->set_input_pages(inp_attn->self_pages, ubatch); } mctx->get_attn()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); mctx->get_attn()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); @@ -2863,7 +2879,8 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * v_mla, int64_t n_kv_max, float kq_scale, - int il) const { + int il, + ggml_tensor * pages) const { const bool v_trans = v->nb[1] > v->nb[2]; // split the batch into streams if needed @@ -2899,6 +2916,7 @@ ggml_tensor * llm_graph_context::build_attn_mha( cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias, hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f); + cur->src[5] = pages; res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); ggml_flash_attn_ext_add_sinks(cur, sinks); @@ -3100,6 +3118,8 @@ static std::unique_ptr build_attn_inp_kv_impl( inp->self_kq_mask_cnv = inp->self_kq_mask; } + inp->self_pages = mctx_cur->build_input_pages(ctx0, ubatch); + GGML_ASSERT(!inp->self_pages || (cparams.flash_attn && cparams.causal_attn)); inp->self_k_rot = mctx_cur->build_input_k_rot(ctx0); inp->self_v_rot = mctx_cur->build_input_v_rot(ctx0); @@ -3171,7 +3191,7 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * kq_mask = inp->get_kq_mask(); - ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, sinks, v_mla, 0, kq_scale, il, cparams.training ? nullptr : inp->self_pages); cb(cur, "kqv_out", il); if (inp->self_v_rot) { @@ -3205,6 +3225,8 @@ static std::unique_ptr build_attn_inp_k_impl( const llama_cparams & cparams, const llama_kv_cache_context * mctx_cur) { + llm_graph_reject_exact_concurrency("V-less KV (attn_k)"); + auto inp = std::make_unique(hparams, cparams, mctx_cur); { @@ -3589,6 +3611,8 @@ static std::unique_ptr build_attn_inp_k_dsa_impl( const llama_cparams & cparams, const llama_kv_cache_dsa_context * mctx_cur) { + llm_graph_reject_exact_concurrency("sparse V-less KV (attn_k_dsa)"); + auto inp = std::make_unique(hparams, cparams, mctx_cur); { @@ -3706,6 +3730,8 @@ llm_graph_input_attn_kv_iswa * llm_graph_context::build_attn_inp_kv_iswa() const llm_graph_input_attn_k_iswa * llm_graph_context::build_attn_inp_k_iswa() const { const auto * mctx_cur = static_cast(mctx); + llm_graph_reject_exact_concurrency("V-less sliding window KV (attn_k_iswa)"); + auto inp = std::make_unique(hparams, cparams, mctx_cur); { diff --git a/src/llama-graph.h b/src/llama-graph.h index fbbe67f25b5a..048fcfb4e96e 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -334,6 +334,7 @@ class llm_graph_input_attn_no_cache : public llm_graph_input_i { class llm_graph_input_attn_kv : public llm_graph_input_i { public: + ggml_tensor * self_pages = nullptr; // I32 [1 + physical pages, n_tokens] llm_graph_input_attn_kv( const llama_hparams & hparams, const llama_cparams & cparams, @@ -1246,7 +1247,8 @@ struct llm_graph_context { ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] int64_t n_kv_max, float kq_scale, - int il) const; + int il, + ggml_tensor * pages = nullptr) const; llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; diff --git a/src/llama-impl.cpp b/src/llama-impl.cpp index c216a310b25d..a00fb0c507d8 100644 --- a/src/llama-impl.cpp +++ b/src/llama-impl.cpp @@ -8,7 +8,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -202,3 +205,160 @@ std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) { return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0); } } + +// [TAG_EXACT_CONCURRENCY] +bool llama_exact_backend_name(const char * reg_name) { + return reg_name && (strcmp(reg_name, "CUDA") == 0 || strcmp(reg_name, "ROCm") == 0 || strcmp(reg_name, "MUSA") == 0); +} + +// [TAG_EXACT_CONCURRENCY] a host buffer is the case that matters: the scheduler runs an op on the backend that holds its weight, and moves a host weight's op to the GPU only once the batch is wide enough (ggml_backend_cuda_device_offload_op). +// The CPU matmul picks between its SGEMM and its vector dot by the batch width too. +bool llama_exact_buft_invariant(ggml_backend_buffer_type_t buft) { + if (!buft || ggml_backend_buft_is_host(buft)) { + return false; + } + + ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); + ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr; + + return reg && llama_exact_backend_name(ggml_backend_reg_name(reg)); +} + +bool llama_exact_concurrency() { + static const bool enabled = []() { + const char * val = getenv("LLAMA_EXACT_CONCURRENCY"); + return val && atoi(val) != 0; + }(); + + return enabled; +} + +// [TAG_EXACT_CONCURRENCY] tokens one sequence contributes to a decode step, see llama.h +static std::atomic g_exact_decode_tokens{1}; + +// one lock for the token figure, the sequence count and the width: a report interleaved with a change of figure could leave the backend with a width that covers neither +static std::recursive_mutex g_exact_mutex; + +// the most sequences any context was created with; the tokens figure is process wide, so raising it re-reports every context's width +static std::atomic g_exact_max_n_seq{0}; + +static bool llama_exact_width_within_explicit_bound(uint32_t n_cols); + +static bool llama_exact_width_of(uint32_t n_seq, uint32_t n_tokens, uint32_t & n_cols) { + const uint64_t w = (uint64_t) n_seq * (uint64_t) n_tokens; + + if (w > (uint64_t) INT32_MAX) { + LLAMA_LOG_ERROR("%s: a decode step of %u sequences with %u tokens each is too wide to report\n", __func__, n_seq, n_tokens); + return false; + } + + n_cols = (uint32_t) w; + + return true; +} + +bool llama_exact_check_n_seq(uint32_t n_seq) { + std::lock_guard lock(g_exact_mutex); + + const uint32_t n_seq_max = std::max(n_seq, g_exact_max_n_seq.load(std::memory_order_relaxed)); + + uint32_t n_cols = 0; + + return llama_exact_width_of(n_seq_max, llama_exact_decode_tokens(), n_cols) && llama_exact_width_within_explicit_bound(n_cols); +} + +bool llama_exact_report_n_seq(uint32_t n_seq) { + std::lock_guard lock(g_exact_mutex); + + const uint32_t n_seq_max = std::max(n_seq, g_exact_max_n_seq.load(std::memory_order_relaxed)); + + uint32_t n_cols = 0; + + if (!llama_exact_width_of(n_seq_max, llama_exact_decode_tokens(), n_cols) || !llama_set_exact_decode_width(n_cols)) { + return false; + } + + uint32_t cur = g_exact_max_n_seq.load(std::memory_order_relaxed); + + while (n_seq > cur && !g_exact_max_n_seq.compare_exchange_weak(cur, n_seq, std::memory_order_relaxed)) { + } + + return true; +} + +bool llama_set_exact_decode_tokens(uint32_t n_tokens) { + n_tokens = n_tokens > 0 ? n_tokens : 1; + + std::lock_guard lock(g_exact_mutex); + + // never lowered: a narrower context set up later would turn an existing speculative context's verify steps into prompts + if (n_tokens <= g_exact_decode_tokens.load(std::memory_order_relaxed)) { + return true; + } + + // every context widens with the figure, so report the width first; one the explicit bound cannot cover leaves the old figure in place + const uint32_t n_seq = g_exact_max_n_seq.load(std::memory_order_relaxed); + + uint32_t n_cols = 0; + + if (n_seq > 0 && (!llama_exact_width_of(n_seq, n_tokens, n_cols) || !llama_set_exact_decode_width(n_cols))) { + return false; + } + + g_exact_decode_tokens.store(n_tokens, std::memory_order_relaxed); + + return true; +} + +uint32_t llama_exact_decode_tokens(void) { + return g_exact_decode_tokens.load(std::memory_order_relaxed); +} + +// [TAG_EXACT_CONCURRENCY] the widest decode ubatch reported so far, see llama.h; reached through the registry so an absent or late-loaded backend costs nothing +static std::atomic g_exact_decode_width{0}; + +// an explicit column bound wins in the CUDA backend, so a width above it would leave decodes batched past the bound +static bool llama_exact_width_within_explicit_bound(uint32_t n_cols) { + static const int explicit_cols = []() { + const char * val = getenv("GGML_CUDA_BATCH_INVARIANT_MAX_COLS"); + return val ? atoi(val) : -1; + }(); + + if (explicit_cols > 0 && (uint32_t) explicit_cols < n_cols) { + LLAMA_LOG_ERROR("%s: GGML_CUDA_BATCH_INVARIANT_MAX_COLS is %d but LLAMA_EXACT_CONCURRENCY needs at least %u columns for the decode step just requested; raise it, set it to 0 for no bound, or unset it\n", + __func__, explicit_cols, n_cols); + return false; + } + + return true; +} + +bool llama_set_exact_decode_width(uint32_t n_cols) { + if (!llama_exact_width_within_explicit_bound(n_cols)) { + return false; + } + + std::lock_guard lock(g_exact_mutex); + + uint32_t cur = g_exact_decode_width.load(std::memory_order_relaxed); + + while (n_cols > cur && !g_exact_decode_width.compare_exchange_weak(cur, n_cols, std::memory_order_relaxed)) { + } + + const uint32_t widest = g_exact_decode_width.load(std::memory_order_relaxed); + + for (size_t i = 0; i < ggml_backend_reg_count(); ++i) { + ggml_backend_reg_t reg = ggml_backend_reg_get(i); + + auto * fn = (void (*)(int)) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cuda_set_exact_decode_width"); + if (fn) { + fn((int) widest); + } + } + + return true; +} + +uint32_t llama_exact_decode_width(void) { + return g_exact_decode_width.load(std::memory_order_relaxed); +} diff --git a/src/llama-impl.h b/src/llama-impl.h index 7ccd23c86eff..f79b5b179b20 100644 --- a/src/llama-impl.h +++ b/src/llama-impl.h @@ -1,6 +1,7 @@ #pragma once #include "ggml.h" // for ggml_log_level +#include "ggml-backend.h" #include #include @@ -108,3 +109,17 @@ std::string llama_format_tensor_shape(const std::vector & ne); std::string llama_format_tensor_shape(const struct ggml_tensor * t); std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i); + +// [TAG_EXACT_CONCURRENCY] opt-in mode under which a sequence's attention depends only on its own cells, so its output does not change when others share the KV cache +bool llama_exact_concurrency(); + +// [TAG_EXACT_CONCURRENCY] whether a backend registry carries the mode's batch-invariant kernels +bool llama_exact_backend_name(const char * reg_name); + +// [TAG_EXACT_CONCURRENCY] whether a tensor placed in this buffer type is computed by such a backend +bool llama_exact_buft_invariant(ggml_backend_buffer_type_t buft); + +// [TAG_EXACT_CONCURRENCY] a context reports how many sequences it was created with, so the backend knows the width every context needs +bool llama_exact_report_n_seq(uint32_t n_seq); + +bool llama_exact_check_n_seq(uint32_t n_seq); diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 804c90532c60..51c4a0201e1a 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -62,6 +63,68 @@ static void ggml_gen_hadamard(ggml_tensor * tensor) { // llama_kv_cache // +// [TAG_EXACT_CONCURRENCY] the paged specialization lives in the CUDA sources; every other backend ignores src[5] and walks the pool in physical cell order +static bool llama_dev_has_paged_attn(ggml_backend_dev_t dev) { + if (!dev) { + return false; + } + + ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev); + if (!reg) { + return false; + } + + return llama_exact_backend_name(ggml_backend_reg_name(reg)); +} + +// [TAG_EXACT_CONCURRENCY] whether the device can actually run the paged attention op for a layer of this shape: the registry name only says which backends carry the kernels +static bool llama_dev_supports_paged_attn( + ggml_backend_dev_t dev, + ggml_type type_k, ggml_type type_v, + uint32_t n_embd_head_k, uint32_t n_embd_head_v, + uint32_t n_head, uint32_t n_head_kv, + uint32_t n_cells, uint32_t page_size) { + if (!llama_dev_has_paged_attn(dev)) { + return false; + } + + ggml_init_params ip = { + /*.mem_size =*/ ggml_tensor_overhead()*16 + ggml_graph_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + + ggml_context * ctx = ggml_init(ip); + if (!ctx) { + return false; + } + + bool res = true; + + const int64_t n_kv = page_size; + + for (const int64_t n_tokens : { (int64_t) 1, (int64_t) 4, (int64_t) 16, (int64_t) 512 }) { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, n_embd_head_k, n_tokens, n_head, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx, type_k, n_embd_head_k, n_kv, n_head_kv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, type_v, n_embd_head_v, n_kv, n_head_kv, 1); + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv, n_tokens, 1, 1); + + ggml_tensor * op = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/sqrtf((float) n_embd_head_k), 0.0f, 0.0f); + ggml_prec_set_acc(op, GGML_PREC_F32); + + op->src[5] = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, 1 + n_cells/page_size, n_tokens); + + if (!ggml_backend_dev_supports_op(dev, op)) { + res = false; + break; + } + } + + ggml_free(ctx); + + return res; +} + llama_kv_cache::llama_kv_cache( const llama_model & model, const llama_hparams & hparams, @@ -86,6 +149,9 @@ llama_kv_cache::llama_kv_cache( v_cells_impl(other ? other->v_cells_impl : std::make_shared()), v_cells(*v_cells_impl) { + // [TAG_EXACT_CONCURRENCY] read the knob through the same cached reader the graph and the CUDA dispatcher use, so a mid-process change cannot leave them disagreeing + exact_pages = llama_exact_concurrency(); + // shared cells view the source cache's K/V tensors, so the cell count // follows the source allocation: a fitted target can be smaller than the // draft default and oversized views would overflow the source tensors @@ -99,6 +165,27 @@ llama_kv_cache::llama_kv_cache( GGML_ASSERT(kv_size % n_pad == 0); + if (exact_pages) { + const char * unsupported = nullptr; + + if (!unified) { + unsupported = "it needs a unified KV cache (pass --kv-unified)"; + } else if (v_trans) { + unsupported = "it needs a non-transposed V cache (pass --flash-attn on)"; + } else if (n_swa != 0) { + unsupported = "the paged pool does not support sliding window attention"; + } else if (type_k != GGML_TYPE_F16 || type_v != GGML_TYPE_F16) { + unsupported = "it needs an F16 KV cache (do not pass --cache-type-k or --cache-type-v)"; + } else if (kv_size % exact_page_size != 0) { + unsupported = "the context size must be a multiple of 256 (pass -c as a multiple of 256)"; + } + + if (unsupported) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but %s\n", __func__, unsupported); + throw std::runtime_error("exact concurrency: unsupported KV cache configuration"); + } + } + const uint32_t n_layer = hparams.n_layer_all; // define a comparator for the buft -> ctx map to ensure that the order is well-defined: @@ -222,6 +309,39 @@ llama_kv_cache::llama_kv_cache( LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name); + // [TAG_EXACT_CONCURRENCY] the paged kernel handles 256-wide K and V heads only; any other width would run unpaged while the mode reports itself as on + if (exact_pages && (hparams.n_embd_head_k(il) != 256 || (!is_mla && hparams.n_embd_head_v(il) != 256) || is_mla)) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but layer %d has %u-wide K heads and %u-wide V heads%s, " + "and the paged attention kernel supports 256-wide K and V heads only\n", + __func__, il, hparams.n_embd_head_k(il), hparams.n_embd_head_v(il), is_mla ? " (MLA)" : ""); + throw std::runtime_error("exact concurrency: unsupported attention head size"); + } + + if (exact_pages && hparams.attn_soft_cap) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but this model soft-caps its attention logits (%.1f), " + "which the paged attention kernel does not apply\n", __func__, hparams.f_attn_logit_softcapping); + throw std::runtime_error("exact concurrency: attention soft cap is not supported"); + } + + if (exact_pages && !(offload && llama_dev_has_paged_attn(model.dev_layer(il)))) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but layer %d keeps its KV cache on %s, " + "which has no paged attention: every layer must be offloaded to the CUDA backend " + "(pass -ngl to offload all layers and do not pass --no-kv-offload)\n", + __func__, il, dev_name); + throw std::runtime_error("exact concurrency: KV cache layer is not on the CUDA backend"); + } + + // [TAG_EXACT_CONCURRENCY] right backend; ask whether this layer's attention, with the page table attached, lands on one of its kernels at all + if (exact_pages && !llama_dev_supports_paged_attn(model.dev_layer(il), type_k, type_v, + hparams.n_embd_head_k(il), hparams.n_embd_head_v(il), + hparams.n_head(il), hparams.n_head_kv(il), kv_size, exact_page_size)) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but %s cannot run the paged attention for layer %d " + "(K %s, V %s, %u-wide heads): the build or the device has no flash attention kernel for it, " + "and the op would fall to the CPU, which ignores the page table\n", + __func__, dev_name, il, ggml_type_name(type_k), ggml_type_name(type_v), hparams.n_embd_head_k(il)); + throw std::runtime_error("exact concurrency: the device cannot run the paged attention"); + } + ggml_context * ctx = ctx_for_buft(buft); if (!ctx) { throw std::runtime_error("failed to create ggml context for kv cache"); @@ -384,7 +504,99 @@ llama_kv_cache::llama_kv_cache( debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0; } +void llama_kv_cache::exact_pages_rebuild() const { + const auto & cells = v_cells[0]; + + exact_page_owner.assign(cells.size()/exact_page_size, exact_page{}); + exact_page_live .assign(cells.size()/exact_page_size, 0); + + for (uint32_t i = 0; i < cells.size(); ++i) { + if (cells.is_empty(i)) { + continue; + } + + GGML_ASSERT(cells.seq_count(i) == 1); + + const auto pos = cells.pos_get(i); + + GGML_ASSERT(pos >= 0 && uint32_t(pos)%exact_page_size == i%exact_page_size); + + const exact_page cur { cells.seq_get(i), llama_pos(pos/(llama_pos) exact_page_size) }; + + auto & owner = exact_page_owner[i/exact_page_size]; + + GGML_ASSERT(owner.seq < 0 || (owner.seq == cur.seq && owner.lpg == cur.lpg)); + + owner = cur; + + ++exact_page_live[i/exact_page_size]; + } + + exact_page_owner_dirty = false; +} + +void llama_kv_cache::exact_pages_sync() const { + if (exact_page_owner_dirty) { + exact_pages_rebuild(); + + return; + } + + if (debug > 0) { + // what was maintained has to say what the cells say + const auto kept = exact_page_owner; + const auto kept_live = exact_page_live; + + exact_pages_rebuild(); + + GGML_ASSERT(kept.size() == exact_page_owner.size()); + + for (size_t p = 0; p < kept.size(); ++p) { + GGML_ASSERT(kept[p].seq == exact_page_owner[p].seq && kept[p].lpg == exact_page_owner[p].lpg); + GGML_ASSERT(kept_live[p] == exact_page_live[p]); + } + } +} + +void llama_kv_cache::exact_pages_claim(uint32_t idx, llama_seq_id seq, llama_pos pos) { + if (exact_page_owner_dirty || exact_page_owner.empty()) { + return; + } + + const exact_page cur { seq, llama_pos(pos/(llama_pos) exact_page_size) }; + + auto & owner = exact_page_owner[idx/exact_page_size]; + + GGML_ASSERT(owner.seq < 0 || (owner.seq == cur.seq && owner.lpg == cur.lpg)); + + owner = cur; + + ++exact_page_live[idx/exact_page_size]; +} + +// [TAG_EXACT_CONCURRENCY] a page stays with its sequence for as long as one of its cells is live, +// so a removal frees it only when it takes the last one. Counting per page is what keeps a removal +// that empties nothing, such as the rejected tail of every accepted speculative step, from costing +// a rescan of the pool. +void llama_kv_cache::exact_pages_release(uint32_t idx) { + ++exact_page_n_release; + + if (exact_page_owner_dirty || exact_page_owner.empty()) { + return; + } + + const uint32_t page = idx/exact_page_size; + + GGML_ASSERT(exact_page_live[page] > 0); + + if (--exact_page_live[page] == 0) { + exact_page_owner[page] = exact_page{}; + } +} + void llama_kv_cache::clear(bool data) { + exact_page_owner_dirty = true; + for (uint32_t s = 0; s < n_stream; ++s) { v_cells[s].reset(); v_heads[s] = 0; @@ -426,6 +638,11 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { } if (cells.seq_has(i, seq_id) && cells.seq_rm(i, seq_id)) { + // [TAG_EXACT_CONCURRENCY] the cell is gone; the page goes with the last of them + if (exact_pages) { + exact_pages_release(i); + } + if (new_head == cells.size()) { new_head = i; } @@ -449,6 +666,10 @@ bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) { continue; } + if (exact_pages) { + exact_pages_release(i); + } + cells.rm(i); if (new_head == cells.size()) { @@ -472,6 +693,14 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll return; } + // [TAG_EXACT_CONCURRENCY] a page belongs to one sequence, so refuse a copy that would share cells rather than abort. After the shared-cells return, so a draft cache is unaffected. + if (exact_pages && seq_id_src != seq_id_dst) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support copying cells between " + "sequences (%d -> %d); ignoring the copy\n", + __func__, seq_id_src, seq_id_dst); + return; + } + GGML_ASSERT(seq_id_src >= 0 && (size_t) seq_id_src < seq_to_stream.size()); GGML_ASSERT(seq_id_dst >= 0 && (size_t) seq_id_dst < seq_to_stream.size()); @@ -573,6 +802,11 @@ void llama_kv_cache::seq_keep(llama_seq_id seq_id) { for (uint32_t i = 0; i < cells.size(); ++i) { if (cells.seq_keep(i, seq_id)) { + // [TAG_EXACT_CONCURRENCY] as in seq_rm, the cell emptied here + if (exact_pages) { + exact_pages_release(i); + } + if (new_head == cells.size()) { new_head = i; } @@ -591,6 +825,14 @@ void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, ll return; } + // [TAG_EXACT_CONCURRENCY] a cell's offset in its page is its position modulo the page size, so shifting positions would misplace every cell + if (exact_pages && shift != 0) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support shifting positions " + "(seq %d, shift %d); ignoring the shift\n", + __func__, seq_id, shift); + return; + } + GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_add() is only supported for n_pos_per_embd() == 1"); @@ -641,6 +883,13 @@ void llama_kv_cache::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, in return; } + if (exact_pages && d != 1) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support dividing positions " + "(seq %d, d %d); ignoring the division\n", + __func__, seq_id, d); + return; + } + GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()); GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_div() is only supported for n_pos_per_embd() == 1"); @@ -722,11 +971,25 @@ llama_memory_context_ptr llama_kv_cache::init_batch( uint32_t n_ubatch, bool embd_all) { do { + // [TAG_EXACT_CONCURRENCY] a token shared by several sequences would be one cell in a page that belongs to one sequence, so refuse it here rather than assert at placement + if (exact_pages && balloc.has_shared_tokens()) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support tokens shared by several sequence ids; " + "give every token exactly one sequence id\n", __func__); + break; + } + balloc.split_reset(); std::vector ubatches; while (true) { - auto ubatch = n_stream == 1 ? balloc.split_simple(n_ubatch) : embd_all ? balloc.split_seq(n_ubatch) : balloc.split_equal(n_ubatch, true, 0); + // [TAG_EXACT_CONCURRENCY] split_simple packs every sequence's prompt into one ubatch, so a prefill would run at a width its solo run never sees; the set split gives each its own + const uint32_t isolate = llama_exact_concurrency() && balloc.has_seq_wider_than(llama_exact_decode_tokens()) ? llama_exact_decode_tokens() : 0; + + auto ubatch = n_stream == 1 && !isolate + ? balloc.split_simple(n_ubatch) + : embd_all + ? balloc.split_seq(n_ubatch) + : balloc.split_equal(n_ubatch, n_stream > 1, 0, isolate); if (ubatch.n_tokens == 0) { break; @@ -773,11 +1036,19 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector v_heads_old; // old positions of the heads, before placing the ubatch std::vector v_cells; // copy of the old cells, before placing the ubatch + + // [TAG_EXACT_CONCURRENCY] page ownership and occupancy before the ubatch, so undoing a speculative placement does not force a rebuild from every cell + std::vector exact_page_owner_old; + std::vector exact_page_live_old; }; // remember the old state of the cells so we can restore it in the end std::vector states; + // [TAG_EXACT_CONCURRENCY] a placement can purge positions outside the cells it restores below, + // and those are not undone; count removals to notice + const uint64_t n_release_before = exact_page_n_release; + bool success = true; for (const auto & ubatch : ubatches) { @@ -793,7 +1064,7 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vectorsinfo; @@ -821,6 +1096,16 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vectorv_cells[s]); head = it->v_heads_old[s]; } + + // [TAG_EXACT_CONCURRENCY] put back what the allocator knew, unless the placement also removed cells, when only the cells can say what is left + if (!exact_rebuild) { + exact_page_owner = it->exact_page_owner_old; + exact_page_live = it->exact_page_live_old; + } + } + + if (exact_rebuild) { + exact_page_owner_dirty = true; } if (!success) { @@ -979,6 +1264,48 @@ llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, } } + if (exact_pages) { + const auto & cells = v_cells[0]; + + exact_pages_sync(); + + using page_key = std::pair; + + exact_page_owner_tmp = exact_page_owner; + + auto & owner = exact_page_owner_tmp; + + std::map pages; + + for (uint32_t p = 0; p < owner.size(); ++p) { + if (owner[p].seq >= 0) { + pages.emplace(page_key {owner[p].seq, owner[p].lpg}, p); + } + } + + std::set assigned; + slot_info res {0, 0, {0}, {{}}}; + for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { + GGML_ASSERT(ubatch.n_seq_id[i] == 1 && ubatch.pos[i] >= 0); + const page_key key {ubatch.seq_id[i][0], ubatch.pos[i]/exact_page_size}; + auto it = pages.find(key); + if (it == pages.end()) { + uint32_t page = v_heads[0]/exact_page_size; + uint32_t tested = 0; + while (tested < owner.size() && owner[page%owner.size()].seq >= 0) { ++page; ++tested; } + if (tested == owner.size()) { return {}; } + page %= owner.size(); + owner[page] = exact_page {key.first, key.second}; + it = pages.emplace(key, page).first; + } + const uint32_t idx = it->second*exact_page_size + ubatch.pos[i]%exact_page_size; + if (!cells.is_empty(idx) || !assigned.insert(idx).second) { return {}; } + res.idxs[0].push_back(idx); + } + if (cont && !res.is_contiguous()) { return {}; } + return res; + } + uint32_t n_tokens = ubatch.n_tokens; uint32_t n_seqs = 1; @@ -1141,6 +1468,10 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos); + if (exact_pages) { + exact_pages_release(idx); + } + cells.rm(idx); } @@ -1172,6 +1503,12 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) { cells.seq_add(idx, ubatch.seq_id[i][s]); } + + if (exact_pages) { + GGML_ASSERT(ubatch.n_seq_id[i] == 1); + + exact_pages_claim(idx, ubatch.seq_id[i][0], ubatch.pos[i]); + } } } @@ -1203,7 +1540,16 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & } } +uint32_t llama_kv_cache::alloc_granularity() const { + // [TAG_EXACT_CONCURRENCY] a page is given to one (sequence, position / page) pair, so n tokens hold round_up(n, exact_page_size) cells: the tail page is charged in full + return exact_pages ? exact_page_size : 1; +} + bool llama_kv_cache::get_can_shift() const { + // [TAG_EXACT_CONCURRENCY] a cell's offset in its page is its position modulo 256, so the pool cannot shift positions; reporting it disables --context-shift and --cache-reuse at load + if (exact_pages) { + return false; + } // Step35 uses per-layer RoPE dims; K-shift assumes a single global n_rot. if (model.arch == LLM_ARCH_STEP35) { return false; @@ -1275,7 +1621,50 @@ uint32_t llama_kv_cache::get_stream(llama_seq_id seq_id) const { return seq_to_stream[seq_id]; } +ggml_tensor * llama_kv_cache::build_input_pages(ggml_context * ctx, const llama_ubatch & ubatch) const { + if (!exact_pages) { return nullptr; } + auto * pages = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, 1 + get_size()/exact_page_size, ubatch.n_tokens); + ggml_set_input(pages); + ggml_set_name(pages, "attn_logical_pages"); + return pages; +} + +void llama_kv_cache::set_input_pages(ggml_tensor * dst, const llama_ubatch * ubatch) const { + GGML_ASSERT(exact_pages && dst->ne[1] == ubatch->n_tokens); + + exact_pages_sync(); + + std::map> pages; + for (uint32_t p = 0; p < exact_page_owner.size(); ++p) { + const auto & owner = exact_page_owner[p]; + if (owner.seq >= 0) { + pages[owner.seq][owner.lpg] = p; + } + } + std::vector data(ggml_nelements(dst), -1); + for (uint32_t i = 0; i < ubatch->n_tokens; ++i) { + GGML_ASSERT(ubatch->n_seq_id[i] == 1); + auto * row = data.data() + i*dst->ne[0]; + row[0] = 0; + for (const auto & page : pages[ubatch->seq_id[i][0]]) { + if (page.first*exact_page_size > uint32_t(ubatch->pos[i])) { break; } + row[++row[0]] = page.second; + } + } + ggml_backend_tensor_set(dst, data.data(), 0, data.size()*sizeof(int32_t)); +} + +ggml_tensor * llama_kv_cache_context::build_input_pages(ggml_context * ctx, const llama_ubatch & ubatch) const { + return kv->build_input_pages(ctx, ubatch); +} + +void llama_kv_cache_context::set_input_pages(ggml_tensor * dst, const llama_ubatch * ubatch) const { + kv->set_input_pages(dst, ubatch); +} + uint32_t llama_kv_cache::get_n_kv(const slot_info & sinfo) const { + // the per-query page map is the only loop bound for exact attention, so neighbours cannot extend it + if (exact_pages) { return get_size(); } uint32_t result = 0; // pad the n_kv value so that the graph remains constant across batches and can be reused @@ -2146,6 +2535,12 @@ void llama_kv_cache::state_read_sinfo( llama_state_seq_flags flags, slot_info_vec_t * sinfos_out, const slot_info_vec_t * sinfos_in) { + // [TAG_EXACT_CONCURRENCY] a whole-cache restore writes cells at their recorded physical index, which the paged pool owns; refused before a byte is read + if (exact_pages && seq_id == -1) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set, which supports per-sequence state restore only\n", __func__); + throw std::runtime_error("whole-cache restore is not supported with LLAMA_EXACT_CONCURRENCY"); + } + // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS] if (other) { return; @@ -2468,6 +2863,8 @@ bool llama_kv_cache::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32 } else { // whole KV cache restore + GGML_ASSERT(!exact_pages); + if (cell_count > cells.size()) { LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__); return false; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 9bfb8f231fe6..86df5613f022 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -133,6 +133,9 @@ class llama_kv_cache : public llama_memory_i { bool get_can_shift() const override; + // [TAG_EXACT_CONCURRENCY] the page size under exact mode, 1 otherwise + uint32_t alloc_granularity() const override; + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; @@ -224,6 +227,8 @@ class llama_kv_cache : public llama_memory_i { ggml_tensor * build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const; ggml_tensor * build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const; + ggml_tensor * build_input_pages(ggml_context * ctx, const llama_ubatch & ubatch) const; + void set_input_pages(ggml_tensor * dst, const llama_ubatch * ubatch) const; ggml_tensor * build_input_k_rot(ggml_context * ctx) const; ggml_tensor * build_input_v_rot(ggml_context * ctx) const; @@ -266,6 +271,38 @@ class llama_kv_cache : public llama_memory_i { std::vector v_stream; }; + static constexpr uint32_t exact_page_size = 256; + bool exact_pages = false; + + // [TAG_EXACT_CONCURRENCY] which (sequence, logical page) owns each physical page; seq < 0 means free, and it is kept current as cells are placed and dirtied by removals + struct exact_page { + llama_seq_id seq = -1; + llama_pos lpg = -1; + }; + + mutable std::vector exact_page_owner; + mutable bool exact_page_owner_dirty = true; + + // live cells in each physical page, so a removal can free the page it emptied without rescanning the pool + mutable std::vector exact_page_live; + + // with LLAMA_KV_CACHE_DEBUG set this also rebuilds, to check what was maintained + void exact_pages_sync() const; + + void exact_pages_rebuild() const; + + void exact_pages_claim(uint32_t idx, llama_seq_id seq, llama_pos pos); + + // record that the cell at physical index idx has just become empty + void exact_pages_release(uint32_t idx); + + // how many cells have been released, so prepare() can tell whether a placement removed cells + // it is not going to restore + uint64_t exact_page_n_release = 0; + + // scratch for find_slot(), which must not touch the ownership it reads + mutable std::vector exact_page_owner_tmp; + bool v_trans = true; // the value tensor is transposed const uint32_t n_seq_max = 1; @@ -421,6 +458,8 @@ class llama_kv_cache_context : public llama_memory_context_i { // helps understand the implementation logic of cpy_k and cpy_v ggml_tensor * build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const; ggml_tensor * build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const; + ggml_tensor * build_input_pages(ggml_context * ctx, const llama_ubatch & ubatch) const; + void set_input_pages(ggml_tensor * dst, const llama_ubatch * ubatch) const; ggml_tensor * build_input_k_rot(ggml_context * ctx) const; ggml_tensor * build_input_v_rot(ggml_context * ctx) const; diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 62f12de954a0..dc5c872b3bd4 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -66,6 +66,13 @@ llama_memory_hybrid::llama_memory_hybrid( llama_memory_context_ptr llama_memory_hybrid::init_batch(llama_batch_allocr & balloc, uint32_t n_ubatch, bool embd_all) { do { + // [TAG_EXACT_CONCURRENCY] refused before the attention half asserts on it, see llama_kv_cache::init_batch + if (llama_exact_concurrency() && balloc.has_shared_tokens()) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support tokens shared by several sequence ids; " + "give every token exactly one sequence id\n", __func__); + break; + } + balloc.split_reset(); // follow the recurrent pattern for creating the ubatch splits @@ -86,7 +93,10 @@ llama_memory_context_ptr llama_memory_hybrid::init_batch(llama_batch_allocr & ba // so that the rollback snapshots remain valid const uint32_t n_rs_seq = mem_recr->n_rs_seq; - ubatch = balloc.split_equal(n_ubatch, !unified, n_rs_seq > 0 ? n_rs_seq + 1 : 0); + // [TAG_EXACT_CONCURRENCY] the recurrent half is not invariant to the ubatch shape, so a prompt gets a ubatch of its own + const uint32_t isolate = llama_exact_concurrency() ? llama_exact_decode_tokens() : 0; + + ubatch = balloc.split_equal(n_ubatch, !unified, n_rs_seq > 0 ? n_rs_seq + 1 : 0, isolate); } if (ubatch.n_tokens == 0) { @@ -135,6 +145,11 @@ bool llama_memory_hybrid::get_can_shift() const { return mem_attn->get_can_shift(); } +uint32_t llama_memory_hybrid::alloc_granularity() const { + // the recurrent half holds one state per sequence, so the attention half is the one whose cells a caller is planning capacity for + return mem_attn->alloc_granularity(); +} + void llama_memory_hybrid::clear(bool data) { mem_attn->clear(data); mem_recr->clear(data); @@ -150,6 +165,13 @@ bool llama_memory_hybrid::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1 } void llama_memory_hybrid::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) { + // [TAG_EXACT_CONCURRENCY] the attention half refuses this, so refuse before either half is touched or the two could end up describing different states + if (llama_exact_concurrency() && seq_id_src != seq_id_dst) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support copying cells between sequences (%d -> %d); ignoring the copy\n", + __func__, seq_id_src, seq_id_dst); + return; + } + mem_attn->seq_cp(seq_id_src, seq_id_dst, p0, p1); mem_recr->seq_cp(seq_id_src, seq_id_dst, p0, p1); } @@ -160,11 +182,23 @@ void llama_memory_hybrid::seq_keep(llama_seq_id seq_id) { } void llama_memory_hybrid::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) { + if (llama_exact_concurrency() && shift != 0) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support shifting positions (seq %d, shift %d); ignoring the shift\n", + __func__, seq_id, shift); + return; + } + mem_attn->seq_add(seq_id, p0, p1, shift); mem_recr->seq_add(seq_id, p0, p1, shift); } void llama_memory_hybrid::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) { + if (llama_exact_concurrency() && d != 1) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support dividing positions (seq %d, d %d); ignoring the division\n", + __func__, seq_id, d); + return; + } + mem_attn->seq_div(seq_id, p0, p1, d); mem_recr->seq_div(seq_id, p0, p1, d); } diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 484eafb74991..70ba19ca3239 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -58,6 +58,8 @@ class llama_memory_hybrid : public llama_memory_i { bool get_can_shift() const override; + uint32_t alloc_granularity() const override; + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 2893d819e507..a1a1272118d2 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -458,7 +458,10 @@ llama_memory_context_ptr llama_memory_recurrent::init_batch(llama_batch_allocr & // [TAG_RECURRENT_ROLLBACK_SPLITS] // the trailing (1 + n_rs_seq) tokens of each seq must stay in the same ubatch // so that the rollback snapshots remain valid - ubatch = balloc.split_equal(n_ubatch, true, n_rs_seq > 0 ? n_rs_seq + 1 : 0); + // [TAG_EXACT_CONCURRENCY] same rule as the hybrid memory: the state a prompt leaves behind depends on what shared its ubatch, so isolate prompts + const uint32_t isolate = llama_exact_concurrency() ? llama_exact_decode_tokens() : 0; + + ubatch = balloc.split_equal(n_ubatch, true, n_rs_seq > 0 ? n_rs_seq + 1 : 0, isolate); } if (ubatch.n_tokens == 0) { diff --git a/src/llama-memory.h b/src/llama-memory.h index b33c7aee4128..87e7fe1f0bc2 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -101,6 +101,9 @@ struct llama_memory_i { // getters virtual bool get_can_shift() const = 0; + // [TAG_EXACT_CONCURRENCY] cells this module hands out in one indivisible unit: 1 unless a mode allocates in larger blocks, when n tokens occupy round_up(n, granularity) cells. Not pure, so old modules inherit 1. + virtual uint32_t alloc_granularity() const { return 1; } + // // ops // diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index daccea0639ad..75f6bdf606b4 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -178,6 +178,8 @@ if (NOT WIN32 OR NOT BUILD_SHARED_LIBS) llama_build_and_test(test-grammar-integration.cpp) llama_build_and_test(test-llama-grammar.cpp LINK llama) llama_build_and_test(test-batch-alloc.cpp LINK llama) + # [TAG_EXACT_CONCURRENCY] the buffer types the mode treats as invariant, through llama-impl.h + llama_build_and_test(test-exact-buft.cpp LINK llama) llama_build_and_test(test-chat.cpp WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) target_include_directories(test-chat PRIVATE ${PROJECT_SOURCE_DIR}/tools/server) target_link_libraries(test-chat PRIVATE server-context) @@ -319,6 +321,15 @@ llama_build_and_test(test-backend-sampler.cpp LABEL "model") llama_build_and_test(test-state-restore-fragmented.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-state-restore-fragmented PROPERTIES FIXTURES_REQUIRED test-download-model) +# Guards on the asynchronous per-sequence state transfer +# Skips itself on a backend that cannot copy asynchronously +llama_build_and_test(test-state-seq-copy.cpp LABEL "model" ARGS -m "${MODEL_DEST}") +set_tests_properties(test-state-seq-copy PROPERTIES FIXTURES_REQUIRED test-download-model) + +# [TAG_EXACT_CONCURRENCY] page bookkeeping of the paged KV pool; skips itself where the mode cannot run +llama_build_and_test(test-exact-pages.cpp LABEL "model" ARGS -m "${MODEL_DEST}") +set_tests_properties(test-exact-pages PROPERTIES FIXTURES_REQUIRED test-download-model) + if (APPLE) llama_build(test-rset-release.cpp) endif() @@ -337,6 +348,16 @@ llama_build_and_test(test-mtmd-c-api.c LINK mtmd) llama_build_and_test(test-mtmd-impl.cpp LINK mtmd) +# [TAG_EXACT_CONCURRENCY] the batch shape the mode requires, checked without a model +llama_build_and_test(test-exact-geometry.cpp) + +# server helpers that need no model +if (LLAMA_BUILD_TOOLS) + llama_build_and_test(test-server-tokens.cpp) + target_link_libraries(test-server-tokens PRIVATE server-context mtmd) + target_include_directories(test-server-tokens PRIVATE ${PROJECT_SOURCE_DIR}/tools/server ${PROJECT_SOURCE_DIR}/tools/mtmd) +endif() + # GGUF model data fetcher library for tests that need real model metadata # Only compile when cpp-httplib has SSL support (CPPHTTPLIB_OPENSSL_SUPPORT) if (TARGET cpp-httplib) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index bd599e99e55d..7deb7139982a 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -8503,6 +8503,40 @@ struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { } }; +// same attention as the CPU mask reference, but visiting nonadjacent pages in a different order +struct test_flash_attn_ext_pages : public test_flash_attn_ext { + test_flash_attn_ext_pages(int64_t batch) : + test_flash_attn_ext(256, 256, 2, {8, 1}, 1024, batch) {} + + std::string vars() override { return test_flash_attn_ext::vars() + ",exact_pages=1"; } + + ggml_tensor * build_graph(ggml_context * ctx) override { + auto * out = test_flash_attn_ext::build_graph(ctx); + out->src[5] = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, 5, nb); + ggml_set_name(out->src[5], "pages"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + test_flash_attn_ext::initialize_tensors(ctx); + auto * pages = ggml_get_tensor(ctx, "pages"); + auto * mask = ggml_get_tensor(ctx, "m"); + std::vector ids(5*nb, -1); + std::vector values(1024*nb, ggml_fp32_to_fp16(-INFINITY)); + for (int64_t q = 0; q < nb; ++q) { + ids[5*q] = q%2 ? 1 : 2; + ids[5*q + 1] = 2; + ids[5*q + 2] = 0; + for (int j = 0; j < 256; ++j) { values[1024*q + 512 + j] = ggml_fp32_to_fp16(0.0f); } + if (q%2 == 0) { + for (int j = 0; j < 17; ++j) { values[1024*q + j] = ggml_fp32_to_fp16(0.0f); } + } + } + ggml_backend_tensor_set(pages, ids.data(), 0, ids.size()*sizeof(int32_t)); + ggml_backend_tensor_set(mask, values.data(), 0, values.size()*sizeof(ggml_fp16_t)); + } +}; + // GGML_OP_CROSS_ENTROPY_LOSS struct test_cross_entropy_loss : public test_case { const ggml_type type; @@ -10691,6 +10725,21 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, m, 2, 1024, { 1, 1 }, { 1, 1 })); } + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_Q4_K, GGML_TYPE_Q6_K, GGML_TYPE_Q8_0}) { + for (int n : {1, 17, 307}) { + test_cases.emplace_back(new test_mul_mat(type, GGML_TYPE_F32, 64, n, 256, {1, 1}, {4, 1})); + test_cases.emplace_back(new test_mul_mat(type, GGML_TYPE_F32, 64, n, 256, {1, 1}, {1, 4})); + } + } + + // MoE projections at the token counts a decode ubatch forms; 17 tokens is past the width exact concurrency pins + for (ggml_type type_a : {GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_Q8_0, GGML_TYPE_F16}) { + for (int n : {1, 2, 4, 8, 17}) { + test_cases.emplace_back(new test_mul_mat_id(type_a, GGML_TYPE_F32, 16, 8, true, 512, n, 2048)); + test_cases.emplace_back(new test_mul_mat_id(type_a, GGML_TYPE_F32, 16, 8, false, 2048, n, 512)); + } + } + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_0, GGML_TYPE_F32, 2880, 32, 2880, {1, 1}, {1, 1})); test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 2880, 32, 2880, {1, 1}, {1, 1})); test_cases.emplace_back(new test_mul_mat(GGML_TYPE_MXFP4, GGML_TYPE_F32, 2880, 32, 2880, {1, 1}, {1, 1})); @@ -11665,6 +11714,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 113, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); // mixed quant and Q1_0 test cases + for (int64_t batch : {1, 4, 12}) { + test_cases.emplace_back(new test_flash_attn_ext_pages(batch)); + } test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0)); test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_F16)); test_cases.emplace_back(new test_flash_attn_ext(72, 72, 4, {1, 1}, 96, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_Q8_0)); diff --git a/tests/test-exact-buft.cpp b/tests/test-exact-buft.cpp new file mode 100644 index 000000000000..c7f93c857d7a --- /dev/null +++ b/tests/test-exact-buft.cpp @@ -0,0 +1,60 @@ +// [TAG_EXACT_CONCURRENCY] which buffer types the mode accepts a weight in. A host buffer is not one +// of them: the scheduler runs an operation on the backend holding its weight, and moves a host +// weight's operation to the GPU only once the batch is wide enough, so its result would depend on +// how many sequences share the step. This is the predicate behind both the context's weight check +// and the refusal of a lora that would inherit such a buffer. + +#include "ggml-backend.h" + +#include "../src/llama-impl.h" + +#include + +#undef NDEBUG +#include + +int main() { + ggml_backend_load_all(); + + // nothing placed anywhere is nothing to trust + assert(!llama_exact_buft_invariant(nullptr)); + + // the plain CPU buffer, and the pinned host buffer a GPU backend offers, are both host memory + assert(!llama_exact_buft_invariant(ggml_backend_cpu_buffer_type())); + + bool checked_gpu = false; + + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + + if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU) { + continue; + } + + ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev); + + const bool invariant = reg && llama_exact_backend_name(ggml_backend_reg_name(reg)); + + // a device's own buffer follows its backend, and its host buffer never does + assert(llama_exact_buft_invariant(ggml_backend_dev_buffer_type(dev)) == invariant); + + if (auto * host = ggml_backend_dev_host_buffer_type(dev)) { + assert(!llama_exact_buft_invariant(host)); + } + + checked_gpu = checked_gpu || invariant; + } + + // the registry names the mode trusts, whatever this build has + assert(llama_exact_backend_name("CUDA")); + assert(llama_exact_backend_name("ROCm")); + assert(llama_exact_backend_name("MUSA")); + assert(!llama_exact_backend_name("CPU")); + assert(!llama_exact_backend_name("BLAS")); + assert(!llama_exact_backend_name(nullptr)); + + printf("%s: all tests passed%s\n", __func__, + checked_gpu ? "" : " (no batch-invariant device here, the positive case was not exercised)"); + + return 0; +} diff --git a/tests/test-exact-geometry.cpp b/tests/test-exact-geometry.cpp new file mode 100644 index 000000000000..7e6e80e07f6b --- /dev/null +++ b/tests/test-exact-geometry.cpp @@ -0,0 +1,55 @@ +// [TAG_EXACT_CONCURRENCY] the batch shape a prefill needs to be split into the ubatches it would +// get alone: the server adds a prompt in whole ubatches, so the batch has to hold one of those +// beside a decode step of every slot, or the prompt is left the shorter remainder. + +#include "common.h" + +#include + +#undef NDEBUG +#include + +int main() { + int n_min = 0; + + // the reported minimum is the ubatch plus the decode step, whether or not the batch reaches it + assert(common_exact_batch_geometry(2048, 512, 4, &n_min)); + assert(n_min == 516); + + // the case that used to warn and carry on: one decoder beside the prompt leaves it 511 tokens + assert(!common_exact_batch_geometry(512, 512, 1, &n_min)); + assert(n_min == 513); + + assert(!common_exact_batch_geometry(512, 512, 2, &n_min)); + assert(n_min == 514); + + // exactly enough, and one short of it + assert(common_exact_batch_geometry(514, 512, 2, &n_min) && n_min == 514); + assert(!common_exact_batch_geometry(513, 512, 2, &n_min) && n_min == 514); + + // a single slot with no draft still needs room for its own decoded token + assert(!common_exact_batch_geometry(512, 512, 1)); + assert(common_exact_batch_geometry(1024, 512, 1)); + + // an unset ubatch is the whole batch, which then cannot hold a decode step as well + assert(!common_exact_batch_geometry(2048, 0, 4, &n_min)); + assert(n_min == 2052); + + // a ubatch larger than the batch is clamped to it, so it cannot pass either + assert(!common_exact_batch_geometry(512, 4096, 1, &n_min)); + assert(n_min == 513); + + // the shape a context settles on when its size clamps the batch: n_batch becomes min(n_ctx, -b) + // and n_ubatch min(n_batch, -ub), so a context of 256 cells leaves the two equal and no column + // for a decode step, whatever -b and -ub asked for + assert(!common_exact_batch_geometry(256, 256, 2, &n_min)); + assert(n_min == 258); + + // no slot decoding at all: the prompt has the batch to itself + assert(common_exact_batch_geometry(512, 512, 0, &n_min)); + assert(n_min == 512); + + printf("%s: all tests passed\n", __func__); + + return 0; +} diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp new file mode 100644 index 000000000000..c9e0993744a2 --- /dev/null +++ b/tests/test-exact-pages.cpp @@ -0,0 +1,162 @@ +// [TAG_EXACT_CONCURRENCY] drives the removal paths of the paged KV pool - a removal that empties nothing, one that leaves holes, and the pages those holes keep reserved - while LLAMA_KV_CACHE_DEBUG=1 makes the pool cross-check page ownership against the live cells every ubatch. +// Needs a CUDA build with 256-wide heads and a fully offloaded F16 cache; without one the test reports what it skipped and passes. + +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include +#include +#include + +static const uint32_t PAGE = 256; + +static bool decode_range(llama_context * ctx, llama_seq_id seq, llama_pos first, llama_pos last) { + common_batch batch(ctx); + + bool ok = true; + + for (llama_pos p = first; p <= last && ok; ) { + batch.clear(); + + for (int i = 0; i < 64 && p <= last; ++i, ++p) { + // every decode asks for one set of logits, so none of them is a batch with no output + batch.add(1, p, seq, i == 63 || p == last); + } + + ok = llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch.get()) == 0; + } + + return ok; +} + +// Windows has no setenv +static void set_env_default(const char * name, const char * value) { + if (getenv(name)) { + return; + } +#ifdef _WIN32 + _putenv_s(name, value); +#else + setenv(name, value, 0); +#endif +} + +int main(int argc, char ** argv) { + // read before the model is loaded: both are latched on first use + set_env_default("LLAMA_EXACT_CONCURRENCY", "1"); + set_env_default("LLAMA_KV_CACHE_DEBUG", "1"); + + common_params params; + + params.sampling.seed = 1234; + params.kv_unified = true; + params.n_parallel = 2; + params.n_ctx = 2*4*PAGE; + params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; + + common_init(); + + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + + // after the parser, which requires the default here + params.n_gpu_layers = 999; + + ggml_backend_load_all(); + + common_init_result_ptr llama_init = common_init_from_params(params); + + llama_context * ctx = llama_init->context(); + + if (llama_init->model() == nullptr || ctx == nullptr) { + printf("%s : skipped, this build and model cannot run exact concurrency\n", __func__); + return 0; + } + + llama_memory_t mem = llama_get_memory(ctx); + + const uint32_t gran = llama_memory_alloc_granularity(mem); + if (gran != PAGE) { + fprintf(stderr, "%s : allocation granularity is %u, expected %u\n", __func__, gran, PAGE); + return 1; + } + + // positions 0..599 of sequence 0: three pages, the last one part full + if (!decode_range(ctx, 0, 0, 599)) { + fprintf(stderr, "%s : failed to fill sequence 0\n", __func__); + return 1; + } + + // a page belongs to one sequence, so a cross-sequence copy is refused whole rather than half + // applied: the pool logs the refusal and leaves the destination empty and the source as it was + llama_memory_seq_cp(mem, 0, 1, -1, -1); + + if (llama_memory_seq_pos_max(mem, 1) != -1 || llama_memory_seq_pos_max(mem, 0) != 599) { + fprintf(stderr, "%s : a refused copy left sequence 1 at %d and sequence 0 at %d\n", __func__, + llama_memory_seq_pos_max(mem, 1), llama_memory_seq_pos_max(mem, 0)); + return 1; + } + + // the removal every accepted speculative step makes: a rejected tail that is not there. It + // must leave the pool alone, ownership included + if (!llama_memory_seq_rm(mem, 0, 600, -1) || llama_memory_seq_pos_max(mem, 0) != 599) { + fprintf(stderr, "%s : a removal past the tail changed the sequence, its end is %d\n", + __func__, llama_memory_seq_pos_max(mem, 0)); + return 1; + } + + if (!decode_range(ctx, 0, 600, 655)) { + fprintf(stderr, "%s : failed to continue sequence 0 after a removal that removed nothing\n", __func__); + return 1; + } + + // holes: positions 1 to 510 go, 0 and 511 to 655 stay, so the first two pages each keep a live + // cell and neither is free for another sequence. A hybrid memory refuses to remove the middle + // of a sequence, and then there is nothing to check here + const bool holes = llama_memory_seq_rm(mem, 0, 1, 511); + + if (holes && llama_memory_seq_pos_max(mem, 0) != 655) { + fprintf(stderr, "%s : a partial removal changed the end of the sequence: %d\n", __func__, + llama_memory_seq_pos_max(mem, 0)); + return 1; + } + + printf("%s : interior removal %s\n", __func__, holes ? "left holes" : "was refused, skipping the hole case"); + + // sequence 1 fills what is left of the pool. The pool holds 8 pages and sequence 0 holds 3 of + // them, holes and a part full tail page included, so 5 remain + if (!decode_range(ctx, 1, 0, 5*PAGE - 1)) { + fprintf(stderr, "%s : failed to fill the pages sequence 0 does not hold\n", __func__); + return 1; + } + + // one page more than the pool has left: it has to refuse rather than take a page that still + // has a live cell in it + if (decode_range(ctx, 1, 5*PAGE, 5*PAGE)) { + fprintf(stderr, "%s : the pool allocated a page that sequence 0 still holds\n", __func__); + return 1; + } + + // a whole sequence goes back to the pool as whole pages, holes included + if (!llama_memory_seq_rm(mem, 0, -1, -1) || llama_memory_seq_pos_max(mem, 0) != -1) { + fprintf(stderr, "%s : sequence 0 is still in the pool after a full removal\n", __func__); + return 1; + } + + if (!decode_range(ctx, 1, 5*PAGE, 8*PAGE - 1)) { + fprintf(stderr, "%s : the three pages of the removed sequence were not reusable\n", __func__); + return 1; + } + + // the pool is full again + if (decode_range(ctx, 1, 8*PAGE, 8*PAGE)) { + fprintf(stderr, "%s : the pool allocated a ninth page\n", __func__); + return 1; + } + + printf("%s : ok, page ownership survived a no-op removal, holes and a full removal\n", __func__); + + return 0; +} diff --git a/tests/test-server-tokens.cpp b/tests/test-server-tokens.cpp new file mode 100644 index 000000000000..051e01a15f0d --- /dev/null +++ b/tests/test-server-tokens.cpp @@ -0,0 +1,184 @@ +// [TAG_PREEMPT] the server converts between a KV position and a token count when it rewinds a slot to +// what the cache holds. With M-RoPE media the two differ, so the conversion is exercised here on a +// hand-built image chunk, without a model. + +#include "server-common.h" + +#include "mtmd.h" + +#include +#include +#include +#include +#include +#include + +#undef NDEBUG +#include + +// the wire format of mtmd_input_chunk_save(), which needs a context to produce a chunk; written here so +// that a chunk of a known shape can be loaded without one +struct chunk_writer { + std::vector buf; + + template void put(T v) { + const char * p = reinterpret_cast(&v); + buf.insert(buf.end(), p, p + sizeof(T)); + } + + void put_str(const std::string & s) { + put(s.size()); + buf.insert(buf.end(), s.begin(), s.end()); + } +}; + +// nx*ny tokens of one image, max(nx, ny) positions under M-RoPE +static mtmd::input_chunk_ptr make_image_chunk(uint32_t nx, uint32_t ny) { + chunk_writer w; + + w.put(2); // MTMD_SERIALIZATION_VERSION + w.put(MTMD_INPUT_CHUNK_TYPE_IMAGE); + w.put(0); // tokens_text + w.put(1); // tokens_image follows + w.put(nx); + w.put(ny); + w.put(1); // MTMD_POS_TYPE_MROPE + w.put(0); // image_idx + w.put(1); // n_temporal_merge + w.put_str("test-image"); // id + w.put(0); // batch_f32.is_audio + w.put(1); // one entry + w.put(0); // entry.add_viewsep + w.put(0); // entry.add_newline + w.put(0); // entry.lead_pad + w.put(1); // entry.nx + w.put(1); // entry.ny + w.put(0); // no tokens_audio + + mtmd::input_chunk_ptr chunk(mtmd_input_chunk_load(w.buf.data(), w.buf.size())); + + assert(chunk && "the serialized image chunk was rejected"); + + return chunk; +} + +// 10 text tokens, an image of 256 tokens and 16 positions, 20 text tokens, then n_gen generated tokens +static server_tokens make_prompt(size_t n_gen, const mtmd_input_chunk * chunk) { + server_tokens res; + + res.has_mtmd = true; + + for (size_t i = 0; i < 10; ++i) { + res.push_back((llama_token) (100 + i)); + } + + res.push_back(chunk); + + for (size_t i = 0; i < 20; ++i) { + res.push_back((llama_token) (200 + i)); + } + + for (size_t i = 0; i < n_gen; ++i) { + res.push_back((llama_token) (300 + i)); + } + + return res; +} + +int main() { + const mtmd::input_chunk_ptr chunk = make_image_chunk(16, 16); + + assert(mtmd_input_chunk_get_n_tokens(chunk.get()) == 256); + assert(mtmd_input_chunk_get_n_pos (chunk.get()) == 16); + + // a cut in the generated tail: the cache reports 86 positions, which is 326 tokens + { + server_tokens prompt = make_prompt(40, chunk.get()); + + assert(prompt.size() == 326); + assert(prompt.pos_next() == 86); + + const llama_pos pos_cached = 86; + const size_t n_cached = prompt.size_up_to_pos(pos_cached); + + assert(n_cached == 326); + assert(prompt.pos_next(n_cached) == pos_cached); + + // the same number taken for a token count falls inside the image + bool threw = false; + + try { + prompt.keep_first((size_t) pos_cached); + } catch (const std::exception &) { + threw = true; + } + + assert(threw && "a position used as a token count cuts the image in half"); + } + + // the same prompt with a longer tail, cut inside the generated tokens + { + server_tokens prompt = make_prompt(300, chunk.get()); + + assert(prompt.size() == 586); + assert(prompt.pos_next() == 346); + + const llama_pos pos_cached = 106; // 10 text + 16 image + 20 text + 60 generated + const size_t n_cached = prompt.size_up_to_pos(pos_cached); + + assert(n_cached == 346); + assert(prompt.pos_next(n_cached) == pos_cached); + + prompt.keep_first(n_cached); + + assert(prompt.size() == 346); + assert(prompt.pos_next() == pos_cached); + } + + // a cut before the image, and one at its first token: both are token boundaries + { + server_tokens prompt = make_prompt(0, chunk.get()); + + assert(prompt.size_up_to_pos(10) == 10); + assert(prompt.pos_next(10) == 10); + + // the image ends at position 26 and token 266 + assert(prompt.size_up_to_pos(26) == 266); + assert(prompt.pos_next(266) == 26); + } + + // a cut inside the image: the conversion cannot land there, and stepping back reaches the chunk's first token + { + server_tokens prompt = make_prompt(0, chunk.get()); + + const llama_pos pos_cached = 20; // inside the image, which spans positions 10..25 + + size_t n_cached = prompt.size_up_to_pos(pos_cached); + + assert(n_cached == 266); // rounded up to the whole chunk + + while (n_cached > 0 && prompt.pos_next(n_cached) > pos_cached) { + n_cached--; + } + + assert(n_cached == 10); + assert(prompt.pos_next(n_cached) == 10); + + prompt.keep_first(n_cached); // would throw if it cut the image in half + assert(prompt.size() == 10); + } + + // an empty cache has to be handled by the caller: the walk always consumes its first token + { + server_tokens prompt = make_prompt(4, chunk.get()); + + const llama_pos pos_cached = 0; + + assert(prompt.size_up_to_pos(pos_cached) == 1); + assert((pos_cached > 0 ? prompt.size_up_to_pos(pos_cached) : 0) == 0); + } + + printf("%s: all tests passed\n", __func__); + + return 0; +} diff --git a/tests/test-state-restore-fragmented.cpp b/tests/test-state-restore-fragmented.cpp index d20c231d71cb..f2f2043dd126 100644 --- a/tests/test-state-restore-fragmented.cpp +++ b/tests/test-state-restore-fragmented.cpp @@ -76,6 +76,13 @@ int main(int argc, char ** argv) { } fprintf(stderr, "%s : saved seq 1 state, %zu bytes\n", __func__, ncopy); + // a fragmented restore may stage a whole device tensor, so check every sequence byte-for-byte, neighbours included + std::vector> before(params.n_parallel); + for (int s = 0; s < params.n_parallel; ++s) { + before[s].resize(llama_state_seq_get_size(ctx, s)); + GGML_ASSERT(llama_state_seq_get_data(ctx, before[s].data(), before[s].size(), s) == before[s].size()); + } + // clear seq 1 to create a "hole" in the KV cache (fragmentation) // 0.20.20.20.2.... llama_memory_t mem = llama_get_memory(ctx); @@ -98,6 +105,13 @@ int main(int argc, char ** argv) { } fprintf(stderr, "%s : restored state into seq 1, %zu bytes\n", __func__, nset); + for (int s = 0; s < params.n_parallel; ++s) { + std::vector after(llama_state_seq_get_size(ctx, s)); + GGML_ASSERT(llama_state_seq_get_data(ctx, after.data(), after.size(), s) == after.size()); + GGML_ASSERT(before[s] == after); + } + fprintf(stderr, "%s : all %d sequence snapshots are byte-identical after restore\n", __func__, params.n_parallel); + // Verify we can decode with the restored state // Generate one token to verify the restored state is usable auto sparams = llama_sampler_chain_default_params(); diff --git a/tests/test-state-seq-copy.cpp b/tests/test-state-seq-copy.cpp new file mode 100644 index 000000000000..9150927661fa --- /dev/null +++ b/tests/test-state-seq-copy.cpp @@ -0,0 +1,144 @@ +// [TAG_STATE_ASYNC] guards on the asynchronous state transfer: the buffer belongs to the transfer, so an oversized size is refused, and ON_DEVICE is refused as these go via the host + +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include +#include +#include + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "%s : FAILED at line %d: %s\n", __func__, \ + __LINE__, #cond); \ + return 1; \ + } \ + } while (0) + +int main(int argc, char ** argv) { + common_params params; + + params.sampling.seed = 1234; + params.kv_unified = true; + params.n_parallel = 2; + params.n_ctx = 256; + + common_init(); + + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + + ggml_backend_load_all(); + + common_init_result_ptr llama_init = common_init_from_params(params); + + llama_context * ctx = llama_init->context(); + + if (llama_init->model() == nullptr || ctx == nullptr) { + fprintf(stderr, "%s : failed to init\n", __func__); + return 1; + } + + // two sequences interleaved, so the cells of each are a comb rather than one block, which is what the transfer is built for + std::vector tokens(60, 1); + + common_batch batch(ctx); + for (size_t i = 0; i < tokens.size(); i++) { + for (int s = 0; s < params.n_parallel; ++s) { + batch.add(tokens[i], i, s, false); + } + } + batch.set_output(batch.size() - 1, true); + + if (llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch.get())) { + fprintf(stderr, "%s : failed to decode\n", __func__); + return 1; + } + + llama_state_seq_copy * cpy = llama_state_seq_copy_init(ctx); + + // a recurrent state does not stay in one row, so these models are refused a transfer whatever the backend can do + if (llama_model_is_recurrent(llama_init->model()) || llama_model_is_hybrid(llama_init->model())) { + CHECK(cpy == nullptr); + fprintf(stderr, "%s : a recurrent or hybrid model is refused a transfer, as it must be\n", __func__); + return 0; + } + + if (cpy == nullptr) { + fprintf(stderr, "%s : this backend cannot copy sequence states asynchronously, skipping\n", __func__); + return 0; + } + + const int seq_id = 1; + const size_t size = llama_state_seq_get_size_ext(ctx, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE); + + CHECK(size > 0); + + // nothing is allocated yet, so nothing is page-locked yet, whatever the backend offers + CHECK(llama_state_seq_copy_buf_is_pinned(cpy) == false); + CHECK(llama_state_seq_copy_buf(cpy) == nullptr); + + CHECK(llama_state_seq_copy_buf_resize(cpy, size) != nullptr); + CHECK(llama_state_seq_copy_buf_size(cpy) == size); + + fprintf(stderr, "%s : seq %d state is %zu bytes, %s host memory (backend offers %s)\n", + __func__, seq_id, size, + llama_state_seq_copy_buf_is_pinned(cpy) ? "pinned" : "pageable", + llama_state_seq_copy_buf_can_pin(cpy) ? "pinned" : "pageable"); + + CHECK(llama_state_seq_copy_get(cpy, size + 1, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == 0); + CHECK(llama_state_seq_copy_set(cpy, size + 1, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == 0); + + CHECK(llama_state_seq_copy_get(cpy, 0, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == 0); + CHECK(llama_state_seq_copy_set(cpy, 0, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == 0); + + CHECK(llama_state_seq_copy_get(cpy, size, seq_id, LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) == 0); + CHECK(llama_state_seq_copy_set(cpy, size, seq_id, LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) == 0); + + CHECK(llama_state_seq_copy_done(cpy)); + + fprintf(stderr, "%s : oversized, empty and ON_DEVICE transfers are all refused\n", __func__); + + // a transfer that fails part way must post nothing: the caller is told it failed and is free to reuse the buffer at once + CHECK(llama_state_seq_copy_get(cpy, size - 1, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == 0); + CHECK(llama_state_seq_copy_n_copies(cpy) == 0); + CHECK(llama_state_seq_copy_done(cpy)); + + fprintf(stderr, "%s : a transfer one byte short is refused and posts no copies\n", __func__); + + std::vector before(llama_state_seq_get_size(ctx, seq_id)); + CHECK(llama_state_seq_get_data(ctx, before.data(), before.size(), seq_id) == before.size()); + + CHECK(llama_state_seq_copy_get(cpy, size, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == size); + llama_state_seq_copy_wait(cpy); + + llama_memory_seq_rm(llama_get_memory(ctx), seq_id, -1, -1); + + CHECK(llama_state_seq_copy_set(cpy, size - 1, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == 0); + CHECK(llama_state_seq_copy_n_copies(cpy) == 0); + CHECK(llama_state_seq_copy_done(cpy)); + + CHECK(llama_state_seq_copy_set(cpy, size, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == size); + llama_state_seq_copy_wait(cpy); + + std::vector after(llama_state_seq_get_size(ctx, seq_id)); + CHECK(after.size() == before.size()); + CHECK(llama_state_seq_get_data(ctx, after.data(), after.size(), seq_id) == after.size()); + CHECK(before == after); + + fprintf(stderr, "%s : a transfer at the buffer's own size round-trips seq %d byte-for-byte\n", + __func__, seq_id); + + llama_state_seq_copy_buf_free(cpy); + CHECK(llama_state_seq_copy_buf_is_pinned(cpy) == false); + CHECK(llama_state_seq_copy_buf_capacity(cpy) == 0); + + llama_state_seq_copy_free(cpy); + + fprintf(stderr, "%s : SUCCESS\n", __func__); + + return 0; +} diff --git a/tools/server/README.md b/tools/server/README.md index 48c40eda7ca0..459b16d071df 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -166,6 +166,8 @@ For the full list of features, please refer to [server's changelog](https://gith | `-ctxcp, --ctx-checkpoints, --swa-checkpoints N` | max number of context checkpoints to create per slot (default: 32)[(more info)](https://github.com/ggml-org/llama.cpp/pull/15293)
(env: LLAMA_ARG_CTX_CHECKPOINTS) | | `-cms, --checkpoint-min-step N` | minimum spacing between context checkpoints in tokens (default: 8192, 0 = no minimum)
(env: LLAMA_ARG_CHECKPOINT_MIN_SPACING_NT) | | `-cram, --cache-ram N` | set the maximum cache size in MiB (default: 8192, -1 - no limit, 0 - disable)[(more info)](https://github.com/ggml-org/llama.cpp/pull/16391)
(env: LLAMA_ARG_CACHE_RAM) | +| `--preempt-ram N` | 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: 0 - disabled, -1 - no limit)
(env: LLAMA_ARG_PREEMPT_RAM) | +| `--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)
(env: LLAMA_ARG_PREEMPT_ASYNC) | | `-kvu, --kv-unified, -no-kvu, --no-kv-unified` | use single unified KV buffer shared across all sequences (default: enabled if number of slots is auto)
(env: LLAMA_ARG_KV_UNIFIED) | | `--cache-idle-slots, --no-cache-idle-slots` | save idle slots to the prompt cache on new task, and clear them when using unified KV (default: enabled, requires cache-ram)
(env: LLAMA_ARG_CACHE_IDLE_SLOTS) | | `--context-shift, --no-context-shift` | whether to use context shift on infinite text generation (default: disabled)
(env: LLAMA_ARG_CONTEXT_SHIFT) | @@ -674,6 +676,18 @@ These words will not be included in the completion, so make sure to add them to - `tokens_cached`: Number of tokens from the prompt which could be re-used from previous completion - `tokens_evaluated`: Number of tokens evaluated in total from the prompt - `truncated`: Boolean indicating if the context size was exceeded during generation, i.e. the number of tokens provided in the prompt (`tokens_evaluated`) plus tokens generated (`tokens predicted`) exceeded the context size (`n_ctx`) +- `preempt`: How the request was served while the unified KV cache was full (see `--preempt-ram`). `parks` is how often the request was parked to make room for another, and `recomputes` is how many of those parks dropped the sequence's cells because `--preempt-ram` was spent, so that the resume re-prefilled its tokens instead of restoring the bytes that were saved. A re-prefilled sequence continues from the same tokens, but its numerics are not guaranteed identical to the sequence that left, `LLAMA_EXACT_CONCURRENCY` included: raise `--preempt-ram` until `recomputes` stays 0 where that matters. Both fields are present in the final response of a streamed completion as well, and on the OpenAI-compatible endpoints: the final chunk of a streamed `/v1/chat/completions`, the `message_delta` event of `/v1/messages`, and the response object of `/v1/responses` streamed or not, which in a stream is the `response` of the `response.completed` event. + +While a request is streaming, the server sends SSE comment lines that a client reading raw lines can act on and every SSE event consumer ignores: + +- `: preempted` - the slot was parked and the stream is silent until it comes back. A parked stream is kept alive with the same comment about every two seconds. +- `: resumed` - the slot is running again. +- `: recomputed` - sent right after `: resumed` when that resume re-prefilled the sequence rather than restoring its saved bytes, i.e. what follows is the continuation `preempt.recomputes` counts. +- `: preempt-keepalive` - sent while the slot stays parked, at most every 2 seconds, or at the request's `sse_ping_interval` when that is shorter. + +A park can happen while the prompt is still being processed, before the request has produced a token. The notice is not held back for the first chunk in that case: the response headers and the `: preempted` line go out at the moment the slot is parked, on every streaming surface (`/completion`, `/v1/chat/completions`, `/v1/responses`, `/v1/messages`), so a client never has to tell that silence from a stall. `: resumed`, and `: recomputed` where it applies, follow when the slot runs again. + +When the request asks for more than one completion, either several prompts or `n` above one, the index of the completion follows the word, for example `: resumed 1`, including index `0`. A request with a single completion carries no index. ### POST `/tokenize`: Tokenize a given text @@ -979,6 +993,8 @@ This endpoint is enabled by default and can be disabled with `--no-slots`. It ca If query param `?fail_on_no_slot=1` is set, this endpoint will respond with status code 503 if there is no available slots. +Every entry also reports how its request has been served under preemption (see `--preempt-ram`): `is_preempted` and `is_transferring` say whether the slot's cells have been released or a copy is in flight, `n_preempt` counts the parks of the current task, and `n_recompute` counts how many of those dropped the cells, so that the resume re-prefilled the sequence instead of restoring its saved bytes. + **Response format**
@@ -1146,6 +1162,11 @@ In *router mode* the query param `?model={model_id}` has to be set. This endpoin | `llamacpp:spec_decode_num_accepted_tokens_total` | Counter | Total draft tokens accepted by the target model (0 when spec-decode is off). | | `llamacpp:spec_decode_num_drafts_total` | Counter | Total speculative decoding verification steps (0 when spec-decode is off). | | `llamacpp:spec_decode_num_accepted_tokens_per_pos_total` | Counter | Accepted tokens per draft position (labeled `position="N"`; absent when spec-decode is off or before the first completed speculative request). | +| `llamacpp:n_preempt_total` | Counter | Slots parked to make room in the unified KV cache (0 unless `--kv-unified` with more than one slot). | +| `llamacpp:n_resume_total` | Counter | Parked slots put back. | +| `llamacpp:preempt_recompute_total` | Counter | Parks that dropped their cells because `--preempt-ram` was spent, so the resume re-prefills the sequence instead of restoring its saved bytes. | +| `llamacpp:requests_preempted` | Gauge | Requests currently parked, waiting for room in the unified KV cache. | +| `llamacpp:preempt_ram_bytes` | Gauge | Host RAM held by parked sequences. | ### POST `/slots/{id_slot}?action=save`: Save the prompt cache of the specified slot to a file. diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 98c72dec16f3..8af29d20e6ef 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -533,6 +533,12 @@ const mtmd::input_chunk_ptr & server_tokens::find_chunk(size_t idx) const { throw std::runtime_error("Chunk not found"); } +size_t server_tokens::chunk_n_tokens_at(size_t idx) const { + auto it = map_idx_to_media.find(idx); + + return it == map_idx_to_media.end() ? 0 : mtmd_input_chunk_get_n_tokens(it->second.get()); +} + std::pair server_tokens::find_next_media_chunk(size_t idx) const { auto it = map_idx_to_media.upper_bound(idx); if (it != map_idx_to_media.end()) { diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 5bd2ed57ab89..6528b35f34b7 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -202,6 +202,9 @@ struct server_tokens { const mtmd::input_chunk_ptr & find_chunk(size_t idx) const; + // tokens of the media chunk that starts at idx, 0 if none starts there + size_t chunk_n_tokens_at(size_t idx) const; + // find next media chunk after idx // returns a pair of pointer to the chunk (nullptr if not found) and its start index in tokens std::pair find_next_media_chunk(size_t idx) const; @@ -517,6 +520,12 @@ struct server_metrics { uint64_t n_decode = 0; uint64_t n_busy_slots = 0; + uint64_t n_preempt = 0; + uint64_t n_resume = 0; + + // [TAG_PREEMPT] parks that dropped their cells: those resumes re-prefill, and a re-prefill is not bit-for-bit the state that left + uint64_t n_preempt_recompute = 0; + uint64_t n_draft_tokens = 0; // Total draft tokens generated uint64_t n_draft_accepted = 0; // Draft tokens actually accepted uint64_t n_draft_verif_steps = 0; // Total draft token verification steps by the target model diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 60c563345399..b1e2e6dcc500 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -19,7 +19,9 @@ #include "mtmd-helper.h" #include +#include #include +#include #include #include #include @@ -130,8 +132,79 @@ enum slot_state { SLOT_STATE_PROCESSING_PROMPT, SLOT_STATE_DONE_PROMPT, SLOT_STATE_GENERATING, + SLOT_STATE_PREEMPTED, // [TAG_PREEMPT] cells released, everything needed to resume is in host RAM + SLOT_STATE_PREEMPTING, // [TAG_PREEMPT_ASYNC] the copy out is running; the cells are still this slot's + SLOT_STATE_RESTORING, // [TAG_PREEMPT_ASYNC] the copy back in is running; the cells are allocated but not yet filled }; +// [TAG_PREEMPT] server-side request preemption: instead of ending every conversation in flight with a context error, one slot's sequence is copied to host RAM and back when there is room +constexpr int32_t PREEMPT_N_MARGIN = 8; // cells left spare on top of the reservation +constexpr int64_t PREEMPT_KEEPALIVE_MS = 2000; // SSE keepalive period while a streaming slot is parked +constexpr int32_t PREEMPT_N_STARVED = 3; // preemptions after which a slot is protected + +static std::string preempt_notice_comment(const server_task_result_preempt_notice & notice) { + const std::string suffix = (notice.batched ? " " + std::to_string(notice.index) : "") + "\n\n"; + + std::string res = (notice.parked ? ": preempted" : ": resumed") + suffix; + + // [TAG_PREEMPT] the resume rebuilt the sequence from its tokens, so what follows is not the continuation the saved bytes would have given + if (!notice.parked && notice.recomputed) { + res += ": recomputed" + suffix; + } + + return res; +} +constexpr int32_t PREEMPT_N_FAIL_MAX = 8; // failed restores before the slot is given up on +constexpr int64_t PREEMPT_FAIL_US = 60ll * 1000 * 1000; // ... and only after this long parked +constexpr int64_t PREEMPT_ROTATE_US = 2ll * 1000 * 1000; // a resident cycling through context shifts gives way to a parked head that has waited this long +constexpr int64_t PREEMPT_ROTATE_RECOMPUTE_US = 30ll * 1000 * 1000; // ... and after this long it gives way even where that costs the resident a re-prefill + +// [TAG_PREEMPT_ASYNC] an asynchronous park only releases its cells when its copy lands, so it must fire this many decode steps before the pool would run out +constexpr int32_t PREEMPT_N_ASYNC_STEPS = 8; + +// [TAG_PREEMPT] test knob: LLAMA_SERVER_PREEMPT_FAIL_SAVE=N fails the host allocation of the Nth park, which no budget check can rule out, so that the fall back to a recompute park is exercised +static bool preempt_fail_save() { + static int32_t n_left = []() { + const char * val = getenv("LLAMA_SERVER_PREEMPT_FAIL_SAVE"); + + return val ? std::max(0, atoi(val)) : 0; + }(); + + return n_left > 0 && --n_left == 0; +} + +using llama_state_seq_copy_ptr = std::shared_ptr; + +static llama_state_seq_copy_ptr llama_state_seq_copy_make(llama_context * ctx) { + llama_state_seq_copy * cpy = ctx ? llama_state_seq_copy_init(ctx) : nullptr; + + return cpy ? llama_state_seq_copy_ptr(cpy, llama_state_seq_copy_free) : llama_state_seq_copy_ptr(); +} + +// [TAG_EXACT_CONCURRENCY] the planner counts cells, not tokens: a page belongs to one sequence, so a token count sees room find_slot cannot find and nobody is ever parked + +static constexpr int32_t preempt_n_cells_g(int32_t n_tokens, int32_t g) { + return (g <= 1 || n_tokens <= 0) ? n_tokens : ((n_tokens + g - 1) / g) * g; +} + +static constexpr int32_t preempt_n_cells_step_g(int32_t n_tokens, int32_t n_step, int32_t g) { + return preempt_n_cells_g(n_tokens + n_step, g) - preempt_n_cells_g(n_tokens, g); +} + +static_assert(preempt_n_cells_g(0, 1) == 0 && preempt_n_cells_g(1, 1) == 1 && + preempt_n_cells_g(8191, 1) == 8191 && preempt_n_cells_g(-3, 1) == -3, + "at a granularity of 1 a run of n tokens has to cost exactly n cells"); +static_assert(preempt_n_cells_step_g(0, 1, 1) == 1 && preempt_n_cells_step_g(8191, 1, 1) == 1 && + preempt_n_cells_step_g(1000, 512, 1) == 512, + "at a granularity of 1 a step of n tokens has to cost exactly n cells"); + +static_assert(preempt_n_cells_g(1, 256) == 256 && preempt_n_cells_g(256, 256) == 256 && + preempt_n_cells_g(257, 256) == 512, + "a tail page is charged in full"); +static_assert(preempt_n_cells_step_g(255, 1, 256) == 0 && preempt_n_cells_step_g(256, 1, 256) == 256 && + preempt_n_cells_step_g(256, 257, 256) == 512, + "a step is free until it crosses a page boundary and costs whole pages when it does"); + struct server_slot; // forward declaration struct server_batch { @@ -348,6 +421,384 @@ struct server_slot { prompt.clear(); } + slot_state state_before_preempt = SLOT_STATE_IDLE; + std::vector preempt_state_tgt; + std::vector preempt_state_dft; + + // [TAG_PREEMPT_ASYNC] the two transfers this slot parks and resumes through; they own the pinned host buffers, and are shared_ptr only so a slot survives the vector's reallocation + llama_state_seq_copy_ptr preempt_cpy_tgt; + llama_state_seq_copy_ptr preempt_cpy_dft; + + bool preempt_is_async() const { + return (bool) preempt_cpy_tgt; + } + + template + auto preempt_sum(F f) const -> decltype(f(preempt_cpy_tgt.get())) { + if (!preempt_is_async()) { + return 0; + } + + return f(preempt_cpy_tgt.get()) + (preempt_cpy_dft ? f(preempt_cpy_dft.get()) : 0); + } + + template + void preempt_each(F f) const { + if (preempt_cpy_tgt) { + f(preempt_cpy_tgt.get()); + } + + if (preempt_cpy_dft) { + f(preempt_cpy_dft.get()); + } + } + + int64_t preempt_sync_us() const { + return preempt_sum(llama_state_seq_copy_sync_us); + } + + size_t preempt_n_copies() const { + return preempt_sum(llama_state_seq_copy_n_copies); + } + + // [TAG_PREEMPT_ASYNC] a copy is running: the slot must not be scheduled but still owns cells, so it is neither running nor parked + bool preempt_in_flight() const { + return state == SLOT_STATE_PREEMPTING || state == SLOT_STATE_RESTORING; + } + + bool preempt_is_out() const { + return state == SLOT_STATE_PREEMPTED || preempt_in_flight(); + } + int32_t n_preempt = 0; // times the CURRENT task has been preempted + int32_t n_recompute = 0; // ... of which parked by dropping the cells, so the resume re-prefilled + int32_t n_ctx_shift = 0; // context shifts it has made: it is at the pool's limit and cycling + int32_t n_preempt_fail = 0; // consecutive failed restores + int64_t t_preempt_us = 0; // when it was parked + int64_t t_preempt_copy_us = 0; // [TAG_PREEMPT_ASYNC] when the current copy was issued + bool preempt_rotation_refused = false; // this park has logged a rotation refused for budget + + // [TAG_PREEMPT] a park with no room left under --preempt-ram: the cells are dropped instead of copied out, and the resume re-prefills the tokens + bool preempt_recompute = false; // parked by dropping its cells + bool preempt_reprefill = false; // putting back, as a prompt, what such a park dropped + server_tokens preempt_tokens; // what the re-prefill decodes: the prompt and everything generated so far + + size_t preempt_state_size() const { + // for a transfer the capacity, not the live size: the pinned buffers are kept between parks, so --preempt-ram has to bound what is held + return preempt_is_async() ? preempt_sum(llama_state_seq_copy_buf_capacity) + : preempt_state_tgt.size() + preempt_state_dft.size(); + } + + void preempt_state_free() { + // waits for anything in flight first: release() is reached with a copy possibly still using the buffer + preempt_each(llama_state_seq_copy_buf_free); + + preempt_state_tgt.clear(); + preempt_state_tgt.shrink_to_fit(); + preempt_state_dft.clear(); + preempt_state_dft.shrink_to_fit(); + } + + void preempt_copy_wait() { + preempt_each(llama_state_seq_copy_wait); + } + + size_t preempt_state_required() const { + return llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE) + + (ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0); + } + + // take the slot out of the step that is about to be built; the draft is a prediction, not a result, so it goes with the cells + void preempt_detach() { + spec_draft.clear(); + spec_i_batch.clear(); + spec_ckpt.clear(); + spec_is_replay = false; + + i_batch = -1; + } + + bool preempt_copy_done() { + return llama_state_seq_copy_done(preempt_cpy_tgt.get()) && + (!preempt_cpy_dft || llama_state_seq_copy_done(preempt_cpy_dft.get())); + } + + bool preempt_resumed() { + n_preempt_fail = 0; + + state = state_before_preempt; + + if (state == SLOT_STATE_GENERATING && can_speculate()) { + common_speculative_begin(spec, id, prompt.tokens.get_text_tokens()); + } + + return true; + } + + bool preempt_save_poll() { + if (!preempt_copy_done()) { + return false; + } + + mem.seq_rm(id, -1, -1); + + state = SLOT_STATE_PREEMPTED; + + return true; + } + + bool preempt_restore_poll() { + if (!preempt_copy_done()) { + return false; + } + + llama_state_seq_copy_buf_resize(preempt_cpy_tgt.get(), 0); + + if (preempt_cpy_dft) { + llama_state_seq_copy_buf_resize(preempt_cpy_dft.get(), 0); + } + + return preempt_resumed(); + } + + // the tokens the prompt step works through: its own list while re-prefilling, the request's otherwise + const server_tokens & preempt_input() const { + return preempt_tokens.empty() ? task->tokens : preempt_tokens; + } + + int32_t preempt_n_input() const { + return preempt_tokens.empty() ? (task ? task->n_tokens() : 0) : (int32_t) preempt_tokens.size(); + } + + // [TAG_PREEMPT] park with the host budget spent: drop the cells, keep the tokens, re-prefill them on resume. The sampler and the counters are untouched, so the stream carries on from the same token; the resume is bit-exact only as far as prefill numerics match decode numerics. A media chunk comes back the way it went in: the prompt step reads the chunk's data off the task and reserves its cells whole, so the placeholder the re-prefill list carries is all it needs + bool preempt_save_recompute() { + preempt_state_free(); + preempt_detach(); + + if (state == SLOT_STATE_GENERATING) { + preempt_tokens = std::move(prompt.tokens); + prompt.tokens = server_tokens(); + + prompt.tokens.has_mtmd = preempt_tokens.has_mtmd; // the re-prefill pushes the chunk's placeholder back into it + } + + prompt_clear(); + + state_before_preempt = state; + state = SLOT_STATE_PREEMPTED; + t_preempt_us = ggml_time_us(); + preempt_recompute = true; + preempt_rotation_refused = false; + + n_preempt++; + n_recompute++; + + return true; + } + + bool preempt_restore_recompute() { + preempt_recompute = false; + n_preempt_fail = 0; + + if (preempt_tokens.empty()) { + state = state_before_preempt; // its prompt had not been processed yet, so it is processed again from the start + + // the park dropped the cells the prompt step had already filled, and the restart does not pass through SLOT_STATE_STARTED, where these two are set: left alone they would count the dropped prefix a second time + stats.n_prompt_cached = 0; + stats.n_prompt_processed = 0; + + return true; + } + + preempt_reprefill = true; + state = SLOT_STATE_PROCESSING_PROMPT; + + return true; + } + + // every token is back in the cache: the slot goes on generating from the token it had already sampled + void preempt_reprefill_done() { + preempt_reprefill = false; + preempt_tokens.clear(); + + i_batch = -1; + state = SLOT_STATE_GENERATING; + + if (can_speculate()) { + common_speculative_begin(spec, id, prompt.tokens.get_text_tokens()); + } + } + + // [TAG_PREEMPT_ASYNC] copy the sequence out and release its cells; with a transfer this returns once the copy is issued and the cells stay the slot's until preempt_save_poll() sees it land + bool preempt_save() { + if (preempt_fail_save()) { + SLT_ERR(*this, "%s", "failed to allocate the host memory for the preemption state (test knob)\n"); + preempt_state_free(); + return false; + } + + const size_t size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); + const size_t size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + + if (preempt_is_async()) { + if (!llama_state_seq_copy_buf_resize(preempt_cpy_tgt.get(), size_tgt) || + (size_dft > 0 && (!preempt_cpy_dft || + !llama_state_seq_copy_buf_resize(preempt_cpy_dft.get(), size_dft)))) { + SLT_ERR(*this, "failed to allocate %.3f MiB of pinned host memory for the preemption state\n", + (size_tgt + size_dft) / (1024.0 * 1024.0)); + preempt_state_free(); + return false; + } + + // [TAG_PREEMPT_ASYNC] the load-time probe saw pinned memory, but a larger buffer can still come back pageable, and a copy into pageable memory blocks; such a slot parks synchronously from now on + const bool pageable = !llama_state_seq_copy_buf_is_pinned(preempt_cpy_tgt.get()) || + (size_dft > 0 && !llama_state_seq_copy_buf_is_pinned(preempt_cpy_dft.get())); + + if (pageable) { + SLT_WRN(*this, "the host memory for a %.3f MiB park is pageable, so this slot parks synchronously from now on\n", + (size_tgt + size_dft) / (1024.0 * 1024.0)); + + preempt_cpy_tgt.reset(); + preempt_cpy_dft.reset(); + } else { + if (llama_state_seq_copy_get(preempt_cpy_tgt.get(), size_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_tgt) { + SLT_ERR(*this, "%s", "failed to issue the copy of the target sequence out of the KV cache\n"); + preempt_state_free(); + return false; + } + + if (size_dft > 0 && + llama_state_seq_copy_get(preempt_cpy_dft.get(), size_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_dft) { + SLT_ERR(*this, "%s", "failed to issue the copy of the draft sequence out of the KV cache\n"); + preempt_state_free(); + return false; + } + + preempt_detach(); + + // note: no mem.seq_rm() here. The copy is still reading these cells; preempt_save_poll() releases them. + state_before_preempt = state; + state = SLOT_STATE_PREEMPTING; + t_preempt_us = ggml_time_us(); + + n_preempt++; + + return true; + } + } + + try { + preempt_state_tgt.resize(size_tgt); + preempt_state_dft.resize(size_dft); + } catch (const std::bad_alloc & e) { + SLT_ERR(*this, "failed to allocate %.3f MiB for the preemption state: %s\n", + (size_tgt + size_dft) / (1024.0 * 1024.0), e.what()); + preempt_state_free(); + return false; + } + + if (llama_state_seq_get_data_ext(ctx_tgt, preempt_state_tgt.data(), size_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_tgt) { + SLT_ERR(*this, "%s", "failed to copy the target sequence out of the KV cache\n"); + preempt_state_free(); + return false; + } + + if (size_dft > 0 && + llama_state_seq_get_data_ext(ctx_dft, preempt_state_dft.data(), size_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_dft) { + SLT_ERR(*this, "%s", "failed to copy the draft sequence out of the KV cache\n"); + preempt_state_free(); + return false; + } + + preempt_detach(); + + // note: prompt.tokens is deliberately kept - the resume sizes its request from it + mem.seq_rm(id, -1, -1); + + state_before_preempt = state; + state = SLOT_STATE_PREEMPTED; + t_preempt_us = ggml_time_us(); + preempt_rotation_refused = false; + + n_preempt++; + + return true; + } + + // [TAG_PREEMPT_ASYNC] put the sequence back; with a transfer this returns once the copy is issued, leaving the slot RESTORING: it owns the cells, but they hold no state until the copy lands + bool preempt_restore() { + if (preempt_recompute) { + return preempt_restore_recompute(); + } + + if (preempt_is_async()) { + const size_t size_tgt = llama_state_seq_copy_buf_size(preempt_cpy_tgt.get()); + const size_t size_dft = preempt_cpy_dft ? llama_state_seq_copy_buf_size(preempt_cpy_dft.get()) : 0; + + if (llama_state_seq_copy_set(preempt_cpy_tgt.get(), size_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_tgt || + (size_dft > 0 && + llama_state_seq_copy_set(preempt_cpy_dft.get(), size_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_dft)) { + // no room after all: let what was issued finish before the half-written sequence is dropped, or cells go while a copy still writes them + preempt_copy_wait(); + mem.seq_rm(id, -1, -1); + n_preempt_fail++; + return false; + } + + state = SLOT_STATE_RESTORING; + + return true; + } + + const size_t size_tgt = preempt_state_tgt.size(); + const size_t size_dft = preempt_state_dft.size(); + + if (llama_state_seq_set_data_ext(ctx_tgt, preempt_state_tgt.data(), size_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_tgt || + (size_dft > 0 && + llama_state_seq_set_data_ext(ctx_dft, preempt_state_dft.data(), size_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_dft)) { + mem.seq_rm(id, -1, -1); + n_preempt_fail++; + return false; + } + + preempt_state_free(); + + return preempt_resumed(); + } + + // [TAG_PREEMPT] bring prompt.tokens back to what the cache holds, for a batch given up after it was built: never-decoded tokens and the draft come off, `sampled` is kept + void rewind_to_cache() { + // the memory counts positions, and with M-RoPE media a position is not a token, so convert before truncating + const llama_pos pos_cached = llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), id) + 1; + + size_t n_cached = pos_cached > 0 ? prompt.tokens.size_up_to_pos(pos_cached) : 0; + + // a cut inside a media chunk is not a token boundary: keep what precedes the chunk, and the cells of its head go too + bool split_chunk = false; + + while (n_cached > 0 && prompt.tokens.pos_next(n_cached) > pos_cached) { + n_cached--; + split_chunk = true; + } + + if (n_cached < (size_t) prompt.n_tokens()) { + prompt.tokens.keep_first(n_cached); + } + + if (split_chunk) { + mem.seq_rm(id, prompt.tokens.pos_next(), -1); + } + + // what is kept ends where the cache does, or the next decode is positioned from the wrong count + GGML_ASSERT(prompt.tokens.pos_next() <= pos_cached); + + // the last chunk was marked done when it was built but never ran, so it is not done + if (state == SLOT_STATE_DONE_PROMPT && task && prompt.n_tokens() < preempt_n_input()) { + state = SLOT_STATE_PROCESSING_PROMPT; + } + + preempt_detach(); + } + std::vector lora; int32_t alora_invocation_start = -1; @@ -406,6 +857,17 @@ struct server_slot { n_predict_max = -1; + preempt_state_free(); + preempt_tokens.clear(); + preempt_recompute = false; + preempt_reprefill = false; + state_before_preempt = SLOT_STATE_IDLE; + n_preempt = 0; + n_recompute = 0; + n_preempt_fail = 0; + n_ctx_shift = 0; + t_preempt_us = 0; + llama_set_sampler(ctx_tgt, id, nullptr); // clear alora start @@ -591,6 +1053,13 @@ struct server_slot { t_last_used = ggml_time_us(); + // [TAG_PREEMPT] [TAG_PREEMPT_ASYNC] a parked slot's cells are already gone, so the mirror must not outlive them or the next task prefix-matches an empty cache; wait for any copy first, its buffer and its cells are about to be handed on + if (preempt_is_out()) { + preempt_copy_wait(); + preempt_state_free(); + prompt_clear(); + } + state = SLOT_STATE_IDLE; // do not keep context of the child slots - the parent's context is enough @@ -733,10 +1202,15 @@ struct server_slot { json res; res = { - {"id", id}, - {"n_ctx", n_ctx}, - {"speculative", can_speculate()}, - {"is_processing", is_processing()}, + {"id", id}, + {"n_ctx", n_ctx}, + {"speculative", can_speculate()}, + {"is_processing", is_processing()}, + // [TAG_PREEMPT] parked means the cells are gone; a copy out still owns them and a restore has already taken them back, so a scraper counting residency has to keep counting those two + {"is_preempted", state == SLOT_STATE_PREEMPTED}, + {"is_transferring", preempt_in_flight()}, + {"n_preempt", n_preempt}, + {"n_recompute", n_recompute}, }; const auto & ptask = task ? task : task_prev; @@ -981,6 +1455,30 @@ struct server_context_impl { metrics.reset_bucket(); } + // [TAG_PREEMPT] the first prompt of a request that cannot be served, with the error response it gets; false when every one of them passes. + // A park notice opens the stream of the member it belongs to, so a member rejected after that could only be told inside a stream that has already answered 200. + bool tasks_prompt_rejected(const std::vector & tasks, json & error) const { + std::string msg; + error_type type = ERROR_TYPE_SERVER; + + for (const auto & task : tasks) { + if (!task_prompt_rejected(task, msg, type)) { + continue; + } + + error = format_error_response(msg, type); + + if (type == ERROR_TYPE_EXCEED_CONTEXT_SIZE) { + error["n_prompt_tokens"] = task.n_tokens(); + error["n_ctx"] = n_ctx_slot(); + } + + return true; + } + + return false; + } + private: // note: accessing these fields outside of this class is not thread-safe // use server_context methods instead @@ -1045,6 +1543,17 @@ struct server_context_impl { int64_t t_last_load_progress_ms = 0; void destroy() { + // [TAG_PREEMPT_ASYNC] the slots outlive this call and may hold a copy reading or writing KV tensors of the contexts about to be freed; release() makes the same wait for one slot + for (auto & slot : slots) { + slot.preempt_copy_wait(); + + slot.preempt_cpy_tgt.reset(); + slot.preempt_cpy_dft.reset(); + } + + preempt_ram_kind_logged = false; + preempt_recompute_logged = false; + spec.reset(); spec_init.reset(); @@ -1451,6 +1960,20 @@ struct server_context_impl { } }; + // [TAG_PREEMPT_ASYNC] one transfer per context, reused for every park and resume, because each owns a backend and installs the fences the context records after every decode + if (preempt_async_possible()) { + slot.preempt_cpy_tgt = llama_state_seq_copy_make(ctx_tgt); + + if (slot.preempt_cpy_tgt && ctx_dft) { + slot.preempt_cpy_dft = llama_state_seq_copy_make(ctx_dft); + + if (!slot.preempt_cpy_dft) { + // a draft that cannot go asynchronously would have to be waited for mid-park, so the whole slot stays synchronous + slot.preempt_cpy_tgt.reset(); + } + } + } + slot.reset(); } @@ -1473,41 +1996,146 @@ struct server_context_impl { } { - const char * LLAMA_SERVER_SLOTS_N_DIFF = getenv("LLAMA_SERVER_SLOTS_N_DIFF"); - slots_n_diff = LLAMA_SERVER_SLOTS_N_DIFF ? atoi(LLAMA_SERVER_SLOTS_N_DIFF) : 0; + preempt_async_ok = !slots.empty(); - if (slots_n_diff) { - SRV_WRN("LLAMA_SERVER_SLOTS_N_DIFF = %d\n", slots_n_diff); + for (const auto & slot : slots) { + preempt_async_ok = preempt_async_ok && slot.preempt_is_async(); } - } - // the update_slots() logic will always submit a maximum of n_batch or n_parallel tokens - // note that n_batch can be > n_ctx (e.g. for non-causal attention models such as BERT where the KV cache is not used) - { - const int32_t n_batch = llama_n_batch(ctx_tgt); - const int32_t n_embd = llama_model_n_embd_inp(model_tgt); - batch.init(ctx_tgt, std::max(n_batch, params_base.n_parallel), n_embd); - } + if (preempt_async_possible()) { + if (preempt_async_ok) { + // a copy into pageable memory is staged by the driver and blocks the thread that issued it, and a host buffer type is free to hand back pageable memory rather than fail + bool pinned = llama_state_seq_copy_buf_can_pin(slots[0].preempt_cpy_tgt.get()); - if (params_base.cache_ram_mib != 0) { - if (params_base.cache_ram_mib < 0) { - SRV_TRC("prompt cache is enabled, size limit: %s\n", "no limit"); - } else { - SRV_TRC("prompt cache is enabled, size limit: %d MiB\n", params_base.cache_ram_mib); + if (pinned) { + auto * cpy = slots[0].preempt_cpy_tgt.get(); + + pinned = llama_state_seq_copy_buf_resize(cpy, 1u << 20) != nullptr && + llama_state_seq_copy_buf_is_pinned(cpy); + + llama_state_seq_copy_buf_free(cpy); + } + + if (pinned) { + SRV_INF("%s", "preemption: parking and resuming asynchronously through pinned host memory\n"); + } else { + SRV_WRN("%s", "preemption: the host memory on offer is pageable, so a copy would block the decode; parking and resuming synchronously\n"); + preempt_async_ok = false; + } + } else { + SRV_WRN("%s", "preemption: this backend cannot copy asynchronously, parking and resuming synchronously\n"); + } + } else if (params_base.preempt_ram_mib != 0 && params_base.preempt_async && + !llama_model_is_recurrent(model_tgt) && preempt_state_relocates()) { + SRV_WRN("%s", "preemption: a recurrent state does not stay in one row, so a copy running beside the decode could read another sequence; parking and resuming synchronously\n"); } - SRV_TRC("%s", "use `--cache-ram 0` to disable the prompt cache\n"); - prompt_cache = std::make_unique(params_base.cache_ram_mib, n_ctx); - } else { - SRV_TRC("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n"); + if (!preempt_async_ok) { + for (auto & slot : slots) { + slot.preempt_cpy_tgt.reset(); + slot.preempt_cpy_dft.reset(); + } + } } - SRV_TRC("%s", "for more info see https://github.com/ggml-org/llama.cpp/pull/16391\n"); - if (params_base.n_ctx_checkpoints > 0) { - SRV_TRC("context checkpoints enabled, max = %d, min spacing = %d\n", - params_base.n_ctx_checkpoints, params_base.checkpoint_min_step); - } else { - SRV_TRC("%s", "context checkpoints disabled\n"); + { + preempt_alloc_granularity = (int32_t) std::max(1u, llama_memory_alloc_granularity(llama_get_memory(ctx_tgt))); + + // test knob: the paged kernel needs a head size of 256, so a harness model cannot reach the paged arithmetic otherwise + const char * LLAMA_SERVER_PREEMPT_GRANULARITY = getenv("LLAMA_SERVER_PREEMPT_GRANULARITY"); + + if (LLAMA_SERVER_PREEMPT_GRANULARITY) { + preempt_alloc_granularity = std::max(1, atoi(LLAMA_SERVER_PREEMPT_GRANULARITY)); + + SRV_WRN("LLAMA_SERVER_PREEMPT_GRANULARITY = %d (test knob: planning the kv pool in blocks of %d cells)\n", + preempt_alloc_granularity, preempt_alloc_granularity); + } else if (preempt_alloc_granularity > 1 && params_base.preempt_ram_mib != 0) { + SRV_INF("preemption: the kv pool allocates %d cells at a time, planning in pages\n", + preempt_alloc_granularity); + } + } + + { + preempt_resume_head = true; + + const char * LLAMA_SERVER_PREEMPT_RESUME = getenv("LLAMA_SERVER_PREEMPT_RESUME"); + if (LLAMA_SERVER_PREEMPT_RESUME && strcmp(LLAMA_SERVER_PREEMPT_RESUME, "head") != 0) { + if (strcmp(LLAMA_SERVER_PREEMPT_RESUME, "pass") != 0) { + SRV_ERR("LLAMA_SERVER_PREEMPT_RESUME = %s is not a resume order; use head (the default) or pass\n", + LLAMA_SERVER_PREEMPT_RESUME); + return false; + } + preempt_resume_head = false; + SRV_WRN("%s", "LLAMA_SERVER_PREEMPT_RESUME = pass (parked slots come back most-preempted first, and a smaller slot may pass a head that does not fit)\n"); + } + + const char * LLAMA_SERVER_PREEMPT_EVERY = getenv("LLAMA_SERVER_PREEMPT_EVERY"); + preempt_test_every = LLAMA_SERVER_PREEMPT_EVERY ? atoi(LLAMA_SERVER_PREEMPT_EVERY) : 0; + + // LLAMA_SERVER_PREEMPT_POLICY: which non-leader the planner parks; smallest (default), largest, youngest, oldest + const char * LLAMA_SERVER_PREEMPT_POLICY = getenv("LLAMA_SERVER_PREEMPT_POLICY"); + preempt_test_policy = LLAMA_SERVER_PREEMPT_POLICY ? LLAMA_SERVER_PREEMPT_POLICY : "smallest"; + + if (preempt_test_policy != "smallest") { + SRV_WRN("LLAMA_SERVER_PREEMPT_POLICY = %s (test knob: victim choice for comparison only)\n", preempt_test_policy.c_str()); + } + + if (preempt_test_every > 0) { + SRV_WRN("LLAMA_SERVER_PREEMPT_EVERY = %d (test knob: preempting every slot every %d tokens)\n", + preempt_test_every, preempt_test_every); + } + + const char * LLAMA_SERVER_PREEMPT_PLANNER = getenv("LLAMA_SERVER_PREEMPT_PLANNER"); + preempt_planner_off = LLAMA_SERVER_PREEMPT_PLANNER && strcmp(LLAMA_SERVER_PREEMPT_PLANNER, "off") == 0; + + if (preempt_planner_off) { + SRV_WRN("%s", "LLAMA_SERVER_PREEMPT_PLANNER = off (test knob: nothing is parked ahead of the decode, only as a last resort)\n"); + } + + // assigned, not only set: a context reloaded with an attention model after a recurrent one gets preemption back + preempt_recurrent = llama_model_is_recurrent(model_tgt); + + if (preempt_recurrent && params_base.preempt_ram_mib != 0) { + SRV_WRN("%s", "preemption: off, the recurrent cache holds one state per sequence whatever its length, so there is no cell pool to run out of\n"); + } + } + + { + const char * LLAMA_SERVER_SLOTS_N_DIFF = getenv("LLAMA_SERVER_SLOTS_N_DIFF"); + slots_n_diff = LLAMA_SERVER_SLOTS_N_DIFF ? atoi(LLAMA_SERVER_SLOTS_N_DIFF) : 0; + + if (slots_n_diff) { + SRV_WRN("LLAMA_SERVER_SLOTS_N_DIFF = %d\n", slots_n_diff); + } + } + + // the update_slots() logic will always submit a maximum of n_batch or n_parallel tokens + // note that n_batch can be > n_ctx (e.g. for non-causal attention models such as BERT where the KV cache is not used) + { + const int32_t n_batch = llama_n_batch(ctx_tgt); + const int32_t n_embd = llama_model_n_embd_inp(model_tgt); + batch.init(ctx_tgt, std::max(n_batch, params_base.n_parallel), n_embd); + } + + if (params_base.cache_ram_mib != 0) { + if (params_base.cache_ram_mib < 0) { + SRV_TRC("prompt cache is enabled, size limit: %s\n", "no limit"); + } else { + SRV_TRC("prompt cache is enabled, size limit: %d MiB\n", params_base.cache_ram_mib); + } + SRV_TRC("%s", "use `--cache-ram 0` to disable the prompt cache\n"); + + prompt_cache = std::make_unique(params_base.cache_ram_mib, n_ctx); + } else { + SRV_TRC("%s", "prompt cache is disabled - use `--cache-ram N` to enable it\n"); + } + SRV_TRC("%s", "for more info see https://github.com/ggml-org/llama.cpp/pull/16391\n"); + + if (params_base.n_ctx_checkpoints > 0) { + SRV_TRC("context checkpoints enabled, max = %d, min spacing = %d\n", + params_base.n_ctx_checkpoints, params_base.checkpoint_min_step); + } else { + SRV_TRC("%s", "context checkpoints disabled\n"); } if (!params_base.model_alias.empty()) { @@ -2187,6 +2815,24 @@ struct server_context_impl { queue_results.send(std::move(res)); } + void send_preempt_notice(server_slot & slot, bool parked, bool recomputed = false) { + if (!slot.task || !slot.task->params.stream) { + return; + } + + auto res = std::make_unique(); + + res->id = slot.task->id; + res->index = slot.task->index; + res->id_slot = slot.id; + res->parked = parked; + res->recomputed = recomputed; + res->n_preempt = slot.n_preempt; + res->batched = slot.task->batched; + + queue_results.send(std::move(res)); + } + void send_partial_response(server_slot & slot, const completion_token_output & tkn, bool is_progress, bool is_begin = false) { auto res = std::make_unique(); @@ -2264,6 +2910,8 @@ struct server_context_impl { res->stopping_word = slot.stopping_word; res->stop = slot.stop; res->post_sampling_probs = slot.task->params.post_sampling_probs; + res->n_preempt = slot.n_preempt; + res->n_recompute = slot.n_recompute; res->verbose = slot.task->params.verbose; res->stream = slot.task->params.stream; @@ -2857,11 +3505,15 @@ struct server_context_impl { case SERVER_TASK_TYPE_METRICS: { int n_processing_slots = 0; + int n_preempted_slots = 0; for (server_slot & slot : slots) { if (slot.is_processing()) { n_processing_slots++; } + if (slot.preempt_is_out()) { + n_preempted_slots++; + } } SRV_DBG("n_processing_slots = %d\n", n_processing_slots); @@ -2869,6 +3521,8 @@ struct server_context_impl { res->id = task.id; res->n_processing_slots = n_processing_slots; res->n_tasks_deferred = queue_tasks.queue_tasks_deferred_size(); + res->n_preempted_slots = n_preempted_slots; + res->preempt_ram_bytes = preempt_ram_used(); res->metrics = metrics; if (task.metrics_reset_bucket) { @@ -3089,71 +3743,1083 @@ struct server_context_impl { } break; } - return true; - } + return true; + } + + void iterate(std::vector & slots, std::function callback) { + for (auto & slot : slots) { + try { + callback(slot); + } catch (const std::exception & e) { + SLT_ERR(slot, "got exception: %s\n", e.what()); + send_error(slot, std::string("got exception: ") + e.what(), ERROR_TYPE_SERVER); + slot.release(); + } + } + } + + void iterate(std::vector & slots, std::function callback) { + for (auto & slot : slots) { + try { + callback(*slot); + } catch (const std::exception & e) { + SLT_ERR(*slot, "got exception: %s\n", e.what()); + send_error(*slot, std::string("got exception: ") + e.what(), ERROR_TYPE_SERVER); + slot->release(); + } + } + } + + void abort_all_slots(const std::string & reason) { + for (auto & slot : slots) { + // [TAG_PREEMPT] a parked slot, or one with a copy in flight, took no part in what failed and comes back when there is room + if (slot.is_processing() && !slot.preempt_is_out()) { + send_error(slot, reason, ERROR_TYPE_SERVER); + slot.release(); + } + } + } + + // @ngxson : for debugging only + int64_t t_pre_decode = 0; + int64_t t_decode = 0; + int64_t t_post_decode = 0; + int64_t t_sampl = 0; + int64_t n_pre_decode = 0; + int64_t n_decode = 0; + int64_t n_post_decode = 0; + int64_t n_sampl = 0; +// #define DEBUG_TIMINGS +#ifdef DEBUG_TIMINGS + struct scoped_timer { + int64_t & t; + int64_t & n; + int64_t t_start; + scoped_timer(int64_t & t_, int64_t & n_) : t(t_), n(n_) { + t_start = ggml_time_us(); + } + ~scoped_timer() { + t += ggml_time_us() - t_start; + n++; + } + }; +#else + struct scoped_timer { + scoped_timer(int64_t &, int64_t &) {} + ~scoped_timer() {} + }; +#endif + + + // LLAMA_SERVER_PREEMPT_EVERY=N: preempt every generating slot every N tokens, pressure or not, so the determinism test can blame any difference on the preemption + int32_t preempt_test_every = 0; + std::string preempt_test_policy = "smallest"; // LLAMA_SERVER_PREEMPT_POLICY, see load_model + + // [TAG_PREEMPT_ASYNC] whether parks go through a transfer; false with --no-preempt-async or a backend that cannot copy asynchronously + bool preempt_async_ok = false; + + // [TAG_EXACT_CONCURRENCY] cells the pool hands out at a time, read once at load: 1 ordinarily, the page size under exact concurrency. LLAMA_SERVER_PREEMPT_GRANULARITY overrides it. + int32_t preempt_alloc_granularity = 1; + + int32_t preempt_n_cells(int32_t n_tokens) const { + return preempt_n_cells_g(n_tokens, preempt_alloc_granularity); + } + + int32_t preempt_n_cells_step(int32_t n_tokens, int32_t n_step) const { + return preempt_n_cells_step_g(n_tokens, n_step, preempt_alloc_granularity); + } + + // LLAMA_SERVER_PREEMPT_PLANNER=off (test knob): no parking ahead of the decode, leaving only the KV-full retry ladder + bool preempt_planner_off = false; + + // LLAMA_SERVER_PREEMPT_RESUME=head or pass, read at load, per context + bool preempt_resume_head = true; + + bool preempt_recurrent = false; + + bool preempt_batch_abandoned = false; + + // [TAG_PREEMPT_ASYNC] a context shift was recorded this round; it is applied in place inside the next llama_decode + bool preempt_shift_pending = false; + + int32_t preempt_n_spec_max() const { + return spec ? std::max(0, common_speculative_n_max(¶ms_base.speculative)) : 0; + } + + bool preempt_ram_kind_logged = false; + + // [TAG_PREEMPT] the fall back to a recompute park is logged once, not per park + bool preempt_recompute_logged = false; + + void preempt_log_ram_kind(const server_slot & slot) { + if (preempt_ram_kind_logged || !slot.preempt_is_async()) { + return; + } + + if (llama_state_seq_copy_buf_capacity(slot.preempt_cpy_tgt.get()) == 0) { + return; // nothing held, so nothing to report yet + } + + preempt_ram_kind_logged = true; + + SRV_INF("preemption: parking into %s host memory\n", + llama_state_seq_copy_buf_is_pinned(slot.preempt_cpy_tgt.get()) ? "pinned" : "pageable"); + } + + int32_t preempt_n_spec(const server_slot & slot) const { + int32_t res = preempt_n_spec_max(); + + if (res == 0 || !slot.task || !slot.can_speculate()) { + return 0; + } + + // a recompute park moved the prompt out of the slot, so the tokens it comes back with bound the draft, not the empty prompt: read as empty, a 2000-token sequence in a 2048-cell pool was charged a whole draft and failed as impossible + const int32_t n_tokens = std::max(slot.prompt.n_tokens(), slot.preempt_n_input()); + + res = std::min(res, slot.n_ctx - n_tokens - 2); + + if (slot.n_remaining() > 0) { + res = std::min(res, slot.n_remaining() - 1); + } + + return std::max(0, res); + } + + size_t preempt_ram_used() const { + size_t res = 0; + + for (const auto & slot : slots) { + res += slot.preempt_state_size(); + } + + return res; + } + + // [TAG_PREEMPT_ASYNC] a restored slot keeps its pinned buffer, so that idle capacity is given back largest first when a park does not fit under --preempt-ram + void preempt_reclaim_idle_ram(size_t budget, size_t extra, const server_slot & keep) { + for (;;) { + if (preempt_ram_used() + extra <= budget) { + return; + } + + server_slot * best = nullptr; + + for (auto & other : slots) { + if (&other == &keep) { + continue; + } + + if (other.state == SLOT_STATE_PREEMPTED || other.state == SLOT_STATE_PREEMPTING || other.state == SLOT_STATE_RESTORING) { + continue; + } + + if (other.preempt_state_size() == 0) { + continue; + } + + if (!best || other.preempt_state_size() > best->preempt_state_size()) { + best = &other; + } + } + + if (!best) { + return; + } + + SLT_INF(*best, "%.1f MiB of idle parked RAM returned so that another slot can park\n", + best->preempt_state_size() / (1024.0 * 1024.0)); + + best->preempt_state_free(); + } + } + + size_t preempt_ram_budget() const { + return params_base.preempt_ram_mib < 0 ? SIZE_MAX : (size_t) params_base.preempt_ram_mib * 1024 * 1024; + } + + bool preempt_fits_budget(const server_slot & slot) { + const size_t budget = preempt_ram_budget(); + + // what this slot already holds is counted by preempt_ram_used() and reused, so a park costs only the rest + const size_t held = slot.preempt_state_size(); + const size_t need = slot.preempt_state_required(); + const size_t extra = need > held ? need - held : 0; + + preempt_reclaim_idle_ram(budget, extra, slot); + + return preempt_ram_used() + extra <= budget; + } + + void preempt_trim_ram(server_slot & slot) { + if (preempt_ram_used() > preempt_ram_budget() && slot.preempt_state_size() > 0) { + SLT_INF(slot, "%.1f MiB of parked RAM returned: the pool is over its budget\n", slot.preempt_state_size() / (1024.0 * 1024.0)); + slot.preempt_state_free(); + } + } + + size_t preempt_n_keep(const server_slot & slot) const { + if (!slot.task->params.cache_prompt) { + return 0; + } + + size_t n_keep = slot.prompt.tokens.get_common_prefix(slot.task->tokens); + + if (slot.alora_invocation_start > 0) { + n_keep = std::min(n_keep, (size_t) (slot.alora_invocation_start - 1)); + } + + return n_keep; + } + + // a slot just given a task still mirrors the previous request's prompt, so what it holds and what it asks for both count from preempt_n_keep() + int32_t preempt_n_retained(const server_slot & slot) const { + if (slot.preempt_recompute) { + return (int32_t) slot.preempt_tokens.size(); // parked by dropping its cells: it comes back needing all of them at once + } + + if (slot.state == SLOT_STATE_STARTED && slot.task) { + return (int32_t) preempt_n_keep(slot); + } + + return slot.prompt.n_tokens(); + } + + // [TAG_PREEMPT] the cells the media chunks pending at n_have take: pre_decode() runs a whole chunk through llama_decode() calls of its own, which no kv-full retry covers, so the planner reserves the lot before it is decoded + int32_t preempt_n_mtmd_pending(const server_slot & slot, int32_t n_have) const { + if (!slot.task || !slot.task->tokens.has_mtmd) { + return 0; + } + + const auto & tokens = slot.task->tokens; + + int32_t res = 0; + + for (int32_t i = n_have; i >= 0 && i < (int32_t) tokens.size(); ) { + const int32_t n = (int32_t) tokens.chunk_n_tokens_at(i); + + if (n <= 0) { + break; + } + + res += n; + i += n; + } + + return res; + } + + int32_t preempt_n_need(const server_slot & slot) const { + int32_t res = preempt_n_retained(slot); + + if (slot.state_before_preempt == SLOT_STATE_GENERATING) { + res += 1 + preempt_n_spec(slot); + } else { + const int32_t n_mtmd = preempt_n_mtmd_pending(slot, res); + const int32_t n_left = slot.preempt_n_input() - res; + + res += n_mtmd > 0 ? n_mtmd : std::max(1, std::min((int32_t) llama_n_batch(ctx_tgt), n_left)); + } + + // [TAG_EXACT_CONCURRENCY] a restore takes fresh pages and its tail page is charged in full; undercounting admits a resume find_slot cannot satisfy + return preempt_n_cells(res); + } + + int32_t preempt_kv_used() const { + int32_t res = 0; + + // n_cmpl > 1: a family shares the prompt's cells through seq_cp, so it is charged once, to the first resident member + std::vector charged; + + for (const auto & slot : slots) { + if (slot.state == SLOT_STATE_PREEMPTED) { + continue; // parked: its cells are in host RAM, not in the pool + } + + // [TAG_PREEMPT_ASYNC] deliberately not skipped: a slot with a copy in flight holds cells either way, and skipping it would hand the same cells out twice + + if (slot.state == SLOT_STATE_WAIT_OTHER) { + res += preempt_n_cells(slot.prompt.n_tokens()); + continue; + } + + if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { + const int family = slot.task->is_parent() ? slot.task->id : slot.task->id_parent; + + if (std::find(charged.begin(), charged.end(), family) != charged.end()) { + res += preempt_n_cells(std::max(0, slot.prompt.n_tokens() - slot.task->n_tokens())); + continue; + } + + charged.push_back(family); + } + + res += preempt_n_cells(slot.prompt.n_tokens()); + } + + return res; + } + + // [TAG_PREEMPT_ASYNC] the room the pool is kept clear of, so everything still decoding has somewhere to put its tokens until a park lands; a resume candidate is charged the same runway + int32_t preempt_n_margin(int32_t n_additional_running = 0) const { + if (!preempt_async_ok) { + // [TAG_EXACT_CONCURRENCY] a margin of eight cells is no margin where a step can cost a whole page + return preempt_n_cells(PREEMPT_N_MARGIN); + } + + int32_t n_running = n_additional_running; + + for (const auto & slot : slots) { + if (slot.is_processing() && (!slot.preempt_is_out() || slot.state == SLOT_STATE_RESTORING)) { + n_running++; + } + } + + // [TAG_EXACT_CONCURRENCY] round the runway up to a page, once and not per slot, which would keep a page per slot out of the users' reach + return preempt_n_cells( + PREEMPT_N_MARGIN + n_running * (1 + preempt_n_spec_max()) * PREEMPT_N_ASYNC_STEPS); + } + + int32_t preempt_kv_reserve() const { + const int32_t n_batch = llama_n_batch(ctx_tgt); + + int32_t res = 0; + int32_t res_pmt = 0; + int32_t res_mm = 0; + int32_t n_pmt = 0; + + // [TAG_EXACT_CONCURRENCY] reserve the cells the next step ADDS, not its tokens: the used figure already rounds every tail page up, and only a page crossing can empty the pool + for (const auto & slot : slots) { + const int32_t n_cur = slot.prompt.n_tokens(); + + // [TAG_PREEMPT_ASYNC] a restoring slot decodes as soon as its copy lands, so it is charged the step of the state it goes back to, or that first step preempts somebody else + const slot_state state = slot.state == SLOT_STATE_RESTORING ? slot.state_before_preempt : slot.state; + + switch (state) { + case SLOT_STATE_GENERATING: + case SLOT_STATE_DONE_PROMPT: + { + res += preempt_n_cells_step(n_cur, 1 + preempt_n_spec(slot)); + } break; + case SLOT_STATE_STARTED: + case SLOT_STATE_PROCESSING_PROMPT: + { + const int32_t n_have = preempt_n_retained(slot); + const int32_t n_mtmd = preempt_n_mtmd_pending(slot, n_have); + + // a media chunk is decoded whole, past the batch cap below and past the kv-full retry + if (n_mtmd > 0) { + res_mm += preempt_n_cells_step(n_have, n_mtmd); + break; + } + + const int32_t n_left = slot.preempt_n_input() - n_have; + + res_pmt += preempt_n_cells_step(n_have, std::max(1, std::min(n_batch, n_left))); + n_pmt++; + } break; + default: + break; + } + } + + return res + res_mm + std::min(res_pmt, preempt_n_cells(n_batch) + std::max(0, n_pmt - 1) * (preempt_alloc_granularity - 1)); + } + + // [TAG_PREEMPT] trim a just-started slot to the prefix it keeps first, or it is copied out, charged and sized by the previous request's prompt + bool preempt_normalize_started_all() { + bool res = false; + + for (auto & slot : slots) { + const int32_t before = slot.prompt.n_tokens(); + + preempt_normalize_started(slot); + + if (slot.prompt.n_tokens() < before) { + SLT_INF(slot, "trimmed to the %d cells its request keeps ahead of the batch builder, %d released\n", + slot.prompt.n_tokens(), before - slot.prompt.n_tokens()); + res = true; + } + } + + return res; + } + + void preempt_normalize_started(server_slot & slot) { + if (slot.state != SLOT_STATE_STARTED || !slot.task) { + return; + } + + const size_t n_keep = preempt_n_keep(slot); + + if (n_keep >= slot.prompt.tokens.size()) { + return; + } + + // a memory that cannot remove part of a sequence aborts on a partial removal, so drop the whole stale sequence + const bool partial_ok = ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_PART && + (!ctx_dft || ctx_dft_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_PART); + + if (!partial_ok) { + slot.prompt.tokens.clear(); + slot.mem.seq_rm(slot.id, -1, -1); + return; + } + + slot.prompt.tokens.keep_first(n_keep); + slot.mem.seq_rm(slot.id, slot.prompt.tokens.pos_next(), -1); + } + + // `recompute` asks for a fallback: with no victim the host budget can hold, the same policy picks again and the park drops the cells instead of copying them + server_slot * preempt_pick_victim(bool * recompute = nullptr) { + server_slot * leader = nullptr; + int32_t n_running = 0; + + for (auto & slot : slots) { + preempt_normalize_started(slot); + } + + for (auto & slot : slots) { + if (slot.is_processing() && !slot.preempt_is_out()) { + n_running++; + + if (!leader || slot.prompt.n_tokens() > leader->prompt.n_tokens()) { + leader = &slot; + } + } + } + + if (n_running < 2) { + // one conversation that does not fit alone is a real overflow, not a scheduling problem + return nullptr; + } + + server_slot * victim = preempt_pick_victim_pass(leader, false); + + if (!victim && recompute) { + victim = preempt_pick_victim_pass(leader, true); + + *recompute = victim != nullptr; + } + + return victim; + } + + server_slot * preempt_pick_victim_pass(const server_slot * leader, bool recompute) { + server_slot * victim = nullptr; + + for (auto & slot : slots) { + // before the batch is built every slot is at a token boundary; one holding no cells is still worth parking + if (slot.state != SLOT_STATE_GENERATING && + slot.state != SLOT_STATE_PROCESSING_PROMPT && + slot.state != SLOT_STATE_STARTED) { + continue; + } + + if (&slot == leader) { + continue; + } + + if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { + continue; // n_cmpl > 1 slots share one sequence, out of scope here + } + + // a started slot the STARTED block is about to reject gets its error on its own pass: a park notice would open the stream and turn that 4xx into 200 plus an in-stream error + if (slot.state == SLOT_STATE_STARTED) { + std::string msg; + error_type type = ERROR_TYPE_SERVER; + + if (slot_prompt_rejected(slot, msg, type)) { + continue; + } + } + + if (!recompute && !preempt_fits_budget(slot)) { + continue; + } + + const bool starved = slot.n_preempt >= PREEMPT_N_STARVED; + const bool starved_cur = victim && victim->n_preempt >= PREEMPT_N_STARVED; + + if (!victim || + (starved_cur && !starved) || + (starved_cur == starved && preempt_better_victim(slot, *victim))) { + victim = &slot; + } + } + + return victim; + } + + bool preempt_better_victim(const server_slot & a, const server_slot & b) const { + if (preempt_test_policy == "largest") { + return a.prompt.n_tokens() > b.prompt.n_tokens(); + } + + if (preempt_test_policy == "youngest") { + return a.task->id > b.task->id; + } + + if (preempt_test_policy == "oldest") { + return a.task->id < b.task->id; + } + + return a.prompt.n_tokens() < b.prompt.n_tokens(); + } + + // [TAG_PREEMPT] park a slot: a synchronous park is finished here, an asynchronous one only issued, and update_preempt_copies() counts it when its copy lands. The notice goes with the save, not the cell release: preempt_save() has already detached the slot, so a release-time notice would leave the copy's silence unexplained. + bool preempt_park(server_slot & slot, int64_t t_start, bool recompute = false) { + slot.t_preempt_copy_us = t_start; + + // [TAG_PREEMPT] a budget check grants permission to allocate, not a successful allocation: preempt_save() unwinds and waits for whatever it issued, so the same victim can still be parked by dropping its cells + if (!recompute && !slot.preempt_save()) { + SLT_WRN(slot, "%s", "the park could not take the host memory the budget allowed, so it drops its cells instead and the resume re-prefills its tokens\n"); + + recompute = true; + } + + if (recompute) { + if (!slot.preempt_save_recompute()) { + return false; + } + + if (!preempt_recompute_logged) { + preempt_recompute_logged = true; + + // [TAG_EXACT_CONCURRENCY] a state that comes back from host memory is the state that left; one rebuilt by re-prefilling is the same on CPU and differs in the last bits on CUDA, where a prefill of a token and a decode of it take different kernels + if (common_exact_concurrency()) { + SRV_WRN("%s", "exact concurrency: a re-prefilled sequence is not guaranteed byte-identical to one that was never parked; raise --preempt-ram until every parked sequence fits it\n"); + } + + SRV_WRN("preemption: --preempt-ram %d MiB holds no further parked sequence, so a park drops its cells and the resume re-prefills its tokens\n", + params_base.preempt_ram_mib); + } + } + + preempt_log_ram_kind(slot); + + if (slot.state == SLOT_STATE_PREEMPTED) { + metrics.n_preempt++; + } + + if (slot.preempt_recompute) { + metrics.n_preempt_recompute++; + } + + send_preempt_notice(slot, true); + + return true; + } + + void preempt_parked(server_slot & slot, const char * note) { + metrics.n_preempt++; + + SLT_WRN(slot, "park completed after %.2f ms%s: %d cells released, %.1f MiB parked, kv %d/%d\n", + (ggml_time_us() - slot.t_preempt_copy_us) / 1e3, note, + slot.prompt.n_tokens(), + slot.preempt_state_size() / (1024.0 * 1024.0), + preempt_kv_used(), n_ctx); + } + + // [TAG_PREEMPT] a resume whose copy has landed; announced here rather than where the restore was issued, this being the first moment the slot can be scheduled again + void preempt_restored(server_slot & slot, const char * note) { + metrics.n_resume++; + + preempt_trim_ram(slot); + + send_preempt_notice(slot, false); + + SLT_WRN(slot, "restore completed after %.2f ms%s: %d tokens back in the cache, kv %d/%d, preemptions %d\n", + (ggml_time_us() - slot.t_preempt_copy_us) / 1e3, note, + slot.prompt.n_tokens(), + preempt_kv_used(), n_ctx, + slot.n_preempt); + } + + void update_preempt_copies() { + for (auto & slot : slots) { + if (slot.state == SLOT_STATE_PREEMPTING) { + if (slot.preempt_save_poll()) { + preempt_parked(slot, ""); + } + } else if (slot.state == SLOT_STATE_RESTORING) { + if (slot.preempt_restore_poll()) { + preempt_restored(slot, ""); + } + } + } + } + + // [TAG_PREEMPT_ASYNC] wait for every copy in flight before a shift: the shift is one in-place graph over the whole K cache, so a copy beside it reads or writes half-shifted cells + void preempt_wait_for_shift() { + if (!preempt_shift_pending) { + return; + } + + preempt_shift_pending = false; + + while (preempt_wait_in_flight()) { + } + + for (auto & slot : slots) { + if (slot.state != SLOT_STATE_RESTORING) { + continue; + } + + slot.preempt_copy_wait(); + + if (slot.preempt_restore_poll()) { + preempt_restored(slot, " (waited for, a context shift is due)"); + } + } + } + + // [TAG_PREEMPT] run the recorded shift here rather than leave it to the next llama_decode(): a park in between would serialize the positions the shift has already moved together with the K values it has not, and removing the sequence would drop the pending deltas with it + void preempt_apply_shift() { + if (!preempt_shift_pending) { + return; + } + + preempt_wait_for_shift(); + + llama_memory_update(ctx_tgt); + + if (ctx_dft) { + llama_memory_update(ctx_dft); + } + } + + bool preempt_copies_in_flight() const { + for (const auto & slot : slots) { + if (slot.state == SLOT_STATE_PREEMPTING) { + return true; + } + } + + return false; + } + + bool preempt_wait_in_flight() { + for (auto & slot : slots) { + if (slot.state != SLOT_STATE_PREEMPTING) { + continue; + } + + slot.preempt_copy_wait(); + + if (!slot.preempt_save_poll()) { + continue; + } + + preempt_parked(slot, " (waited for)"); + + return true; + } + + return false; + } + + void update_preemption() { + if (!params_base.kv_unified || slots.size() < 2) { + return; // with a cache per slot, no slot can take another one's cells + } + + if (!llama_get_memory(ctx_tgt)) { + return; // no cache at all (an embedding model): nothing to run out of, nothing to park + } + + update_preempt_copies(); + + if (params_base.preempt_ram_mib == 0 || preempt_recurrent) { + return; // --preempt-ram 0, or a recurrent cache: the KV-full retry ladder, as before + } + + const int32_t n_cells = n_ctx; + + const bool head_of_line = preempt_resume_head; + + for (;;) { + std::vector parked; + + for (auto & slot : slots) { + if (slot.state == SLOT_STATE_PREEMPTED) { + parked.push_back(&slot); + } + } + + if (parked.empty()) { + break; + } + + std::sort(parked.begin(), parked.end(), [head_of_line](const server_slot * a, const server_slot * b) { + if (!head_of_line && a->n_preempt != b->n_preempt) { + return a->n_preempt > b->n_preempt; + } + + return a->t_preempt_us < b->t_preempt_us; + }); + + if (head_of_line) { + parked.resize(1); + } + + server_slot * best = nullptr; + + const auto impossible = std::find_if(parked.begin(), parked.end(), + [this, n_cells](const server_slot * slot) { return preempt_n_need(*slot) > n_cells; }); + + if (impossible != parked.end()) { + SLT_WRN(**impossible, "parked sequence of %d tokens cannot fit the pool of %d cells even alone, failing it\n", + preempt_n_need(**impossible), n_cells); + send_error(**impossible, "Context size has been exceeded."); + (*impossible)->release(); + continue; + } + + // room for the sequence and for the next step of everything running, the candidate included, or a resume immediately preempts somebody; with nobody resident an exact fit is let in + for (;;) { + const int32_t occupied = preempt_kv_used() + preempt_kv_reserve(); + const int32_t margin = occupied == 0 ? 0 : preempt_n_margin(1); + + for (auto * slot : parked) { + if (occupied + preempt_n_need(*slot) + margin <= n_cells) { + best = slot; + break; + } + } + + if (best) { + break; + } + + if (preempt_normalize_started_all()) { + continue; + } + + if (!try_clear_idle_slots()) { + break; + } + } + + // nothing fits: a resident cycling through context shifts holds the room for as long as it generates, so it is parked once the head has waited its turn + if (!best) { + server_slot * head = parked.front(); + + // [TAG_PREEMPT_ASYNC] a park still copying holds its cells, so a rotation now would only park another resident on top + if (!preempt_copies_in_flight() && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_US) { + const int32_t occupied = preempt_kv_used() + preempt_kv_reserve(); + const int32_t need = preempt_n_need(*head) + preempt_n_margin(1); + + server_slot * pick = nullptr; + bool pick_enough = false; + bool budget_refused = false; + bool recompute = false; + + auto rotate_pick = [&](bool with_recompute) { + for (auto & slot : slots) { + if (slot.state != SLOT_STATE_GENERATING || slot.n_ctx_shift == 0) { + continue; + } + + if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { + continue; + } + + // the head's own bytes are not credited as leaving: the resident is parked before the head is restored and freed, so both states are held at once + if (!with_recompute && !preempt_fits_budget(slot)) { + budget_refused = true; + continue; + } + + const bool enough = occupied - preempt_n_cells(slot.prompt.n_tokens()) + need <= n_cells; + + if (!pick || + (enough && !pick_enough) || + (enough == pick_enough && (enough ? slot.prompt.n_tokens() < pick->prompt.n_tokens() + : slot.prompt.n_tokens() > pick->prompt.n_tokens()))) { + pick = &slot; + pick_enough = enough; + } + } + }; + + rotate_pick(false); + + // [TAG_PREEMPT] a resident the budget cannot swap out is rotated by dropping its cells, as ordinary victim selection does: waiting instead has no bound, a resident that keeps shifting need never finish. The head waits longer for this than for a swap: the rotated resident pays a whole re-prefill, and under exact concurrency it stops being the sequence that was parked + if (!pick && budget_refused && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_RECOMPUTE_US) { + rotate_pick(true); + + recompute = pick != nullptr; + } + + const int64_t t_start = ggml_time_us(); + const int32_t n_rotated = pick ? pick->prompt.n_tokens() : 0; + + if (!pick && budget_refused && !head->preempt_rotation_refused) { + head->preempt_rotation_refused = true; + + SLT_WRN(*head, "no rotation: --preempt-ram %d MiB does not hold this parked state and a resident's at once, and the two are held together while the resident is parked and the head restored; the head waits for a resident to finish, or %.0f s for one to be rotated out by dropping its cells\n", + params_base.preempt_ram_mib, PREEMPT_ROTATE_RECOMPUTE_US / 1e6); + } + + if (pick && preempt_park(*pick, t_start, recompute)) { + server_slot & slot = *pick; + + if (slot.preempt_recompute) { + SLT_WRN(slot, "rotated out after %d context shifts: %d cells dropped, %d tokens to re-prefill on resume, a head parked %.1f s takes its turn%s, preemptions %d\n", + slot.n_ctx_shift, n_rotated, + slot.preempt_n_input(), + (ggml_time_us() - head->t_preempt_us) / 1e6, + pick_enough ? "" : " (not enough room by itself)", + slot.n_preempt); + } else { + SLT_WRN(slot, "rotated out after %d context shifts: %d cells released, %.1f MiB parked, a head parked %.1f s takes its turn%s, preemptions %d\n", + slot.n_ctx_shift, slot.prompt.n_tokens(), + slot.preempt_state_size() / (1024.0 * 1024.0), + (ggml_time_us() - head->t_preempt_us) / 1e6, + pick_enough ? "" : " (not enough room by itself)", + slot.n_preempt); + } + + // [TAG_PREEMPT_ASYNC] a synchronous park has released its cells, so the head is re-examined now; an asynchronous one on the pass that sees the copy land + if (slot.state == SLOT_STATE_PREEMPTED) { + best = head; + } + } + } + + if (best) { + continue; + } + + break; + } + + const int64_t t_start = ggml_time_us(); + + const bool recompute = best->preempt_recompute; + + best->t_preempt_copy_us = t_start; + + if (!best->preempt_restore()) { + if (best->n_preempt_fail % 64 == 1) { + SLT_WRN(*best, "resume failed (%d in a row, parked %.1f s), staying preempted\n", + best->n_preempt_fail, (ggml_time_us() - best->t_preempt_us) / 1e6); + } + + if (best->n_preempt_fail >= PREEMPT_N_FAIL_MAX && + ggml_time_us() - best->t_preempt_us > PREEMPT_FAIL_US) { + send_error(*best, "failed to restore the preempted sequence"); + best->release(); + } + + break; + } + + if (best->state == SLOT_STATE_RESTORING) { + SLT_WRN(*best, "resumed after %.2f s: %d tokens, restore issued in %.2f ms (%zu transfers, %.2f ms sync), kv %d/%d, preemptions %d\n", + (ggml_time_us() - best->t_preempt_us) / 1e6, + best->prompt.n_tokens(), + (ggml_time_us() - t_start) / 1e3, + best->preempt_n_copies(), best->preempt_sync_us() / 1e3, + preempt_kv_used(), n_cells, + best->n_preempt); + + continue; + } + + metrics.n_resume++; + + // [TAG_PREEMPT] the synchronous restore returns with the slot already back in its old state, so issue and landing are the same moment here + send_preempt_notice(*best, false, recompute); + + if (recompute) { + SLT_WRN(*best, "resumed after %.2f s: %d tokens to re-prefill, kv %d/%d, preemptions %d\n", + (ggml_time_us() - best->t_preempt_us) / 1e6, + best->preempt_n_input(), + preempt_kv_used(), n_cells, + best->n_preempt); + } else { + SLT_WRN(*best, "resumed after %.2f s: %d tokens back in the cache in %.2f ms, kv %d/%d, preemptions %d\n", + (ggml_time_us() - best->t_preempt_us) / 1e6, + best->prompt.n_tokens(), + (ggml_time_us() - t_start) / 1e3, + preempt_kv_used(), n_cells, + best->n_preempt); + } + } + + if (preempt_test_every > 0) { + for (auto & slot : slots) { + if (slot.state != SLOT_STATE_GENERATING || + (int32_t) slot.stats.n_gen < (slot.n_preempt + 1) * preempt_test_every) { + continue; + } + + // the budget refusing is the recompute park's case, so the knob reaches it too + const bool recompute = !preempt_fits_budget(slot); + + if (preempt_park(slot, ggml_time_us(), recompute)) { + SLT_WRN(slot, "preempted on request after %d generated tokens, %.1f MiB parked\n", + (int32_t) slot.stats.n_gen, slot.preempt_state_size() / (1024.0 * 1024.0)); + } + } + } + + if (preempt_planner_off) { + return; // test knob: leave the pool to the retry ladder and its last resort + } + + for (;;) { + const int32_t n_used = preempt_kv_used() + preempt_kv_reserve(); - void iterate(std::vector & slots, std::function callback) { - for (auto & slot : slots) { - try { - callback(slot); - } catch (const std::exception & e) { - SLT_ERR(slot, "got exception: %s\n", e.what()); - send_error(slot, std::string("got exception: ") + e.what(), ERROR_TYPE_SERVER); - slot.release(); + if (n_used + preempt_n_margin() <= n_cells) { + break; } - } - } - void iterate(std::vector & slots, std::function callback) { - for (auto & slot : slots) { - try { - callback(*slot); - } catch (const std::exception & e) { - SLT_ERR(*slot, "got exception: %s\n", e.what()); - send_error(*slot, std::string("got exception: ") + e.what(), ERROR_TYPE_SERVER); - slot->release(); + if (try_clear_idle_slots()) { + continue; + } + + // [TAG_PREEMPT_ASYNC] a park issued and not landed holds cells that are already spoken for, so waiting for it is quicker than parking somebody else + if (preempt_copies_in_flight()) { + if (n_used > n_cells) { + if (preempt_wait_in_flight()) { + continue; + } + } else { + break; + } + } + + bool recompute = false; + + server_slot * victim = preempt_pick_victim(&recompute); + + if (!victim) { + SRV_DBG("the kv pool needs %d of %d cells and nothing can be preempted (parked %.1f MiB of the %d MiB --preempt-ram budget)\n", + n_used, n_cells, preempt_ram_used() / (1024.0 * 1024.0), params_base.preempt_ram_mib); + break; + } + + const int32_t n_tokens = victim->prompt.n_tokens(); + const int64_t t_start = ggml_time_us(); + + if (!preempt_park(*victim, t_start, recompute)) { + break; // could not park it; the existing retry ladder is still behind us + } + + if (victim->state == SLOT_STATE_PREEMPTING) { + SLT_WRN(*victim, "preempted: %d cells, park issued in %.2f ms (%zu transfers, %.2f ms sync), %.1f MiB parked, kv %d/%d (wanted %d), preemptions %d\n", + n_tokens, + (ggml_time_us() - t_start) / 1e3, + victim->preempt_n_copies(), victim->preempt_sync_us() / 1e3, + victim->preempt_state_size() / (1024.0 * 1024.0), + preempt_kv_used(), n_cells, n_used, + victim->n_preempt); + + // [TAG_PREEMPT_ASYNC] short of the lookahead only, the step still fits and leaving is the point; out of room for it the cells are held until the copy lands, so the retry ladder ends every request instead of waiting + if (n_used + preempt_n_margin() > n_cells) { + continue; + } + + break; + } + + if (victim->preempt_recompute) { + SLT_WRN(*victim, "preempted: %d cells dropped in %.2f ms, %d tokens to re-prefill on resume, kv %d/%d (wanted %d), preemptions %d\n", + n_tokens, + (ggml_time_us() - t_start) / 1e3, + victim->preempt_n_input(), + preempt_kv_used(), n_cells, n_used, + victim->n_preempt); + } else { + SLT_WRN(*victim, "preempted: %d cells released in %.2f ms, %.1f MiB parked, kv %d/%d (wanted %d), preemptions %d\n", + n_tokens, + (ggml_time_us() - t_start) / 1e3, + victim->preempt_state_size() / (1024.0 * 1024.0), + preempt_kv_used(), n_cells, n_used, + victim->n_preempt); } } } - void abort_all_slots(const std::string & reason) { - for (auto & slot : slots) { - if (slot.is_processing()) { - send_error(slot, reason, ERROR_TYPE_SERVER); - slot.release(); + // the checks a request has to pass before its prompt is processed; true when it is rejected. An empty prompt is not here: it is a final response, not an error. + bool task_prompt_rejected(const server_task & task, std::string & msg, error_type & type) const { + // TODO: support memory-less logits computation + if (task.need_logits() && !llama_get_memory(ctx_tgt)) { + msg = "the current context does not support logits computation. skipping"; + type = ERROR_TYPE_SERVER; + return true; + } + + // as launch_slot_with_task(), ahead of it: a sibling parked behind a running one used to fail inside a stream that had already opened 200 + if (!task.tokens.validate(ctx_tgt)) { + msg = "Prompt contains invalid tokens"; + type = ERROR_TYPE_INVALID_REQUEST; + return true; + } + + // as server_slot::can_split(), from the task alone + const auto pooling = llama_pooling_type(ctx_tgt); + const bool can_split = + !task.need_embd() || + (llama_get_memory(ctx_tgt) && + (pooling == LLAMA_POOLING_TYPE_LAST || (pooling == LLAMA_POOLING_TYPE_RANK && llama_get_causal_attn(ctx_tgt)) || + task.type == SERVER_TASK_TYPE_DECISION)); + + if (!can_split) { + const int32_t n_ubatch = llama_n_ubatch(ctx_tgt); + + if (task.n_tokens() > n_ubatch) { + msg = string_format( + "input (%d tokens) is too large to process. increase the physical batch " + "size (current batch size: %d)", + task.n_tokens(), n_ubatch); + type = ERROR_TYPE_SERVER; + return true; + } + + if (task.n_tokens() > n_ctx_slot()) { + msg = string_format( + "input (%d tokens) is larger than the max context size (%d tokens). skipping", + task.n_tokens(), n_ctx_slot()); + type = ERROR_TYPE_EXCEED_CONTEXT_SIZE; + return true; } + + return false; } - } - // @ngxson : for debugging only - int64_t t_pre_decode = 0; - int64_t t_decode = 0; - int64_t t_post_decode = 0; - int64_t t_sampl = 0; - int64_t n_pre_decode = 0; - int64_t n_decode = 0; - int64_t n_post_decode = 0; - int64_t n_sampl = 0; -// #define DEBUG_TIMINGS -#ifdef DEBUG_TIMINGS - struct scoped_timer { - int64_t & t; - int64_t & n; - int64_t t_start; - scoped_timer(int64_t & t_, int64_t & n_) : t(t_), n(n_) { - t_start = ggml_time_us(); + if (task.n_tokens() >= n_ctx_slot()) { + msg = string_format( + "request (%d tokens) exceeds the available context size (%d tokens), try increasing it", + task.n_tokens(), n_ctx_slot()); + type = ERROR_TYPE_EXCEED_CONTEXT_SIZE; + return true; } - ~scoped_timer() { - t += ggml_time_us() - t_start; - n++; + + // the outputs of a decision are read from one batch + const int32_t n_batch = llama_n_batch(ctx_tgt); + const int32_t n_decision_first = task.type == SERVER_TASK_TYPE_DECISION ? task.decision.pos_first() : -1; + if (n_decision_first >= 0 && task.n_tokens() - n_decision_first > n_batch) { + msg = string_format( + "the question and its options (%d tokens) are too large to process. " + "increase the batch size (current batch size: %d)", + task.n_tokens() - n_decision_first, n_batch); + type = ERROR_TYPE_INVALID_REQUEST; + return true; } - }; -#else - struct scoped_timer { - scoped_timer(int64_t &, int64_t &) {} - ~scoped_timer() {} - }; -#endif + + return false; + } + + bool slot_prompt_rejected(const server_slot & slot, std::string & msg, error_type & type) const { + if (!slot.task) { + return false; + } + + return task_prompt_rejected(*slot.task, msg, type); + } void update_slots() { #ifdef DEBUG_TIMINGS @@ -3169,7 +4835,6 @@ struct server_context_impl { } #endif - // check if all slots are idle { bool all_idle = true; @@ -3197,6 +4862,14 @@ struct server_context_impl { } try { + // [TAG_PREEMPT] make the pool fit the step about to be built, measured after any context shift; inside the guard because a shift or a park can throw + pre_decode_shift(); + + // before update_preemption(), and not only before the decode: a slot must never be parked with a shift still pending on its cells + preempt_apply_shift(); + + update_preemption(); + scoped_timer t(t_pre_decode, n_pre_decode); pre_decode(); } catch (const std::exception & e) { @@ -3230,6 +4903,10 @@ struct server_context_impl { int32_t off_next = 0; int32_t n_batch = llama_n_batch(ctx_tgt); + + // [TAG_PREEMPT_ASYNC] and once more here: a shift --cache-reuse asks for is found inside pre_decode(), after the wait above + preempt_wait_for_shift(); + for (int32_t off = 0; off < batch.size(); off = off_next) { const int32_t n_tokens = std::min(n_batch, batch.size() - off); try { @@ -3242,6 +4919,11 @@ struct server_context_impl { llama_synchronize(ctx_tgt); #endif + if (preempt_batch_abandoned) { + preempt_batch_abandoned = false; + break; + } + if (ok) { // move the head of the batch forward with the number of tokens we just processed off_next = off + n_tokens; @@ -3269,9 +4951,9 @@ struct server_context_impl { } } - void pre_decode() { - // apply context-shift if needed - // TODO: simplify and improve + // apply context-shift if needed + // TODO: simplify and improve + void pre_decode_shift() { iterate(slots, [&](server_slot & slot) { if (slot.state == SLOT_STATE_GENERATING && slot.prompt.n_tokens() + 1 >= slot.n_ctx) { if (!params_base.ctx_shift) { @@ -3311,6 +4993,9 @@ struct server_context_impl { SLT_WRN(slot, "slot context shift, n_keep = %d, n_left = %d, n_discard = %d\n", n_keep, n_left, n_discard); + slot.n_ctx_shift++; + preempt_shift_pending = true; + slot.mem.seq_rm (slot.id, n_keep , n_keep + n_discard); slot.mem.seq_add(slot.id, n_keep + n_discard, slot.prompt.tokens.pos_next(), -n_discard); @@ -3333,7 +5018,9 @@ struct server_context_impl { slot.truncated = true; } }); + } + void pre_decode() { // start populating the batch for this iteration batch.clear(); @@ -3487,7 +5174,8 @@ struct server_context_impl { return; // batch is full, skip remaining slots } - if (!slot.is_processing()) { + // [TAG_PREEMPT] a parked slot is processing but has nothing in the cache to batch until it is restored + if (!slot.is_processing() || slot.preempt_is_out()) { return; } @@ -3504,7 +5192,10 @@ struct server_context_impl { // this slot still has a prompt to be processed if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) { - const auto & input_tokens = slot.task->tokens; + const auto & input_tokens = slot.preempt_input(); + + // [TAG_PREEMPT] what the prompt step works towards: the re-prefill list of a park that dropped its cells, the request otherwise + const int32_t n_input_tokens = slot.preempt_n_input(); // used to determine the number of tokens added to the batch for the current slot const auto n_tokens_prev = batch.size(); @@ -3545,58 +5236,18 @@ struct server_context_impl { return; } - // TODO: support memory-less logits computation - if (slot.task->need_logits() && !llama_get_memory(ctx_tgt)) { - send_error(slot, "the current context does not support logits computation. skipping", ERROR_TYPE_SERVER); - slot.release(); - return; - } - - if (!slot.can_split()) { - if (slot.task->n_tokens() > n_ubatch) { - send_error(slot, - string_format( - "input (%d tokens) is too large to process. increase the physical batch " - "size (current batch size: %d)", - slot.task->n_tokens(), n_ubatch), - ERROR_TYPE_SERVER); - slot.release(); - return; - } - - if (slot.task->n_tokens() > slot.n_ctx) { - send_error( - slot, - string_format( - "input (%d tokens) is larger than the max context size (%d tokens). skipping", - slot.task->n_tokens(), slot.n_ctx), - ERROR_TYPE_EXCEED_CONTEXT_SIZE); - slot.release(); - return; - } - } else { - if (slot.task->n_tokens() >= slot.n_ctx) { - send_error(slot, - string_format("request (%d tokens) exceeds the available context size (%d " - "tokens), try increasing it", - slot.task->n_tokens(), slot.n_ctx), - ERROR_TYPE_EXCEED_CONTEXT_SIZE); - slot.release(); - return; - } + { + std::string msg; + error_type type = ERROR_TYPE_SERVER; - // the outputs of a decision are read from one batch - const int32_t n_decision_first = slot.task->type == SERVER_TASK_TYPE_DECISION ? slot.task->decision.pos_first() : -1; - if (n_decision_first >= 0 && slot.task->n_tokens() - n_decision_first > n_batch) { - send_error(slot, - string_format("the question and its options (%d tokens) are too large to process. " - "increase the batch size (current batch size: %d)", - slot.task->n_tokens() - n_decision_first, n_batch), - ERROR_TYPE_INVALID_REQUEST); + if (slot_prompt_rejected(slot, msg, type)) { + send_error(slot, msg, type); slot.release(); return; } + } + if (slot.can_split()) { const bool is_stateless_task = slot.task->type == SERVER_TASK_TYPE_EMBEDDING || slot.task->type == SERVER_TASK_TYPE_RERANK; if (slot.task->params.cache_prompt && !is_stateless_task) { @@ -3664,6 +5315,8 @@ struct server_context_impl { slot.mem.seq_rm (slot.id, head_p, head_c); slot.mem.seq_add(slot.id, head_c, head_c + n_match, kv_shift); + preempt_shift_pending = true; + for (size_t i = 0; i < n_match; i++) { slot.prompt.tokens.set_token(head_p + i, slot.prompt.tokens[head_c + i]); n_past++; @@ -3832,11 +5485,32 @@ struct server_context_impl { if (!slot.can_split()) { // cannot fit the prompt in the current batch - will try next iter - if (batch.size() + slot.task->n_tokens() > n_batch) { + if (batch.size() + n_input_tokens > n_batch) { return; } } + // [TAG_EXACT_CONCURRENCY] a prompt is isolated into ubatches of its own, so it gets the shapes it would get alone only if what it adds here is a whole number of ubatches: otherwise a neighbour's decoded token shortens the last one, and 512,512,512,509 is not 512,512,512,512 + int32_t n_batch_cur = n_batch; + + if (common_exact_concurrency() && slot.can_split() && !slot.prompt.tokens.has_mtmd) { + const int32_t n_avail = n_batch - (int32_t) batch.size(); + const int32_t n_left = n_input_tokens - slot.prompt.n_tokens(); + + if (n_left > n_avail) { + const int32_t n_take = n_avail - n_avail % n_ubatch; + + if (n_take > 0) { + n_batch_cur = (int32_t) batch.size() + n_take; + } else { + // the waiting ends: common_exact_batch_geometry() refused a batch that cannot hold a whole ubatch beside a decode step of every slot, and the prompts ahead of this one in the same batch are finite + SLT_DBG(slot, "exact concurrency: %d of %d batch tokens left, short of a %d-token ubatch: the prefill waits\n", + n_avail, n_batch, n_ubatch); + return; + } + } + } + // note: the prompt timing is advanced in post_decode(), so it does not cover // the tokens added to the batch below slot.print_timings_pp(); @@ -3885,6 +5559,9 @@ struct server_context_impl { // make checkpoints only for completion tasks do_checkpoint = do_checkpoint && slot.task->type == SERVER_TASK_TYPE_COMPLETION; + // a re-prefill walks its own list, which the request's message spans do not index + do_checkpoint = do_checkpoint && !slot.preempt_reprefill; + // make a checkpoint of the parts of the memory that cannot be rolled back. // checkpoints are created only if: // - the model does not support partial sequence removal @@ -3908,12 +5585,16 @@ struct server_context_impl { while (true) { auto cur_token_idx = slot.prompt.n_tokens(); if ( - cur_token_idx >= slot.task->n_tokens() || + cur_token_idx >= n_input_tokens || input_tokens[cur_token_idx] != LLAMA_TOKEN_NULL // encountered a text token ) { break; } + // [TAG_PREEMPT_ASYNC] the chunk decodes whole, past the kv-full retry, so a park the planner issued for it has to land first + while (preempt_wait_in_flight()) { + } + // process the mtmd chunk // note: it submits its own decode, potentially be async // so the timing is queued and flushed on the next sync @@ -3934,8 +5615,12 @@ struct server_context_impl { } metrics_queue_prompt(n_tokens_out); - slot.stats.n_prompt_processed += n_tokens_out; - slot.stats.update_prompt_last(); + + // [TAG_PREEMPT] a re-prefill puts back what a park dropped: real compute, counted above, but it is not the request's prompt + if (!slot.preempt_reprefill) { + slot.stats.n_prompt_processed += n_tokens_out; + slot.stats.update_prompt_last(); + } // add the mtmd chunk to cache { @@ -3953,7 +5638,7 @@ struct server_context_impl { const int32_t n_decision_first = slot.task->type == SERVER_TASK_TYPE_DECISION ? slot.task->decision.pos_first() : -1; // add prompt tokens for processing in the current batch - while (slot.prompt.n_tokens() < slot.task->n_tokens() && batch.size() < n_batch) { + while (slot.prompt.n_tokens() < n_input_tokens && batch.size() < n_batch_cur) { // get next token to process llama_token cur_tok = input_tokens[slot.prompt.n_tokens()]; if (cur_tok == LLAMA_TOKEN_NULL) { @@ -3991,6 +5676,11 @@ struct server_context_impl { } slot.prompt.tokens.push_back(cur_tok); + // [TAG_EXACT_CONCURRENCY] a token that was decoded goes back through the arithmetic that decoded it: one per step, in the narrow set beside the other decodes. Re-prefilled wide it went through batched arithmetic, and the output diverged at the second park + if (slot.preempt_reprefill && common_exact_concurrency() && slot.prompt.n_tokens() >= slot.task->n_tokens()) { + break; + } + // break at the last user message, or at user messages at least min step past the last checkpoint if (do_checkpoint && spans.is_user_start(slot.prompt.n_tokens())) { const auto pos = slot.prompt.n_tokens(); @@ -4012,7 +5702,7 @@ struct server_context_impl { bool should_break = false; for (int offset : checkpoint_offsets) { const int n_last = std::min(n_batch, offset); - if (slot.task->n_tokens() == slot.prompt.n_tokens() + n_last) { + if (n_input_tokens == slot.prompt.n_tokens() + n_last) { should_break = true; break; } @@ -4028,13 +5718,13 @@ struct server_context_impl { const auto n_tokens_start = slot.prompt.n_tokens() - n_tokens_cur; - const bool near_prompt_end = slot.task->n_tokens() < slot.prompt.n_tokens() + n_ubatch; + const bool near_prompt_end = n_input_tokens < slot.prompt.n_tokens() + n_ubatch; const bool is_user_start = spans.is_user_start(n_tokens_start); const bool is_last_user_message = n_tokens_start == last_user_pos; // entire prompt has been processed - if (slot.prompt.n_tokens() == slot.task->n_tokens()) { + if (slot.prompt.n_tokens() == n_input_tokens) { slot.state = SLOT_STATE_DONE_PROMPT; GGML_ASSERT(batch.size() > 0); @@ -4042,10 +5732,14 @@ struct server_context_impl { // extract the logits only for the last token batch.set_output(batch.size() - 1, true); - slot.stats.n_gen = 0; - slot.i_batch = batch.size() - 1; + slot.i_batch = batch.size() - 1; + + // [TAG_PREEMPT] a re-prefill only puts back what the park dropped: the sampler and the counters carry on from where the park found them + if (!slot.preempt_reprefill) { + slot.stats.n_gen = 0; - slot.init_sampler(); + slot.init_sampler(); + } } else { // skip ordinary mid-prompt checkpoints, unless the batch starts a user // message or we are near the end of the prompt @@ -4145,6 +5839,123 @@ struct server_context_impl { return true; } + // [TAG_PREEMPT_ASYNC] a recurrent memory keeps no fixed row per sequence: find_slot() gathers the active ones into contiguous rows, so a decode beside a park moves or overwrites the row the copy is still reading. A hybrid carries that half too, and so can the draft. + static bool preempt_state_relocates(const llama_model * model) { + return model && (llama_model_is_recurrent(model) || llama_model_is_hybrid(model)); + } + + bool preempt_state_relocates() const { + return preempt_state_relocates(model_tgt) || preempt_state_relocates(model_dft); + } + + // [TAG_PREEMPT_ASYNC] whether a park can happen at all and go asynchronously + bool preempt_async_possible() const { + return params_base.preempt_async && params_base.kv_unified && params_base.preempt_ram_mib != 0 && + slots.size() >= 2 && llama_get_memory(ctx_tgt) && !preempt_state_relocates(); + } + + bool preempt_last_resort_possible() const { + return params_base.kv_unified && params_base.preempt_ram_mib != 0 && !preempt_recurrent && slots.size() >= 2 && llama_get_memory(ctx_tgt); + } + + // [TAG_PREEMPT] the retry ladder ran out: give the batch up, rewind every resident to the token boundary the cache is at and park the smallest. A media chunk mid-prompt keeps the old path. + bool preempt_last_resort(int32_t off) { + if (!preempt_last_resort_possible()) { + return false; + } + + int32_t n_running = 0; + + for (auto & slot : slots) { + if (!slot.is_processing() || slot.state == SLOT_STATE_PREEMPTED || slot.preempt_in_flight()) { + continue; + } + + // a media chunk decodes whole through calls of its own, so a resident still inside its prompt cannot be rewound to a token boundary; one that is generating can + if (slot.prompt.tokens.has_mtmd && slot.state != SLOT_STATE_GENERATING) { + return false; + } + + n_running++; + } + + if (n_running < 2) { + return false; // one conversation that does not fit alone is a real overflow + } + + for (auto & slot : slots) { + if (slot.is_processing() && slot.state != SLOT_STATE_PREEMPTED && slot.state != SLOT_STATE_WAIT_OTHER && + !slot.preempt_in_flight()) { + slot.rewind_to_cache(); + } + } + + const int32_t n_cells = n_ctx; + int32_t n_parked = 0; + + for (;;) { + const int32_t n_used = preempt_kv_used() + preempt_kv_reserve(); + + if (n_parked > 0 && n_used + preempt_n_margin() <= n_cells) { + break; + } + + bool recompute = false; + + server_slot * victim = preempt_pick_victim(&recompute); + + if (!victim) { + break; + } + + const int32_t n_tokens = victim->prompt.n_tokens(); + const int64_t t_start = ggml_time_us(); + + if (!preempt_park(*victim, t_start, recompute)) { + break; + } + + n_parked++; + + // [TAG_PREEMPT_ASYNC] the cells are wanted now, not next iteration: wait for the copy, which releases them + if (victim->state == SLOT_STATE_PREEMPTING) { + while (preempt_wait_in_flight()) { + } + + SLT_WRN(*victim, "preempted as a last resort: %d cells released, kv %d/%d (wanted %d), preemptions %d\n", + n_tokens, preempt_kv_used(), n_cells, n_used, victim->n_preempt); + continue; + } + + SLT_WRN(*victim, "preempted as a last resort%s: %d cells released in %.2f ms, %.1f MiB parked, kv %d/%d (wanted %d), preemptions %d\n", + victim->preempt_recompute ? " by dropping its cells" : "", + n_tokens, + (ggml_time_us() - t_start) / 1e3, + victim->preempt_state_size() / (1024.0 * 1024.0), + preempt_kv_used(), n_cells, n_used, + victim->n_preempt); + } + + if (n_parked == 0) { + return false; // nothing could be parked: the error path clears what the rewind left + } + + SRV_WRN("last resort: batch given up at off = %d, %d slot(s) parked, kv %d/%d resident\n", + off, n_parked, preempt_kv_used(), n_cells); + + return true; + } + + bool batch_has_spec_groups() const { + for (const auto & slot : slots) { + if (!slot.spec_i_batch.empty()) { + return true; + } + } + + return false; + } + // returns true = success ; false = retry with smaller batch size // throw std::runtime_error on fatal error bool decode(int32_t & n_batch, int32_t off) { @@ -4189,10 +6000,31 @@ struct server_context_impl { }); if (ret != 0) { + // [TAG_PREEMPT_ASYNC] halving the batch returns no cells, so wait for an issued park first, or the ladder runs down to n_batch == 1 and ends every request + if (ret == 1 && preempt_wait_in_flight()) { + SRV_WRN("%s", "waited for an in-flight park before retrying the decode\n"); + return false; // retry at the same batch size, with the cells it freed + } + { std::string err; + // [TAG_PREEMPT] a slot's sampled token and its draft have to stay in one view, so halving would split the group and make the verify step throw + if (ret == 1 && n_batch > 1 && preempt_last_resort_possible() && batch_has_spec_groups()) { + if (try_clear_idle_slots()) { + SRV_WRN("%s", "failed to find free space in the KV cache, retrying after purging an idle slot\n"); + return false; // retry at the same width + } + + n_batch = 1; + } + if (n_batch == 1 && ret == 1) { + if (preempt_last_resort(off)) { + preempt_batch_abandoned = true; + return true; + } + // TODO: try to terminate only the largest active slot/sequence and continue with the rest // need to remove the tokens from the current batch too err = "Context size has been exceeded."; @@ -4213,7 +6045,7 @@ struct server_context_impl { SRV_ERR("%s off = %d, n_batch = %d, ret = %d\n", err.c_str(), off, n_batch, ret); for (auto & slot : slots) { - if (slot.is_processing()) { + if (slot.is_processing() && slot.state != SLOT_STATE_PREEMPTED && !slot.preempt_in_flight()) { send_error(slot, err); slot.release(); @@ -4310,7 +6142,7 @@ struct server_context_impl { iterate(slots, [&](server_slot & slot) { // optionally send prompt processing progress if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_DONE_PROMPT) { - if (slot.task->params.stream && slot.task->params.return_progress) { + if (slot.task->params.stream && slot.task->params.return_progress && !slot.preempt_reprefill) { send_partial_response(slot, {}, true); } } @@ -4321,6 +6153,12 @@ struct server_context_impl { } if (slot.state == SLOT_STATE_DONE_PROMPT) { + // [TAG_PREEMPT] the re-prefill is back in the cache; the token this slot had already sampled is decoded next, so nothing is sampled here + if (slot.preempt_reprefill) { + slot.preempt_reprefill_done(); + return; + } + if (slot.task->type == SERVER_TASK_TYPE_EMBEDDING) { // prompt evaluated for embedding send_embedding(slot, batch.view); @@ -4596,7 +6434,7 @@ struct server_context_impl { void metrics_post_decode(int32_t off, int32_t n_tokens, bool has_output) { metrics.n_decode++; for (const auto & slot : slots) { - if (slot.is_processing()) { + if (slot.is_processing() && !slot.preempt_is_out()) { metrics.n_busy_slots++; } metrics.n_tokens_max = std::max(metrics.n_tokens_max, (uint64_t) slot.prompt.n_tokens()); @@ -4617,7 +6455,8 @@ struct server_context_impl { n_prompt_tokens++; auto & slot = slots[t.id_slot]; - if (slot.stats.is_set()) { + // [TAG_PREEMPT] replayed tokens stay out of the slot's prompt count, they were counted when the request first processed its prompt + if (slot.stats.is_set() && !slot.preempt_reprefill) { slot.stats.n_prompt_processed++; } } @@ -4635,7 +6474,8 @@ struct server_context_impl { for (int i = off; i < off + n_tokens; ++i) { const auto & t = batch.tokens[i]; auto & slot = slots[t.id_slot]; - if (t.is_prompt && slot.stats.is_set()) { + // [TAG_PREEMPT] a re-prefill must not move the prompt/generation boundary: n_gen carries across the park, so the generation time would then cover only the tokens after it + if (t.is_prompt && slot.stats.is_set() && !slot.preempt_reprefill) { slot.stats.set_prompt_last(t_now); } } @@ -4850,6 +6690,14 @@ std::unique_ptr server_routes::handle_completions_impl( task.params.oaicompat_cmpl_id = completion_id; task.params.oaicompat_model = meta->model_name; + // [TAG_EXACT_CONCURRENCY] exact mode gives a page to a single sequence, so refuse an n_cmpl > 1 child here, where it becomes a 400 rather than at seq_cp + if (task.params.n_cmpl > 1 && common_exact_concurrency()) { + throw std::runtime_error( + "n > 1 is not supported while LLAMA_EXACT_CONCURRENCY is set: each " + "completion needs its own sequence, and in exact mode a KV page belongs " + "to a single sequence. Send n separate requests, or unset the variable."); + } + // prepare child tasks if (task.params.n_cmpl > 1) { int n_children = task.params.n_cmpl - 1; @@ -4861,6 +6709,16 @@ std::unique_ptr server_routes::handle_completions_impl( tasks.push_back(std::move(task)); } + // [TAG_PREEMPT] every prompt of the request, before any of them is queued: one member can be parked, and its notice opens the stream, before another member is rejected + { + json error; + + if (ctx_server.tasks_prompt_rejected(tasks, error)) { + res->error(error); + return res; + } + } + rd.post_tasks(std::move(tasks), chat_session); } catch (const std::exception & e) { res->error(format_error_response(e.what(), ERROR_TYPE_INVALID_REQUEST)); @@ -4903,37 +6761,51 @@ std::unique_ptr server_routes::handle_completions_impl( // in streaming mode, the first error must be treated as non-stream response // this is to match the OAI API behavior // ref: https://github.com/ggml-org/llama.cpp/pull/16486#discussion_r2419657309 + // [TAG_PREEMPT] a slot can be parked before any token exists, so those notices are kept and sent in front of the first real result + std::string preempt_prefix; + std::set parked_idx; // prompts of this request that are parked right now auto first_result = rd.next(req.should_stop); - if (first_result == nullptr) { - GGML_ASSERT(req.should_stop()); - return res; // connection is closed - } + if (first_result != nullptr && dynamic_cast(first_result.get()) != nullptr) { + const auto * notice = static_cast(first_result.get()); + preempt_prefix = preempt_notice_comment(*notice); + if (notice->parked) { + parked_idx.insert(notice->index); + } else { + parked_idx.erase(notice->index); + } + first_result.reset(); + } else { + if (first_result == nullptr) { + GGML_ASSERT(req.should_stop()); + return res; // connection is closed + } - if (first_result->is_error()) { - res->error(first_result->to_json()); - return res; - } + if (first_result->is_error()) { + res->error(first_result->to_json()); + return res; + } - GGML_ASSERT( - dynamic_cast(first_result.get()) != nullptr || - dynamic_cast (first_result.get()) != nullptr - ); + GGML_ASSERT( + dynamic_cast(first_result.get()) != nullptr || + dynamic_cast (first_result.get()) != nullptr + ); + } - // next responses are streamed - // to be sent immediately - json first_result_json = first_result->to_json(); + json first_result_json = first_result ? first_result->to_json() : json(nullptr); if (first_result_json == nullptr) { - res->data = ""; // simply send HTTP headers and status code + res->data = preempt_prefix; // simply send HTTP headers and status code } else if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) { - res->data = format_anthropic_sse(first_result_json); + res->data = preempt_prefix + format_anthropic_sse(first_result_json); } else if (res_type == TASK_RESPONSE_TYPE_OAI_RESP) { - res->data = format_oai_resp_sse(first_result_json); + res->data = preempt_prefix + format_oai_resp_sse(first_result_json); } else { - res->data = format_oai_sse(first_result_json); + res->data = preempt_prefix + format_oai_sse(first_result_json); } res->status = 200; res->content_type = "text/event-stream"; - res->set_next([res_this = res.get(), res_type, sse_ping_interval](std::string & output) -> bool { + res->set_next([res_this = res.get(), res_type, sse_ping_interval, parked_idx](std::string & output) mutable -> bool { + const bool parked = !parked_idx.empty(); + static auto format_error = [](task_response_type res_type, const json & res_json) { if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) { return format_anthropic_sse({ @@ -4984,10 +6856,13 @@ std::unique_ptr server_routes::handle_completions_impl( // receive subsequent results bool timeout = false; int64_t start_time = ggml_time_ms(); - auto result = rd.next([&timeout, &start_time, sse_ping_interval, &effective_should_stop]() { + // [TAG_PREEMPT] a parked slot produces nothing, so ping at least every 2 s whether or not --sse-ping asked for one, and name it; a shorter interval asked for is kept + const int64_t ping_cfg = sse_ping_interval > 0 ? (int64_t) sse_ping_interval * 1000 : -1; + const int64_t ping_ms = parked ? (ping_cfg > 0 ? std::min(ping_cfg, PREEMPT_KEEPALIVE_MS) : PREEMPT_KEEPALIVE_MS) : ping_cfg; + auto result = rd.next([&timeout, &start_time, ping_ms, &effective_should_stop]() { if (effective_should_stop()) { return true; // should_stop condition met - } else if (sse_ping_interval > 0 && ggml_time_ms() - start_time > (int64_t)sse_ping_interval * 1000) { + } else if (ping_ms > 0 && ggml_time_ms() - start_time > ping_ms) { timeout = true; return true; // timeout } @@ -4997,7 +6872,7 @@ std::unique_ptr server_routes::handle_completions_impl( if (timeout) { // some clients may time out (e.g. undici) will time out if no data is received for a while, so we need to send a ping to keep the connection alive SRV_DBG("%s", "sending SSE ping\n"); - output = ":\n\n"; + output = parked ? ": preempt-keepalive\n\n" : ":\n\n"; return true; } @@ -5013,12 +6888,23 @@ std::unique_ptr server_routes::handle_completions_impl( output = format_error(res_type, res_json); SRV_DBG("%s", "error received during streaming, terminating stream\n"); return false; // terminate on error + } else if (const auto * notice = dynamic_cast(result.get())) { + if (notice->parked) { + parked_idx.insert(notice->index); + } else { + parked_idx.erase(notice->index); + } + output = preempt_notice_comment(*notice); } else { GGML_ASSERT( dynamic_cast(result.get()) != nullptr || dynamic_cast(result.get()) != nullptr ); json res_json = result->to_json(); + if (res_json.is_null()) { + // [TAG_PREEMPT] the empty signal a prompt sends before its first token has nothing to add once a notice has opened the stream + return true; + } if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) { output = format_anthropic_sse(res_json); } else if (res_type == TASK_RESPONSE_TYPE_OAI_RESP) { @@ -5151,6 +7037,8 @@ static json get_res_props(const server_context_meta & meta, const common_params { "endpoint_slots", params.endpoint_slots }, { "endpoint_props", params.endpoint_props }, { "endpoint_metrics", params.endpoint_metrics }, + // [TAG_EXACT_CONCURRENCY] a client that asked for the mode reads here whether this process runs it: a build that ignores the variable starts all the same + { "exact_concurrency", common_exact_concurrency() }, { "ui", params.ui }, { "ui_settings", meta.json_ui_settings }, { "chat_template", tmpl_default }, diff --git a/tools/server/server-queue.cpp b/tools/server/server-queue.cpp index 3352c3cb5d17..b37ccebe11f8 100644 --- a/tools/server/server-queue.cpp +++ b/tools/server/server-queue.cpp @@ -448,6 +448,9 @@ server_task_result_ptr server_response::recv(const std::unordered_set & id_ } server_task_result_ptr server_response::recv_with_timeout(const std::unordered_set & id_tasks, int timeout) { + // [TAG_PREEMPT] the timeout is a deadline, not a per-wait duration: send() notify_all()s for every result of every task, and with wait_for() each wakeup restarted the wait + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout); + while (true) { std::unique_lock lock(mutex_results); @@ -459,7 +462,7 @@ server_task_result_ptr server_response::recv_with_timeout(const std::unordered_s } } - std::cv_status cr_res = condition_results.wait_for(lock, std::chrono::seconds(timeout)); + std::cv_status cr_res = condition_results.wait_until(lock, deadline); if (!running) { RES_DBG("%s : queue result stop\n", __func__); std::terminate(); // we cannot return here since the caller is HTTP code @@ -527,12 +530,16 @@ void server_response_reader::post_tasks(std::vector && tasks, const id_tasks = server_task::get_list_id(tasks); states.reserve(tasks.size()); size_t index = 0; + // [TAG_PREEMPT] several prompts, or several completions of one prompt, all number their results, and their preempt notices have to say which one they belong to + const bool batched = id_tasks.size() > 1; for (auto & task : tasks) { - task.index = index++; + task.index = index++; + task.batched = batched; states.push_back(task_result_state(session)); // for child tasks for (auto & child_task : task.child_tasks) { - child_task.index = index++; + child_task.index = index++; + child_task.batched = batched; states.push_back(task_result_state(session)); } } diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 3f30da2cd6f5..fbdb2b5ac52f 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -347,6 +347,7 @@ json server_task_result_cmpl_final::to_json_non_oaicompat() { {"stopping_word", stopping_word}, {"tokens_cached", n_tokens_cached}, {"timings", stats.to_json()}, + {"preempt", preempt_to_json()}, }; if (!stream && !probs_output.empty()) { res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs); @@ -354,6 +355,14 @@ json server_task_result_cmpl_final::to_json_non_oaicompat() { return response_fields.empty() ? res : json_get_nested_values(response_fields, res); } +// [TAG_PREEMPT] how the request was served: a recompute resume re-prefilled its tokens, so its continuation is not the bytes that were parked +json server_task_result_cmpl_final::preempt_to_json() const { + return json { + {"parks", n_preempt}, + {"recomputes", n_recompute}, + }; +} + json server_task_result_cmpl_final::usage_json_oaicompat() { return json { {"completion_tokens", n_decoded}, @@ -398,6 +407,7 @@ json server_task_result_cmpl_final::to_json_oaicompat() { } if (stats.is_set()) { res["timings"] = stats.to_json(); + res["preempt"] = preempt_to_json(); } return res; @@ -446,6 +456,7 @@ json server_task_result_cmpl_final::to_json_oaicompat_chat() { } if (stats.is_set()) { res["timings"] = stats.to_json(); + res["preempt"] = preempt_to_json(); } return res; @@ -507,6 +518,7 @@ json server_task_result_cmpl_final::to_json_oaicompat_chat_stream() { if (stats.is_set()) { deltas.back()["timings"] = stats.to_json(); + deltas.back()["preempt"] = preempt_to_json(); } // extra fields for debugging purposes @@ -583,6 +595,7 @@ json server_task_result_cmpl_final::to_json_oaicompat_resp() { {"total_tokens", n_decoded + n_prompt_tokens}, {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }}, }}, + {"preempt", preempt_to_json()}, }; return res; @@ -693,7 +706,9 @@ json server_task_result_cmpl_final::to_json_oaicompat_resp_stream() { {"output_tokens", n_decoded}, {"total_tokens", n_decoded + n_prompt_tokens}, {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }}, - }} + }}, + // [TAG_PREEMPT] inside the response object, where the non-streaming body carries it: that object is what a client keeps from the stream + {"preempt", preempt_to_json()}, }}, }} }); @@ -716,6 +731,7 @@ json server_task_result_cmpl_final::to_json_oaicompat_asr() { {"total_tokens", n_decoded + n_prompt_tokens}, {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }}, }}, + {"preempt", preempt_to_json()}, }; return event; } @@ -780,7 +796,8 @@ json server_task_result_cmpl_final::to_json_anthropic() { {"cache_read_input_tokens", n_prompt_tokens_cache}, {"input_tokens", n_prompt_tokens - n_prompt_tokens_cache}, {"output_tokens", n_decoded} - }} + }}, + {"preempt", preempt_to_json()} }; return res; @@ -960,7 +977,8 @@ json server_task_result_cmpl_final::to_json_anthropic_stream() { }}, {"usage", { {"output_tokens", n_decoded} - }} + }}, + {"preempt", preempt_to_json()} }} }); @@ -1015,6 +1033,14 @@ void server_task_result_cmpl_partial::update(task_result_state & state) { } } +json server_task_result_preempt_notice::to_json() { + return json { + {"preempted", parked}, + {"recomputed", recomputed}, + {"n_preempt", n_preempt}, + }; +} + json server_task_result_cmpl_partial::to_json() { GGML_ASSERT(is_updated && "update() must be called before to_json()"); if (is_begin) { @@ -1565,6 +1591,18 @@ std::string server_task_result_metrics::to_metrics() { "spec_decode_num_drafts_total", "Speculative: Total speculative decoding verification steps", (double) metrics.n_draft_verif_steps + }, { + "n_preempt_total", + "Preemption: Total slots parked to make room in the unified KV cache", + (double) metrics.n_preempt + }, { + "n_resume_total", + "Preemption: Total parked slots put back", + (double) metrics.n_resume + }, { + "preempt_recompute_total", + "Preemption: Total parks that dropped their cells, whose resume re-prefills instead of restoring the saved bytes", + (double) metrics.n_preempt_recompute }, }; @@ -1589,6 +1627,14 @@ std::string server_task_result_metrics::to_metrics() { "n_busy_slots_per_decode", "Average number of busy slots per llama_decode() call", (double) metrics.n_busy_slots / std::max((double) metrics.n_decode, 1.0) + }, { + "requests_preempted", + "Preemption: Number of requests currently parked, waiting for room in the unified KV cache", + (double) n_preempted_slots + }, { + "preempt_ram_bytes", + "Preemption: Host RAM held by parked sequences", + (double) preempt_ram_bytes }, }; diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 50926ec3ca8a..2c24cf5b6205 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -140,6 +140,9 @@ struct server_task { // TODO @ngxson : remove this field and implement a mapping task_id -> idx in the response_reader size_t index = 0; // used when there are multiple prompts (batch request) + // [TAG_PREEMPT] this request yielded more than one task, so index tells its results apart and the preempt notices carry it + bool batched = false; + // used by SERVER_TASK_TYPE_CANCEL int id_target = -1; int id_slot = -1; @@ -382,6 +385,12 @@ struct server_task_result_cmpl_final : server_task_result { std::vector probs_output; std::vector response_fields; + // [TAG_PREEMPT] how the request was served: how often it was parked, and how many of those parks re-prefilled instead of restoring saved bytes + int32_t n_preempt = 0; + int32_t n_recompute = 0; + + json preempt_to_json() const; + task_params generation_params; // response formatting @@ -435,6 +444,19 @@ struct server_task_result_cmpl_final : server_task_result { json to_json_anthropic_stream(); }; +// [TAG_PREEMPT] out-of-band notice for a streaming task whose slot was parked or restored, sent as an SSE comment (": preempted", ": resumed") every existing client ignores +struct server_task_result_preempt_notice : server_task_result { + bool parked = false; // true when the slot was just parked, false when restored + bool recomputed = false; // this resume re-prefilled its tokens instead of restoring saved bytes + int32_t n_preempt = 0; // how many times this task has been parked so far + bool batched = false; // one of several tasks of its request, so the notice names which one by index + + virtual bool is_stop() override { + return false; + } + virtual json to_json() override; +}; + struct server_task_result_cmpl_partial : server_task_result { common_chat_input content; llama_tokens tokens; @@ -545,6 +567,8 @@ struct server_task_result_metrics : server_task_result { // these are immediate stats, not accumulated (server_metrics is cumulative) int n_processing_slots = 0; int n_tasks_deferred = 0; + int n_preempted_slots = 0; // [TAG_PREEMPT] processing slots currently parked + size_t preempt_ram_bytes = 0; // [TAG_PREEMPT] host RAM their parked sequences hold server_metrics metrics; diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py new file mode 100644 index 000000000000..c47cda62b17f --- /dev/null +++ b/tools/server/tests/unit/test_preempt.py @@ -0,0 +1,1094 @@ +import base64 +import json +import os +import re +import struct +import subprocess +import threading +from concurrent.futures import ThreadPoolExecutor +import time +import tempfile +import pytest +import requests +from utils import * + +# Preemption on a unified KV pool: one slot is parked, its sequence copied to host RAM and its cells released, instead of every slot being terminated. Needs --kv-unified. + +server = ServerPreset.tinyllama2() + +_ASYNC_BANNER = "parking and resuming asynchronously" + +_PROMPT_A = "Once upon a time there was a brave knight who" +_PROMPT_B = "The quick brown fox jumps over the lazy dog and" +_PROMPT_C = "In a small village by the sea there lived a fisherman who" + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinyllama2() + server.n_slots = 2 + server.kv_unified = True + # the server parks only when asked: --preempt-ram defaults to 0, and this suite is about parking + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" + server.server_slots = True + server.server_metrics = True + server.temperature = 0.0 + server.seed = 42 + fd, server.log_path = tempfile.mkstemp(suffix=".log") + os.close(fd) + yield + for name in ("LLAMA_SERVER_PREEMPT_EVERY", "LLAMA_SERVER_PREEMPT_GRANULARITY", + "LLAMA_SERVER_PREEMPT_PLANNER", "LLAMA_ARG_PREEMPT_RAM", "LLAMA_ARG_PREEMPT_ASYNC", + "LLAMA_SERVER_PREEMPT_FAIL_SAVE", "LLAMA_ARG_SPEC_DRAFT_P_MIN", "LLAMA_ARG_LOG_VERBOSITY", + "LLAMA_BATCH_DEBUG", "LLAMA_ARG_CTX_CHECKPOINTS", + "LLAMA_MEDIA_MARKER", "LLAMA_EXACT_CONCURRENCY"): + os.environ.pop(name, None) + + +def _start(**kwargs): + """Start the server with these settings; its log starts empty again on every start.""" + for key, value in kwargs.items(): + setattr(server, key, value) + server.start() + + +def _start_async(**kwargs): + """As _start, on the asynchronous park path; a backend that cannot copy off-thread skips the test.""" + os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "1" + _start(n_gpu_layer=99, **kwargs) + _require_async(_log()) + + +def _log() -> str: + """The server log once its writer thread has stopped growing it: on a loaded host the log lags the response that came from it.""" + deadline = time.time() + 5.0 + last = -1 + while time.time() < deadline: + size = os.path.getsize(server.log_path) + if size == last: + break + last = size + time.sleep(0.1) + return open(server.log_path, errors="replace").read() + + +def _require_async(text: str): + if _ASYNC_BANNER not in text: + pytest.skip("this backend cannot copy asynchronously, the async park path is not exercised") + + +def _complete(n_predict: int, prompt="Hi how are you", id_slot: int = -1, delay: float = 0.0, after_slot_busy=None, + timeout: float = DEFAULT_REQUEST_TIMEOUT): + time.sleep(delay) + if after_slot_busy is not None: + # sent once that slot is processing, so the request queues behind it whatever the host's speed + for _ in range(200): + slots = server.make_request("GET", "/slots").body + if any(s["id"] == after_slot_busy and s["is_processing"] for s in slots): + break + time.sleep(0.02) + return server.make_request("POST", "/completion", data={ + "n_predict": n_predict, "prompt": prompt, "id_slot": id_slot, + "ignore_eos": True, "return_tokens": True, "temperature": 0.0, "seed": 42, + }, timeout=timeout) + + +def _complete_all(n_predict: int, prompts=(_PROMPT_A, _PROMPT_B), timeout: float = DEFAULT_REQUEST_TIMEOUT): + return parallel_function_calls([(_complete, (n_predict, prompt, -1, 0.0, None, timeout)) for prompt in prompts]) + + +def _wait_processing(slot_ids, timeout: float = 30.0): + """Return once every one of these slots is processing; a request that ended first is a failure, not a hang.""" + deadline = time.time() + timeout + while time.time() < deadline: + slots = server.make_request("GET", "/slots").body + if all(any(s["id"] == i and s["is_processing"] for s in slots) for i in slot_ids): + return + time.sleep(0.005) + pytest.fail(f"slots {slot_ids} never showed as processing") + + +def _complete_overlapping(n_predict, n_prompt, timeout: float = DEFAULT_REQUEST_TIMEOUT): + """A leader on slot 0 and a follower on slot 1 that certainly overlap: the follower is sent once the leader is seen processing, so the lengths and not the client's speed decide what the pool has to hold.""" + leader = _prompt_of(n_prompt[0], _PROMPT_A) + other = _prompt_of(n_prompt[1], _PROMPT_B) + with ThreadPoolExecutor(1) as pool: + first = pool.submit(_complete, n_predict[0], leader, 0, 0.0, None, timeout) + _wait_processing([0]) + second = _complete(n_predict[1], other, 1, 0.0, None, timeout) + return [first.result(), second] + + +def _wait_preempted(timeout: float = 30.0) -> bool: + """True once some slot is parked: its cells are in host RAM and it wants them back.""" + deadline = time.time() + timeout + while time.time() < deadline: + slots = server.make_request("GET", "/slots").body + if any(s["is_preempted"] for s in slots): + return True + time.sleep(0.005) + return False + + +def _prompt_of(n_tokens: int, text: str) -> list: + """A prompt of exactly n_tokens tokens, as ids: no BOS is added to one of those.""" + base = server.make_request("POST", "/tokenize", data={"content": text}).body["tokens"] + assert base + return (base * (n_tokens // len(base) + 1))[:n_tokens] + + +def _assert_completed(results, n_predict: int): + for res in results: + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + + +_PARK_MARKERS = ("preempted:", "preempted as a last resort", "preempted on request") + + +def _assert_nothing_parked(text: str): + # the park log lines, not the bare word: a verbose log prints every slot's "is_preempted" + assert not any(m in text for m in _PARK_MARKERS), "nothing could be parked here" + + +def _assert_recovered(text: str, parked: str = "preempted:"): + """Nothing was ended for want of cells: a slot was parked and came back.""" + assert "Context size has been exceeded" not in text + assert parked in text + assert "resumed after" in text + + +def _metrics() -> dict: + res = server.make_request("GET", "/metrics") + assert res.status_code == 200 + return { + name[len("llamacpp:"):]: float(value) + for name, value in (line.split(" ", 1) for line in res.body.splitlines() if line.startswith("llamacpp:")) + } + + +@pytest.mark.parametrize("mode", ["sync", "async", "no-async"]) +def test_forced_parks_do_not_change_the_output(mode): + if mode != "sync": + server.n_gpu_layer = 99 + os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "1" if mode == "async" else "0" + _start(n_ctx=512) + if mode == "async": + _require_async(_log()) + reference = _complete(64) + assert reference.status_code == 200 + server.stop() + + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start() + preempted = _complete(64) + assert preempted.status_code == 200 + assert preempted.body["timings"]["predicted_n"] == 64 + assert preempted.body["content"] == reference.body["content"] + assert preempted.body["tokens"] == reference.body["tokens"] + + text = _log() + assert text.count("preempted on request") >= 6 + assert text.count("resumed after") >= 6 + if mode == "async": + assert "park completed after" in text + assert "restore issued in" in text + assert "restore completed after" in text + if mode == "no-async": + assert _ASYNC_BANNER not in text + assert "park issued in" not in text + + +@pytest.mark.parametrize("knob", ["planner", "pages", "async", "last-resort", "last-resort-unlimited"]) +def test_two_generations_that_do_not_fit_together_both_finish(knob): + # each request fits the pool alone (960 and 600 of 1024 cells) but not together; without preemption both end with "Context size has been exceeded" + if knob == "pages": + # a block allocator gives a whole block to one sequence, so the planner has to count cells: counting tokens it sees room the allocator cannot find + os.environ["LLAMA_SERVER_PREEMPT_GRANULARITY"] = "64" + if knob.startswith("last-resort"): + os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" + if knob == "last-resort-unlimited": + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "-1" + n_ctx = 1024 + (_start_async if knob == "async" else _start)(n_ctx=n_ctx) + + # the lengths, not the client's speed, decide the overlap: two equal requests fired together did not overlap on a Windows runner, the first finished before the second arrived, and the last resort never saw the two residents it needs. + # the follower is sent once the leader is seen processing, so it holds its cells while the leader grows into the rest of the pool + n_predict = (460, 400) + results = _complete_overlapping(n_predict, (500, 200)) + + text = _log() + _assert_recovered(text, "preempted as a last resort" if knob.startswith("last-resort") else "preempted:") + for res, n_wanted in zip(results, n_predict): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_wanted + assert res.body["truncated"] is False + assert len(res.body["tokens"]) == n_wanted + + if knob == "pages": + held = [int(n) for n in re.findall(rf"kv (\d+)/{n_ctx}", text)] + wanted = [int(n) for n in re.findall(r"\(wanted (\d+)\)", text)] + assert held and wanted, f"the planner logged no figures:\n{text}" + assert all(n % 64 == 0 for n in held + wanted), f"not whole blocks: {held} {wanted}" + if knob.startswith("last-resort"): + assert "preempted:" not in text, "the planner was off, nothing may be parked ahead of the decode" + assert "last resort: batch given up" in text + if knob == "planner": + metrics = _metrics() + assert metrics["n_preempt_total"] >= 1 + assert metrics["n_resume_total"] == metrics["n_preempt_total"] + assert metrics["requests_preempted"] == 0 + assert metrics["preempt_ram_bytes"] == 0 + + +@pytest.mark.parametrize("knob", ["ram-0", "family"]) +def test_a_request_that_cannot_be_helped_gets_the_context_error_and_the_server_lives(knob): + if knob == "ram-0": + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "0" + else: + # a family member is not a victim for the other, so a two-completion request gets the error it would get alone + os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" + _start(n_ctx=256) + + if knob == "ram-0": + # the overflow has to be a matter of lengths: two equal requests fired together did not overlap on a Windows runner, and each one fits the pool alone + assert any(res.status_code != 200 for res in _complete_overlapping((110, 100), (120, 60))) + else: + res = server.make_request("POST", "/completion", data={ + "n_predict": 160, "n_cmpl": 2, "prompt": _PROMPT_A, + "ignore_eos": True, "temperature": 0.0, "seed": 42, + }) + assert res.status_code == 500 + assert "Context size has been exceeded" in res.body["error"]["message"] + + text = _log() + assert "Context size has been exceeded" in text + _assert_nothing_parked(text) + assert "GGML_ASSERT" not in text + after = _complete(8) + assert after.status_code == 200 + assert after.body["timings"]["predicted_n"] == 8 + + +def test_a_server_that_never_asked_for_parking_behaves_as_upstream(): + """--preempt-ram defaults to 0, so a unified-cache server started without it parks nothing.""" + os.environ.pop("LLAMA_ARG_PREEMPT_RAM", None) + _start(n_ctx=256) + + text = _log() + assert "preemption:" not in text, "a server that did not ask for parking announced it" + assert _ASYNC_BANNER not in text, "the async park path was set up without being asked for" + + # as above, the two have to be resident together for the pool to overflow at all + assert any(res.status_code != 200 for res in _complete_overlapping((110, 100), (120, 60))) + + text = _log() + assert "Context size has been exceeded" in text + _assert_nothing_parked(text) + assert "last resort" not in text, "the retry ladder consulted the planner" + assert "GGML_ASSERT" not in text + + metrics = _metrics() + assert metrics["n_preempt_total"] == 0 + assert metrics["preempt_ram_bytes"] == 0 + + after = _complete(8) + assert after.status_code == 200 + assert after.body["timings"]["predicted_n"] == 8 + + +@pytest.mark.parametrize("planner", ["on", "off"]) +def test_a_late_prompt_and_a_generating_slot_both_finish(planner): + if planner == "off": + os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" + _start(n_ctx=256) + + n_b = 150 + n_predict_a = 230 + n_predict_b = 90 + assert 8 + n_predict_a + n_b + n_predict_b > 256 + results = parallel_function_calls([ + (_complete, (n_predict_a, "Hi how are you")), + (_complete, (n_predict_b, _prompt_of(n_b, _PROMPT_C), -1, 0.02)), + ]) + + text = _log() + assert "Context size has been exceeded" not in text + assert ("preempted as a last resort" if planner == "off" else "preempted:") in text + for res, n_predict in zip(results, (n_predict_a, n_predict_b)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + # the chunk in the batch given up is processed once after the rewind, never twice + assert results[1].body["timings"]["prompt_n"] == n_b + + +def test_a_prompt_parked_before_its_first_token_is_issued_whole(): + # both prompts are too close to n_ctx to leave the usual margin, so the second is parked before it takes a cell and has to come back once the first has finished + _start(n_ctx=256, n_batch=256) + + n_prompt = 240 + n_predict = 4 + long_prompt = _prompt_of(n_prompt, "Once upon a time there was a little girl") + together = _complete_all(n_predict, [long_prompt, long_prompt]) + + assert "cannot fit the pool" not in _log() + _assert_completed(together, n_predict) + for res in together: + assert res.body["timings"]["prompt_n"] == n_prompt, "the prompt was not issued once and whole" + + +def test_a_resident_cycling_through_context_shifts_is_rotated_out_for_a_parked_head(): + # with context shift on a resident would hold its cells for as long as it generates, so once the head has waited its turn the resident is parked and the two take turns + _start(n_slots=3, n_ctx=384, enable_ctx_shift=True) + + # the rotation waits on a clock, not on a token count, so the generation has to be long enough on a fast host; that is a lot of tokens for a slow one, and it takes turns with two others, so it is given more than the usual wait + n_predict = 9000 + _assert_completed(_complete_all(n_predict, (_PROMPT_A, _PROMPT_B, _PROMPT_C), timeout=1800), n_predict) + + text = _log() + _assert_recovered(text, "rotated out after") + assert "slot context shift" in text + + +def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): + # the budget grants permission to allocate, not a successful allocation: a failed save used to stop the planner and leave the pool to overflow, although the same victim could be parked by dropping its cells + os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" + _start(n_ctx=1024, n_slots=2) + + # lengths decide the overlap, not the host's speed: two 171-cell requests fired together did not overlap on a Windows runner, so nothing was parked. The leader ends at 960 of 1024 cells, so the second is parked whatever the client's lag + leader = _prompt_of(500, _PROMPT_A) + other = _prompt_of(200, _PROMPT_B) + with ThreadPoolExecutor(1) as pool: + first = pool.submit(_complete, 460, leader, 0) + _wait_processing([0]) + second = _complete(400, other, 1) + results = [first.result(), second] + + text = _log() + assert "could not take the host memory" in text, "the injected allocation failure never fired" + assert "tokens to re-prefill" in text, "the failed save did not fall back to recompute" + assert "Context size has been exceeded" not in text + for res, n_predict in zip(results, (460, 400)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + + +def test_a_resident_that_cannot_be_swapped_out_is_rotated_by_recompute(): + # 1 MiB holds no snapshot, so rotation refused every resident and only logged that the head waits: a resident that keeps context-shifting need never finish, and the head waited behind it for good + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + _start(n_ctx=2048, n_slots=2, n_batch=2048, enable_ctx_shift=True) + + # a small n_discard keeps the resident near the end of the pool, so its state never fits the budget + def unending_request(): + return server.make_request("POST", "/completion", data={ + "n_predict": 100000, "prompt": _PROMPT_A, "n_keep": 1, "n_discard": 64, + "ignore_eos": True, "temperature": 0.0, "seed": 42, + }, timeout=600) + + # the server is stopped below with this request still in flight, so the disconnect it then sees is expected and must not surface as an unhandled thread exception + unending = [] + + def run_unending(): + try: + unending.append(unending_request()) + except requests.exceptions.RequestException: + pass + + t = threading.Thread(target=run_unending) + t.start() + + try: + # the resident has to be at the pool's limit and cycling before a second prompt cannot fit beside it + for _ in range(3000): + if "slot context shift" in _log(): + break + time.sleep(0.05) + else: + pytest.fail("the resident never reached the end of the pool") + + waiting = server.make_request("POST", "/completion", data={ + "n_predict": 8, "prompt": _prompt_of(1800, _PROMPT_C), + "ignore_eos": True, "temperature": 0.0, "seed": 42, + }, timeout=300) + + assert waiting.status_code == 200, waiting.body + assert waiting.body["timings"]["predicted_n"] == 8, "the second request never made progress" + assert not unending, "the first request ended before the second made progress" + finally: + server.stop() + t.join(60) + + text = _log() + assert "slot context shift" in text + assert re.search(r"rotated out after .* cells dropped", text), "the rotation did not fall back to recompute" + assert "Context size has been exceeded" not in text + + +def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): + # a cancelled request can reach release() with a park or a resume still running, where the host buffer is freed and the cells handed on, so both have to wait for the copy + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start_async(n_ctx=512) + + for i in range(4): + try: + server.make_request("POST", "/completion", data={ + "n_predict": 96, "prompt": _PROMPT_A, "ignore_eos": True, "temperature": 0.0, "seed": 42, + }, timeout=0.05 + 0.1 * i) + except Exception: + pass # the point is the drop, not the response + + for _ in range(600): + res = server.make_request("GET", "/slots") + assert res.status_code == 200 + if all(not slot["is_processing"] for slot in res.body): + break + time.sleep(0.2) + else: + pytest.fail("a slot never came back after a cancel during a copy") + for slot in res.body: + assert slot["is_preempted"] is False + assert slot["is_transferring"] is False + assert _metrics()["preempt_ram_bytes"] == 0, "a cancelled slot kept its parked memory" + + res = _complete(16) + assert res.status_code == 200 + assert res.body["timings"]["predicted_n"] == 16 + + +def test_a_started_slot_is_counted_by_the_cells_it_holds_not_by_the_prompt_it_keeps(): + # the last request waits for slot 0 and is started on it holding the first request's cells; counted by the prompt it keeps instead, the pool looks free and a parked slot is restored into cells that are still taken + _start(n_ctx=1024, n_slots=3) + + # the lengths, not the host's speed, decide who is parked: the three prompts (500 + 200 + 200) fit the 1024 cells, so both of the others are parked holding at least their whole prompt once slot 0 grows into the rest, and slot 0 is the largest slot throughout, which the planner never picks as a victim. Slot 0 ends holding 960 of the 1024 cells, too few left for either parked slot to come back + ids = _prompt_of(500, _PROMPT_C) + + with ThreadPoolExecutor(4) as pool: + first = pool.submit(_complete, 460, ids, 0) + _wait_processing([0]) + # queued behind slot 0 whatever the host's speed, and a real prefix of what slot 0 holds: it starts on 960 cells while keeping 8 of them + follower = pool.submit(_complete, 8, ids[:8], 0) + long_ones = [pool.submit(_complete, 400, _prompt_of(200, _PROMPT_A), 1), + pool.submit(_complete, 400, _prompt_of(200, _PROMPT_B), 2)] + parked = _wait_preempted() + results = [first.result(), follower.result(), long_ones[0].result(), long_ones[1].result()] + + text = _log() + assert parked, "the pool never came under pressure, so no slot was waiting for the cells slot 0 keeps" + assert "trimmed to the" in text, "the started slot kept the cells of the request before it" + assert "resume failed" not in text + assert "Context size has been exceeded" not in text + for res, n_predict in zip(results, (460, 8, 400, 400)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + + +def test_a_recurrent_model_is_served_without_preemption(): + server.model_file = os.environ.get("LLAMA_SERVER_TEST_RECURRENT_MODEL") + if server.model_file: + server.model_hf_repo = server.model_hf_file = None + else: + server.model_hf_repo = "Felladrin/gguf-mamba-130m-hf" + server.model_hf_file = "mamba-130m-hf.Q2_K.gguf" + server.offline = False + server.n_ctx = 1024 + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + server.start(timeout_seconds=300) + + # not "Once upon a time": what this Q2_K model decodes from it on CUDA carries bytes the content parser refuses, master included, which is not what this test measures + results = _complete_all(64, ["The quick brown fox", "Hello world"]) + _assert_completed(results, 64) + + text = _log() + assert "preemption: off, the recurrent cache holds one state per sequence" in text + _assert_nothing_parked(text) + assert "Context size has been exceeded" not in text + + +def _stream_completion(n_predict: int, prompt: str) -> tuple[list[str], dict]: + """One streaming completion: its SSE comment lines and the last response object.""" + url = f"http://{server.server_host}:{server.server_port}/completion" + res = requests.post(url, json={ + "prompt": prompt, "n_predict": n_predict, "ignore_eos": True, + "temperature": 0.0, "seed": 42, "stream": True, + }, stream=True, timeout=600) + assert res.status_code == 200, res.text + comments, datas = [], [] + for raw in res.iter_lines(): + line = raw.decode("utf-8") + if line.startswith(":"): + comments.append(line) + elif line.startswith("data: ") and line[6:] != "[DONE]": + datas.append(json.loads(line[6:])) + return comments, datas[-1] + + +@pytest.mark.parametrize("planner", ["on", "off"]) +def test_a_budget_that_holds_no_sequence_parks_by_dropping_the_cells(planner): + # 1 MiB holds neither sequence, so no victim fits the budget: the park drops the cells and the resume re-prefills the tokens, instead of the pool overflowing and ending both; the last resort falls back the same way + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + if planner == "off": + os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" + # one batch for the re-prefill: a prompt of this length in 32-token batches hangs the CUDA build with graphs on, master included, so that is not what this test measures + _start(n_ctx=3840, n_batch=2048) + + n_predict = 2000 + if planner == "on": + results = parallel_function_calls([(_stream_completion, (n_predict, p)) for p in (_PROMPT_A, _PROMPT_B)]) + for comments, final in results: + assert "error" not in final, final + assert final["tokens_predicted"] == n_predict + comments = [c for cs, _ in results for c in cs] + assert ": preempted" in comments and ": resumed" in comments, comments + else: + _assert_completed(_complete_all(n_predict), n_predict) + + text = _log() + assert "Context size has been exceeded" not in text + assert "tokens to re-prefill" in text, "no park fell back to recompute" + if planner == "off": + assert "preempted as a last resort by dropping its cells" in text + + +_IMG_URL = "https://huggingface.co/ggml-org/tinygemma3-GGUF/resolve/main/test/11_truck.png" + + +def test_a_media_chunk_is_reserved_whole_before_it_is_decoded(): + # a chunk is decoded whole inside one iteration, through decodes the kv-full retry does not cover: unless the planner reserves every cell it takes, the second of two image requests that each fit alone fails part way through its chunk + os.environ["LLAMA_MEDIA_MARKER"] = "<__media__>" + server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" + server.model_hf_file = None + server.model_alias = "tinygemma3" + _start(n_ctx=400, n_batch=64, n_ubatch=64) + + image = base64.b64encode(requests.get(_IMG_URL, timeout=60).content).decode() + prompt = {"prompt_string": "<__media__>\nWhat is in this image?", "multimodal_data": [image]} + results = parallel_function_calls([ + (server.make_request, ("POST", "/completion", { + "prompt": prompt, "n_predict": 4, "temperature": 0.0, "seed": 42, + })) for _ in range(2) + ]) + + text = _log() + assert "failed to process mtmd chunk" not in text + assert "preempted:" in text, "nothing was parked to make room for a chunk" + for res in results: + assert res.status_code == 200, res.body + assert res.body["timings"]["prompt_n"] > 64, "the chunk fits one batch, so it never spans several decodes" + + +def test_an_mtp_draft_stays_inside_the_reservation_it_was_priced_for(): + # near the end of the pool the planner prices one draft token and one sampled token, but the draft loop stopped against the configured window and could attempt positions past the reservation + path = os.environ.get("LLAMA_SERVER_TEST_MTP_MODEL") + if not path: + pytest.skip("set LLAMA_SERVER_TEST_MTP_MODEL to a gguf carrying an MTP head") + server.model_file = path + server.model_hf_repo = server.model_hf_file = None + server.spec_type = "draft-mtp" + os.environ["LLAMA_ARG_SPEC_DRAFT_P_MIN"] = "0.0" # nothing but the bounds stops the draft loop + os.environ["LLAMA_ARG_LOG_VERBOSITY"] = "5" # the wrapper says so when it truncates what an implementation returned + _start(n_ctx=2048, n_slots=2, n_batch=2048, n_gpu_layer=99, spec_draft_n_max=128, spec_draft_n_min=1) + + n_prompt = 2045 + res = server.make_request("POST", "/completion", data={ + "prompt": _prompt_of(n_prompt, _PROMPT_C), "n_predict": 2, "ignore_eos": True, + "temperature": 0.0, "seed": 42, "cache_prompt": False, + }, timeout=600) + + assert res.status_code == 200, res.body + assert res.body["timings"]["prompt_n"] == n_prompt + assert res.body["tokens_predicted"] == 2 + + text = _log() + assert "truncating draft to" not in text, "the draft was scheduled past the tokens the planner reserved" + assert "llama_decode[" not in text + assert "Context size has been exceeded" not in text + + +def test_a_hybrid_model_parks_synchronously(): + # the recurrent half of a hybrid gathers the active sequences into contiguous rows on every batch, so a copy running beside the decode could read a row another sequence has been moved into + path = os.environ.get("LLAMA_SERVER_TEST_HYBRID_MODEL") + if not path: + pytest.skip("set LLAMA_SERVER_TEST_HYBRID_MODEL to a hybrid attention/recurrent gguf") + server.model_file = path + server.model_hf_repo = server.model_hf_file = None + os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "1" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start(n_ctx=1024, n_gpu_layer=99) + + res = _complete(24, "Once upon a time") + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == 24 + + text = _log() + assert "a recurrent state does not stay in one row" in text + assert _ASYNC_BANNER not in text + assert "park issued in" not in text + _assert_recovered(text, "preempted on request") + + +# [TAG_EXACT_CONCURRENCY] the paged pool places a cell from the sequence and the position alone, so a layout that gives several tokens one position cannot be served + +def _mrope_model() -> str: + path = os.environ.get("LLAMA_SERVER_TEST_MROPE_MODEL") + if not path: + pytest.skip("set LLAMA_SERVER_TEST_MROPE_MODEL to an M-RoPE gguf") + return path + + +def test_exact_concurrency_refuses_an_mrope_model_with_a_projector(): + # every token of one image shares a temporal position under M-RoPE, so the pool would give the second one the first one's cell + path = _mrope_model() + with tempfile.TemporaryDirectory() as tmp: + mmproj = os.path.join(tmp, "mmproj.gguf") + with open(mmproj, "wb") as f: + f.write(b"GGUF" + struct.pack(" list: + """The tokens of every ubatch a split produced, in order; needs LLAMA_BATCH_DEBUG.""" + res = [] + pending = False + for line in text.splitlines(): + if "added ubatch to split" in line: + pending = True + elif pending and "n_tokens" in line: + res.append(int(line.split("=")[-1])) + pending = False + return res + + +def test_exact_concurrency_prefills_a_prompt_in_the_ubatches_it_would_get_alone(): + # generated tokens enter the batch first and a prompt took what was left, so its ubatches were 512,512,512,509 beside three decoders and 512,512,512,512 alone: isolating the sequences does not make the shapes equal by itself + # geometry: -b 2048 -ub 512 -np 4, so the batch holds a whole ubatch beside a decode step of every slot (516 tokens), which is what common_exact_batch_geometry() requires of a start + path = os.environ.get("LLAMA_SERVER_TEST_EXACT_MODEL") + if not path: + pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") + server.model_file = path + server.model_hf_repo = server.model_hf_file = None + os.environ["LLAMA_EXACT_CONCURRENCY"] = "1" + os.environ["LLAMA_BATCH_DEBUG"] = "1" + os.environ["LLAMA_ARG_LOG_VERBOSITY"] = "5" + os.environ["LLAMA_ARG_CTX_CHECKPOINTS"] = "0" + _start(n_ctx=16384, n_slots=4, n_batch=2048, n_ubatch=512, fa="on", n_gpu_layer=99, cache_ram=0) + + def prefill(first_token: int) -> list: + mark = len(_log()) + res = server.make_request("POST", "/completion", data={ + "prompt": list(range(first_token, first_token + 3500)), "n_predict": 1, + "cache_prompt": False, "temperature": 0.0, "seed": 42, + }, timeout=600) + assert res.status_code == 200, res.body + assert res.body["timings"]["prompt_n"] == 3500 + text = _log()[mark:] + # a decode step is one token per slot, so the prompt's own ubatches are the wide ones + return [w for w in _ubatch_widths(text) if w > 3] + + alone = prefill(1000) + assert alone, "no ubatch was recorded, LLAMA_BATCH_DEBUG did not reach the log" + + def decoder(i): + server.make_request("POST", "/completion", data={ + "prompt": list(range(20000 + 100 * i, 20000 + 100 * i + 8)), "n_predict": 100000, + "cache_prompt": False, "ignore_eos": True, "temperature": 0.0, "seed": 42, + }, timeout=600) + + threads = [threading.Thread(target=decoder, args=(i,), daemon=True) for i in range(3)] + for t in threads: + t.start() + + try: + for _ in range(600): + slots = server.make_request("GET", "/slots").body + if sum(1 for s in slots if s["is_processing"] and s["n_prompt_tokens"] > 0) >= 3: + break + time.sleep(0.1) + else: + pytest.fail("the decoders never started") + time.sleep(1.0) + + beside = prefill(50000) + finally: + server.stop() + for t in threads: + t.join(30) + + assert beside == alone, f"alone {alone}, beside three decoders {beside}" + + +def test_slots_reports_a_transferring_slot_apart_from_a_parked_one(): + # a copy out still owns its cells and a restore has already taken them back, so a reader counting residency has to keep counting both; only a fully parked slot holds nothing + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "1" + _start_async(n_ctx=256) + + done = [] + t = threading.Thread(target=lambda: done.extend(_complete_all(900))) + t.start() + seen_parked = seen_transferring = False + try: + deadline = time.time() + 120 + while time.time() < deadline and not (seen_parked and seen_transferring): + res = server.make_request("GET", "/slots") + assert res.status_code == 200 + for slot in res.body: + assert not (slot["is_preempted"] and slot["is_transferring"]), slot + if slot["is_transferring"]: + seen_transferring = True + assert slot["n_prompt_tokens"] > 0, "a slot with a copy in flight still holds its cells" + seen_parked = seen_parked or slot["is_preempted"] + finally: + t.join(180) + + assert len(done) == 2, done + for res in done: + assert res.status_code == 200, res.body + assert res.body["tokens_predicted"] > 0 + assert seen_parked, "no parked slot was ever reported" + assert seen_transferring, "no slot with a copy in flight was ever reported" + + +def _shift_completion(n_predict: int): + """A completion whose context shifts, on a token prompt so its length is exact.""" + return server.make_request("POST", "/completion", data={ + "prompt": [1] + list(range(10, 70)), "n_predict": n_predict, "n_keep": 16, "n_discard": 64, + "ignore_eos": True, "return_tokens": True, "cache_prompt": False, "temperature": 0.0, "seed": 42, + }) + + +def test_a_park_right_after_a_context_shift_does_not_change_the_output(): + # the shift moves the positions and leaves the K transformation for the next decode, so a park in between used to save the new positions with the old K + os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "0" + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "0" + _start(n_ctx=256, n_batch=32, n_ubatch=32, enable_ctx_shift=True, cache_ram=0) + + n_predict = 320 + reference = _shift_completion(n_predict) + assert reference.status_code == 200, reference.body + assert reference.body["timings"]["predicted_n"] == n_predict + n_prompt = reference.body["timings"]["prompt_n"] + server.stop() + + # park on the step the shift lands on: the pool holds n_ctx cells, so the first shift is that many tokens in + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = str(256 - n_prompt) + _start() + + parked = _shift_completion(n_predict) + assert parked.status_code == 200, parked.body + assert parked.body["timings"]["predicted_n"] == n_predict + + text = _log() + assert "slot context shift" in text + _assert_recovered(text, "preempted on request") + first_diff = next((i for i, (a, b) in enumerate(zip(reference.body["tokens"], parked.body["tokens"])) if a != b), None) + assert first_diff is None, f"the parked run diverged at token {first_diff}" + + +def test_a_sibling_prompt_with_an_invalid_token_is_refused_before_anything_streams(): + # validated with the others ahead of posting: parked behind a running sibling, it used to fail inside a stream that had already opened 200 + _start(n_ctx=256, n_slots=2, n_batch=256) + + res = server.make_request("POST", "/completion", data={ + "prompt": [[1] * 240, [1] * 240, [9999999]], "n_predict": 4, "temperature": 0.0, "seed": 42, + }) + assert res.status_code == 400, res.body + assert "invalid tokens" in str(res.body) + + text = _log() + _assert_nothing_parked(text) + + +def test_a_recompute_park_bounds_its_draft_by_the_tokens_it_comes_back_with(): + # a recompute park moves the prompt out of the slot, and the draft was bounded by the empty prompt: 2000 tokens and a whole draft could not fit a 2048-cell pool "even alone", failing a request that fits + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "1" + server.spec_type = "ngram-mod" + _start(n_ctx=2048, n_slots=2, n_batch=2048, n_ubatch=512, spec_ngram_mod_n_max=128, spec_ngram_mod_n_min=1) + + prompt = [1] + list(range(10, 110)) * 19 + list(range(10, 109)) + assert len(prompt) == 2000 + res = server.make_request("POST", "/completion", data={ + "prompt": prompt, "n_predict": 24, "ignore_eos": True, "temperature": 0.0, "seed": 42, "cache_prompt": False, + }) + assert res.status_code == 200, res.body + assert res.body["tokens_predicted"] == 24 + + text = _log() + assert "tokens to re-prefill" in text + assert "cannot fit the pool" not in text + assert "Context size has been exceeded" not in text + + +def test_props_says_whether_exact_concurrency_is_running(): + # a client that asked for the mode reads the answer here: a build that ignores the variable starts all the same + _start(n_ctx=256) + res = server.make_request("GET", "/props") + assert res.status_code == 200 + assert res.body["exact_concurrency"] is False + + +def test_props_reports_exact_concurrency_on(): + server.model_file = _mrope_model() + server.model_hf_repo = server.model_hf_file = None + os.environ["LLAMA_EXACT_CONCURRENCY"] = "1" + _start(n_ctx=512, n_slots=2, n_batch=512, n_ubatch=128, fa="on", n_gpu_layer=99) + res = server.make_request("GET", "/props") + assert res.status_code == 200 + assert res.body["exact_concurrency"] is True + + +def test_a_recompute_park_under_exact_concurrency_says_it_is_not_byte_identical(): + # a state that comes back from host memory is the state that left; one rebuilt by re-prefilling differs in the last bits on CUDA, so the mode says so the first time it happens + server.model_file = _mrope_model() + server.model_hf_repo = server.model_hf_file = None + os.environ["LLAMA_EXACT_CONCURRENCY"] = "1" + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "4" + _start(n_ctx=512, n_slots=2, n_batch=512, n_ubatch=128, fa="on", n_gpu_layer=99) + + res = _complete(16, "Once upon a time") + assert res.status_code == 200, res.body + text = _log() + assert "tokens to re-prefill" in text + assert "not guaranteed byte-identical" in text + + +def test_a_recompute_park_is_reported_to_the_client_and_to_metrics(): + # a recompute resume re-prefills instead of restoring the saved bytes, so it is not the continuation the parked state would have given: the request, /slots and /metrics all say how often that happened + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + # a sequence this long holds more than the 1 MiB budget, so every park drops its cells + _start(n_ctx=2048, n_batch=2048) + + n_predict = 24 + prompt = _prompt_of(1950, _PROMPT_C) + comments, final = _stream_completion(n_predict, prompt) + + assert "error" not in final, final + assert final["tokens_predicted"] == n_predict + assert final["preempt"]["parks"] >= 2, final["preempt"] + assert final["preempt"]["recomputes"] == final["preempt"]["parks"], final["preempt"] + + # the notice comes right after the resume it belongs to + resumed = [i for i, c in enumerate(comments) if c.startswith(": resumed")] + assert len(resumed) == final["preempt"]["recomputes"], comments + for i in resumed: + assert comments[i + 1].startswith(": recomputed"), comments + + metrics = _metrics() + assert metrics["preempt_recompute_total"] == final["preempt"]["recomputes"] + assert metrics["preempt_recompute_total"] == metrics["n_preempt_total"] + + # a request that is never parked says so + plain = server.make_request("POST", "/completion", data={ + "n_predict": 4, "prompt": _PROMPT_B, "temperature": 0.0, "seed": 42, + }) + assert plain.status_code == 200, plain.body + assert plain.body["preempt"] == {"parks": 0, "recomputes": 0} + + +def test_a_recompute_restore_does_not_count_its_replay_as_prompt(): + # the re-prefill puts back what the park dropped: counted as prompt it would move the prompt/generation boundary, and since n_gen carries across the park the generation time would then cover only the tokens after the last re-prefill + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start(n_ctx=2048, n_batch=2048) + + n_prompt = 1950 + n_predict = 24 + res = _complete(n_predict, _prompt_of(n_prompt, _PROMPT_C)) + + assert res.status_code == 200, res.body + assert res.body["preempt"]["recomputes"] >= 1, res.body["preempt"] + + timings = res.body["timings"] + assert timings["prompt_n"] == n_prompt, timings + assert timings["predicted_n"] == n_predict, timings + # every re-prefill happens inside the generation, so the generation holds the longer time of the two + assert timings["predicted_ms"] > timings["prompt_ms"], timings + + +def test_slots_reports_the_recomputes_of_the_current_task(): + # a reader watching the slots sees the same count the request is given at the end + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start(n_ctx=2048, n_batch=2048) + + done = [] + prompt = _prompt_of(1950, _PROMPT_C) + t = threading.Thread(target=lambda: done.append(_complete(64, prompt))) + t.start() + + seen = 0 + try: + deadline = time.time() + 180 + while time.time() < deadline and seen == 0 and t.is_alive(): + res = server.make_request("GET", "/slots") + assert res.status_code == 200 + for slot in res.body: + assert slot["n_recompute"] <= slot["n_preempt"] + seen = max(seen, slot["n_recompute"]) + time.sleep(0.02) + finally: + t.join(180) + + assert seen > 0, "no slot ever reported a recompute park" + assert done and done[0].status_code == 200, done + assert done[0].body["preempt"]["recomputes"] >= seen + + +def test_a_swap_park_is_not_reported_as_a_recompute(): + # the same park with room for its bytes keeps the sequence it saved, and the client is told so + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start(n_ctx=512) + + comments, final = _stream_completion(24, _PROMPT_A) + + assert final["preempt"]["parks"] >= 1, final["preempt"] + assert final["preempt"]["recomputes"] == 0, final["preempt"] + assert ": resumed" in comments and not any(c.startswith(": recomputed") for c in comments), comments + assert _metrics()["preempt_recompute_total"] == 0 + + +def _stream_responses(n_predict: int, prompt: str) -> dict: + """One streaming /v1/responses request: the data of its response.completed event.""" + url = f"http://{server.server_host}:{server.server_port}/v1/responses" + res = requests.post(url, json={ + "model": "test", "input": prompt, "max_output_tokens": n_predict, + "temperature": 0.0, "stream": True, + }, stream=True, timeout=600) + assert res.status_code == 200, res.text + completed = None + for raw in res.iter_lines(): + line = raw.decode("utf-8") + if line.startswith("data: "): + data = json.loads(line[6:]) + if data.get("type") == "response.completed": + completed = data + assert completed is not None, "the stream never reached response.completed" + return completed + + +def test_a_streamed_response_carries_the_preempt_record_where_a_plain_one_does(): + # what a client keeps from a streamed /v1/responses is data["response"], so the record has to be in that object, the same place the non-streamed body carries it + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start(n_ctx=512) + + completed = _stream_responses(24, _PROMPT_A) + + assert completed["response"]["preempt"]["parks"] >= 1, completed["response"] + assert completed["response"]["preempt"]["recomputes"] == 0, completed["response"] + + plain = server.make_request("POST", "/v1/responses", data={ + "model": "test", "input": _PROMPT_B, "max_output_tokens": 4, "temperature": 0.0, + }) + assert plain.status_code == 200, plain.body + assert sorted(plain.body["preempt"]) == sorted(completed["response"]["preempt"]) == ["parks", "recomputes"] + + +def test_two_image_chats_that_outgrow_the_parking_budget_both_finish(): + # a media chunk could not be parked by recompute, so with the host budget spent nothing could be parked at all and the pool overflowing ended both chats. The chunk comes back the way it went in: re-encoded off the task, its cells reserved whole + os.environ["LLAMA_MEDIA_MARKER"] = "<__media__>" + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" + server.model_hf_file = None + server.model_alias = "tinygemma3" + _start(n_ctx=1024, n_slots=2, n_batch=64, n_ubatch=64) + + image = base64.b64encode(requests.get(_IMG_URL, timeout=60).content).decode() + prompt = {"prompt_string": "<__media__>\nWhat is in this image?", "multimodal_data": [image]} + n_predict = 700 + results = parallel_function_calls([ + (server.make_request, ("POST", "/completion", { + "prompt": prompt, "n_predict": n_predict, "ignore_eos": True, "temperature": 0.0, "seed": 42, + })) for _ in range(2) + ]) + + text = _log() + assert "Context size has been exceeded" not in text + assert "failed to process mtmd chunk" not in text + assert "tokens to re-prefill" in text, "no park fell back to recompute" + for res in results: + assert res.status_code == 200, res.body + assert res.body["tokens_predicted"] == n_predict + + +def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): + # a park with no budget for the state drops the cells of a prompt that is still being processed, and the resume starts that prefill again from nothing: what it had counted before the park has to go with the cells, or the request reports more prompt tokens than it has + # the park is made to fail its host allocation, so it drops the cells instead: the state of a half processed prompt is small enough to fit any budget + os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" + _start(n_ctx=2048, n_batch=256) + + resident = [] + t = threading.Thread(target=lambda: resident.append(_complete(1900, _PROMPT_A)), daemon=True) + t.start() + + # the pool has to be nearly full before the second prompt starts, so that it is that prefill which runs out of cells + deadline = time.time() + 90 + while t.is_alive() and time.time() < deadline: + slots = server.make_request("GET", "/slots").body + if any(slot.get("n_prompt_tokens", 0) >= 1600 for slot in slots): + break + time.sleep(0.005) + else: + pytest.fail("the resident never grew into the pool") + + n_prompt = 500 + n_predict = 8 + comments, final = _stream_completion(n_predict, _prompt_of(n_prompt, _PROMPT_B)) + t.join(120) + + assert resident and resident[0].status_code == 200, resident + assert "error" not in final, final + assert comments and comments[0] == ": preempted", comments + + # a park that dropped fewer cells than the resume has tokens to put back is a park taken mid-prefill, which is the case this test is about + parks = [(int(cells), int(again)) for cells, again in re.findall( + r"preempted: (\d+) cells dropped .*? (\d+) tokens to re-prefill", _log())] + assert any(0 < cells < again for cells, again in parks), parks + + timings = final["timings"] + assert timings["prompt_n"] == n_prompt, timings + assert timings["cache_n"] == 0, timings + assert timings["predicted_n"] == n_predict, timings diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py new file mode 100644 index 000000000000..420f557fa009 --- /dev/null +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -0,0 +1,298 @@ +import json +import os +import re +import tempfile +import time +import threading +import pytest +import requests +from utils import * + +# [TAG_PREEMPT] a streaming client is told when its slot is parked and restored, as SSE comments every existing client ignores; a keepalive every 2 s keeps proxies from giving up + +server = ServerPreset.tinyllama2() + +_PROMPT_A = "Once upon a time there was a brave knight who" +_PROMPT_B = "The quick brown fox jumps over the lazy dog and" +_PROMPT_C = "In a small village by the sea there lived a fisherman who" + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinyllama2() + server.n_slots = 2 + server.kv_unified = True + # the server parks only when asked: --preempt-ram defaults to 0, and this suite is about parking + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" + server.temperature = 0.0 + server.seed = 42 + fd, server.log_path = tempfile.mkstemp(suffix=".log") + os.close(fd) + yield + for name in ("LLAMA_SERVER_PREEMPT_EVERY", "LLAMA_ARG_PREEMPT_RAM"): + os.environ.pop(name, None) + + +def _start(**kwargs): + for key, value in kwargs.items(): + setattr(server, key, value) + server.start() + + +def _completion_payload(n_predict: int, prompt: str = "Hi how are you", **extra) -> dict: + return {"n_predict": n_predict, "prompt": prompt, "ignore_eos": True, + "temperature": 0.0, "seed": 42, "stream": True, **extra} + + +def _chat_payload(n_predict: int) -> dict: + return {"max_tokens": n_predict, "messages": [{"role": "user", "content": "Hi how are you"}], + "temperature": 0.0, "seed": 42, "stream": True} + + +def _log() -> str: + """The server log once its writer thread has stopped growing it: on a loaded host the log lags the response that came from it.""" + deadline = time.time() + 5.0 + last = -1 + while time.time() < deadline: + size = os.path.getsize(server.log_path) + if size == last: + break + last = size + time.sleep(0.1) + return open(server.log_path, errors="replace").read() + + +def _post(path: str, data: dict): + return requests.post(f"http://{server.server_host}:{server.server_port}{path}", json=data, stream=True) + + +def _stream_raw(path: str, data: dict) -> tuple[list[str], list[str]]: + """The SSE lines of one streaming request: (comment lines, data lines).""" + res = _post(path, data) + assert res.status_code == 200 + comments, datas = [], [] + for raw in res.iter_lines(): + line = raw.decode("utf-8") + if line.startswith(":"): + comments.append(line) + elif line.startswith("data: "): + datas.append(line[6:]) + return comments, datas + + +def _stream_all(n_predict: int, prompts, **extra): + return parallel_function_calls([ + (_stream_raw, ("/completion", _completion_payload(n_predict, prompt, **extra))) for prompt in prompts + ]) + + +def _behind_a_resident(payload: dict) -> tuple[int, str, list[str]]: + """Run this request behind a resident holding the pool: its status, its body, and its SSE lines.""" + started = threading.Event() + + def _resident(): + res = _post("/completion", _completion_payload(390, " ".join([_PROMPT_A] * 6))) + assert res.status_code == 200 + for raw in res.iter_lines(): + if raw.decode("utf-8").startswith("data: "): + started.set() + + t = threading.Thread(target=_resident) + t.start() + try: + assert started.wait(60) + res = _post("/completion", payload) + if res.status_code != 200: + return res.status_code, res.text, [] + lines, alive = [], None + for raw in res.iter_lines(): + line = raw.decode("utf-8") + if line: + alive = t.is_alive() if alive is None else alive + lines.append(line) + assert alive, "the resident had finished before this request was told anything" + return 200, "", lines + finally: + t.join(120) + + +def _content(datas: list[str]) -> str: + out = "" + for d in datas: + if d == "[DONE]": + break + j = json.loads(d) + out += j.get("content") or "" + for ch in j.get("choices", []) or []: + out += (ch.get("delta") or {}).get("content") or "" + return out + + +def _final(datas: list[str]) -> dict: + """The last response object of a finished stream, past the [DONE] marker.""" + return json.loads([d for d in datas if d != "[DONE]"][-1]) + + +def _notices(comments: list[str]) -> list[str]: + return [c for c in comments if c in (": preempted", ": resumed")] + + +@pytest.mark.parametrize("path,payload", [ + ("/completion", _completion_payload(64)), + ("/v1/chat/completions", _chat_payload(64)), +]) +def test_every_park_in_a_stream_is_announced_paired_with_a_resume_and_changes_nothing(path, payload): + _start(n_ctx=512) + ref_comments, ref_datas = _stream_raw(path, payload) + assert _notices(ref_comments) == [] + assert _content(ref_datas) + server.stop() + + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + server.start() + comments, datas = _stream_raw(path, payload) + seq = _notices(comments) + assert len(seq) >= 12, comments + assert seq == [": preempted", ": resumed"] * (len(seq) // 2), seq + assert _content(datas) == _content(ref_datas) + + +def _prefill_payload(path: str, prompt: str, n_predict: int) -> dict: + """The same request on each streaming surface.""" + if path == "/completion": + return {"prompt": prompt, "n_predict": n_predict, "ignore_eos": True, + "temperature": 0.0, "seed": 42, "stream": True} + if path == "/v1/responses": + return {"model": "test", "input": prompt, "max_output_tokens": n_predict, + "temperature": 0.0, "stream": True} + return {"model": "test", "messages": [{"role": "user", "content": prompt}], + "max_tokens": n_predict, "temperature": 0.0, "stream": True} + + +@pytest.mark.parametrize("path", ["/completion", "/v1/chat/completions", "/v1/responses", "/v1/messages"]) +def test_a_park_during_prompt_processing_opens_the_stream_with_the_notice(path): + # a park before the first token is the case a client cannot tell from a stall, so the notice goes out with the response headers rather than waiting for a chunk that is not coming + server.server_slots = True + _start(n_ctx=2048, n_batch=256) + + def _resident(): + res = _post("/completion", _completion_payload(1900, _PROMPT_A)) + for _ in res.iter_lines(): + pass + + t = threading.Thread(target=_resident, daemon=True) + t.start() + + # the pool has to be nearly full before the second prompt starts, so that its prefill is what runs out of cells + # the resident grows by decoding: 1400 tokens took over 12 s on a loaded CI runner + deadline = time.time() + 90 + while t.is_alive() and time.time() < deadline: + slots = requests.get(f"http://{server.server_host}:{server.server_port}/slots").json() + if any(slot.get("n_prompt_tokens", 0) >= 1400 for slot in slots): + break + time.sleep(0.02) + else: + pytest.fail("the resident never grew into the pool") + + res = _post(path, _prefill_payload(path, " ".join([_PROMPT_B] * 31), 8)) + assert res.status_code == 200 + + t0 = time.time() + seen = [] + for raw in res.iter_lines(): + line = raw.decode("utf-8") + if line: + seen.append((time.time() - t0, line)) + t.join(120) + + text = _log() + assert "preempted:" in text, "nothing was parked while the prompt was being processed" + + comments = [(at, line) for at, line in seen if line.startswith(":")] + datas = [(at, line) for at, line in seen if line.startswith("data:")] + + assert comments and comments[0][1] == ": preempted", [line for _, line in seen[:4]] + assert datas, "the request never produced a chunk" + + # sent when the slot was parked, not batched with the chunk that came later + assert comments[0][0] + 0.05 < datas[0][0], [(round(at, 3), line[:24]) for at, line in seen[:4]] + assert any(line == ": resumed" for _, line in comments), [line for _, line in comments[:4]] + + +def test_a_stream_parked_before_its_first_token_starts_with_the_notice(): + # n_batch: the whole prompt in one batch, so the planner sees its size at once + _start(n_ctx=512, n_batch=512) + + status, _, lines = _behind_a_resident(_completion_payload(32, " ".join([_PROMPT_B] * 14))) + assert status == 200 + events = [l for l in lines if l in (": preempted", ": resumed") or l.startswith("data: ")] + assert events[:2] == [": preempted", ": resumed"], events[:3] + assert events[2].startswith("data: "), events[:3] + datas = [l[6:] for l in lines if l.startswith("data: ")] + assert _content(datas) + assert _final(datas)["tokens_predicted"] == 32 + + +def test_an_oversized_prompt_is_errored_instead_of_parked(): + # a slot just given a task has not passed the prompt checks yet, and a notice opens the stream, so parking it would turn a plain error response into 200 plus an in-stream one + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start(n_ctx=512, n_batch=512) + + status, body, _ = _behind_a_resident(_completion_payload(16, " ".join([_PROMPT_B] * 80))) + assert status != 200, body + assert not body.lstrip().startswith(":"), body + assert "error" in json.loads(body), body + + +def test_a_rotation_tells_both_streams_and_a_head_parked_past_the_budget_is_kept_alive(): + # --preempt-ram 2 MiB holds one parked state but not a resident's and the head's at once, so that rotation is refused and the head waits parked for longer than the 2 s keepalive + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "2" + _start(n_slots=3, n_ctx=2048, enable_ctx_shift=True) + + n_predict = 12000 + # the default parked keepalive is 2 s, which is also when a resident is rotated out for the head: + # a park that ends with that rotation could beat its own keepalive. Ask for a 1 s ping instead, so + # any park that outlasts one rotation window is still required to say so + results = _stream_all(n_predict, (_PROMPT_A, _PROMPT_B, _PROMPT_C), sse_ping_interval=1) + n_parked = n_keepalive = 0 + for comments, datas in results: + assert _final(datas)["tokens_predicted"] == n_predict + seq = _notices(comments) + assert seq == [": preempted", ": resumed"] * (len(seq) // 2), seq + n_parked += len(seq) // 2 + n_keepalive += comments.count(": preempt-keepalive") + assert n_parked >= 2, [r[0] for r in results] + assert n_keepalive >= 1, "a parked stream was left silent past its keepalive interval" + + text = _log() + assert "rotated out after" in text + assert "no rotation: --preempt-ram 2 MiB" in text + assert "resumed after" in text + assert "Context size has been exceeded" not in text + + +def test_every_notice_of_a_multi_prompt_stream_names_the_prompt_it_is_about(): + # one request, two prompts: a client reading the shared stream can only tell the notices apart by their index, so index 0 has to be spelled out like any other + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start(n_ctx=512) + + comments, datas = _stream_raw("/completion", _completion_payload(32) | {"prompt": [_PROMPT_A, _PROMPT_B]}) + notices = [c for c in comments if c.startswith(": preempted") or c.startswith(": resumed")] + assert notices, comments + assert all(re.fullmatch(r": (preempted|resumed) [01]", c) for c in notices), notices + for index in (0, 1): + assert f": preempted {index}" in notices, notices + assert f": resumed {index}" in notices, notices + + +def test_an_oversized_sibling_prompt_is_errored_before_a_valid_one_is_parked(): + # a request can carry several prompts; a valid one can be parked and its notice opens the stream, so the sibling that does not fit has to be found before any of them is queued + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" + _start(n_ctx=256, n_slots=3, n_batch=512) + + status, body, _ = _behind_a_resident(_completion_payload(8) | {"prompt": [[1] * 120, [1] * 300]}) + assert status == 400, (status, body) + assert not body.lstrip().startswith(":"), body + assert "error" in json.loads(body), body + From eb1e4fe6c34181ed689296e196f4e92529e9ff91 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 10 Oct 2026 21:53:59 -0700 Subject: [PATCH 002/109] server: preemption reservation for an aged head, rotation of any resident, deficit-aware victim choice A parked head that has waited PREEMPT_ROTATE_US is owed the cells: a prompt that has never been resident waits until it is back, so a stream of short requests can no longer overtake it for good. Rotation now considers every generating resident, the longest included, and a held prompt that sits on cells, choosing the fewest cells that make room; a resumed slot is not rotated again before it has decoded 32 tokens, or one token and 2 s. Ordinary victim choice parks the single eligible slot that covers the shortfall where there is one, and LLAMA_SERVER_PREEMPT_POLICY=largest can now pick the largest slot. /props reports a preempt block (enabled, ram_mib, async, notices, recurrent, granularity). A pinned park buffer grows by half again instead of to the exact size, within --preempt-ram, and update_preemption() returns at once with --preempt-ram 0 and nothing parked. --- tools/server/server-context.cpp | 330 ++++++++++++++++++++++++++++---- tools/server/server-context.h | 3 + 2 files changed, 296 insertions(+), 37 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index b1e2e6dcc500..e3c6928f8099 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -156,8 +156,9 @@ static std::string preempt_notice_comment(const server_task_result_preempt_notic } constexpr int32_t PREEMPT_N_FAIL_MAX = 8; // failed restores before the slot is given up on constexpr int64_t PREEMPT_FAIL_US = 60ll * 1000 * 1000; // ... and only after this long parked -constexpr int64_t PREEMPT_ROTATE_US = 2ll * 1000 * 1000; // a resident cycling through context shifts gives way to a parked head that has waited this long +constexpr int64_t PREEMPT_ROTATE_US = 2ll * 1000 * 1000; // a parked head that has waited this long is owed the cells: a resident is rotated out for it and new prompts wait constexpr int64_t PREEMPT_ROTATE_RECOMPUTE_US = 30ll * 1000 * 1000; // ... and after this long it gives way even where that costs the resident a re-prefill +constexpr int32_t PREEMPT_ROTATE_MIN_GEN = 32; // tokens a resumed slot decodes before it can be rotated out again, or one token and PREEMPT_ROTATE_US // [TAG_PREEMPT_ASYNC] an asynchronous park only releases its cells when its copy lands, so it must fire this many decode steps before the pool would run out constexpr int32_t PREEMPT_N_ASYNC_STEPS = 8; @@ -476,6 +477,61 @@ struct server_slot { int64_t t_preempt_us = 0; // when it was parked int64_t t_preempt_copy_us = 0; // [TAG_PREEMPT_ASYNC] when the current copy was issued bool preempt_rotation_refused = false; // this park has logged a rotation refused for budget + bool preempt_hold_logged = false; // this request has logged waiting for a parked head + bool preempt_grow = false; // the next park may reserve its pinned buffer ahead of the sequence + + // [TAG_PREEMPT] service since the last resume, so that two slots rotating for each other both make progress + int64_t t_preempt_resume_us = 0; + int32_t n_gen_resume = 0; + + void preempt_mark_resumed() { + t_preempt_resume_us = ggml_time_us(); + n_gen_resume = (int32_t) stats.n_gen; + } + + // [TAG_PREEMPT_ASYNC] grow a pinned buffer by half again rather than to the exact size, so a sequence parked again a little longer is not unpinned and pinned anew + static size_t preempt_grown_capacity(size_t held, size_t need) { + if (need <= held || held == 0) { + return need; + } + + const size_t step = 1u << 20; + + return ((std::max(need, held + held / 2) + step - 1) / step) * step; + } + + bool preempt_buf_reserve(llama_state_seq_copy * cpy, size_t size, bool grow) const { + const size_t held = llama_state_seq_copy_buf_capacity(cpy); + const size_t cap = grow ? preempt_grown_capacity(held, size) : size; + + if (llama_state_seq_copy_buf_resize(cpy, cap) == nullptr || llama_state_seq_copy_buf_resize(cpy, size) == nullptr) { + return false; + } + + if (llama_state_seq_copy_buf_capacity(cpy) != held) { + SLT_INF(*this, "pinned park buffer %s: %.3f MiB for a %.3f MiB state\n", held == 0 ? "allocated" : "grown", + llama_state_seq_copy_buf_capacity(cpy) / (1024.0 * 1024.0), size / (1024.0 * 1024.0)); + } + + return true; + } + + size_t preempt_state_grown() const { + if (!preempt_is_async()) { + return preempt_state_required(); + } + + const size_t size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); + const size_t size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + + size_t res = preempt_grown_capacity(llama_state_seq_copy_buf_capacity(preempt_cpy_tgt.get()), size_tgt); + + if (size_dft > 0 && preempt_cpy_dft) { + res += preempt_grown_capacity(llama_state_seq_copy_buf_capacity(preempt_cpy_dft.get()), size_dft); + } + + return res; + } // [TAG_PREEMPT] a park with no room left under --preempt-ram: the cells are dropped instead of copied out, and the resume re-prefills the tokens bool preempt_recompute = false; // parked by dropping its cells @@ -527,6 +583,8 @@ struct server_slot { state = state_before_preempt; + preempt_mark_resumed(); + if (state == SLOT_STATE_GENERATING && can_speculate()) { common_speculative_begin(spec, id, prompt.tokens.get_text_tokens()); } @@ -602,6 +660,8 @@ struct server_slot { if (preempt_tokens.empty()) { state = state_before_preempt; // its prompt had not been processed yet, so it is processed again from the start + preempt_mark_resumed(); + // the park dropped the cells the prompt step had already filled, and the restart does not pass through SLOT_STATE_STARTED, where these two are set: left alone they would count the dropped prefix a second time stats.n_prompt_cached = 0; stats.n_prompt_processed = 0; @@ -623,6 +683,8 @@ struct server_slot { i_batch = -1; state = SLOT_STATE_GENERATING; + preempt_mark_resumed(); // the re-prefill is not service: it only put back what the park dropped + if (can_speculate()) { common_speculative_begin(spec, id, prompt.tokens.get_text_tokens()); } @@ -640,9 +702,9 @@ struct server_slot { const size_t size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; if (preempt_is_async()) { - if (!llama_state_seq_copy_buf_resize(preempt_cpy_tgt.get(), size_tgt) || + if (!preempt_buf_reserve(preempt_cpy_tgt.get(), size_tgt, preempt_grow) || (size_dft > 0 && (!preempt_cpy_dft || - !llama_state_seq_copy_buf_resize(preempt_cpy_dft.get(), size_dft)))) { + !preempt_buf_reserve(preempt_cpy_dft.get(), size_dft, preempt_grow)))) { SLT_ERR(*this, "failed to allocate %.3f MiB of pinned host memory for the preemption state\n", (size_tgt + size_dft) / (1024.0 * 1024.0)); preempt_state_free(); @@ -867,6 +929,9 @@ struct server_slot { n_preempt_fail = 0; n_ctx_shift = 0; t_preempt_us = 0; + t_preempt_resume_us = 0; + n_gen_resume = 0; + preempt_hold_logged = false; llama_set_sampler(ctx_tgt, id, nullptr); @@ -4103,6 +4168,11 @@ struct server_context_impl { case SLOT_STATE_STARTED: case SLOT_STATE_PROCESSING_PROMPT: { + // [TAG_PREEMPT] a prompt held back for a parked head takes no step until the head is back + if (preempt_held(slot)) { + break; + } + const int32_t n_have = preempt_n_retained(slot); const int32_t n_mtmd = preempt_n_mtmd_pending(slot, n_have); @@ -4169,8 +4239,8 @@ struct server_context_impl { slot.mem.seq_rm(slot.id, slot.prompt.tokens.pos_next(), -1); } - // `recompute` asks for a fallback: with no victim the host budget can hold, the same policy picks again and the park drops the cells instead of copying them - server_slot * preempt_pick_victim(bool * recompute = nullptr) { + // `recompute` asks for a fallback: with no victim the host budget can hold, the same policy picks again and the park drops the cells instead of copying them. `n_deficit` is the room the caller is short of: one victim that covers it alone is parked rather than several smaller ones. + server_slot * preempt_pick_victim(bool * recompute = nullptr, int32_t n_deficit = 0) { server_slot * leader = nullptr; int32_t n_running = 0; @@ -4193,10 +4263,18 @@ struct server_context_impl { return nullptr; } - server_slot * victim = preempt_pick_victim_pass(leader, false); + // the test knob asking for the largest has to be able to pick it, so it exempts nobody + const server_slot * exempt = preempt_test_policy == "largest" ? nullptr : leader; + + // the deficit is only weighed under the default policy: the others exist to pin down the order + if (preempt_test_policy != "smallest") { + n_deficit = 0; + } + + server_slot * victim = preempt_pick_victim_pass(exempt, false, n_deficit); if (!victim && recompute) { - victim = preempt_pick_victim_pass(leader, true); + victim = preempt_pick_victim_pass(exempt, true, n_deficit); *recompute = victim != nullptr; } @@ -4204,36 +4282,71 @@ struct server_context_impl { return victim; } - server_slot * preempt_pick_victim_pass(const server_slot * leader, bool recompute) { - server_slot * victim = nullptr; + // [TAG_PREEMPT] the room a park gives back: the slot's cells and the step it would have taken next + int32_t preempt_n_freed(const server_slot & slot) const { + const int32_t n_cur = slot.prompt.n_tokens(); - for (auto & slot : slots) { - // before the batch is built every slot is at a token boundary; one holding no cells is still worth parking - if (slot.state != SLOT_STATE_GENERATING && - slot.state != SLOT_STATE_PROCESSING_PROMPT && - slot.state != SLOT_STATE_STARTED) { - continue; - } + int32_t res = preempt_n_cells(n_cur); - if (&slot == leader) { - continue; - } + if (slot.state == SLOT_STATE_GENERATING) { + res += preempt_n_cells_step(n_cur, 1 + preempt_n_spec(slot)); + } else if (!preempt_held(slot)) { + const int32_t n_have = preempt_n_retained(slot); + const int32_t n_mtmd = preempt_n_mtmd_pending(slot, n_have); + const int32_t n_left = slot.preempt_n_input() - n_have; - if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { - continue; // n_cmpl > 1 slots share one sequence, out of scope here - } + res += preempt_n_cells_step(n_have, n_mtmd > 0 ? n_mtmd : std::max(1, std::min((int32_t) llama_n_batch(ctx_tgt), n_left))); + } - // a started slot the STARTED block is about to reject gets its error on its own pass: a park notice would open the stream and turn that 4xx into 200 plus an in-stream error - if (slot.state == SLOT_STATE_STARTED) { - std::string msg; - error_type type = ERROR_TYPE_SERVER; + return res; + } - if (slot_prompt_rejected(slot, msg, type)) { - continue; - } + bool preempt_victim_eligible(server_slot & slot, const server_slot * exempt, bool recompute) { + // before the batch is built every slot is at a token boundary; one holding no cells is still worth parking + if (slot.state != SLOT_STATE_GENERATING && + slot.state != SLOT_STATE_PROCESSING_PROMPT && + slot.state != SLOT_STATE_STARTED) { + return false; + } + + if (&slot == exempt) { + return false; + } + + // a held prompt with no cells takes no step either, so parking it gives nothing back + if (preempt_held(slot) && slot.prompt.n_tokens() == 0) { + return false; + } + + if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { + return false; // n_cmpl > 1 slots share one sequence, out of scope here + } + + // a started slot the STARTED block is about to reject gets its error on its own pass: a park notice would open the stream and turn that 4xx into 200 plus an in-stream error + if (slot.state == SLOT_STATE_STARTED) { + std::string msg; + error_type type = ERROR_TYPE_SERVER; + + if (slot_prompt_rejected(slot, msg, type)) { + return false; } + } + + if (!recompute && !preempt_fits_budget(slot)) { + return false; + } + + return true; + } + + server_slot * preempt_pick_victim_pass(const server_slot * exempt, bool recompute, int32_t n_deficit = 0) { + server_slot * victim = nullptr; + + // the single victim that covers the deficit with the least, among the unstarved first + server_slot * cover[2] = { nullptr, nullptr }; - if (!recompute && !preempt_fits_budget(slot)) { + for (auto & slot : slots) { + if (!preempt_victim_eligible(slot, exempt, recompute)) { continue; } @@ -4245,6 +4358,27 @@ struct server_context_impl { (starved_cur == starved && preempt_better_victim(slot, *victim))) { victim = &slot; } + + if (n_deficit > 0) { + const int32_t n_freed = preempt_n_freed(slot); + + server_slot *& best = cover[starved ? 1 : 0]; + + if (n_freed >= n_deficit && (!best || n_freed < preempt_n_freed(*best))) { + best = &slot; + } + } + } + + // a starved slot covering the deficit is only taken where the order above would take a starved one anyway + const bool victim_starved = victim && victim->n_preempt >= PREEMPT_N_STARVED; + + if (cover[0]) { + return cover[0]; + } + + if (cover[1] && victim_starved) { + return cover[1]; } return victim; @@ -4266,10 +4400,93 @@ struct server_context_impl { return a.prompt.n_tokens() < b.prompt.n_tokens(); } + // [TAG_PREEMPT] the oldest parked slot once it has waited PREEMPT_ROTATE_US: from then on no prompt that has never been resident may take the cells it needs + const server_slot * preempt_reserved_for = nullptr; + + void preempt_update_reservation() { + const server_slot * head = nullptr; + + for (const auto & slot : slots) { + if (slot.state == SLOT_STATE_PREEMPTED && (!head || slot.t_preempt_us < head->t_preempt_us)) { + head = &slot; + } + } + + preempt_reserved_for = head && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_US ? head : nullptr; + } + + // [TAG_PREEMPT] a prompt waits while the reservation stands: a request that has never been resident, either not started or started after the head was parked. A re-prefill and a resumed prompt are parked slots coming back, and an empty or rejected prompt takes no cells, so those go on. + bool preempt_held(const server_slot & slot) const { + if (!preempt_reserved_for || &slot == preempt_reserved_for || !slot.task) { + return false; + } + + if (slot.n_preempt > 0 || slot.preempt_reprefill) { + return false; + } + + if (slot.state == SLOT_STATE_STARTED) { + if (slot.preempt_input().empty()) { + return false; + } + + std::string msg; + error_type type = ERROR_TYPE_SERVER; + + return !slot_prompt_rejected(slot, msg, type); + } + + if (slot.state == SLOT_STATE_PROCESSING_PROMPT) { + return slot.stats.t_start > preempt_reserved_for->t_preempt_us; + } + + return false; + } + + void preempt_log_held(server_slot & slot) { + if (slot.preempt_hold_logged) { + return; + } + + slot.preempt_hold_logged = true; + + SLT_INF(slot, "prompt held: slot %d has been parked %.1f s and is owed the cells first\n", + preempt_reserved_for->id, (ggml_time_us() - preempt_reserved_for->t_preempt_us) / 1e6); + } + + // [TAG_PREEMPT] a slot back from a park is not rotated out again before it has decoded PREEMPT_ROTATE_MIN_GEN tokens, or one token and PREEMPT_ROTATE_US, so two slots cannot hand the cells back and forth without progress + bool preempt_served(const server_slot & slot) const { + if (slot.n_preempt == 0) { + return true; + } + + const int32_t n_gen = (int32_t) slot.stats.n_gen - slot.n_gen_resume; + + return n_gen >= PREEMPT_ROTATE_MIN_GEN || + (n_gen > 0 && ggml_time_us() - slot.t_preempt_resume_us >= PREEMPT_ROTATE_US); + } + + bool preempt_any_out() const { + for (const auto & slot : slots) { + if (slot.preempt_is_out()) { + return true; + } + } + + return false; + } + // [TAG_PREEMPT] park a slot: a synchronous park is finished here, an asynchronous one only issued, and update_preempt_copies() counts it when its copy lands. The notice goes with the save, not the cell release: preempt_save() has already detached the slot, so a release-time notice would leave the copy's silence unexplained. bool preempt_park(server_slot & slot, int64_t t_start, bool recompute = false) { slot.t_preempt_copy_us = t_start; + // [TAG_PREEMPT_ASYNC] reserve ahead only where the budget holds the larger capacity, which is what preempt_state_size() then charges + if (!recompute && slot.preempt_is_async()) { + const size_t held = slot.preempt_state_size(); + + slot.preempt_grow = preempt_ram_used() - held + slot.preempt_state_grown() <= preempt_ram_budget(); + } + // [TAG_PREEMPT] a budget check grants permission to allocate, not a successful allocation: preempt_save() unwinds and waits for whatever it issued, so the same victim can still be parked by dropping its cells if (!recompute && !slot.preempt_save()) { SLT_WRN(slot, "%s", "the park could not take the host memory the budget allowed, so it drops its cells instead and the resume re-prefills its tokens\n"); @@ -4419,6 +4636,8 @@ struct server_context_impl { } void update_preemption() { + preempt_reserved_for = nullptr; + if (!params_base.kv_unified || slots.size() < 2) { return; // with a cache per slot, no slot can take another one's cells } @@ -4427,6 +4646,11 @@ struct server_context_impl { return; // no cache at all (an embedding model): nothing to run out of, nothing to park } + // [TAG_PREEMPT] --preempt-ram 0 parks nothing, so with nothing out there is nothing to scan + if (params_base.preempt_ram_mib == 0 && !preempt_any_out()) { + return; + } + update_preempt_copies(); if (params_base.preempt_ram_mib == 0 || preempt_recurrent) { @@ -4438,6 +4662,8 @@ struct server_context_impl { const bool head_of_line = preempt_resume_head; for (;;) { + preempt_update_reservation(); + std::vector parked; for (auto & slot : slots) { @@ -4500,7 +4726,7 @@ struct server_context_impl { } } - // nothing fits: a resident cycling through context shifts holds the room for as long as it generates, so it is parked once the head has waited its turn + // nothing fits: a resident holds the room for as long as it generates, and one cycling through context shifts for good, so one is parked once the head has waited its turn if (!best) { server_slot * head = parked.front(); @@ -4516,7 +4742,10 @@ struct server_context_impl { auto rotate_pick = [&](bool with_recompute) { for (auto & slot : slots) { - if (slot.state != SLOT_STATE_GENERATING || slot.n_ctx_shift == 0) { + // [TAG_PREEMPT] any resident that has had its service since its last resume, the longest included, and a held prompt that sits on cells + const bool held = preempt_held(slot) && slot.prompt.n_tokens() > 0; + + if (!held && (slot.state != SLOT_STATE_GENERATING || !preempt_served(slot))) { continue; } @@ -4530,12 +4759,15 @@ struct server_context_impl { continue; } - const bool enough = occupied - preempt_n_cells(slot.prompt.n_tokens()) + need <= n_cells; + // the fewest cells that make room, else the most + const int32_t n_freed = preempt_n_freed(slot); + const int32_t n_pick = pick ? preempt_n_freed(*pick) : 0; + + const bool enough = occupied - n_freed + need <= n_cells; if (!pick || (enough && !pick_enough) || - (enough == pick_enough && (enough ? slot.prompt.n_tokens() < pick->prompt.n_tokens() - : slot.prompt.n_tokens() > pick->prompt.n_tokens()))) { + (enough == pick_enough && (enough ? n_freed < n_pick : n_freed > n_pick))) { pick = &slot; pick_enough = enough; } @@ -4648,6 +4880,8 @@ struct server_context_impl { } } + preempt_update_reservation(); + if (preempt_test_every > 0) { for (auto & slot : slots) { if (slot.state != SLOT_STATE_GENERATING || @@ -4693,7 +4927,7 @@ struct server_context_impl { bool recompute = false; - server_slot * victim = preempt_pick_victim(&recompute); + server_slot * victim = preempt_pick_victim(&recompute, n_used + preempt_n_margin() - n_cells); if (!victim) { SRV_DBG("the kv pool needs %d of %d cells and nothing can be preempted (parked %.1f MiB of the %d MiB --preempt-ram budget)\n", @@ -5190,6 +5424,12 @@ struct server_context_impl { return; } + // [TAG_PREEMPT] a parked head that has waited its turn is not overtaken by a prompt that has never been resident + if (preempt_held(slot)) { + preempt_log_held(slot); + return; + } + // this slot still has a prompt to be processed if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) { const auto & input_tokens = slot.preempt_input(); @@ -5854,6 +6094,19 @@ struct server_context_impl { slots.size() >= 2 && llama_get_memory(ctx_tgt) && !preempt_state_relocates(); } + // [TAG_PREEMPT] read by clients deciding whether to rely on parking; notices is the version of the in-stream notice protocol + json preempt_props() const { + return json { + { "enabled", params_base.kv_unified && slots.size() >= 2 && params_base.preempt_ram_mib != 0 && + !preempt_recurrent && ctx_tgt && llama_get_memory(ctx_tgt) }, + { "ram_mib", params_base.preempt_ram_mib }, + { "async", preempt_async_ok }, + { "notices", 2 }, + { "recurrent", preempt_recurrent }, + { "granularity", preempt_alloc_granularity }, + }; + } + bool preempt_last_resort_possible() const { return params_base.kv_unified && params_base.preempt_ram_mib != 0 && !preempt_recurrent && slots.size() >= 2 && llama_get_memory(ctx_tgt); } @@ -5902,7 +6155,7 @@ struct server_context_impl { bool recompute = false; - server_slot * victim = preempt_pick_victim(&recompute); + server_slot * victim = preempt_pick_victim(&recompute, n_used + preempt_n_margin() - n_cells); if (!victim) { break; @@ -6587,6 +6840,7 @@ server_context_meta server_context::get_meta() const { /* model_n_params */ llama_model_n_params(impl->model_tgt), /* model_size */ llama_model_size(impl->model_tgt), /* model_ftype */ ftype_name, + /* preempt */ impl->preempt_props(), }; } @@ -7039,6 +7293,8 @@ static json get_res_props(const server_context_meta & meta, const common_params { "endpoint_metrics", params.endpoint_metrics }, // [TAG_EXACT_CONCURRENCY] a client that asked for the mode reads here whether this process runs it: a build that ignores the variable starts all the same { "exact_concurrency", common_exact_concurrency() }, + // [TAG_PREEMPT] whether this process parks sequences under pressure and how + { "preempt", meta.preempt }, { "ui", params.ui }, { "ui_settings", meta.json_ui_settings }, { "chat_template", tmpl_default }, diff --git a/tools/server/server-context.h b/tools/server/server-context.h index ed23f7d4e6ce..340b336b520f 100644 --- a/tools/server/server-context.h +++ b/tools/server/server-context.h @@ -53,6 +53,9 @@ struct server_context_meta { uint64_t model_n_params; uint64_t model_size; std::string model_ftype; + + // [TAG_PREEMPT] the /props "preempt" block + json preempt = json::object(); }; enum server_state { From f9e79f8212857992b328b5cf5ff4db9422a11494 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 10 Oct 2026 21:53:59 -0700 Subject: [PATCH 003/109] server: tests for the preemption reservation, rotation, victim choice, /props and buffer growth --- tools/server/tests/unit/test_preempt.py | 223 ++++++++++++++++++++++++ 1 file changed, 223 insertions(+) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index c47cda62b17f..226ea258c27c 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -18,6 +18,8 @@ _ASYNC_BANNER = "parking and resuming asynchronously" +_scratch = [] # files a test wrote, removed after it + _PROMPT_A = "Once upon a time there was a brave knight who" _PROMPT_B = "The quick brown fox jumps over the lazy dog and" _PROMPT_C = "In a small village by the sea there lived a fisherman who" @@ -38,6 +40,10 @@ def create_server(): fd, server.log_path = tempfile.mkstemp(suffix=".log") os.close(fd) yield + if _scratch: + server.stop() + while _scratch: + os.remove(_scratch.pop()) for name in ("LLAMA_SERVER_PREEMPT_EVERY", "LLAMA_SERVER_PREEMPT_GRANULARITY", "LLAMA_SERVER_PREEMPT_PLANNER", "LLAMA_ARG_PREEMPT_RAM", "LLAMA_ARG_PREEMPT_ASYNC", "LLAMA_SERVER_PREEMPT_FAIL_SAVE", "LLAMA_ARG_SPEC_DRAFT_P_MIN", "LLAMA_ARG_LOG_VERBOSITY", @@ -1092,3 +1098,220 @@ def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): assert timings["prompt_n"] == n_prompt, timings assert timings["cache_n"] == 0, timings assert timings["predicted_n"] == n_predict, timings + + +def _slot_view(slot_id: int) -> dict: + return next(s for s in server.make_request("GET", "/slots").body if s["id"] == slot_id) + + +def _n_decoded(slot: dict) -> int: + return slot.get("next_token", [{}])[0].get("n_decoded", 0) if slot.get("is_processing") else 0 + + +def _raw_completion(n_predict: int, prompt, id_slot: int = -1, timeout: float = DEFAULT_REQUEST_TIMEOUT): + return server.make_request("POST", "/completion", data={ + "n_predict": n_predict, "prompt": prompt, "id_slot": id_slot, "cache_prompt": False, + "ignore_eos": True, "temperature": 0.0, "seed": 42, + }, timeout=timeout) + + +def _serve_with_training_context(n_ctx_train: int): + """Serve a copy of the model that claims a longer training context, which caps the slot context: a generation that outlasts the 2 s a parked head waits needs more than 2048 tokens.""" + _start(n_ctx=256) + path = server.make_request("GET", "/props").body["model_path"] + server.stop() + with open(path, "rb") as f: + data = bytearray(f.read()) + key = b"llama.context_length" + at = data.find(key) + len(key) + assert at > len(key) and struct.unpack_from(" 0 for s in slots if s["id"] < 3): + break + time.sleep(0.002) + last = pool.submit(_raw_completion, 8, leader, 3) + results = [r.result() for r in residents] + [last.result()] + + for res, n_predict in zip(results, (300, 300, 300, 8)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + + text = _log() + assert "Context size has been exceeded" not in text + first_resume = text.find("resumed after") + assert first_resume > 0, "nothing was parked" + parks = [int(n) for n in re.findall(r"preempted: (\d+) cells", text[:first_resume])] + assert len(parks) == 1, f"parked {parks} where one resident covered the shortfall" + assert parks[0] >= 1400, parks + + +@pytest.mark.parametrize("ram", ["8192", "0", "unset"]) +def test_props_reports_the_preemption_setup(ram): + # a client deciding whether to rely on parking reads this instead of guessing from the version + if ram == "unset": + os.environ.pop("LLAMA_ARG_PREEMPT_RAM", None) + else: + os.environ["LLAMA_ARG_PREEMPT_RAM"] = ram + _start(n_ctx=256) + + res = server.make_request("GET", "/props") + assert res.status_code == 200 + preempt = res.body["preempt"] + assert sorted(preempt) == ["async", "enabled", "granularity", "notices", "ram_mib", "recurrent"] + assert preempt["enabled"] is (ram == "8192") + assert preempt["ram_mib"] == (8192 if ram == "8192" else 0) + assert preempt["async"] is False or ram == "8192" + assert isinstance(preempt["async"], bool) + assert preempt["notices"] == 2 + assert preempt["recurrent"] is False + assert preempt["granularity"] == 1 + + +def test_props_reports_preemption_off_without_a_unified_cache(): + _start(n_ctx=256, kv_unified=False) + preempt = server.make_request("GET", "/props").body["preempt"] + assert preempt["enabled"] is False + assert preempt["ram_mib"] == 8192 + assert preempt["async"] is False + + +def test_props_reports_the_planning_granularity(): + os.environ["LLAMA_SERVER_PREEMPT_GRANULARITY"] = "64" + _start(n_ctx=1024) + preempt = server.make_request("GET", "/props").body["preempt"] + assert preempt["enabled"] is True + assert preempt["granularity"] == 64 + + +def test_a_growing_sequence_keeps_its_pinned_buffer_across_parks(): + # the pinned buffer was sized to the exact state, so every park of a sequence that had grown since the last one unpinned it and pinned a new one, which costs about as long as the copy itself + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start_async(n_ctx=2048) + + res = _complete(400, _prompt_of(1000, _PROMPT_A)) + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == 400 + + text = _log() + parks = text.count("park completed after") + sizes = re.findall(r"pinned park buffer (?:allocated|grown)", text) + assert parks >= 40, parks + assert 1 <= len(sizes) <= 4, f"{len(sizes)} pinned allocations for {parks} parks" From 24570211c1afbef2ede810a99362d1560544f0a6 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 11 Oct 2026 00:41:25 -0700 Subject: [PATCH 004/109] server: grow a pinned park buffer only with room for another state left in --preempt-ram Rounded to 1 MiB and taken whenever it fitted, the reserved slack filled a small budget: under --preempt-ram 2 MiB a 0.5 MiB state held 1 MiB, and the rotation that needs the head's and a resident's states at once was refused. Round to 64 KiB, and grow only where the budget still holds a second state of the grown size. --- tools/server/server-context.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index e3c6928f8099..31f65c30acd8 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -495,7 +495,7 @@ struct server_slot { return need; } - const size_t step = 1u << 20; + const size_t step = 64u << 10; return ((std::max(need, held + held / 2) + step - 1) / step) * step; } @@ -4480,11 +4480,12 @@ struct server_context_impl { bool preempt_park(server_slot & slot, int64_t t_start, bool recompute = false) { slot.t_preempt_copy_us = t_start; - // [TAG_PREEMPT_ASYNC] reserve ahead only where the budget holds the larger capacity, which is what preempt_state_size() then charges + // [TAG_PREEMPT_ASYNC] reserve ahead only where the budget still holds another state of that size afterwards: preempt_state_size() charges the slack, which must not crowd out the next park if (!recompute && slot.preempt_is_async()) { - const size_t held = slot.preempt_state_size(); + const size_t held = slot.preempt_state_size(); + const size_t grown = slot.preempt_state_grown(); - slot.preempt_grow = preempt_ram_used() - held + slot.preempt_state_grown() <= preempt_ram_budget(); + slot.preempt_grow = preempt_ram_used() - held + 2 * grown <= preempt_ram_budget(); } // [TAG_PREEMPT] a budget check grants permission to allocate, not a successful allocation: preempt_save() unwinds and waits for whatever it issued, so the same victim can still be parked by dropping its cells From 6429b053f2c8162f372d3da7b59f2555378c4bdd Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 11 Oct 2026 00:41:25 -0700 Subject: [PATCH 005/109] server: keep the reservation test off a CUDA decode hang past position 2048 --- tools/server/tests/unit/test_preempt.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 226ea258c27c..46a641174cda 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -19,6 +19,7 @@ _ASYNC_BANNER = "parking and resuming asynchronously" _scratch = [] # files a test wrote, removed after it +_cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES") # put back after a test that hides the GPUs _PROMPT_A = "Once upon a time there was a brave knight who" _PROMPT_B = "The quick brown fox jumps over the lazy dog and" @@ -40,6 +41,10 @@ def create_server(): fd, server.log_path = tempfile.mkstemp(suffix=".log") os.close(fd) yield + if _cuda_devices is None: + os.environ.pop("CUDA_VISIBLE_DEVICES", None) + else: + os.environ["CUDA_VISIBLE_DEVICES"] = _cuda_devices if _scratch: server.stop() while _scratch: @@ -1135,16 +1140,18 @@ def _serve_with_training_context(n_ctx_train: int): def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): - # a parked head of 6900 cells needs nearly the whole pool, and short requests that fit kept arriving and finishing, two queued per slot, so a resident was always there and the head waited for as long as the stream lasted. Once the head has waited its turn, a prompt that has never been resident waits for it. + # a parked head of 7300 cells needs nearly the whole pool, and short requests that fit kept arriving and finishing, two queued per slot, so a resident was always there and the head waited for as long as the stream lasted. Once the head has waited its turn, a prompt that has never been resident waits for it. # 1 MiB holds no short request's state, so none is rotated out for the head before PREEMPT_ROTATE_RECOMPUTE_US: what brings the head back early is the reservation alone os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" # parks the head while it generates; a short request never gets that far os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "48" + # the scheduling under test is host code; on CUDA a prompt chunk across position 2048 of this context-extended model hangs llama_decode, the pin's base included, so the server runs on the CPU + os.environ["CUDA_VISIBLE_DEVICES"] = "" _serve_with_training_context(8192) - _start(n_ctx=8192, n_slots=4, n_batch=2048) + _start(n_ctx=8192, n_slots=4, n_batch=1024) short_prompt = _prompt_of(1700, _PROMPT_B) - head_prompt = _prompt_of(6800, _PROMPT_A) + head_prompt = _prompt_of(7200, _PROMPT_A) n_short, n_head = 32, 100 t_stream_max = 40.0 From c69f0e64007c6fc08db85b55626c76072978c1ff Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 12 Oct 2026 22:15:41 -0700 Subject: [PATCH 006/109] server: keep the decision start in scope for the prefix reuse bound on b11577 The decision size check moved into slot_prompt_rejected, so the n_past clamp upstream added beside it needs its own copy of the first decision position. --- tools/server/server-context.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 31f65c30acd8..7d51aa9bf421 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -5489,6 +5489,9 @@ struct server_context_impl { } if (slot.can_split()) { + // the size of a decision is checked in slot_prompt_rejected, its first position bounds the reuse below + const int32_t n_decision_first = slot.task->type == SERVER_TASK_TYPE_DECISION ? slot.task->decision.pos_first() : -1; + const bool is_stateless_task = slot.task->type == SERVER_TASK_TYPE_EMBEDDING || slot.task->type == SERVER_TASK_TYPE_RERANK; if (slot.task->params.cache_prompt && !is_stateless_task) { From 83b6ca0d47965f33d078df40e2d18f3322aee949 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 00:34:22 -0700 Subject: [PATCH 007/109] rpc: refuse a paged FLASH_ATTN_EXT at the server supports_op keeps the scheduler from sending a page table over RPC, but the server rebuilds whatever graph a client submits and computes it without asking, so a paged node would reach a backend that trusts its page ids and counts. graph_compute now rejects a FLASH_ATTN_EXT node with src[5] and drops that connection. test-rpc-paged-fa sends the graph from its own client against a CPU server: on the previous commit the paged graph computes, here it is refused and the server keeps serving. --- ggml/src/ggml-rpc/ggml-rpc.cpp | 5 ++ tests/CMakeLists.txt | 5 ++ tests/test-rpc-paged-fa.cpp | 139 +++++++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+) create mode 100644 tests/test-rpc-paged-fa.cpp diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index da4bb1e593f2..3864bc736ce1 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -2146,6 +2146,11 @@ bool rpc_server::graph_compute(const std::vector & input) { LOG_ERROR("[%s] failed to create graph node %d (id=%" PRId64 ")\n", __func__, i, id); return false; } + // [TAG_EXACT_CONCURRENCY] supports_op never offers a page table to RPC, so a graph carrying one is not from a ggml scheduler, and the backend would trust its page ids and counts + if (graph->nodes[i] != nullptr && graph->nodes[i]->op == GGML_OP_FLASH_ATTN_EXT && graph->nodes[i]->src[5] != nullptr) { + LOG_ERROR("[%s] graph node %d (id=%" PRId64 ") is a paged FLASH_ATTN_EXT, which RPC does not support\n", __func__, i, id); + return false; + } if (graph->nodes[i] != nullptr) { LOG_DBG3("[%s] node %u: id=%" PRId64 ", op=%s, name=%s\n", __func__, i, id, ggml_op_name(graph->nodes[i]->op), graph->nodes[i]->name); const size_t hash_pos = ggml_hash_insert(&graph->visited_hash_set, graph->nodes[i]); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 75f6bdf606b4..5a3e2a58722e 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -310,6 +310,11 @@ endif() llama_build(test-backend-ops.cpp LINK ggml) +# [TAG_EXACT_CONCURRENCY] the RPC server refuses a paged FLASH_ATTN_EXT; the test forks its own server, so POSIX only +if (GGML_RPC AND NOT GGML_BACKEND_DL AND NOT WIN32) + llama_build_and_test(test-rpc-paged-fa.cpp LINK ggml) +endif() + llama_build_and_test(test-tiled-mulmat.cpp LINK ggml) llama_build_and_test(test-model-load-cancel.cpp LABEL "model") llama_build_and_test(test-autorelease.cpp LABEL "model") diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp new file mode 100644 index 000000000000..a2a6ccf0ed3d --- /dev/null +++ b/tests/test-rpc-paged-fa.cpp @@ -0,0 +1,139 @@ +// [TAG_EXACT_CONCURRENCY] an RPC server refuses a FLASH_ATTN_EXT that carries a page table (src[5]). +// supports_op keeps the scheduler from sending one, but a client can submit any graph, and a paged +// backend would trust the page ids it was given. The server runs on the CPU in a child process and +// each graph is sent from a child of its own, so a refused graph only costs that client its connection. + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-rpc.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +static bool port_open(int port) { + const int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + return false; + } + sockaddr_in addr = {}; + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + const bool ok = connect(fd, (sockaddr *) &addr, sizeof(addr)) == 0; + close(fd); + return ok; +} + +// runs in a child: one FLASH_ATTN_EXT over a single 256-cell page, computed on the server +[[noreturn]] static void send_graph(const std::string & endpoint, bool paged) { + alarm(120); + + ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str(), 0); + if (!backend) { + _exit(10); + } + + ggml_init_params params = { 16*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true }; + ggml_context * ctx = ggml_init(params); + + const int64_t d = 64, n_kv = 256, n_tokens = 1; + + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_tokens, 1, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, d, n_kv, 1, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, d, n_kv, 1, 1); + ggml_tensor * pages = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, 2, n_tokens); + + ggml_tensor * out = ggml_flash_attn_ext(ctx, q, k, v, nullptr, 0.125f, 0.0f, 0.0f); + if (paged) { + out->src[5] = pages; + } + + ggml_cgraph * gf = ggml_new_graph(ctx); + ggml_build_forward_expand(gf, out); + + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend); + if (!buf) { + _exit(11); + } + ggml_backend_buffer_clear(buf, 0); + + ggml_backend_graph_compute(backend, gf); + + // the read is the round trip that sees whether the server kept the connection + std::vector res(ggml_nelements(out)); + ggml_backend_tensor_get(out, res.data(), 0, ggml_nbytes(out)); + + _exit(0); +} + +// exit status of one client, or -signal +static int run_client(const std::string & endpoint, bool paged) { + const pid_t pid = fork(); + if (pid == 0) { + send_graph(endpoint, paged); + } + int status = 0; + waitpid(pid, &status, 0); + return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status); +} + +int main() { + const int port = 41000 + getpid() % 9000; + const std::string endpoint = "127.0.0.1:" + std::to_string(port); + + const pid_t server = fork(); + if (server == 0) { + ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); + ggml_backend_rpc_start_server(endpoint.c_str(), nullptr, 1, 1, &dev); + _exit(1); + } + + bool up = false; + for (int i = 0; i < 300 && !up; ++i) { + up = port_open(port); + if (!up) { + usleep(100*1000); + } + } + + int rc = 0; + + if (!up) { + fprintf(stderr, "the RPC server did not start on %s\n", endpoint.c_str()); + rc = 1; + } else { + // an unpaged graph computes, which shows the harness works + const int plain = run_client(endpoint, false); + // a paged one is refused, so the client loses its connection and its read fails + const int paged = run_client(endpoint, true); + // and the server is still there for the next client + const int after = run_client(endpoint, false); + + printf("unpaged: %d, paged: %d, unpaged after: %d\n", plain, paged, after); + + if (plain != 0 || after != 0) { + fprintf(stderr, "an unpaged graph failed over RPC, so this test proves nothing\n"); + rc = 1; + } else if (paged == 0) { + fprintf(stderr, "the RPC server computed a FLASH_ATTN_EXT that carries a page table\n"); + rc = 1; + } else { + printf("ok, the RPC server refused the paged graph and kept serving\n"); + } + } + + kill(server, SIGKILL); + waitpid(server, nullptr, 0); + + return rc; +} From 75dabc10522e223454b0881e283907ac796485cf Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 01:17:29 -0700 Subject: [PATCH 008/109] kv-cache: refuse a negative restored position in exact mode instead of asserting The paged pool files every cell under its position's page, and find_slot asserts the position is not negative. A sequence state with a negative position, from a corrupt or foreign file, reached that assert and aborted the process. state_read_meta now fails the restore through its error path, so llama_state_seq_set_data returns 0. test-exact-pages patches the first position of a saved sequence to -1: on the previous commit the restore aborts on the assert, here it returns 0 and the unpatched state still restores. --- src/llama-kv-cache.cpp | 6 +++++ tests/test-exact-pages.cpp | 45 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 51c4a0201e1a..fbdae96f2690 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2778,6 +2778,12 @@ bool llama_kv_cache::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32 return false; } + // [TAG_EXACT_CONCURRENCY] the paged pool files a cell under its position's page, and a negative position has none + if (exact_pages && pos < 0) { + LLAMA_LOG_ERROR("%s: invalid position %d in a restored kv cell\n", __func__, pos); + return false; + } + if (has_cell_ext()) { llama_kv_cell_ext ext; io.read(&ext, sizeof(ext)); diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index c9e0993744a2..86515f77ecbb 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -1,4 +1,4 @@ -// [TAG_EXACT_CONCURRENCY] drives the removal paths of the paged KV pool - a removal that empties nothing, one that leaves holes, and the pages those holes keep reserved - while LLAMA_KV_CACHE_DEBUG=1 makes the pool cross-check page ownership against the live cells every ubatch. +// [TAG_EXACT_CONCURRENCY] drives the removal paths of the paged KV pool - a removal that empties nothing, one that leaves holes, the pages those holes keep reserved, and a restore whose position has no page - while LLAMA_KV_CACHE_DEBUG=1 makes the pool cross-check page ownership against the live cells every ubatch. // Needs a CUDA build with 256-wide heads and a fully offloaded F16 cache; without one the test reports what it skipped and passes. #include "arg.h" @@ -7,6 +7,7 @@ #include #include +#include #include static const uint32_t PAGE = 256; @@ -156,7 +157,47 @@ int main(int argc, char ** argv) { return 1; } - printf("%s : ok, page ownership survived a no-op removal, holes and a full removal\n", __func__); + // a restored cell with a negative position has no page: the restore fails as a bad state does, + // and the same state unpatched still restores. After the magic and the sequence id, the + // attention cache comes first, as n_stream, cell_count, then the first cell's position + { + std::vector state(llama_state_seq_get_size(ctx, 1)); + state.resize(llama_state_seq_get_data(ctx, state.data(), state.size(), 1)); + + const size_t off_pos = 4*sizeof(uint32_t); + + uint32_t head[4] = {}; + int32_t pos0 = -1; + if (state.size() >= off_pos + sizeof(pos0)) { + memcpy(head, state.data(), sizeof(head)); + memcpy(&pos0, state.data() + off_pos, sizeof(pos0)); + } + + if (head[1] != 1 || head[2] != 1 || head[3] != 8*PAGE || pos0 < 0 || pos0 >= (int32_t) (8*PAGE)) { + fprintf(stderr, "%s : unexpected state layout: sequence %u, %u streams, %u cells, first position %d\n", + __func__, head[1], head[2], head[3], pos0); + return 1; + } + + std::vector bad = state; + const int32_t neg = -1; + memcpy(bad.data() + off_pos, &neg, sizeof(neg)); + + if (llama_state_seq_set_data(ctx, bad.data(), bad.size(), 1) != 0) { + fprintf(stderr, "%s : a state with a negative position was restored\n", __func__); + return 1; + } + + if (llama_state_seq_set_data(ctx, state.data(), state.size(), 1) == 0 || + llama_memory_seq_pos_max(mem, 1) != (llama_pos) (8*PAGE - 1)) { + fprintf(stderr, "%s : the unpatched state did not restore, sequence 1 ends at %d\n", + __func__, llama_memory_seq_pos_max(mem, 1)); + return 1; + } + + } + + printf("%s : ok, page ownership survived a no-op removal, holes and a full removal, and a negative restored position was refused\n", __func__); return 0; } From 64399f3ee7a794d2b0f0129862d6b36016360f24 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 01:17:29 -0700 Subject: [PATCH 009/109] tests: a whole-context restore is refused in exact mode through the error return state_read_sinfo refuses a whole-context restore before reading a byte, so the assert in state_read_meta's whole-cache branch is not reachable in this mode. test-exact-pages now holds that in place: llama_state_set_data on a saved whole-context state returns 0 and the process lives. --- tests/test-exact-pages.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index 86515f77ecbb..c8ce527e9499 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -195,9 +195,17 @@ int main(int argc, char ** argv) { return 1; } + // a whole-context restore is refused up front in this mode, through the same error return + std::vector whole(llama_state_get_size(ctx)); + whole.resize(llama_state_get_data(ctx, whole.data(), whole.size())); + + if (whole.empty() || llama_state_set_data(ctx, whole.data(), whole.size()) != 0) { + fprintf(stderr, "%s : a whole-context state was %s\n", __func__, whole.empty() ? "not saved" : "restored"); + return 1; + } } - printf("%s : ok, page ownership survived a no-op removal, holes and a full removal, and a negative restored position was refused\n", __func__); + printf("%s : ok, page ownership survived a no-op removal, holes and a full removal, and a negative restored position and a whole-context restore were refused\n", __func__); return 0; } From 1161f5947b71bfabc5a9ccd41099f1475ff7f2d7 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 02:38:59 -0700 Subject: [PATCH 010/109] ggml: publish the event query through the backend registry, not ggml_backend_device_i Appending event_query to ggml_backend_device_i changed its layout without a backend API version bump, so a backend module built against the old layout would load and the core would read the device's reg pointer as event_query. A fork-side bump would instead collide with upstream's next one. The member and every NULL initialiser of it are gone, so the interface is upstream's again; the CUDA backend returns its implementation from get_proc_address as "ggml_backend_dev_event_query", and ggml_backend_event_query() and ggml_backend_dev_supports_event_query() look it up there, keeping the blocking fallback for a backend that does not publish it. test-event-query checks that a CUDA device reports the query and that every device that does reads a completed event as complete. --- ggml/src/ggml-backend-impl.h | 3 - ggml/src/ggml-backend-meta.cpp | 1 - ggml/src/ggml-backend.cpp | 20 ++++++- ggml/src/ggml-blas/ggml-blas.cpp | 1 - ggml/src/ggml-cann/ggml-cann.cpp | 1 - ggml/src/ggml-cpu/ggml-cpu.cpp | 1 - ggml/src/ggml-cuda/ggml-cuda.cu | 5 +- ggml/src/ggml-et/ggml-et.cpp | 1 - ggml/src/ggml-hexagon/ggml-hexagon.cpp | 1 - ggml/src/ggml-metal/ggml-metal.cpp | 1 - ggml/src/ggml-opencl/ggml-opencl.cpp | 1 - ggml/src/ggml-openvino/ggml-openvino.cpp | 1 - ggml/src/ggml-rpc/ggml-rpc.cpp | 1 - ggml/src/ggml-sycl/ggml-sycl.cpp | 1 - ggml/src/ggml-virtgpu/ggml-backend-device.cpp | 1 - ggml/src/ggml-vulkan/ggml-vulkan.cpp | 1 - ggml/src/ggml-webgpu/ggml-webgpu.cpp | 1 - ggml/src/ggml-zdnn/ggml-zdnn.cpp | 1 - ggml/src/ggml-zendnn/ggml-zendnn.cpp | 1 - tests/CMakeLists.txt | 3 + tests/test-event-query.cpp | 59 +++++++++++++++++++ 21 files changed, 83 insertions(+), 23 deletions(-) create mode 100644 tests/test-event-query.cpp diff --git a/ggml/src/ggml-backend-impl.h b/ggml/src/ggml-backend-impl.h index 121762359397..dc7367dec4fe 100644 --- a/ggml/src/ggml-backend-impl.h +++ b/ggml/src/ggml-backend-impl.h @@ -216,9 +216,6 @@ extern "C" { ggml_backend_event_t (*event_new) (ggml_backend_dev_t dev); void (*event_free) (ggml_backend_dev_t dev, ggml_backend_event_t event); void (*event_synchronize) (ggml_backend_dev_t dev, ggml_backend_event_t event); - - // (optional) non-blocking completion test for an event. Kept last: a missing entry is NULL and ggml_backend_event_query() then blocks instead. - bool (*event_query) (ggml_backend_dev_t dev, ggml_backend_event_t event); }; struct ggml_backend_device { diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index ea405d56e0c6..86748b689a8a 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -193,7 +193,6 @@ static const ggml_backend_device_i ggml_backend_meta_device_iface = { /* .event_new = */ nullptr, /* .event_free = */ nullptr, /* .event_synchronize = */ nullptr, - /* .event_query = */ NULL, }; static bool ggml_backend_dev_is_meta(ggml_backend_dev_t dev) { diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 1cbd01534f0e..adfbe355ec82 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -704,16 +704,30 @@ void ggml_backend_event_synchronize(ggml_backend_event_t event) { event->device->iface.event_synchronize(event->device, event); } +// (optional) non-blocking completion test for an event, published by the backend's registry as +// "ggml_backend_dev_event_query" so that ggml_backend_device_i, and with it the backend API version, +// stays as upstream has it. A backend that does not publish it gets the blocking fallback. +typedef bool (*ggml_backend_dev_event_query_t)(ggml_backend_dev_t dev, ggml_backend_event_t event); + +static ggml_backend_dev_event_query_t ggml_backend_dev_get_event_query(ggml_backend_dev_t device) { + ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(device); + if (reg == NULL) { + return NULL; + } + return (ggml_backend_dev_event_query_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_dev_event_query"); +} + bool ggml_backend_event_query(ggml_backend_event_t event) { GGML_ASSERT(event); - if (event->device->iface.event_query == NULL) { + ggml_backend_dev_event_query_t event_query = ggml_backend_dev_get_event_query(event->device); + if (event_query == NULL) { // no way to ask: the honest answer is to wait for it and then say yes ggml_backend_event_synchronize(event); return true; } - return event->device->iface.event_query(event->device, event); + return event_query(event->device, event); } void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event) { @@ -794,7 +808,7 @@ bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_t bool ggml_backend_dev_supports_event_query(ggml_backend_dev_t device) { GGML_ASSERT(device); - return device->iface.event_query != NULL; + return ggml_backend_dev_get_event_query(device) != NULL; } bool ggml_backend_dev_supports_buft(ggml_backend_dev_t device, ggml_backend_buffer_type_t buft) { diff --git a/ggml/src/ggml-blas/ggml-blas.cpp b/ggml/src/ggml-blas/ggml-blas.cpp index 8266b994b1b9..6feb370bb5e6 100644 --- a/ggml/src/ggml-blas/ggml-blas.cpp +++ b/ggml/src/ggml-blas/ggml-blas.cpp @@ -471,7 +471,6 @@ static const struct ggml_backend_device_i ggml_backend_blas_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; // backend reg interface diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index e66b9a12b3ad..c2f37b7cc178 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2960,7 +2960,6 @@ static const ggml_backend_device_i ggml_backend_cann_device_interface = { /* .event_new = */ ggml_backend_cann_device_event_new, /* .event_free = */ ggml_backend_cann_device_event_free, /* .event_synchronize = */ ggml_backend_cann_device_event_synchronize, - /* .event_query = */ NULL, }; // backend reg diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index 42dfe86291e0..31f66b9a8fbe 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -508,7 +508,6 @@ static const struct ggml_backend_device_i ggml_backend_cpu_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; // CPU backend - backend (reg) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 85402c11cd21..56b4998bd333 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -6234,7 +6234,6 @@ static const ggml_backend_device_i ggml_backend_cuda_device_interface = { /* .event_new = */ ggml_backend_cuda_device_event_new, /* .event_free = */ ggml_backend_cuda_device_event_free, /* .event_synchronize = */ ggml_backend_cuda_device_event_synchronize, - /* .event_query = */ ggml_backend_cuda_device_event_query, }; // backend reg @@ -6331,6 +6330,10 @@ static void * ggml_backend_cuda_reg_get_proc_address(ggml_backend_reg_t reg, con if (strcmp(name, "ggml_backend_cuda_set_exact_decode_width") == 0) { return (void *)ggml_backend_cuda_set_exact_decode_width; } + // reached through the registry rather than ggml_backend_device_i, so the interface keeps its layout + if (strcmp(name, "ggml_backend_dev_event_query") == 0) { + return (void *)ggml_backend_cuda_device_event_query; + } if (strcmp(name, "ggml_backend_register_host_buffer") == 0) { return (void *)ggml_backend_cuda_register_host_buffer; } diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp index cb1e39f37fc4..773cc3b7d1da 100644 --- a/ggml/src/ggml-et/ggml-et.cpp +++ b/ggml/src/ggml-et/ggml-et.cpp @@ -1691,7 +1691,6 @@ static const struct ggml_backend_device_i ggml_backend_et_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; /* diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp index a44a93f6f080..d2828802b149 100644 --- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp +++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp @@ -9520,7 +9520,6 @@ static const struct ggml_backend_device_i ggml_backend_hexagon_device_i = { /* .event_new = */ ggml_backend_hexagon_device_event_new, /* .event_free = */ ggml_backend_hexagon_device_event_free, /* .event_synchronize = */ ggml_backend_hexagon_device_event_synchronize, - /* .event_query = */ NULL, }; //** backend registry diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 191051906f80..344882e044f3 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -833,7 +833,6 @@ static ggml_backend_device_i ggml_backend_metal_device_i = { /* .event_new = */ ggml_backend_metal_device_event_new, /* .event_free = */ ggml_backend_metal_device_event_free, /* .event_synchronize = */ ggml_backend_metal_device_event_synchronize, - /* .event_query = */ NULL, }; // backend registry diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index f5b7c68d8f67..e901fcf48285 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -13237,7 +13237,6 @@ struct ggml_backend_device_i ggml_backend_opencl_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; } diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index d539d1d9dd55..2d63e8e8d200 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1926,7 +1926,6 @@ static const struct ggml_backend_device_i ggml_backend_openvino_device_interface /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; namespace { diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index 3864bc736ce1..5b6ffa4e06e2 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -2908,7 +2908,6 @@ static const struct ggml_backend_device_i ggml_backend_rpc_device_i = { /* .event_new = */ ggml_backend_rpc_device_event_new, /* .event_free = */ ggml_backend_rpc_device_event_free, /* .event_synchronize = */ ggml_backend_rpc_device_event_synchronize, - /* .event_query = */ NULL, }; // backend reg interface diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index dcab08dcb210..a59fa6574299 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7194,7 +7194,6 @@ static const ggml_backend_device_i ggml_backend_sycl_device_interface = { /* .event_new = */ ggml_backend_sycl_device_event_new, /* .event_free = */ ggml_backend_sycl_device_event_free, /* .event_synchronize = */ ggml_backend_sycl_device_event_synchronize, - /* .event_query = */ NULL, }; // backend reg diff --git a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp index 13a70c594df6..987ce9dd110c 100644 --- a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp +++ b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp @@ -157,5 +157,4 @@ const ggml_backend_device_i ggml_backend_remoting_device_interface = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 502e5c6c32db..eddf2a5c68ae 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -16131,7 +16131,6 @@ static const struct ggml_backend_device_i ggml_backend_vk_device_i = { /* .event_new = */ ggml_backend_vk_device_event_new, /* .event_free = */ ggml_backend_vk_device_event_free, /* .event_synchronize = */ ggml_backend_vk_device_event_synchronize, - /* .event_query = */ NULL, }; static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) { diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index b54d02ba3bfd..eeb141edc763 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -4842,7 +4842,6 @@ static struct ggml_backend_device_i ggml_backend_webgpu_device_i = { /* .event_new = */ ggml_backend_webgpu_device_event_new, /* .event_free = */ ggml_backend_webgpu_device_event_free, /* .event_synchronize = */ ggml_backend_webgpu_device_event_synchronize, - /* .event_query = */ NULL, }; /* End GGML Backend Device Interface */ diff --git a/ggml/src/ggml-zdnn/ggml-zdnn.cpp b/ggml/src/ggml-zdnn/ggml-zdnn.cpp index 37e9f9aab145..5d1209357ff5 100644 --- a/ggml/src/ggml-zdnn/ggml-zdnn.cpp +++ b/ggml/src/ggml-zdnn/ggml-zdnn.cpp @@ -578,7 +578,6 @@ static ggml_backend_device_i ggml_backend_zdnn_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; // diff --git a/ggml/src/ggml-zendnn/ggml-zendnn.cpp b/ggml/src/ggml-zendnn/ggml-zendnn.cpp index 89c6c36a0f19..ec7ce233145a 100644 --- a/ggml/src/ggml-zendnn/ggml-zendnn.cpp +++ b/ggml/src/ggml-zendnn/ggml-zendnn.cpp @@ -781,7 +781,6 @@ static const struct ggml_backend_device_i ggml_backend_zendnn_device_i = { /* .event_new = */ NULL, /* .event_free = */ NULL, /* .event_synchronize = */ NULL, - /* .event_query = */ NULL, }; // backend reg interface diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5a3e2a58722e..65933d61c6c0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -315,6 +315,9 @@ if (GGML_RPC AND NOT GGML_BACKEND_DL AND NOT WIN32) llama_build_and_test(test-rpc-paged-fa.cpp LINK ggml) endif() +# [TAG_EXACT_CONCURRENCY] the event query a backend publishes through its registry is found and answers +llama_build_and_test(test-event-query.cpp LINK ggml) + llama_build_and_test(test-tiled-mulmat.cpp LINK ggml) llama_build_and_test(test-model-load-cancel.cpp LABEL "model") llama_build_and_test(test-autorelease.cpp LABEL "model") diff --git a/tests/test-event-query.cpp b/tests/test-event-query.cpp new file mode 100644 index 000000000000..f4187472b2f9 --- /dev/null +++ b/tests/test-event-query.cpp @@ -0,0 +1,59 @@ +// [TAG_EXACT_CONCURRENCY] a non-blocking event query is found through the backend registry. A CUDA +// device must report it, since without it every poll of an asynchronous park blocks, and on every +// device that reports it a recorded event that has been waited for reads as complete. + +#include "ggml-backend.h" + +#include +#include + +int main() { + ggml_backend_load_all(); + + int rc = 0; + + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + + const char * reg_name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)); + const bool supported = ggml_backend_dev_supports_event_query(dev); + + printf("%s (%s): event query %s\n", ggml_backend_dev_name(dev), reg_name, supported ? "yes" : "no"); + + if (!supported) { + if (strcmp(reg_name, "CUDA") == 0) { + fprintf(stderr, "%s is a CUDA device without a non-blocking event query\n", ggml_backend_dev_name(dev)); + rc = 1; + } + continue; + } + + ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr); + ggml_backend_event_t event = backend ? ggml_backend_event_new(dev) : nullptr; + + if (!event) { + fprintf(stderr, "%s reports an event query but gave no event\n", ggml_backend_dev_name(dev)); + rc = 1; + } else { + ggml_backend_event_record(event, backend); + ggml_backend_event_synchronize(event); + + if (!ggml_backend_event_query(event)) { + fprintf(stderr, "%s says a completed event is still pending\n", ggml_backend_dev_name(dev)); + rc = 1; + } + + ggml_backend_event_free(event); + } + + if (backend) { + ggml_backend_free(backend); + } + } + + if (rc == 0) { + printf("ok\n"); + } + + return rc; +} From 40cd74449717b9f9eff78ce37e0b70d43f06f3c8 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 03:47:28 -0700 Subject: [PATCH 011/109] server: do not group decision tasks on a shared prompt in exact mode A grouped child continues from the parent's cells through seq_cp, which LLAMA_EXACT_CONCURRENCY refuses (a page belongs to one sequence), while copy_prompt_to() still clones the parent's prompt metadata. The child then decoded its suffix at the shared position with no KV prefix behind it. Each task now keeps its whole prompt in exact mode. --- tests/CMakeLists.txt | 3 ++ tests/test-server-decision-exact.cpp | 46 ++++++++++++++++++++++++++++ tools/server/server-decision.cpp | 5 +++ 3 files changed, 54 insertions(+) create mode 100644 tests/test-server-decision-exact.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 65933d61c6c0..44169fdde623 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -364,6 +364,9 @@ if (LLAMA_BUILD_TOOLS) llama_build_and_test(test-server-tokens.cpp) target_link_libraries(test-server-tokens PRIVATE server-context mtmd) target_include_directories(test-server-tokens PRIVATE ${PROJECT_SOURCE_DIR}/tools/server ${PROJECT_SOURCE_DIR}/tools/mtmd) + llama_build_and_test(test-server-decision-exact.cpp) + target_link_libraries(test-server-decision-exact PRIVATE server-context mtmd) + target_include_directories(test-server-decision-exact PRIVATE ${PROJECT_SOURCE_DIR}/tools/server ${PROJECT_SOURCE_DIR}/tools/mtmd) endif() # GGUF model data fetcher library for tests that need real model metadata diff --git a/tests/test-server-decision-exact.cpp b/tests/test-server-decision-exact.cpp new file mode 100644 index 000000000000..87f86e6026f6 --- /dev/null +++ b/tests/test-server-decision-exact.cpp @@ -0,0 +1,46 @@ +// [TAG_EXACT_CONCURRENCY] a decision request whose questions share a prompt prefix is grouped so the +// children continue from the parent's cells through seq_cp. Exact mode gives a page to one sequence +// and refuses that copy, so the grouping must not happen there: every task keeps its whole prompt. + +#include "server-decision.h" + +#include +#include + +#undef NDEBUG +#include + +static server_task make_task(int id, const llama_tokens & tokens) { + server_task task(SERVER_TASK_TYPE_DECISION); + task.id = id; + task.tokens = server_tokens(tokens, false); + return task; +} + +int main() { + // latched on first use, so set before anything reads it +#ifdef _WIN32 + _putenv_s("LLAMA_EXACT_CONCURRENCY", "1"); +#else + setenv("LLAMA_EXACT_CONCURRENCY", "1", 1); +#endif + assert(common_exact_concurrency()); + + std::vector tasks; + tasks.push_back(make_task(0, { 1, 2, 3, 4, 5 })); + tasks.push_back(make_task(1, { 1, 2, 3, 4, 6 })); + tasks.push_back(make_task(2, { 1, 2, 3, 7 })); + + const auto groups = server_decision_group_tasks(std::move(tasks), 4); + + assert(groups.size() == 3); + for (size_t i = 0; i < groups.size(); ++i) { + assert(groups[i].id == (int) i); + assert(groups[i].n_tokens_shared == 0); + assert(groups[i].child_tasks.empty()); + assert(groups[i].id_parent == -1); + } + + printf("ok: no shared-prompt grouping under LLAMA_EXACT_CONCURRENCY\n"); + return 0; +} diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp index bd2c9c4aa73c..8ddcdc27dda1 100644 --- a/tools/server/server-decision.cpp +++ b/tools/server/server-decision.cpp @@ -1233,6 +1233,11 @@ json server_decision_context::format_answer(const server_decision_question & que // std::vector server_decision_group_tasks(std::vector && tasks, size_t n_slots) { + // [TAG_EXACT_CONCURRENCY] a child continues from the parent's cells through seq_cp, which exact mode refuses (a page belongs to one sequence): every task keeps its whole prompt + if (common_exact_concurrency()) { + return std::move(tasks); + } + n_slots = std::max(n_slots, (size_t) 1); std::vector groups; From 2bf0e4afed11cc534f0bfd37609144c4db920e5b Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 04:25:17 -0700 Subject: [PATCH 012/109] context: refuse a whole-context save in exact mode, which cannot be reloaded The whole-context restore is already refused under LLAMA_EXACT_CONCURRENCY, but llama_state_get_size/get_data and llama_state_save_file still succeeded, so llama-completion --prompt-cache wrote a session that made the next run fail to load it and exit. The save now fails the same way, before the file is opened, so no session is left behind and the next run starts fresh. Per-sequence saves, which the server uses, are unchanged. --- src/llama-context.cpp | 12 ++++++++++++ src/llama-context.h | 1 + tests/test-exact-pages.cpp | 32 ++++++++++++++++++++++++++------ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 81c40c9dbc29..6fc335805c38 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -4279,6 +4279,9 @@ bool llama_context::state_load_file(const char * filepath, llama_token * tokens_ } bool llama_context::state_save_file(const char * filepath, const llama_token * tokens, size_t n_token_count) { + // [TAG_EXACT_CONCURRENCY] refused before the file is opened, so no session is left behind that the next load would reject + state_write_check(); + llama_file file(filepath, "wb"); file.write_u32(LLAMA_SESSION_MAGIC); @@ -4369,7 +4372,16 @@ size_t llama_context::state_seq_save_file(llama_seq_id seq_id, const char * file return res; } +// [TAG_EXACT_CONCURRENCY] a whole-context state cannot be restored in this mode (see state_read_data), so it is not produced either +void llama_context::state_write_check() const { + if (memory && memory->alloc_granularity() > 1) { + throw std::runtime_error("whole-context save is not supported with LLAMA_EXACT_CONCURRENCY, save per sequence"); + } +} + size_t llama_context::state_write_data(llama_io_write_i & io) { + state_write_check(); + LLAMA_LOG_DEBUG("%s: writing state\n", __func__); // write model info diff --git a/src/llama-context.h b/src/llama-context.h index dd8dabe97cde..3c9bdd480572 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -304,6 +304,7 @@ struct llama_context { // TODO: read/write lora adapters and cvec size_t state_write_data(llama_io_write_i & io); + void state_write_check() const; size_t state_read_data (llama_io_read_i & io); size_t state_seq_write_data(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags); diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index c8ce527e9499..fb067780f2bc 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -195,17 +195,37 @@ int main(int argc, char ** argv) { return 1; } - // a whole-context restore is refused up front in this mode, through the same error return - std::vector whole(llama_state_get_size(ctx)); - whole.resize(llama_state_get_data(ctx, whole.data(), whole.size())); + // a whole-context state cannot be restored in this mode, so it is not saved either: the size, + // the copy and the session file all fail, and no file is left behind to fail at the next load + std::vector whole(state.size() + 4096); - if (whole.empty() || llama_state_set_data(ctx, whole.data(), whole.size()) != 0) { - fprintf(stderr, "%s : a whole-context state was %s\n", __func__, whole.empty() ? "not saved" : "restored"); + if (llama_state_get_size(ctx) != 0 || llama_state_get_data(ctx, whole.data(), whole.size()) != 0) { + fprintf(stderr, "%s : a whole-context state was saved\n", __func__); + return 1; + } + + const char * session = "test-exact-pages.session"; + std::remove(session); + + const llama_token tok = 1; + FILE * f = nullptr; + if (llama_state_save_file(ctx, session, &tok, 1) || (f = fopen(session, "rb")) != nullptr) { + if (f) { + fclose(f); + } + std::remove(session); + fprintf(stderr, "%s : a whole-context session file was written\n", __func__); + return 1; + } + + // the restore stays refused through the same error return + if (llama_state_set_data(ctx, state.data(), state.size()) != 0) { + fprintf(stderr, "%s : a whole-context state was restored\n", __func__); return 1; } } - printf("%s : ok, page ownership survived a no-op removal, holes and a full removal, and a negative restored position and a whole-context restore were refused\n", __func__); + printf("%s : ok, page ownership survived a no-op removal, holes and a full removal, and a negative restored position and a whole-context save and restore were refused\n", __func__); return 0; } From d0d9828dd79fadbe3a0e79a902b652cb54ed057a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 04:53:22 -0700 Subject: [PATCH 013/109] server: no output for a re-prefill's last token under a backend sampler The token was sampled before the park and post_decode discards the output, but a backend sampler runs on every output of its sequence and, at one output per sequence, draws its uniform from the stream's RNG. Every recompute park left the stream one draw ahead. --- tools/server/server-context.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 7d51aa9bf421..6472c6242f45 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -536,6 +536,7 @@ struct server_slot { // [TAG_PREEMPT] a park with no room left under --preempt-ram: the cells are dropped instead of copied out, and the resume re-prefills the tokens bool preempt_recompute = false; // parked by dropping its cells bool preempt_reprefill = false; // putting back, as a prompt, what such a park dropped + bool backend_sampler = false; // the task's sampler chain runs on the backend, see the re-prefill's last token in update_slots server_tokens preempt_tokens; // what the re-prefill decodes: the prompt and everything generated so far size_t preempt_state_size() const { @@ -934,6 +935,7 @@ struct server_slot { preempt_hold_logged = false; llama_set_sampler(ctx_tgt, id, nullptr); + backend_sampler = false; // clear alora start alora_invocation_start = -1; @@ -2635,9 +2637,10 @@ struct server_context_impl { // TODO: tmp until backend sampling is fully implemented if (use_backend_sampling) { - llama_set_sampler(ctx_tgt, slot.id, common_sampler_get(slot.smpl.get())); + slot.backend_sampler = llama_set_sampler(ctx_tgt, slot.id, common_sampler_get(slot.smpl.get())); } else { llama_set_sampler(ctx_tgt, slot.id, nullptr); + slot.backend_sampler = false; } SLT_TRC(slot, "sampler chain: %s\n", common_sampler_print(slot.smpl.get()).c_str()); @@ -5974,7 +5977,10 @@ struct server_context_impl { GGML_ASSERT(batch.size() > 0); // extract the logits only for the last token - batch.set_output(batch.size() - 1, true); + // [TAG_PREEMPT] except a re-prefill's under a backend sampler: that token was sampled before the park and post_decode throws the output away, but the sampler runs on every output of its sequence and, at one output per sequence, draws its uniform from the stream's own RNG, which would come back a draw ahead + if (!(slot.preempt_reprefill && slot.backend_sampler && !slot.can_speculate())) { + batch.set_output(batch.size() - 1, true); + } slot.i_batch = batch.size() - 1; From 02dcf7341bc45d6608cb70c85ff64299db7a3ee9 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 04:53:36 -0700 Subject: [PATCH 014/109] server: document that requests_preempted counts parks still in transfer --- tools/server/README.md | 2 +- tools/server/server-context.cpp | 1 + tools/server/server-task.cpp | 2 +- tools/server/server-task.h | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/tools/server/README.md b/tools/server/README.md index 459b16d071df..2893283e7357 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -1165,7 +1165,7 @@ In *router mode* the query param `?model={model_id}` has to be set. This endpoin | `llamacpp:n_preempt_total` | Counter | Slots parked to make room in the unified KV cache (0 unless `--kv-unified` with more than one slot). | | `llamacpp:n_resume_total` | Counter | Parked slots put back. | | `llamacpp:preempt_recompute_total` | Counter | Parks that dropped their cells because `--preempt-ram` was spent, so the resume re-prefills the sequence instead of restoring its saved bytes. | -| `llamacpp:requests_preempted` | Gauge | Requests currently parked, waiting for room in the unified KV cache. | +| `llamacpp:requests_preempted` | Gauge | Requests currently parked for room in the unified KV cache, including those whose copy out or back in is still in flight (the `/slots` entries with `is_preempted` or `is_transferring`). None of them is decoding. | | `llamacpp:preempt_ram_bytes` | Gauge | Host RAM held by parked sequences. | ### POST `/slots/{id_slot}?action=save`: Save the prompt cache of the specified slot to a file. diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 6472c6242f45..63fa571bed31 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -3579,6 +3579,7 @@ struct server_context_impl { if (slot.is_processing()) { n_processing_slots++; } + // [TAG_PREEMPT] a transfer counts with the parked: none of them decodes, and a client excusing a silent stream needs all three if (slot.preempt_is_out()) { n_preempted_slots++; } diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index fbdb2b5ac52f..0a5dbf24225e 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1629,7 +1629,7 @@ std::string server_task_result_metrics::to_metrics() { (double) metrics.n_busy_slots / std::max((double) metrics.n_decode, 1.0) }, { "requests_preempted", - "Preemption: Number of requests currently parked, waiting for room in the unified KV cache", + "Preemption: Number of requests currently parked for room in the unified KV cache, including those whose copy out or back in is still in flight", (double) n_preempted_slots }, { "preempt_ram_bytes", diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 2c24cf5b6205..6bb5db8baaa9 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -567,7 +567,7 @@ struct server_task_result_metrics : server_task_result { // these are immediate stats, not accumulated (server_metrics is cumulative) int n_processing_slots = 0; int n_tasks_deferred = 0; - int n_preempted_slots = 0; // [TAG_PREEMPT] processing slots currently parked + int n_preempted_slots = 0; // [TAG_PREEMPT] processing slots currently parked or moving to or from host memory size_t preempt_ram_bytes = 0; // [TAG_PREEMPT] host RAM their parked sequences hold server_metrics metrics; From b8f7b90d72f27bc63d5a13e29ffb7df92ef25eb6 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 04:50:00 -0700 Subject: [PATCH 015/109] server: sum the preempt counters of every prompt in a merged OAI response A multi-prompt /v1/completions request is one ordinary task per prompt, each of which can be parked; the non-streaming OAI merge kept only the first result's preempt object, so parks of the other prompts were dropped. --- tools/server/server-context.cpp | 15 +++++++++++++++ tools/server/tests/unit/test_preempt.py | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 63fa571bed31..a0b26e145246 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -7016,6 +7016,21 @@ std::unique_ptr server_routes::handle_completions_impl( for (size_t i = 1; i < arr.size(); i++) { choices.push_back(std::move(arr[i]["choices"][0])); } + // [TAG_PREEMPT] one response stands for every prompt (or choice), so its counters are the sum of each result's: a park of any member is the request's + if (arr[0].contains("preempt")) { + int64_t n_parks = 0; + int64_t n_recomputes = 0; + for (const auto & r : arr) { + if (r.contains("preempt")) { + n_parks += json_value(r.at("preempt"), "parks", (int64_t) 0); + n_recomputes += json_value(r.at("preempt"), "recomputes", (int64_t) 0); + } + } + arr[0]["preempt"] = json { + {"parks", n_parks}, + {"recomputes", n_recomputes}, + }; + } res->ok(arr[0]); } else { // multi-results, non-OAI compat diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 46a641174cda..b570873021c5 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1322,3 +1322,22 @@ def test_a_growing_sequence_keeps_its_pinned_buffer_across_parks(): sizes = re.findall(r"pinned park buffer (?:allocated|grown)", text) assert parks >= 40, parks assert 1 <= len(sizes) <= 4, f"{len(sizes)} pinned allocations for {parks} parks" + + +def test_a_multi_prompt_oai_completion_counts_the_parks_of_every_prompt(): + # an array prompt is one ordinary task per prompt, each parked on its own; the OAI response merges them into one object, so its counters are the sum, as /completion reports them per prompt + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + _start() + + body = {"prompt": [_PROMPT_A, _PROMPT_B], "max_tokens": 40, "temperature": 0.0} + + per_prompt = server.make_request("POST", "/completion", data=body) + assert per_prompt.status_code == 200, per_prompt.body + counts = [r["preempt"] for r in per_prompt.body] + assert all(c["parks"] > 0 for c in counts), counts + + merged = server.make_request("POST", "/v1/completions", data=body) + assert merged.status_code == 200, merged.body + assert len(merged.body["choices"]) == 2 + assert merged.body["preempt"]["parks"] == sum(c["parks"] for c in counts), (merged.body["preempt"], counts) + assert merged.body["preempt"]["recomputes"] == sum(c["recomputes"] for c in counts), (merged.body["preempt"], counts) From 49e12b9e04a2895c3988ed38a00455483e5b3256 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 06:22:33 -0700 Subject: [PATCH 016/109] llama-adapter: condense the exact concurrency lora placement comment --- src/llama-adapter.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/llama-adapter.cpp b/src/llama-adapter.cpp index e8175539533e..ea8c604cc3eb 100644 --- a/src/llama-adapter.cpp +++ b/src/llama-adapter.cpp @@ -358,10 +358,7 @@ static void llama_adapter_lora_init_impl(llama_model & model, FILE * file, llama LLAMA_LOG_DEBUG("%s: lora for '%s' -> '%s'\n", __func__, model_tensor->name, ggml_backend_buft_name(buft)); - // [TAG_EXACT_CONCURRENCY] the adapter follows the weight it adapts, so a weight the mode - // leaves on the host puts the adapted matmul there too. token_embd is exempt from the - // context's weight check because get_rows is not offloaded by width, but its adapter is - // applied with a mul_mat, which is: see llm_graph_context::build_inp_embd(). + // [TAG_EXACT_CONCURRENCY] the adapter follows its weight's buffer; a host token_embd passes the context check (get_rows) but its adapter is a mul_mat, see build_inp_embd() if (llama_exact_concurrency() && !llama_exact_buft_invariant(buft)) { LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but the lora for '%s' would sit in a %s " "buffer, which has no batch-invariant kernels: the adapted matmul's result would " From 5bfe43f4594195a2de4bf9be3696a5ab429e199d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 07:10:39 -0700 Subject: [PATCH 017/109] llama-context: refuse every host-placed weight outside the input layer in exact concurrency mode The weight check only looked at blk.* tensors and the output head, so an --override-tensor that kept output_norm, cls or cls.output on the host passed while those ops ran with a batch-width-dependent placement. Exempt only the input-layer tables (token_embd and friends), which feed GET_ROWS. --- src/llama-arch.cpp | 21 +++++++++ src/llama-arch.h | 3 ++ src/llama-context.cpp | 8 ++-- tests/CMakeLists.txt | 4 ++ tests/test-exact-weights.cpp | 88 ++++++++++++++++++++++++++++++++++++ 5 files changed, 120 insertions(+), 4 deletions(-) create mode 100644 tests/test-exact-weights.cpp diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 0dc4cc961b4c..fa3f2e25514a 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -2,6 +2,7 @@ #include "llama-impl.h" +#include #include #include @@ -1140,6 +1141,26 @@ const llm_tensor_info & llm_tensor_info_for(llm_tensor tensor) { return LLM_TENSOR_INFOS.at(tensor); } +bool llm_tensor_name_is_input_layer(const std::string & name) { + for (const auto & [tensor, info] : LLM_TENSOR_INFOS) { + if (info.layer != LLM_TENSOR_LAYER_INPUT) { + continue; + } + + const auto it = LLM_TENSOR_NAMES.find(tensor); + if (it == LLM_TENSOR_NAMES.end()) { + continue; + } + + const size_t n = strlen(it->second); + if (name.compare(0, n, it->second) == 0 && (name.size() == n || name[n] == '.')) { + return true; + } + } + + return false; +} + bool llm_arch_is_recurrent(const llm_arch & arch) { switch (arch) { case LLM_ARCH_MAMBA: diff --git a/src/llama-arch.h b/src/llama-arch.h index 8f8cc27ed25d..aff187169c04 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -846,6 +846,9 @@ llm_arch llm_arch_from_string(const std::string & name); const llm_tensor_info & llm_tensor_info_for(llm_tensor tensor); +// true for a tensor name (with any suffix, e.g. ".weight") of the input layer, such as token_embd +bool llm_tensor_name_is_input_layer(const std::string & name); + bool llm_arch_is_recurrent (const llm_arch & arch); bool llm_arch_is_hybrid (const llm_arch & arch); bool llm_arch_is_diffusion (const llm_arch & arch); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 6fc335805c38..cf8253b80c5f 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -118,8 +118,8 @@ static llm_graph_type ctx_type_to_graph_type(llama_context_type ctx_type) { throw std::runtime_error("Unsupported ctx type"); } -// [TAG_EXACT_CONCURRENCY] the caches check where the KV lives; this checks the weights. Every per-layer weight and the output head must sit on a backend with the mode's kernels, else a sequence's own matmuls change with the width of the step it shares. -// token_embd is exempt: it feeds GET_ROWS, a per-row copy that reports a batch size of 0 to the offload test, so it stays put at every width. A tied head is that same tensor and model.output points at it, so the head check covers it; a lora on it runs as MUL_MAT, which llama_adapter_lora_init_impl() refuses on a host buffer. +// [TAG_EXACT_CONCURRENCY] the caches check where the KV lives; this checks the weights. Every weight outside the input layer (per-layer weights, output head, classifier heads, norms) must sit on a backend with the mode's kernels, else a sequence's own ops change with the width of the step it shares. +// Input-layer tensors (token_embd and the other embedding tables) are exempt: they feed GET_ROWS, a per-row copy that reports a batch size of 0 to the offload test, so it stays put at every width. A tied head is that same tensor and model.output points at it, so the head check covers it; a lora on it runs as MUL_MAT, which llama_adapter_lora_init_impl() refuses on a host buffer. static void llama_exact_check_weights(const llama_model & model) { auto host_buft = [](const ggml_tensor * t) -> ggml_backend_buffer_type_t { if (!t || !t->buffer) { @@ -150,12 +150,12 @@ static void llama_exact_check_weights(const llama_model & model) { }; for (const auto & [name, t] : model.tensors_by_name) { - if (name.rfind("blk.", 0) != 0) { + if (llm_tensor_name_is_input_layer(name)) { continue; } if (auto * buft = host_buft(t)) { - refuse(name.c_str(), buft, "layer weight"); + refuse(name.c_str(), buft, name.rfind("blk.", 0) == 0 ? "layer weight" : "weight"); } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 44169fdde623..20a985b1cec7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -338,6 +338,10 @@ set_tests_properties(test-state-seq-copy PROPERTIES FIXTURES_REQUIRED test-downl llama_build_and_test(test-exact-pages.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-exact-pages PROPERTIES FIXTURES_REQUIRED test-download-model) +# [TAG_EXACT_CONCURRENCY] a non-layer weight on the host is refused; skips itself where the mode cannot run +llama_build_and_test(test-exact-weights.cpp LABEL "model" ARGS -m "${MODEL_DEST}") +set_tests_properties(test-exact-weights PROPERTIES FIXTURES_REQUIRED test-download-model) + if (APPLE) llama_build(test-rset-release.cpp) endif() diff --git a/tests/test-exact-weights.cpp b/tests/test-exact-weights.cpp new file mode 100644 index 000000000000..82098af1f955 --- /dev/null +++ b/tests/test-exact-weights.cpp @@ -0,0 +1,88 @@ +// [TAG_EXACT_CONCURRENCY] the context refuses a weight outside the per-layer blocks (here output_norm) that an override keeps on the host, and still accepts the same model fully offloaded. +// Needs a batch-invariant GPU backend; without one the test reports what it skipped and passes. + +#include "llama.h" +#include "ggml-backend.h" + +#include +#include +#include + +// Windows has no setenv +static void set_env_default(const char * name, const char * value) { + if (getenv(name)) { + return; + } +#ifdef _WIN32 + _putenv_s(name, value); +#else + setenv(name, value, 0); +#endif +} + +static bool context_ok(const char * path, const llama_model_tensor_buft_override * overrides) { + llama_model_params mparams = llama_model_default_params(); + mparams.n_gpu_layers = 999; + mparams.tensor_buft_overrides = overrides; + + llama_model * model = llama_model_load_from_file(path, mparams); + if (model == nullptr) { + fprintf(stderr, "failed to load %s\n", path); + exit(1); + } + + llama_context_params cparams = llama_context_default_params(); + cparams.n_ctx = 2048; + cparams.n_seq_max = 2; + cparams.kv_unified = true; + cparams.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED; + + llama_context * ctx = llama_init_from_model(model, cparams); + const bool ok = ctx != nullptr; + + llama_free(ctx); + llama_model_free(model); + + return ok; +} + +int main(int argc, char ** argv) { + // read before the model is loaded: latched on first use + set_env_default("LLAMA_EXACT_CONCURRENCY", "1"); + + const char * path = nullptr; + for (int i = 1; i + 1 < argc; ++i) { + if (strcmp(argv[i], "-m") == 0) { + path = argv[i + 1]; + } + } + + if (path == nullptr) { + fprintf(stderr, "usage: %s -m model.gguf\n", argv[0]); + return 1; + } + + ggml_backend_load_all(); + llama_backend_init(); + + if (!context_ok(path, nullptr)) { + printf("%s : skipped, this build and model cannot run exact concurrency\n", __func__); + llama_backend_free(); + return 0; + } + + const llama_model_tensor_buft_override host_norm[] = { + { "^output_norm\\.weight$", ggml_backend_cpu_buffer_type() }, + { nullptr, nullptr }, + }; + + if (context_ok(path, host_norm)) { + fprintf(stderr, "%s : FAIL, output_norm.weight on the host passed the exact concurrency weight check\n", __func__); + llama_backend_free(); + return 1; + } + + printf("%s : all tests passed\n", __func__); + llama_backend_free(); + return 0; +} From eeee4d2d7219b6ce8ec6c6785cc902de646a5de8 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 07:10:39 -0700 Subject: [PATCH 018/109] ggml : document the optional page table in src[5] of ggml_flash_attn_ext --- ggml/include/ggml.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 224bdef927ac..f41d71295086 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2484,6 +2484,8 @@ extern "C" { // n_head % ne32 == 0 // ne3 % ne33 == 0 // + // optional src[5] (pages): [1 + n_pages, n_batch] I32, set by the caller after this call; row i is a count followed by the physical KV page ids query i reads, in logical order + // only the CUDA backend (also its HIP and MUSA builds) uses it, to visit those pages in that order; other backends ignore it and rely on the mask, which must still hide every cell outside those pages GGML_API struct ggml_tensor * ggml_flash_attn_ext( struct ggml_context * ctx, struct ggml_tensor * q, From 3e94edff08e394bfbfbffe80e4b6e51ac072455f Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 06:16:04 -0700 Subject: [PATCH 019/109] server tests: satisfy ty in the preemption tests Mark pytest.skip/pytest.fail calls the way the other server tests do, since ty misreads their positional reason, and type the streamed prompt as text or token ids. --- tools/server/tests/unit/test_preempt.py | 24 +++++++++---------- .../server/tests/unit/test_preempt_notify.py | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index b570873021c5..37b593caf1b2 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -86,7 +86,7 @@ def _log() -> str: def _require_async(text: str): if _ASYNC_BANNER not in text: - pytest.skip("this backend cannot copy asynchronously, the async park path is not exercised") + pytest.skip("this backend cannot copy asynchronously, the async park path is not exercised") # ty: ignore[too-many-positional-arguments] def _complete(n_predict: int, prompt="Hi how are you", id_slot: int = -1, delay: float = 0.0, after_slot_busy=None, @@ -117,7 +117,7 @@ def _wait_processing(slot_ids, timeout: float = 30.0): if all(any(s["id"] == i and s["is_processing"] for s in slots) for i in slot_ids): return time.sleep(0.005) - pytest.fail(f"slots {slot_ids} never showed as processing") + pytest.fail(f"slots {slot_ids} never showed as processing") # ty: ignore[invalid-argument-type] def _complete_overlapping(n_predict, n_prompt, timeout: float = DEFAULT_REQUEST_TIMEOUT): @@ -416,7 +416,7 @@ def run_unending(): break time.sleep(0.05) else: - pytest.fail("the resident never reached the end of the pool") + pytest.fail("the resident never reached the end of the pool") # ty: ignore[invalid-argument-type] waiting = server.make_request("POST", "/completion", data={ "n_predict": 8, "prompt": _prompt_of(1800, _PROMPT_C), @@ -456,7 +456,7 @@ def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): break time.sleep(0.2) else: - pytest.fail("a slot never came back after a cancel during a copy") + pytest.fail("a slot never came back after a cancel during a copy") # ty: ignore[invalid-argument-type] for slot in res.body: assert slot["is_preempted"] is False assert slot["is_transferring"] is False @@ -516,7 +516,7 @@ def test_a_recurrent_model_is_served_without_preemption(): assert "Context size has been exceeded" not in text -def _stream_completion(n_predict: int, prompt: str) -> tuple[list[str], dict]: +def _stream_completion(n_predict: int, prompt: str | list[int]) -> tuple[list[str], dict]: """One streaming completion: its SSE comment lines and the last response object.""" url = f"http://{server.server_host}:{server.server_port}/completion" res = requests.post(url, json={ @@ -592,7 +592,7 @@ def test_an_mtp_draft_stays_inside_the_reservation_it_was_priced_for(): # near the end of the pool the planner prices one draft token and one sampled token, but the draft loop stopped against the configured window and could attempt positions past the reservation path = os.environ.get("LLAMA_SERVER_TEST_MTP_MODEL") if not path: - pytest.skip("set LLAMA_SERVER_TEST_MTP_MODEL to a gguf carrying an MTP head") + pytest.skip("set LLAMA_SERVER_TEST_MTP_MODEL to a gguf carrying an MTP head") # ty: ignore[too-many-positional-arguments] server.model_file = path server.model_hf_repo = server.model_hf_file = None server.spec_type = "draft-mtp" @@ -620,7 +620,7 @@ def test_a_hybrid_model_parks_synchronously(): # the recurrent half of a hybrid gathers the active sequences into contiguous rows on every batch, so a copy running beside the decode could read a row another sequence has been moved into path = os.environ.get("LLAMA_SERVER_TEST_HYBRID_MODEL") if not path: - pytest.skip("set LLAMA_SERVER_TEST_HYBRID_MODEL to a hybrid attention/recurrent gguf") + pytest.skip("set LLAMA_SERVER_TEST_HYBRID_MODEL to a hybrid attention/recurrent gguf") # ty: ignore[too-many-positional-arguments] server.model_file = path server.model_hf_repo = server.model_hf_file = None os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "1" @@ -643,7 +643,7 @@ def test_a_hybrid_model_parks_synchronously(): def _mrope_model() -> str: path = os.environ.get("LLAMA_SERVER_TEST_MROPE_MODEL") if not path: - pytest.skip("set LLAMA_SERVER_TEST_MROPE_MODEL to an M-RoPE gguf") + pytest.skip("set LLAMA_SERVER_TEST_MROPE_MODEL to an M-RoPE gguf") # ty: ignore[too-many-positional-arguments] return path @@ -668,7 +668,7 @@ def test_exact_concurrency_refuses_a_batch_that_cannot_hold_a_whole_ubatch(): # a prompt is added in whole ubatches, so -b 512 -ub 512 -np 2 would leave a prefill 511 tokens beside one decoder: the geometry is refused at startup rather than reported as exact and served short path = os.environ.get("LLAMA_SERVER_TEST_EXACT_MODEL") if not path: - pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") + pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") # ty: ignore[too-many-positional-arguments] proc = subprocess.run([ os.environ.get("LLAMA_SERVER_BIN_PATH", "../../../build/bin/llama-server"), "--model", path, "--host", "127.0.0.1", "--port", str(server.server_port), @@ -716,7 +716,7 @@ def test_exact_concurrency_prefills_a_prompt_in_the_ubatches_it_would_get_alone( # geometry: -b 2048 -ub 512 -np 4, so the batch holds a whole ubatch beside a decode step of every slot (516 tokens), which is what common_exact_batch_geometry() requires of a start path = os.environ.get("LLAMA_SERVER_TEST_EXACT_MODEL") if not path: - pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") + pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") # ty: ignore[too-many-positional-arguments] server.model_file = path server.model_hf_repo = server.model_hf_file = None os.environ["LLAMA_EXACT_CONCURRENCY"] = "1" @@ -757,7 +757,7 @@ def decoder(i): break time.sleep(0.1) else: - pytest.fail("the decoders never started") + pytest.fail("the decoders never started") # ty: ignore[invalid-argument-type] time.sleep(1.0) beside = prefill(50000) @@ -1083,7 +1083,7 @@ def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): break time.sleep(0.005) else: - pytest.fail("the resident never grew into the pool") + pytest.fail("the resident never grew into the pool") # ty: ignore[invalid-argument-type] n_prompt = 500 n_predict = 8 diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py index 420f557fa009..f99712f98d77 100644 --- a/tools/server/tests/unit/test_preempt_notify.py +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -193,7 +193,7 @@ def _resident(): break time.sleep(0.02) else: - pytest.fail("the resident never grew into the pool") + pytest.fail("the resident never grew into the pool") # ty: ignore[invalid-argument-type] res = _post(path, _prefill_payload(path, " ".join([_PROMPT_B] * 31), 8)) assert res.status_code == 200 From 19bd423b890add2558eb991f5b25a3488dcc9965 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 06:34:51 -0700 Subject: [PATCH 020/109] hip: follow the vec kernel's new paged parameter in the VGPR ignore list The paged template parameter adds one bool to flash_attn_ext_vec's mangled name, so the already ignored D=256 q4_0 instance no longer matched its entry. Its register use is unchanged. --- scripts/hip/gcn-cdna-vgpr-check.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/hip/gcn-cdna-vgpr-check.py b/scripts/hip/gcn-cdna-vgpr-check.py index 1f1c2c903bc7..df57fd378ae3 100644 --- a/scripts/hip/gcn-cdna-vgpr-check.py +++ b/scripts/hip/gcn-cdna-vgpr-check.py @@ -82,7 +82,7 @@ def main(): '_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiPfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', '_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiPfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', '_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiPfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', - '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPKcS2_S2_S2_S2_PKiPfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiiil', + '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0ELb0EEvPKcS2_S2_S2_S2_PKiPfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiiil', '_ZL18flash_attn_ext_f16ILi320ELi256ELi2ELi32ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiPfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', } From 6a423332c782411de92e10627e762d3bd60bd89e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 06:40:37 -0700 Subject: [PATCH 021/109] server tests: give the overtaken-head test a stream long enough for slow runners The head re-prefills its 7200 tokens after each of its two parks, which took 46 s on the arm64 ubuntu runner and 92 s on the Windows one, past the 40 s the stream ran for. A starved head waits for as long as the stream lasts, so a longer bound still catches it; the request timeout grows with it. --- tools/server/tests/unit/test_preempt.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 37b593caf1b2..249369b9a449 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1153,7 +1153,8 @@ def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): short_prompt = _prompt_of(1700, _PROMPT_B) head_prompt = _prompt_of(7200, _PROMPT_A) n_short, n_head = 32, 100 - t_stream_max = 40.0 + # a starved head waits for as long as the stream lasts, so any bound catches it; the head prefills its 7200 tokens three times (two parks, no room to keep them), which took 46 s on a CPU CI runner and 92 s on a Windows one + t_stream_max = 240.0 stop = threading.Event() shorts = [] @@ -1175,7 +1176,7 @@ def stream(id_slot): time.sleep(0.01) t_head = time.time() with ThreadPoolExecutor(1) as pool: - fut = pool.submit(_raw_completion, n_head, head_prompt, 3, 180) + fut = pool.submit(_raw_completion, n_head, head_prompt, 3, t_stream_max + 180) while not fut.done() and time.time() - t_head < t_stream_max: time.sleep(0.05) stopped_early = not fut.done() From 419791c739147f29a13d2325a0cad8581cb6c348 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 07:30:25 -0700 Subject: [PATCH 022/109] trim and unwrap comments in the preemption change --- common/common.cpp | 4 +-- ggml/src/ggml-backend.cpp | 5 ++-- ggml/src/ggml-cuda/fattn-common.cuh | 3 +-- src/llama-context.cpp | 4 +-- src/llama-kv-cache.cpp | 12 +++------ src/llama-kv-cache.h | 3 +-- tests/test-event-query.cpp | 5 ++-- tests/test-exact-buft.cpp | 7 ++--- tests/test-exact-geometry.cpp | 8 ++---- tests/test-exact-pages.cpp | 27 +++++++------------ tests/test-rpc-paged-fa.cpp | 6 ++--- tests/test-server-decision-exact.cpp | 5 ++-- tests/test-server-tokens.cpp | 7 ++--- .../server/tests/unit/test_preempt_notify.py | 4 +-- 14 files changed, 35 insertions(+), 65 deletions(-) diff --git a/common/common.cpp b/common/common.cpp index 98847dce260d..33afdf0d7365 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1517,8 +1517,8 @@ bool common_exact_concurrency_init(const common_params & params) { } } - // a prompt is added to a batch in whole ubatches, so a batch that cannot hold one beside a decode step of every slot would leave a prefill shorter ubatches than it gets alone, and the mode would report itself as on while a shared step changed the prompt's arithmetic - // a causal context clamps the batch to the context size, so that is the batch a prefill really gets; an unset -c is only known once the context exists, which common_exact_concurrency_context() checks + // 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; diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index adfbe355ec82..384e34ca8ed0 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -704,9 +704,8 @@ void ggml_backend_event_synchronize(ggml_backend_event_t event) { event->device->iface.event_synchronize(event->device, event); } -// (optional) non-blocking completion test for an event, published by the backend's registry as -// "ggml_backend_dev_event_query" so that ggml_backend_device_i, and with it the backend API version, -// stays as upstream has it. A backend that does not publish it gets the blocking fallback. +// (optional) non-blocking event test, published as "ggml_backend_dev_event_query" so ggml_backend_device_i stays unchanged. +// A backend that does not publish it gets the blocking fallback. typedef bool (*ggml_backend_dev_event_query_t)(ggml_backend_dev_t dev, ggml_backend_event_t event); static ggml_backend_dev_event_query_t ggml_backend_dev_get_event_query(ggml_backend_dev_t device) { diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 7eaa6454d4db..1f1cca882348 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -10,8 +10,7 @@ #define HALF_MAX_HALF __float2half(65504.0f/2) // Use neg. of this instead of -INFINITY to initialize KQ max vals to avoid NaN upon subtraction. #define SOFTMAX_FTZ_THRESHOLD -20.0f // Softmax exp. of values smaller than this are flushed to zero to avoid NaNs. -// [TAG_EXACT_CONCURRENCY] the page table of the paged path, which only the ordinary flash -// attention op carries: another op is free to keep a tensor of its own in the same slot +// [TAG_EXACT_CONCURRENCY] page table of the paged path; only the plain flash attention op carries it in this slot. static __forceinline__ const ggml_tensor * ggml_cuda_fattn_pages(const ggml_tensor * dst) { return dst->op == GGML_OP_FLASH_ATTN_EXT ? dst->src[5] : nullptr; } diff --git a/src/llama-context.cpp b/src/llama-context.cpp index cf8253b80c5f..5b65c6a4738f 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -118,8 +118,8 @@ static llm_graph_type ctx_type_to_graph_type(llama_context_type ctx_type) { throw std::runtime_error("Unsupported ctx type"); } -// [TAG_EXACT_CONCURRENCY] the caches check where the KV lives; this checks the weights. Every weight outside the input layer (per-layer weights, output head, classifier heads, norms) must sit on a backend with the mode's kernels, else a sequence's own ops change with the width of the step it shares. -// Input-layer tensors (token_embd and the other embedding tables) are exempt: they feed GET_ROWS, a per-row copy that reports a batch size of 0 to the offload test, so it stays put at every width. A tied head is that same tensor and model.output points at it, so the head check covers it; a lora on it runs as MUL_MAT, which llama_adapter_lora_init_impl() refuses on a host buffer. +// [TAG_EXACT_CONCURRENCY] every weight outside the input layer must sit on a backend with the mode's kernels, else a sequence's ops change with the step width. +// Embedding tables are exempt: GET_ROWS reports batch size 0 to the offload test; a tied head is model.output, so the head check covers it. static void llama_exact_check_weights(const llama_model & model) { auto host_buft = [](const ggml_tensor * t) -> ggml_backend_buffer_type_t { if (!t || !t->buffer) { diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index fbdae96f2690..c76a7022317b 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -574,10 +574,8 @@ void llama_kv_cache::exact_pages_claim(uint32_t idx, llama_seq_id seq, llama_pos ++exact_page_live[idx/exact_page_size]; } -// [TAG_EXACT_CONCURRENCY] a page stays with its sequence for as long as one of its cells is live, -// so a removal frees it only when it takes the last one. Counting per page is what keeps a removal -// that empties nothing, such as the rejected tail of every accepted speculative step, from costing -// a rescan of the pool. +// [TAG_EXACT_CONCURRENCY] a page stays with its sequence while one of its cells is live, so a removal frees it only when it takes the last one. +// Per-page counts keep a removal that empties nothing (a rejected speculative tail) from rescanning the pool. void llama_kv_cache::exact_pages_release(uint32_t idx) { ++exact_page_n_release; @@ -1045,8 +1043,7 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector states; - // [TAG_EXACT_CONCURRENCY] a placement can purge positions outside the cells it restores below, - // and those are not undone; count removals to notice + // [TAG_EXACT_CONCURRENCY] a placement can purge cells it does not restore below, so count removals to notice. const uint64_t n_release_before = exact_page_n_release; bool success = true; @@ -1081,8 +1078,7 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector state(llama_state_seq_get_size(ctx, 1)); state.resize(llama_state_seq_get_data(ctx, state.data(), state.size(), 1)); @@ -195,8 +189,7 @@ int main(int argc, char ** argv) { return 1; } - // a whole-context state cannot be restored in this mode, so it is not saved either: the size, - // the copy and the session file all fail, and no file is left behind to fail at the next load + // a whole-context state cannot be restored in this mode, so size, copy and session save all fail and leave no file. std::vector whole(state.size() + 4096); if (llama_state_get_size(ctx) != 0 || llama_state_get_data(ctx, whole.data(), whole.size()) != 0) { diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp index a2a6ccf0ed3d..81187a88ec63 100644 --- a/tests/test-rpc-paged-fa.cpp +++ b/tests/test-rpc-paged-fa.cpp @@ -1,7 +1,5 @@ -// [TAG_EXACT_CONCURRENCY] an RPC server refuses a FLASH_ATTN_EXT that carries a page table (src[5]). -// supports_op keeps the scheduler from sending one, but a client can submit any graph, and a paged -// backend would trust the page ids it was given. The server runs on the CPU in a child process and -// each graph is sent from a child of its own, so a refused graph only costs that client its connection. +// [TAG_EXACT_CONCURRENCY] an RPC server must refuse a FLASH_ATTN_EXT with a page table (src[5]), since a client can send any graph. +// The server and each client run in child processes, so a refused graph only drops that client. #include "ggml.h" #include "ggml-alloc.h" diff --git a/tests/test-server-decision-exact.cpp b/tests/test-server-decision-exact.cpp index 87f86e6026f6..7466298bfcbc 100644 --- a/tests/test-server-decision-exact.cpp +++ b/tests/test-server-decision-exact.cpp @@ -1,6 +1,5 @@ -// [TAG_EXACT_CONCURRENCY] a decision request whose questions share a prompt prefix is grouped so the -// children continue from the parent's cells through seq_cp. Exact mode gives a page to one sequence -// and refuses that copy, so the grouping must not happen there: every task keeps its whole prompt. +// [TAG_EXACT_CONCURRENCY] decision questions with a shared prefix are grouped through seq_cp, which exact mode refuses. +// So in exact mode no grouping happens and every task keeps its whole prompt. #include "server-decision.h" diff --git a/tests/test-server-tokens.cpp b/tests/test-server-tokens.cpp index 051e01a15f0d..65290ec4174e 100644 --- a/tests/test-server-tokens.cpp +++ b/tests/test-server-tokens.cpp @@ -1,6 +1,4 @@ -// [TAG_PREEMPT] the server converts between a KV position and a token count when it rewinds a slot to -// what the cache holds. With M-RoPE media the two differ, so the conversion is exercised here on a -// hand-built image chunk, without a model. +// [TAG_PREEMPT] KV position and token count differ with M-RoPE media, so test the rewind conversion on a hand-built image chunk. #include "server-common.h" @@ -16,8 +14,7 @@ #undef NDEBUG #include -// the wire format of mtmd_input_chunk_save(), which needs a context to produce a chunk; written here so -// that a chunk of a known shape can be loaded without one +// the mtmd_input_chunk_save() wire format, written by hand so a chunk loads without a context. struct chunk_writer { std::vector buf; diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py index f99712f98d77..561641d2cc70 100644 --- a/tools/server/tests/unit/test_preempt_notify.py +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -251,9 +251,7 @@ def test_a_rotation_tells_both_streams_and_a_head_parked_past_the_budget_is_kept _start(n_slots=3, n_ctx=2048, enable_ctx_shift=True) n_predict = 12000 - # the default parked keepalive is 2 s, which is also when a resident is rotated out for the head: - # a park that ends with that rotation could beat its own keepalive. Ask for a 1 s ping instead, so - # any park that outlasts one rotation window is still required to say so + # the default 2 s keepalive equals the rotation window, so a park could end before its ping; ask for 1 s instead. results = _stream_all(n_predict, (_PROMPT_A, _PROMPT_B, _PROMPT_C), sse_ping_interval=1) n_parked = n_keepalive = 0 for comments, datas in results: From d2b16e6404b67b413b8622ef10745582ba703b25 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 08:01:02 -0700 Subject: [PATCH 023/109] server tests: run the 24k-token rotation regression in the slow suite It generates 16000 and then 8000 tokens with waits of up to 900 s, and tests.sh runs every unmarked test twice, once with backend sampling. --- tools/server/tests/unit/test_preempt.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 249369b9a449..bc84edf8b947 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1203,6 +1203,7 @@ def stream(id_slot): assert max(waits) < 10.0, f"the head waited {waits} s behind requests that came after it" +@pytest.mark.slow def test_a_long_resident_that_never_shifts_is_rotated_out_for_an_aged_head(): # only a resident cycling through context shifts used to be rotated, so a long generation that fits the pool held it to the end, and the parked slot waited for all of it _serve_with_training_context(16384) From f7cdcb8b1935a66a2f06d69f14e04e563f244b53 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 08:01:02 -0700 Subject: [PATCH 024/109] server: describe preempt_ram_bytes as all host RAM held for parking A restored slot keeps its pinned buffer for reuse, and that capacity is still allocated and still counts against --preempt-ram, so the gauge reports it; the help text and README said parked sequences only. --- tools/server/README.md | 2 +- tools/server/server-task.cpp | 2 +- tools/server/server-task.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/server/README.md b/tools/server/README.md index 2893283e7357..d60593d28ad7 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -1166,7 +1166,7 @@ In *router mode* the query param `?model={model_id}` has to be set. This endpoin | `llamacpp:n_resume_total` | Counter | Parked slots put back. | | `llamacpp:preempt_recompute_total` | Counter | Parks that dropped their cells because `--preempt-ram` was spent, so the resume re-prefills the sequence instead of restoring its saved bytes. | | `llamacpp:requests_preempted` | Gauge | Requests currently parked for room in the unified KV cache, including those whose copy out or back in is still in flight (the `/slots` entries with `is_preempted` or `is_transferring`). None of them is decoding. | -| `llamacpp:preempt_ram_bytes` | Gauge | Host RAM held by parked sequences. | +| `llamacpp:preempt_ram_bytes` | Gauge | Host RAM held for parking: parked sequences plus the pinned buffers kept for reuse after a restore, which count against `--preempt-ram`. | ### POST `/slots/{id_slot}?action=save`: Save the prompt cache of the specified slot to a file. diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 0a5dbf24225e..b22371f863c8 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1633,7 +1633,7 @@ std::string server_task_result_metrics::to_metrics() { (double) n_preempted_slots }, { "preempt_ram_bytes", - "Preemption: Host RAM held by parked sequences", + "Preemption: Host RAM held for parking: parked sequences plus the pinned buffers kept for reuse after a restore", (double) preempt_ram_bytes }, }; diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 6bb5db8baaa9..941fad0e552d 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -568,7 +568,7 @@ struct server_task_result_metrics : server_task_result { int n_processing_slots = 0; int n_tasks_deferred = 0; int n_preempted_slots = 0; // [TAG_PREEMPT] processing slots currently parked or moving to or from host memory - size_t preempt_ram_bytes = 0; // [TAG_PREEMPT] host RAM their parked sequences hold + size_t preempt_ram_bytes = 0; // [TAG_PREEMPT] host RAM held for parking, including buffers kept after a restore server_metrics metrics; From 9fb7fd81357f05e08e034a573b93a2f45e66040a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 08:37:23 -0700 Subject: [PATCH 025/109] server tests: give the whole-prompt test two different prompts With the same prompt twice, the parked one could come back on the slot the first had just finished on and reuse its cached cells, so prompt_n was 1 (seen on the windows runner). --- tools/server/tests/unit/test_preempt.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index bc84edf8b947..2ece78eef16e 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -340,8 +340,8 @@ def test_a_prompt_parked_before_its_first_token_is_issued_whole(): n_prompt = 240 n_predict = 4 - long_prompt = _prompt_of(n_prompt, "Once upon a time there was a little girl") - together = _complete_all(n_predict, [long_prompt, long_prompt]) + # two different prompts: with the same one, the second can be served from the first one's cached cells after it finishes, and prompt_n is then 1 + together = _complete_all(n_predict, [_prompt_of(n_prompt, _PROMPT_A), _prompt_of(n_prompt, _PROMPT_B)]) assert "cannot fit the pool" not in _log() _assert_completed(together, n_predict) From 24bec04608b86fba68aaf43f449963d7d37a7109 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 13 Oct 2026 08:59:49 -0700 Subject: [PATCH 026/109] trim comments in the preemption change --- common/common.cpp | 10 +- common/common.h | 2 +- ggml/include/ggml.h | 4 +- ggml/src/ggml-cpu/ggml-cpu.cpp | 2 +- ggml/src/ggml-cuda/ggml-cuda.cu | 20 +- ggml/src/ggml-cuda/mmvq.cu | 6 +- ggml/src/ggml-rpc/ggml-rpc.cpp | 2 +- include/llama.h | 4 +- src/llama-adapter.cpp | 2 +- src/llama-batch.cpp | 2 +- src/llama-context.cpp | 44 +-- src/llama-context.h | 2 +- src/llama-impl.cpp | 4 +- src/llama-kv-cache.cpp | 22 +- src/llama-kv-cache.h | 2 +- src/llama-memory.h | 2 +- tests/test-exact-weights.cpp | 2 +- tests/test-state-seq-copy.cpp | 2 +- tools/server/server-context.cpp | 335 +++++++++--------- tools/server/server-decision.cpp | 2 +- tools/server/server-queue.cpp | 4 +- tools/server/server-task.h | 2 +- tools/server/tests/unit/test_preempt.py | 153 ++++---- .../server/tests/unit/test_preempt_notify.py | 14 +- 24 files changed, 317 insertions(+), 327 deletions(-) diff --git a/common/common.cpp b/common/common.cpp index 33afdf0d7365..84bc5a5801e5 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1239,7 +1239,7 @@ 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] before any context exists, so one is never created under a figure the explicit bound does not cover + // [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"); return; @@ -1472,7 +1472,7 @@ bool common_exact_concurrency_model(const common_params & params, const llama_mo return true; } - // the paged pool places a cell from the sequence and the position alone, and M-RoPE gives every token of one image the same temporal position, so the second of them lands on the first one's cell and the batch is refused at the first image + // 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) { @@ -1488,7 +1488,7 @@ bool common_exact_concurrency_init(const common_params & params) { return true; } - // DFlash drafting turns causal attention off on its draft context, which the paged attention needs; say so instead of asserting in the graph. DSpark is the same. + // 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"); @@ -1533,7 +1533,7 @@ bool common_exact_concurrency_init(const common_params & params) { return false; } - // the batch splitter isolates prompts by width, so tell it how wide one sequence's decode step is; this also covers a caller that decodes before creating a context + // 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"); @@ -1554,7 +1554,7 @@ bool common_exact_concurrency_context(const common_params & params, const llama_ return false; // already reported by common_exact_concurrency_init() } - // the context clamps the batch to the context size and the ubatch to the batch, and an unset -c takes its size from the model or from the fit to device memory, so this is the geometry a prefill really gets + // 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); diff --git a/common/common.h b/common/common.h index b4f557115209..6e2ca06f902e 100644 --- a/common/common.h +++ b/common/common.h @@ -1009,7 +1009,7 @@ 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, which a prefill needs to be split into the ubatches it would get alone; n_batch_min reports the batch size that would +// [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 diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index f41d71295086..d238cf7ea78c 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2484,8 +2484,8 @@ extern "C" { // n_head % ne32 == 0 // ne3 % ne33 == 0 // - // optional src[5] (pages): [1 + n_pages, n_batch] I32, set by the caller after this call; row i is a count followed by the physical KV page ids query i reads, in logical order - // only the CUDA backend (also its HIP and MUSA builds) uses it, to visit those pages in that order; other backends ignore it and rely on the mask, which must still hide every cell outside those pages + // optional src[5] (pages): [1 + n_pages, n_batch] I32, set after this call; row i is a count then the physical KV page ids query i reads, in logical order. + // Only the CUDA backend (incl. HIP and MUSA) reads it; others ignore it and rely on the mask, which must still hide every cell outside those pages. GGML_API struct ggml_tensor * ggml_flash_attn_ext( struct ggml_context * ctx, struct ggml_tensor * q, diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index 31f66b9a8fbe..a8e6a69f3a66 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -481,7 +481,7 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st return ggml_is_contiguous(op->src[0]); case GGML_OP_SSM_SCAN: return ggml_get_op_params_i32(op, 0) == 1 || op->src[3]->ne[0] == 1; - // [TAG_EXACT_CONCURRENCY] note: FLASH_ATTN_EXT with src[5], the page table, is deliberately still accepted: the CPU ignores it, but it is the reference test-backend-ops uses + // [TAG_EXACT_CONCURRENCY] FLASH_ATTN_EXT with a page table in src[5] is still accepted: the CPU ignores it, and it is the test-backend-ops reference. default: return true; } diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 56b4998bd333..737273fd73c5 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -1795,7 +1795,7 @@ static bool ggml_cuda_should_fuse_mul_mat(const ggml_tensor * ffn_up, } static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor) { - // [TAG_BATCH_INVARIANT] mul_mat+GLU is fused for a single destination column only, so leaving it on would give a solo request a different code path from a batched one + // [TAG_BATCH_INVARIANT] mul_mat+GLU fuses only for one destination column, so a solo request would take a different path from a batched one. if (ggml_cuda_batch_invariant()) { return false; } @@ -2031,7 +2031,7 @@ static ggml_cuda_mm_path ggml_cuda_mul_mat_path( static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); -// [TAG_BATCH_INVARIANT] the widest slice of columns that can be recomputed in one launch while every column still sums as a batch of one; always below ncols_dst, so the recursion ends +// [TAG_BATCH_INVARIANT] The widest column slice one launch can compute with batch-of-one sums; always below ncols_dst, so the recursion ends. static int64_t ggml_cuda_mul_mat_invariant_width( int cc, int warp_size, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst, ggml_cuda_mm_path path_one, int64_t ncols_dst) { @@ -2086,9 +2086,9 @@ static bool ggml_cuda_mul_mat_split_columns( return false; } - // mode 1 recomputes one column at a time; mode 2, which exact concurrency runs under, uses the widest slices that keep the batch-of-one arithmetic + // Mode 1 recomputes one column at a time; mode 2 (used by exact concurrency) uses the widest slices that keep batch-of-one arithmetic. int64_t width = 1; - // F32 weights go one column at a time: the predictor cannot see precision rules another pin adds to the dispatch for them + // F32 weights go one column at a time: the predictor cannot see precision rules other pins add for them. if (ggml_cuda_batch_invariant() >= 2 && src0->type != GGML_TYPE_F32) { const ggml_cuda_mm_path path_one = ggml_cuda_mul_mat_path(cc, warp_size, src0, src1, dst, 1); const ggml_cuda_mm_path path_batched = ggml_cuda_mul_mat_path(cc, warp_size, src0, src1, dst, ncols_dst); @@ -2136,7 +2136,7 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor return; } - // [TAG_BATCH_INVARIANT] ahead of the dispatch below, which is left as upstream wrote it so other pins that edit it still merge + // [TAG_BATCH_INVARIANT] Placed before the upstream dispatch, left unchanged so other pins still merge. if (ggml_cuda_batch_invariant() && ggml_cuda_mul_mat_split_columns(ctx, ggml_cuda_info().devices[ctx.device].cc, ggml_cuda_info().devices[ctx.device].warp_size, src0, src1, dst)) { @@ -2217,7 +2217,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c return true; } - // [TAG_BATCH_INVARIANT] a split node runs as ntokens single-token calls, so the path that decides whether the stream is synchronized is the single-token one + // [TAG_BATCH_INVARIANT] A split node runs as single-token calls, so the single-token path decides stream synchronization. const int64_t ntokens = ggml_cuda_mul_mat_id_splits_tokens(dst) ? 1 : dst->ne[2]; if (ntokens <= MMVQ_MAX_BATCH_SIZE) { @@ -2247,7 +2247,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst); -// [TAG_BATCH_INVARIANT] recompute dst one token at a time: every implementation below groups the ubatch's tokens by the expert they routed to, so shapes depend on the other tokens +// [TAG_BATCH_INVARIANT] Recompute dst one token at a time: every implementation below groups tokens by expert, so shapes depend on the other tokens. static void ggml_cuda_mul_mat_id_split_tokens(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * src1 = dst->src[1]; const ggml_tensor * ids = dst->src[2]; @@ -2294,7 +2294,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * // [TAG_BATCH_INVARIANT] if (ggml_cuda_mul_mat_id_splits_tokens(dst)) { GGML_ASSERT(ne3 == 1 && src1->ne[3] == 1 && ids->ne[2] == 1 && ids->ne[3] == 1); - // a quantized expert matrix takes the single-token MMVQ path at every token count and can put the tokens on its sample axis in one launch; anything else goes token by token + // Quantized experts use single-token MMVQ with tokens on the sample axis in one launch; anything else goes token by token. if (ggml_is_quantized(src0->type) && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst); return; @@ -3977,7 +3977,7 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph } //topk-moe - // [TAG_BATCH_INVARIANT] the routing fusion passes its memory-range check only for a one-token ubatch, so a solo request takes the fused top-k kernel and a batched one the long chain + // [TAG_BATCH_INVARIANT] The routing fusion only passes its range check for one-token ubatches, so solo and batched runs would take different kernels. if (!ggml_cuda_batch_invariant() && (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX || cgraph->nodes[i]->op == GGML_OP_ARGSORT)) { @@ -6208,7 +6208,7 @@ static bool ggml_backend_cuda_device_event_query(ggml_backend_dev_t dev, ggml_ba const cudaError_t err = cudaEventQuery((cudaEvent_t)event->context); - // not an error, and nothing to clear: cudaEventQuery() returns cudaErrorNotReady without recording it, so collecting one here would consume somebody else's + // cudaEventQuery() returns cudaErrorNotReady without recording it, so do not collect an error here or it would consume someone else's. if (err == cudaErrorNotReady) { return false; } diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 0ad0d293b37a..7c53edd6a593 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -606,7 +606,7 @@ bool ggml_cuda_mmvq_matches_single_column(enum ggml_type type, int cc, int64_t n // There nwarps also depends on the K loop trip count, which the caller does not pass in. return ncols_dst == 1; } - // blocks_per_iter, which assigns K blocks to threads, is proportional to nwarps; rows_per_cuda_block only changes which rows a block owns, not the order within a row + // blocks_per_iter (K blocks per thread) scales with nwarps; rows_per_cuda_block only changes which rows a block owns, not the order within a row. return calc_nwarps(type, 1, table_id) == calc_nwarps(type, (int) ncols_dst, table_id); } @@ -653,7 +653,7 @@ static __global__ void mul_mat_vec_q( ggml_cuda_pdl_sync(); sample_dst = blockIdx.z; - // [TAG_BATCH_INVARIANT] with ids, a sample is a token: every token goes on the z axis of one single-column launch, so each (token, expert slot) block runs the single-token configuration + // [TAG_BATCH_INVARIANT] With ids each token goes on the z axis of one single-column launch, so every (token, expert) block runs the single-token configuration. channel_x = shared_expert ? 0 : ncols_dst == 1 && ids ? ids[sample_dst*ids_stride + channel_dst] : fastdiv(channel_dst, channel_ratio); channel_y = ncols_dst == 1 && ids ? fastmodulo(channel_dst, nchannels_y) : channel_dst; @@ -1466,7 +1466,7 @@ void ggml_cuda_mul_mat_vec_q( GGML_ASSERT( nb0 == ts_dst); GGML_ASSERT(!ids || ids->nb[0] == ggml_type_size(ids->type)); - // [TAG_BATCH_INVARIANT] a multi-token MUL_MAT_ID becomes one launch of the single-token configuration with the tokens on the sample axis, so the count is not bounded by the column templates + // [TAG_BATCH_INVARIANT] Multi-token MUL_MAT_ID is one single-token launch with tokens on the sample axis, so the count is not bounded by the column templates. const bool tokens_as_samples = ids && ne2 > 1 && ggml_cuda_batch_invariant(); GGML_ASSERT(!ids || ne12 <= MMVQ_MAX_BATCH_SIZE || tokens_as_samples); diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index 5b6ffa4e06e2..c85b436c9959 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -2146,7 +2146,7 @@ bool rpc_server::graph_compute(const std::vector & input) { LOG_ERROR("[%s] failed to create graph node %d (id=%" PRId64 ")\n", __func__, i, id); return false; } - // [TAG_EXACT_CONCURRENCY] supports_op never offers a page table to RPC, so a graph carrying one is not from a ggml scheduler, and the backend would trust its page ids and counts + // [TAG_EXACT_CONCURRENCY] supports_op never offers RPC a page table, so a graph with one is not from a scheduler and its page ids cannot be trusted. if (graph->nodes[i] != nullptr && graph->nodes[i]->op == GGML_OP_FLASH_ATTN_EXT && graph->nodes[i]->src[5] != nullptr) { LOG_ERROR("[%s] graph node %d (id=%" PRId64 ") is a paged FLASH_ATTN_EXT, which RPC does not support\n", __func__, i, id); return false; diff --git a/include/llama.h b/include/llama.h index 505f0bd4a441..0be310bca764 100644 --- a/include/llama.h +++ b/include/llama.h @@ -977,7 +977,7 @@ extern "C" { LLAMA_API struct llama_state_seq_copy * llama_state_seq_copy_init(struct llama_context * ctx); LLAMA_API void llama_state_seq_copy_free(struct llama_state_seq_copy * cpy); - // size the transfer's host buffer, keeping no contents; NULL on failure. Grow-only: page-locking is far too slow to redo per transfer, so only llama_state_seq_copy_buf_free() frees it. + // Size the transfer's host buffer, keeping no contents; NULL on failure. Grow-only, since page-locking is too slow to redo; only llama_state_seq_copy_buf_free() frees it. LLAMA_API uint8_t * llama_state_seq_copy_buf_resize (struct llama_state_seq_copy * cpy, size_t size); LLAMA_API uint8_t * llama_state_seq_copy_buf (struct llama_state_seq_copy * cpy); LLAMA_API size_t llama_state_seq_copy_buf_size (struct llama_state_seq_copy * cpy); @@ -989,7 +989,7 @@ extern "C" { LLAMA_API bool llama_state_seq_copy_buf_can_pin(struct llama_state_seq_copy * cpy); - // issue the copies; the bytes covered, 0 on failure. size must be within llama_state_seq_copy_buf_size(), and LLAMA_STATE_SEQ_FLAGS_ON_DEVICE is refused. + // Issue the copies; returns bytes covered, 0 on failure. size must fit llama_state_seq_copy_buf_size(); LLAMA_STATE_SEQ_FLAGS_ON_DEVICE is refused. LLAMA_API size_t llama_state_seq_copy_get( struct llama_state_seq_copy * cpy, size_t size, diff --git a/src/llama-adapter.cpp b/src/llama-adapter.cpp index ea8c604cc3eb..e1c0038c35ff 100644 --- a/src/llama-adapter.cpp +++ b/src/llama-adapter.cpp @@ -358,7 +358,7 @@ static void llama_adapter_lora_init_impl(llama_model & model, FILE * file, llama LLAMA_LOG_DEBUG("%s: lora for '%s' -> '%s'\n", __func__, model_tensor->name, ggml_backend_buft_name(buft)); - // [TAG_EXACT_CONCURRENCY] the adapter follows its weight's buffer; a host token_embd passes the context check (get_rows) but its adapter is a mul_mat, see build_inp_embd() + // [TAG_EXACT_CONCURRENCY] The adapter follows its weight's buffer; a host token_embd passes the get_rows check but its adapter is a mul_mat, see build_inp_embd(). if (llama_exact_concurrency() && !llama_exact_buft_invariant(buft)) { LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but the lora for '%s' would sit in a %s " "buffer, which has no batch-invariant kernels: the adapted matmul's result would " diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index 26b60fbc986a..dd837374baa5 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -699,7 +699,7 @@ llama_ubatch llama_batch_allocr::split_equal(uint32_t n_ubatch, bool sequential, } if (add) { - // [TAG_EXACT_CONCURRENCY] a set with more tokens left than a decode step carries is a prompt and gets a ubatch of its own; grouped sets need equal tokens left, or the expansion below changes their sum order + // [TAG_EXACT_CONCURRENCY] A set with more tokens left than a decode step is a prompt and gets its own ubatch; grouped sets need equal tokens left, or the sum order changes. if (isolate_seqs_above > 0) { uint32_t n_left = 0; diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 5b65c6a4738f..2630e592e031 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -645,7 +645,7 @@ llama_context::~llama_context() { // wait for any pending asynchronous copies into the output buffers before they are freed synchronize(); - // a transfer still alive is drained first: synchronize() covers the graph backends, not the copy backend a transfer owns, and its KV buffers are about to go + // Drain live transfers first: synchronize() does not cover their copy backends, and the KV buffers are about to go. state_seq_copies_drain(); for (auto & it : state_copy_fences) { @@ -2991,7 +2991,7 @@ class llama_io_write_dummy : public llama_io_write_i { size_t size_written = 0; }; -// [TAG_STATE_COALESCE] one transfer per run of cells, not one per cell; the restore side asks for one per cell, and the transposed V layout repeats every run once per row +// [TAG_STATE_COALESCE] One transfer per run of cells, not per cell; the transposed V layout repeats every run once per row. template static size_t llama_io_run_end(const std::vector & infos, size_t i) { size_t end = i + 1; @@ -3017,7 +3017,7 @@ static size_t llama_io_run_size(const std::vector & infos, size_t i, siz return size; } -// [TAG_STATE_COALESCE] a comb of equal runs at a constant stride is one strided copy: sequences sharing a unified cache take their cells in turn +// [TAG_STATE_COALESCE] Equal runs at a constant stride (sequences interleaved in a unified cache) are one strided copy. template static void llama_io_emit(const std::vector & infos, size_t first, size_t last, emit_t emit) { std::vector> runs; @@ -3180,7 +3180,7 @@ class llama_io_read_host : public llama_io_read_i { while (end < rinfos.size() && rinfos[end].tensor == tensor) { end++; } - // [TAG_STATE_COALESCE] the restore emits one fragment per cell, but the cost is the number of runs of adjacent cells, so count runs before falling back to staging + // [TAG_STATE_COALESCE] The cost is the number of runs of adjacent cells, not fragments, so count runs before falling back to staging. const size_t tensor_bytes = ggml_nbytes(tensor); auto * buffer = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; @@ -3657,7 +3657,7 @@ size_t llama_context::state_set_data(const uint8_t * src, size_t size) { } } -// [TAG_STATE_ASYNC] a sequence state transfer that runs beside the decode instead of in it: the host buffer, one backend per device, each with its own stream, and one event per device +// [TAG_STATE_ASYNC] A sequence state transfer that runs beside the decode: a host buffer, plus one backend, stream and event per device. struct llama_state_seq_copy { llama_context * ctx = nullptr; @@ -3696,7 +3696,7 @@ struct llama_state_seq_copy { } } - // the stream this tensor is copied on, or null when it needs none: a host tensor is a memcpy, and a split buffer fails every backend's async copy assert + // The copy stream for this tensor, or null: a host tensor is a memcpy, and a split buffer fails every backend's async copy assert. ggml_backend_t backend_for(const ggml_tensor * t) { ggml_backend_buffer_t buf = t->view_src ? t->view_src->buffer : t->buffer; @@ -3732,7 +3732,7 @@ struct llama_state_seq_copy { } } - // order the copies behind the compute already queued on each device: the copy stream waits for the context's fence, recorded at the end of every decode + // Order the copies after compute already queued: the copy stream waits for the fence recorded at the end of every decode. void order_after(const std::map & fences) { for (auto & it : devs) { const auto fence = fences.find(it.first); @@ -3743,7 +3743,7 @@ struct llama_state_seq_copy { } } - // order the context's compute behind the copies just recorded, for a restore only: its copies write KV cells while other sequences read every cell up to n_kv + // For restores, order compute after the copies: they write KV cells while other sequences read every cell up to n_kv. void order_before(const std::vector & compute) { for (auto & it : devs) { if (!it.second.pending) { @@ -3788,7 +3788,7 @@ struct llama_state_seq_copy { } } - // grow-only: pinning host memory costs about as long as the copy it is for, and a caller parking the same sequence asks for a slightly different size each time + // Grow-only: pinning costs about as much as the copy, and re-parks ask for slightly different sizes. uint8_t * buf_resize(size_t size_new) { if (size_new <= capacity) { size = size_new; @@ -3826,7 +3826,7 @@ struct llama_state_seq_copy { data = base; size = size_new; capacity = size_new; - // a host buffer type may quietly hand back ordinary memory when pinning is off, so believe the buffer that came back rather than the type + // A host buffer type may return ordinary memory when pinning is off, so trust the returned buffer, not the type. pinned = can_pin && ggml_backend_buffer_get_type(buf) == host_buft; return data; @@ -3862,7 +3862,7 @@ class llama_io_write_host_async : public llama_io_write_host { llama_io_write_host_async(uint8_t * p, size_t len, llama_state_seq_copy & cpy) : llama_io_write_host(p, len, true), cpy(cpy) {} - // posted from the destructor, and only once serialisation reached the end: a caller told of a partial failure by a zero return is free to reuse the buffer at once + // Posted from the destructor, only if serialisation completed: after a zero return the caller may reuse the buffer at once. void commit() { committed = true; } @@ -3890,13 +3890,13 @@ class llama_io_write_host_async : public llama_io_write_host { bool committed = false; }; -// [TAG_STATE_ASYNC] the read half of the same, without llama_io_read_host's whole-tensor staging: a write-back would undo whatever the sequences sharing the tensor wrote while these copies ran +// [TAG_STATE_ASYNC] Read side, without llama_io_read_host's whole-tensor staging: a write-back would undo writes by sequences sharing the tensor. class llama_io_read_host_async : public llama_io_read_host { public: llama_io_read_host_async(const uint8_t * p, size_t len, llama_state_seq_copy & cpy) : llama_io_read_host(p, len, true), cpy(cpy) {} - // see llama_io_write_host_async::commit(): a restore that failed part way has dropped the sequence, and copies posted for it would write cells that are no longer its own + // See llama_io_write_host_async::commit(): a failed restore dropped the sequence, so its copies would write cells it no longer owns. void commit() { committed = true; } @@ -4033,7 +4033,7 @@ void llama_context::state_seq_copy_fence() { } llama_state_seq_copy * llama_context::state_seq_copy_init() { - // [TAG_STATE_ASYNC] a recurrent state keeps no fixed row: find_slot() gathers the live rows together, so a decode beside a transfer moves or overwrites the row the transfer reads. A hybrid carries that half too + // [TAG_STATE_ASYNC] Recurrent states have no fixed row: find_slot() compacts live rows, so a decode beside a transfer can move the row being read. Hybrids too. if (llm_arch_is_recurrent(model.arch) || llm_arch_is_hybrid(model.arch)) { LLAMA_LOG_INFO("%s: this model moves sequence states between rows, so they are copied synchronously\n", __func__); return nullptr; @@ -4057,7 +4057,7 @@ llama_state_seq_copy * llama_context::state_seq_copy_init() { continue; } - // a device that advertises events but does not implement event_query makes the first poll wait for the whole copy, so leave it out and let state_seq_copy_init() return NULL + // A device with events but no event_query would make the first poll block on the whole copy, so skip it and let state_seq_copy_init() return NULL. if (!ggml_backend_dev_supports_event_query(dev)) { static std::atomic warned(false); @@ -4069,7 +4069,7 @@ llama_state_seq_copy * llama_context::state_seq_copy_init() { continue; } - // a backend of its own, not the one the graphs are computed on: that one moves its copies to whichever stream it is using, so a transfer could end up ordered behind a graph + // A separate backend: the graph backend moves copies to whichever stream it uses, which could order a transfer behind a graph. ggml_backend_t backend_cpy = ggml_backend_dev_init(dev, nullptr); if (!backend_cpy) { @@ -4093,7 +4093,7 @@ llama_state_seq_copy * llama_context::state_seq_copy_init() { return nullptr; } - // the devices above are the ones the graphs run on, not the ones the state lives on: with most layers on the CPU every copy takes the synchronous branch of backend_for() + // These are the graph devices, not where the state lives: with most layers on the CPU every copy takes the synchronous branch of backend_for(). if (memory) { bool on_device = false; @@ -4121,7 +4121,7 @@ llama_state_seq_copy * llama_context::state_seq_copy_init() { cpy->can_pin = cpy->host_buffer_type() != ggml_backend_cpu_buffer_type(); - // one fence per device, shared by every transfer and recorded after every decode; installed only after the checks above, so a refused transfer leaves nothing behind + // One fence per device, shared by all transfers and recorded after every decode; installed after the checks so a refused transfer leaves nothing. std::vector fences_new; for (const auto & it : cpy->devs) { @@ -4153,13 +4153,13 @@ llama_state_seq_copy * llama_context::state_seq_copy_init() { } size_t llama_context::state_seq_copy_get(llama_state_seq_copy & cpy, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) { - // the library owns this buffer, so the extent can be checked instead of believed: every bounds check validates against it, so an oversized one agrees and the copy overruns + // The library owns this buffer, so check the extent against it; trusting an oversized value would pass every bounds check and overrun. if (!cpy.data || size == 0 || size > cpy.size) { LLAMA_LOG_ERROR("%s: cannot cover %zu bytes, the transfer's buffer holds %zu\n", __func__, size, cpy.size); return 0; } - // LLAMA_STATE_SEQ_FLAGS_ON_DEVICE has nowhere to leave the data here, and get_size_ext() with that flag reports a metadata-sized state, so the two cannot be paired + // ON_DEVICE has nowhere to put the data here, and get_size_ext() reports a metadata-only size with it, so they cannot be paired. if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) { LLAMA_LOG_ERROR("%s: LLAMA_STATE_SEQ_FLAGS_ON_DEVICE is not supported here, the copies go through host memory\n", __func__); return 0; @@ -4199,7 +4199,7 @@ size_t llama_context::state_seq_copy_set(llama_state_seq_copy & cpy, size_t size return 0; } - // the cells this restore was given may still be read, masked, by a graph in flight, so the copy stream waits for the compute stream on the device, see order_after() + // A graph in flight may still read these cells (masked), so the copy stream waits for compute, see order_after(). const int64_t t_sync = ggml_time_us(); cpy.order_after(state_copy_fences); cpy.t_sync_us = ggml_time_us() - t_sync; @@ -4402,7 +4402,7 @@ size_t llama_context::state_write_data(llama_io_write_i & io) { } size_t llama_context::state_read_data(llama_io_read_i & io) { - // [TAG_EXACT_CONCURRENCY] a whole-context restore writes cells at their recorded physical index, which the paged pool owns; refused before anything is parsed + // [TAG_EXACT_CONCURRENCY] A whole-context restore writes cells at recorded physical indices, which the paged pool owns; refused before parsing. if (memory && memory->alloc_granularity() > 1) { throw std::runtime_error("whole-context restore is not supported with LLAMA_EXACT_CONCURRENCY, restore per sequence"); } diff --git a/src/llama-context.h b/src/llama-context.h index 3c9bdd480572..af1609521e5b 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -411,7 +411,7 @@ struct llama_context { // [TAG_STATE_ASYNC] one event per device that copies asynchronously, recorded on the compute stream at the end of every decode; see state_seq_copy_fence() std::map state_copy_fences; - // transfers alive on this context; the fences go when the last one does, and a context freed with transfers still alive drains them and lets them go first + // Live transfers; the fences go with the last one, and freeing the context drains live transfers first. std::set state_copies; // training diff --git a/src/llama-impl.cpp b/src/llama-impl.cpp index a00fb0c507d8..99fe83823c1e 100644 --- a/src/llama-impl.cpp +++ b/src/llama-impl.cpp @@ -211,7 +211,7 @@ bool llama_exact_backend_name(const char * reg_name) { return reg_name && (strcmp(reg_name, "CUDA") == 0 || strcmp(reg_name, "ROCm") == 0 || strcmp(reg_name, "MUSA") == 0); } -// [TAG_EXACT_CONCURRENCY] a host buffer is the case that matters: the scheduler runs an op on the backend that holds its weight, and moves a host weight's op to the GPU only once the batch is wide enough (ggml_backend_cuda_device_offload_op). +// [TAG_EXACT_CONCURRENCY] Host buffers matter: an op runs where its weight lives, and a host weight's op moves to the GPU only for wide batches (ggml_backend_cuda_device_offload_op). // The CPU matmul picks between its SGEMM and its vector dot by the batch width too. bool llama_exact_buft_invariant(ggml_backend_buffer_type_t buft) { if (!buft || ggml_backend_buft_is_host(buft)) { @@ -236,7 +236,7 @@ bool llama_exact_concurrency() { // [TAG_EXACT_CONCURRENCY] tokens one sequence contributes to a decode step, see llama.h static std::atomic g_exact_decode_tokens{1}; -// one lock for the token figure, the sequence count and the width: a report interleaved with a change of figure could leave the backend with a width that covers neither +// One lock for token figure, sequence count and width, so an interleaved report cannot leave a width that covers neither. static std::recursive_mutex g_exact_mutex; // the most sequences any context was created with; the tokens figure is process wide, so raising it re-reports every context's width diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index c76a7022317b..00b0c5a135f2 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -77,7 +77,7 @@ static bool llama_dev_has_paged_attn(ggml_backend_dev_t dev) { return llama_exact_backend_name(ggml_backend_reg_name(reg)); } -// [TAG_EXACT_CONCURRENCY] whether the device can actually run the paged attention op for a layer of this shape: the registry name only says which backends carry the kernels +// [TAG_EXACT_CONCURRENCY] Whether the device can run paged attention for this layer shape; the registry name only says which backends carry the kernels. static bool llama_dev_supports_paged_attn( ggml_backend_dev_t dev, ggml_type type_k, ggml_type type_v, @@ -149,7 +149,7 @@ llama_kv_cache::llama_kv_cache( v_cells_impl(other ? other->v_cells_impl : std::make_shared()), v_cells(*v_cells_impl) { - // [TAG_EXACT_CONCURRENCY] read the knob through the same cached reader the graph and the CUDA dispatcher use, so a mid-process change cannot leave them disagreeing + // [TAG_EXACT_CONCURRENCY] Use the same cached reader as the graph and CUDA dispatcher so they cannot disagree. exact_pages = llama_exact_concurrency(); // shared cells view the source cache's K/V tensors, so the cell count @@ -309,7 +309,7 @@ llama_kv_cache::llama_kv_cache( LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name); - // [TAG_EXACT_CONCURRENCY] the paged kernel handles 256-wide K and V heads only; any other width would run unpaged while the mode reports itself as on + // [TAG_EXACT_CONCURRENCY] The paged kernel only handles 256-wide K and V heads; other widths would silently run unpaged. if (exact_pages && (hparams.n_embd_head_k(il) != 256 || (!is_mla && hparams.n_embd_head_v(il) != 256) || is_mla)) { LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but layer %d has %u-wide K heads and %u-wide V heads%s, " "and the paged attention kernel supports 256-wide K and V heads only\n", @@ -691,7 +691,7 @@ void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, ll return; } - // [TAG_EXACT_CONCURRENCY] a page belongs to one sequence, so refuse a copy that would share cells rather than abort. After the shared-cells return, so a draft cache is unaffected. + // [TAG_EXACT_CONCURRENCY] A page belongs to one sequence, so refuse cell-sharing copies rather than abort. After the shared-cells return, so draft caches are unaffected. if (exact_pages && seq_id_src != seq_id_dst) { LLAMA_LOG_ERROR("%s: exact concurrency does not support copying cells between " "sequences (%d -> %d); ignoring the copy\n", @@ -969,7 +969,7 @@ llama_memory_context_ptr llama_kv_cache::init_batch( uint32_t n_ubatch, bool embd_all) { do { - // [TAG_EXACT_CONCURRENCY] a token shared by several sequences would be one cell in a page that belongs to one sequence, so refuse it here rather than assert at placement + // [TAG_EXACT_CONCURRENCY] A token shared by several sequences would need one cell in a single-owner page, so refuse it here rather than assert later. if (exact_pages && balloc.has_shared_tokens()) { LLAMA_LOG_ERROR("%s: exact concurrency does not support tokens shared by several sequence ids; " "give every token exactly one sequence id\n", __func__); @@ -980,7 +980,7 @@ llama_memory_context_ptr llama_kv_cache::init_batch( std::vector ubatches; while (true) { - // [TAG_EXACT_CONCURRENCY] split_simple packs every sequence's prompt into one ubatch, so a prefill would run at a width its solo run never sees; the set split gives each its own + // [TAG_EXACT_CONCURRENCY] split_simple packs all prompts into one ubatch, a width no solo run sees; the set split gives each its own. const uint32_t isolate = llama_exact_concurrency() && balloc.has_seq_wider_than(llama_exact_decode_tokens()) ? llama_exact_decode_tokens() : 0; auto ubatch = n_stream == 1 && !isolate @@ -1035,7 +1035,7 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector v_cells; // copy of the old cells, before placing the ubatch - // [TAG_EXACT_CONCURRENCY] page ownership and occupancy before the ubatch, so undoing a speculative placement does not force a rebuild from every cell + // [TAG_EXACT_CONCURRENCY] Snapshot page ownership and occupancy, so undoing a speculative placement needs no full rebuild. std::vector exact_page_owner_old; std::vector exact_page_live_old; }; @@ -1093,7 +1093,7 @@ llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vectorv_heads_old[s]; } - // [TAG_EXACT_CONCURRENCY] put back what the allocator knew, unless the placement also removed cells, when only the cells can say what is left + // [TAG_EXACT_CONCURRENCY] Restore the allocator state unless the placement also removed cells; then only the cells say what is left. if (!exact_rebuild) { exact_page_owner = it->exact_page_owner_old; exact_page_live = it->exact_page_live_old; @@ -1537,12 +1537,12 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & } uint32_t llama_kv_cache::alloc_granularity() const { - // [TAG_EXACT_CONCURRENCY] a page is given to one (sequence, position / page) pair, so n tokens hold round_up(n, exact_page_size) cells: the tail page is charged in full + // [TAG_EXACT_CONCURRENCY] Each page belongs to one (sequence, page) pair, so n tokens hold round_up(n, exact_page_size) cells. return exact_pages ? exact_page_size : 1; } bool llama_kv_cache::get_can_shift() const { - // [TAG_EXACT_CONCURRENCY] a cell's offset in its page is its position modulo 256, so the pool cannot shift positions; reporting it disables --context-shift and --cache-reuse at load + // [TAG_EXACT_CONCURRENCY] A cell's page offset is its position mod 256, so positions cannot shift; this disables --context-shift and --cache-reuse at load. if (exact_pages) { return false; } @@ -2531,7 +2531,7 @@ void llama_kv_cache::state_read_sinfo( llama_state_seq_flags flags, slot_info_vec_t * sinfos_out, const slot_info_vec_t * sinfos_in) { - // [TAG_EXACT_CONCURRENCY] a whole-cache restore writes cells at their recorded physical index, which the paged pool owns; refused before a byte is read + // [TAG_EXACT_CONCURRENCY] A whole-cache restore writes cells at recorded physical indices, which the paged pool owns; refused before reading. if (exact_pages && seq_id == -1) { LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set, which supports per-sequence state restore only\n", __func__); throw std::runtime_error("whole-cache restore is not supported with LLAMA_EXACT_CONCURRENCY"); diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 84ed29ee487e..c5fe9e675add 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -274,7 +274,7 @@ class llama_kv_cache : public llama_memory_i { static constexpr uint32_t exact_page_size = 256; bool exact_pages = false; - // [TAG_EXACT_CONCURRENCY] which (sequence, logical page) owns each physical page; seq < 0 means free, and it is kept current as cells are placed and dirtied by removals + // [TAG_EXACT_CONCURRENCY] The (sequence, logical page) owning each physical page; seq < 0 is free. Kept current on placement and removal. struct exact_page { llama_seq_id seq = -1; llama_pos lpg = -1; diff --git a/src/llama-memory.h b/src/llama-memory.h index 87e7fe1f0bc2..4df3ca9e452d 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -101,7 +101,7 @@ struct llama_memory_i { // getters virtual bool get_can_shift() const = 0; - // [TAG_EXACT_CONCURRENCY] cells this module hands out in one indivisible unit: 1 unless a mode allocates in larger blocks, when n tokens occupy round_up(n, granularity) cells. Not pure, so old modules inherit 1. + // [TAG_EXACT_CONCURRENCY] Allocation granularity: n tokens occupy round_up(n, granularity) cells. Not pure virtual, so old modules inherit 1. virtual uint32_t alloc_granularity() const { return 1; } // diff --git a/tests/test-exact-weights.cpp b/tests/test-exact-weights.cpp index 82098af1f955..0244424226b2 100644 --- a/tests/test-exact-weights.cpp +++ b/tests/test-exact-weights.cpp @@ -1,4 +1,4 @@ -// [TAG_EXACT_CONCURRENCY] the context refuses a weight outside the per-layer blocks (here output_norm) that an override keeps on the host, and still accepts the same model fully offloaded. +// [TAG_EXACT_CONCURRENCY] The context refuses a non-layer weight (output_norm) kept on host by an override, and accepts the same model fully offloaded. // Needs a batch-invariant GPU backend; without one the test reports what it skipped and passes. #include "llama.h" diff --git a/tests/test-state-seq-copy.cpp b/tests/test-state-seq-copy.cpp index 9150927661fa..5a9f9a49047a 100644 --- a/tests/test-state-seq-copy.cpp +++ b/tests/test-state-seq-copy.cpp @@ -1,4 +1,4 @@ -// [TAG_STATE_ASYNC] guards on the asynchronous state transfer: the buffer belongs to the transfer, so an oversized size is refused, and ON_DEVICE is refused as these go via the host +// [TAG_STATE_ASYNC] Async state transfer guards: an oversized size is refused since the transfer owns the buffer, and ON_DEVICE is refused since copies go via host. #include "arg.h" #include "common.h" diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index a0b26e145246..9398b6e10219 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -137,33 +137,33 @@ enum slot_state { SLOT_STATE_RESTORING, // [TAG_PREEMPT_ASYNC] the copy back in is running; the cells are allocated but not yet filled }; -// [TAG_PREEMPT] server-side request preemption: instead of ending every conversation in flight with a context error, one slot's sequence is copied to host RAM and back when there is room +// [TAG_PREEMPT] Server-side preemption: under KV pressure a slot's sequence is parked in host RAM and restored later instead of failing the request. constexpr int32_t PREEMPT_N_MARGIN = 8; // cells left spare on top of the reservation -constexpr int64_t PREEMPT_KEEPALIVE_MS = 2000; // SSE keepalive period while a streaming slot is parked -constexpr int32_t PREEMPT_N_STARVED = 3; // preemptions after which a slot is protected +constexpr int64_t PREEMPT_KEEPALIVE_MS = 2000; // SSE keepalive period while a streaming slot is parked. +constexpr int32_t PREEMPT_N_STARVED = 3; // Preemptions after which a slot is protected. static std::string preempt_notice_comment(const server_task_result_preempt_notice & notice) { const std::string suffix = (notice.batched ? " " + std::to_string(notice.index) : "") + "\n\n"; std::string res = (notice.parked ? ": preempted" : ": resumed") + suffix; - // [TAG_PREEMPT] the resume rebuilt the sequence from its tokens, so what follows is not the continuation the saved bytes would have given + // [TAG_PREEMPT] The resume re-prefilled from tokens, so the output is not bit-identical to an uninterrupted run. if (!notice.parked && notice.recomputed) { res += ": recomputed" + suffix; } return res; } -constexpr int32_t PREEMPT_N_FAIL_MAX = 8; // failed restores before the slot is given up on -constexpr int64_t PREEMPT_FAIL_US = 60ll * 1000 * 1000; // ... and only after this long parked -constexpr int64_t PREEMPT_ROTATE_US = 2ll * 1000 * 1000; // a parked head that has waited this long is owed the cells: a resident is rotated out for it and new prompts wait -constexpr int64_t PREEMPT_ROTATE_RECOMPUTE_US = 30ll * 1000 * 1000; // ... and after this long it gives way even where that costs the resident a re-prefill -constexpr int32_t PREEMPT_ROTATE_MIN_GEN = 32; // tokens a resumed slot decodes before it can be rotated out again, or one token and PREEMPT_ROTATE_US +constexpr int32_t PREEMPT_N_FAIL_MAX = 8; // Failed restores before the slot is given up. +constexpr int64_t PREEMPT_FAIL_US = 60ll * 1000 * 1000; // Only applies after the slot was parked this long. +constexpr int64_t PREEMPT_ROTATE_US = 2ll * 1000 * 1000; // A parked head waiting this long gets a resident rotated out for it, and new prompts wait. +constexpr int64_t PREEMPT_ROTATE_RECOMPUTE_US = 30ll * 1000 * 1000; // After this long the head may also rotate a resident that would need a re-prefill. +constexpr int32_t PREEMPT_ROTATE_MIN_GEN = 32; // Tokens a resumed slot decodes before it can be rotated out again. -// [TAG_PREEMPT_ASYNC] an asynchronous park only releases its cells when its copy lands, so it must fire this many decode steps before the pool would run out +// [TAG_PREEMPT_ASYNC] An async park frees cells only when its copy lands, so it must start this many steps before the pool runs out. constexpr int32_t PREEMPT_N_ASYNC_STEPS = 8; -// [TAG_PREEMPT] test knob: LLAMA_SERVER_PREEMPT_FAIL_SAVE=N fails the host allocation of the Nth park, which no budget check can rule out, so that the fall back to a recompute park is exercised +// [TAG_PREEMPT] Test knob: LLAMA_SERVER_PREEMPT_FAIL_SAVE=N fails the Nth park's host allocation to exercise the recompute fallback. static bool preempt_fail_save() { static int32_t n_left = []() { const char * val = getenv("LLAMA_SERVER_PREEMPT_FAIL_SAVE"); @@ -182,7 +182,7 @@ static llama_state_seq_copy_ptr llama_state_seq_copy_make(llama_context * ctx) { return cpy ? llama_state_seq_copy_ptr(cpy, llama_state_seq_copy_free) : llama_state_seq_copy_ptr(); } -// [TAG_EXACT_CONCURRENCY] the planner counts cells, not tokens: a page belongs to one sequence, so a token count sees room find_slot cannot find and nobody is ever parked +// [TAG_EXACT_CONCURRENCY] The planner counts cells, not tokens: pages are per sequence, so a token count overestimates the room. static constexpr int32_t preempt_n_cells_g(int32_t n_tokens, int32_t g) { return (g <= 1 || n_tokens <= 0) ? n_tokens : ((n_tokens + g - 1) / g) * g; @@ -426,7 +426,7 @@ struct server_slot { std::vector preempt_state_tgt; std::vector preempt_state_dft; - // [TAG_PREEMPT_ASYNC] the two transfers this slot parks and resumes through; they own the pinned host buffers, and are shared_ptr only so a slot survives the vector's reallocation + // [TAG_PREEMPT_ASYNC] Park and resume transfers; shared_ptr so they survive vector reallocation. llama_state_seq_copy_ptr preempt_cpy_tgt; llama_state_seq_copy_ptr preempt_cpy_dft; @@ -462,7 +462,7 @@ struct server_slot { return preempt_sum(llama_state_seq_copy_n_copies); } - // [TAG_PREEMPT_ASYNC] a copy is running: the slot must not be scheduled but still owns cells, so it is neither running nor parked + // [TAG_PREEMPT_ASYNC] A copy is running: not schedulable, but the slot still owns its cells. bool preempt_in_flight() const { return state == SLOT_STATE_PREEMPTING || state == SLOT_STATE_RESTORING; } @@ -471,16 +471,16 @@ struct server_slot { return state == SLOT_STATE_PREEMPTED || preempt_in_flight(); } int32_t n_preempt = 0; // times the CURRENT task has been preempted - int32_t n_recompute = 0; // ... of which parked by dropping the cells, so the resume re-prefilled - int32_t n_ctx_shift = 0; // context shifts it has made: it is at the pool's limit and cycling + int32_t n_recompute = 0; // of which recompute parks + int32_t n_ctx_shift = 0; // a slot cycling through shifts is at the pool's limit int32_t n_preempt_fail = 0; // consecutive failed restores - int64_t t_preempt_us = 0; // when it was parked - int64_t t_preempt_copy_us = 0; // [TAG_PREEMPT_ASYNC] when the current copy was issued - bool preempt_rotation_refused = false; // this park has logged a rotation refused for budget - bool preempt_hold_logged = false; // this request has logged waiting for a parked head - bool preempt_grow = false; // the next park may reserve its pinned buffer ahead of the sequence + int64_t t_preempt_us = 0; + int64_t t_preempt_copy_us = 0; // [TAG_PREEMPT_ASYNC] + bool preempt_rotation_refused = false; + bool preempt_hold_logged = false; + bool preempt_grow = false; // the next park may pin a buffer larger than the sequence - // [TAG_PREEMPT] service since the last resume, so that two slots rotating for each other both make progress + // [TAG_PREEMPT] Service since the last resume, so two slots rotating for each other both make progress. int64_t t_preempt_resume_us = 0; int32_t n_gen_resume = 0; @@ -489,7 +489,7 @@ struct server_slot { n_gen_resume = (int32_t) stats.n_gen; } - // [TAG_PREEMPT_ASYNC] grow a pinned buffer by half again rather than to the exact size, so a sequence parked again a little longer is not unpinned and pinned anew + // [TAG_PREEMPT_ASYNC] Grow pinned buffers by 1.5x so a slightly longer re-park does not re-pin. static size_t preempt_grown_capacity(size_t held, size_t need) { if (need <= held || held == 0) { return need; @@ -533,20 +533,20 @@ struct server_slot { return res; } - // [TAG_PREEMPT] a park with no room left under --preempt-ram: the cells are dropped instead of copied out, and the resume re-prefills the tokens - bool preempt_recompute = false; // parked by dropping its cells - bool preempt_reprefill = false; // putting back, as a prompt, what such a park dropped - bool backend_sampler = false; // the task's sampler chain runs on the backend, see the re-prefill's last token in update_slots - server_tokens preempt_tokens; // what the re-prefill decodes: the prompt and everything generated so far + // [TAG_PREEMPT] With --preempt-ram exhausted, a park drops the cells and the resume re-prefills the tokens. + bool preempt_recompute = false; + bool preempt_reprefill = false; + bool backend_sampler = false; // see the re-prefill's last token in update_slots + server_tokens preempt_tokens; // prompt plus generated tokens, for the re-prefill size_t preempt_state_size() const { - // for a transfer the capacity, not the live size: the pinned buffers are kept between parks, so --preempt-ram has to bound what is held + // Count capacity, not live size: pinned buffers persist between parks and --preempt-ram must bound them. return preempt_is_async() ? preempt_sum(llama_state_seq_copy_buf_capacity) : preempt_state_tgt.size() + preempt_state_dft.size(); } void preempt_state_free() { - // waits for anything in flight first: release() is reached with a copy possibly still using the buffer + // release() can be reached while a copy still uses the buffer. preempt_each(llama_state_seq_copy_buf_free); preempt_state_tgt.clear(); @@ -564,7 +564,7 @@ struct server_slot { (ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0); } - // take the slot out of the step that is about to be built; the draft is a prediction, not a result, so it goes with the cells + // Take the slot out of the next step; the draft is a prediction, so it is dropped with the cells. void preempt_detach() { spec_draft.clear(); spec_i_batch.clear(); @@ -619,7 +619,6 @@ struct server_slot { return preempt_resumed(); } - // the tokens the prompt step works through: its own list while re-prefilling, the request's otherwise const server_tokens & preempt_input() const { return preempt_tokens.empty() ? task->tokens : preempt_tokens; } @@ -628,7 +627,7 @@ struct server_slot { return preempt_tokens.empty() ? (task ? task->n_tokens() : 0) : (int32_t) preempt_tokens.size(); } - // [TAG_PREEMPT] park with the host budget spent: drop the cells, keep the tokens, re-prefill them on resume. The sampler and the counters are untouched, so the stream carries on from the same token; the resume is bit-exact only as far as prefill numerics match decode numerics. A media chunk comes back the way it went in: the prompt step reads the chunk's data off the task and reserves its cells whole, so the placeholder the re-prefill list carries is all it needs + // [TAG_PREEMPT] Recompute park: drop the cells, keep the tokens, re-prefill on resume. Sampler and counters are kept, so the stream continues; it is bit-exact only if prefill and decode numerics match. bool preempt_save_recompute() { preempt_state_free(); preempt_detach(); @@ -637,7 +636,7 @@ struct server_slot { preempt_tokens = std::move(prompt.tokens); prompt.tokens = server_tokens(); - prompt.tokens.has_mtmd = preempt_tokens.has_mtmd; // the re-prefill pushes the chunk's placeholder back into it + prompt.tokens.has_mtmd = preempt_tokens.has_mtmd; // the re-prefill pushes the chunk's placeholder back } prompt_clear(); @@ -659,11 +658,11 @@ struct server_slot { n_preempt_fail = 0; if (preempt_tokens.empty()) { - state = state_before_preempt; // its prompt had not been processed yet, so it is processed again from the start + state = state_before_preempt; // its prompt was not processed yet, so restart it preempt_mark_resumed(); - // the park dropped the cells the prompt step had already filled, and the restart does not pass through SLOT_STATE_STARTED, where these two are set: left alone they would count the dropped prefix a second time + // The restart skips SLOT_STATE_STARTED, so reset these here or the dropped prefix is counted twice. stats.n_prompt_cached = 0; stats.n_prompt_processed = 0; @@ -676,7 +675,6 @@ struct server_slot { return true; } - // every token is back in the cache: the slot goes on generating from the token it had already sampled void preempt_reprefill_done() { preempt_reprefill = false; preempt_tokens.clear(); @@ -684,14 +682,14 @@ struct server_slot { i_batch = -1; state = SLOT_STATE_GENERATING; - preempt_mark_resumed(); // the re-prefill is not service: it only put back what the park dropped + preempt_mark_resumed(); // a re-prefill is not service if (can_speculate()) { common_speculative_begin(spec, id, prompt.tokens.get_text_tokens()); } } - // [TAG_PREEMPT_ASYNC] copy the sequence out and release its cells; with a transfer this returns once the copy is issued and the cells stay the slot's until preempt_save_poll() sees it land + // [TAG_PREEMPT_ASYNC] With a transfer this only issues the copy; the cells stay the slot's until preempt_save_poll() sees it land. bool preempt_save() { if (preempt_fail_save()) { SLT_ERR(*this, "%s", "failed to allocate the host memory for the preemption state (test knob)\n"); @@ -712,7 +710,7 @@ struct server_slot { return false; } - // [TAG_PREEMPT_ASYNC] the load-time probe saw pinned memory, but a larger buffer can still come back pageable, and a copy into pageable memory blocks; such a slot parks synchronously from now on + // [TAG_PREEMPT_ASYNC] A large buffer can still come back pageable, and copies into pageable memory block, so this slot parks synchronously from now on. const bool pageable = !llama_state_seq_copy_buf_is_pinned(preempt_cpy_tgt.get()) || (size_dft > 0 && !llama_state_seq_copy_buf_is_pinned(preempt_cpy_dft.get())); @@ -738,7 +736,7 @@ struct server_slot { preempt_detach(); - // note: no mem.seq_rm() here. The copy is still reading these cells; preempt_save_poll() releases them. + // No seq_rm() here: the copy still reads these cells; preempt_save_poll() releases them. state_before_preempt = state; state = SLOT_STATE_PREEMPTING; t_preempt_us = ggml_time_us(); @@ -774,7 +772,7 @@ struct server_slot { preempt_detach(); - // note: prompt.tokens is deliberately kept - the resume sizes its request from it + // prompt.tokens is kept: the resume sizes its request from it. mem.seq_rm(id, -1, -1); state_before_preempt = state; @@ -787,7 +785,7 @@ struct server_slot { return true; } - // [TAG_PREEMPT_ASYNC] put the sequence back; with a transfer this returns once the copy is issued, leaving the slot RESTORING: it owns the cells, but they hold no state until the copy lands + // [TAG_PREEMPT_ASYNC] With a transfer this only issues the copy; the slot is RESTORING and its cells hold no state until it lands. bool preempt_restore() { if (preempt_recompute) { return preempt_restore_recompute(); @@ -800,7 +798,7 @@ struct server_slot { if (llama_state_seq_copy_set(preempt_cpy_tgt.get(), size_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_tgt || (size_dft > 0 && llama_state_seq_copy_set(preempt_cpy_dft.get(), size_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) != size_dft)) { - // no room after all: let what was issued finish before the half-written sequence is dropped, or cells go while a copy still writes them + // Let issued copies finish before dropping the half-written sequence. preempt_copy_wait(); mem.seq_rm(id, -1, -1); n_preempt_fail++; @@ -828,14 +826,14 @@ struct server_slot { return preempt_resumed(); } - // [TAG_PREEMPT] bring prompt.tokens back to what the cache holds, for a batch given up after it was built: never-decoded tokens and the draft come off, `sampled` is kept + // [TAG_PREEMPT] Rewind prompt.tokens to what the cache holds after a built batch is given up; `sampled` is kept. void rewind_to_cache() { - // the memory counts positions, and with M-RoPE media a position is not a token, so convert before truncating + // With M-RoPE media a position is not a token, so convert before truncating. const llama_pos pos_cached = llama_memory_seq_pos_max(llama_get_memory(ctx_tgt), id) + 1; size_t n_cached = pos_cached > 0 ? prompt.tokens.size_up_to_pos(pos_cached) : 0; - // a cut inside a media chunk is not a token boundary: keep what precedes the chunk, and the cells of its head go too + // A cut inside a media chunk drops the whole chunk. bool split_chunk = false; while (n_cached > 0 && prompt.tokens.pos_next(n_cached) > pos_cached) { @@ -851,10 +849,9 @@ struct server_slot { mem.seq_rm(id, prompt.tokens.pos_next(), -1); } - // what is kept ends where the cache does, or the next decode is positioned from the wrong count GGML_ASSERT(prompt.tokens.pos_next() <= pos_cached); - // the last chunk was marked done when it was built but never ran, so it is not done + // The last chunk was marked done when built but never ran. if (state == SLOT_STATE_DONE_PROMPT && task && prompt.n_tokens() < preempt_n_input()) { state = SLOT_STATE_PROCESSING_PROMPT; } @@ -1120,7 +1117,7 @@ struct server_slot { t_last_used = ggml_time_us(); - // [TAG_PREEMPT] [TAG_PREEMPT_ASYNC] a parked slot's cells are already gone, so the mirror must not outlive them or the next task prefix-matches an empty cache; wait for any copy first, its buffer and its cells are about to be handed on + // [TAG_PREEMPT] [TAG_PREEMPT_ASYNC] A parked slot has no cells, so drop the mirror or the next task prefix-matches an empty cache; wait for any copy first. if (preempt_is_out()) { preempt_copy_wait(); preempt_state_free(); @@ -1273,7 +1270,7 @@ struct server_slot { {"n_ctx", n_ctx}, {"speculative", can_speculate()}, {"is_processing", is_processing()}, - // [TAG_PREEMPT] parked means the cells are gone; a copy out still owns them and a restore has already taken them back, so a scraper counting residency has to keep counting those two + // [TAG_PREEMPT] Slots copying out or restoring still hold cells, so they count as resident. {"is_preempted", state == SLOT_STATE_PREEMPTED}, {"is_transferring", preempt_in_flight()}, {"n_preempt", n_preempt}, @@ -1522,8 +1519,8 @@ struct server_context_impl { metrics.reset_bucket(); } - // [TAG_PREEMPT] the first prompt of a request that cannot be served, with the error response it gets; false when every one of them passes. - // A park notice opens the stream of the member it belongs to, so a member rejected after that could only be told inside a stream that has already answered 200. + // [TAG_PREEMPT] The first prompt of a request that cannot be served, with its error; false if all pass. + // Checked up front because a park notice opens the stream with 200, after which a rejection could only be sent in-stream. bool tasks_prompt_rejected(const std::vector & tasks, json & error) const { std::string msg; error_type type = ERROR_TYPE_SERVER; @@ -1610,7 +1607,7 @@ struct server_context_impl { int64_t t_last_load_progress_ms = 0; void destroy() { - // [TAG_PREEMPT_ASYNC] the slots outlive this call and may hold a copy reading or writing KV tensors of the contexts about to be freed; release() makes the same wait for one slot + // [TAG_PREEMPT_ASYNC] Slots may hold copies touching KV tensors of the contexts about to be freed. for (auto & slot : slots) { slot.preempt_copy_wait(); @@ -2027,7 +2024,7 @@ struct server_context_impl { } }; - // [TAG_PREEMPT_ASYNC] one transfer per context, reused for every park and resume, because each owns a backend and installs the fences the context records after every decode + // [TAG_PREEMPT_ASYNC] One transfer per context: each owns a backend and installs the fences the context records after every decode. if (preempt_async_possible()) { slot.preempt_cpy_tgt = llama_state_seq_copy_make(ctx_tgt); @@ -2035,7 +2032,7 @@ struct server_context_impl { slot.preempt_cpy_dft = llama_state_seq_copy_make(ctx_dft); if (!slot.preempt_cpy_dft) { - // a draft that cannot go asynchronously would have to be waited for mid-park, so the whole slot stays synchronous + // a draft that cannot copy asynchronously would block mid-park, so the slot stays synchronous slot.preempt_cpy_tgt.reset(); } } @@ -2071,7 +2068,7 @@ struct server_context_impl { if (preempt_async_possible()) { if (preempt_async_ok) { - // a copy into pageable memory is staged by the driver and blocks the thread that issued it, and a host buffer type is free to hand back pageable memory rather than fail + // A host buffer type may return pageable memory, and copies into it block the issuing thread. bool pinned = llama_state_seq_copy_buf_can_pin(slots[0].preempt_cpy_tgt.get()); if (pinned) { @@ -2108,7 +2105,7 @@ struct server_context_impl { { preempt_alloc_granularity = (int32_t) std::max(1u, llama_memory_alloc_granularity(llama_get_memory(ctx_tgt))); - // test knob: the paged kernel needs a head size of 256, so a harness model cannot reach the paged arithmetic otherwise + // Test knob: the paged kernel needs head size 256, which harness models lack. const char * LLAMA_SERVER_PREEMPT_GRANULARITY = getenv("LLAMA_SERVER_PREEMPT_GRANULARITY"); if (LLAMA_SERVER_PREEMPT_GRANULARITY) { @@ -2139,7 +2136,7 @@ struct server_context_impl { const char * LLAMA_SERVER_PREEMPT_EVERY = getenv("LLAMA_SERVER_PREEMPT_EVERY"); preempt_test_every = LLAMA_SERVER_PREEMPT_EVERY ? atoi(LLAMA_SERVER_PREEMPT_EVERY) : 0; - // LLAMA_SERVER_PREEMPT_POLICY: which non-leader the planner parks; smallest (default), largest, youngest, oldest + // LLAMA_SERVER_PREEMPT_POLICY: smallest (default), largest, youngest or oldest. const char * LLAMA_SERVER_PREEMPT_POLICY = getenv("LLAMA_SERVER_PREEMPT_POLICY"); preempt_test_policy = LLAMA_SERVER_PREEMPT_POLICY ? LLAMA_SERVER_PREEMPT_POLICY : "smallest"; @@ -2159,7 +2156,7 @@ struct server_context_impl { SRV_WRN("%s", "LLAMA_SERVER_PREEMPT_PLANNER = off (test knob: nothing is parked ahead of the decode, only as a last resort)\n"); } - // assigned, not only set: a context reloaded with an attention model after a recurrent one gets preemption back + // assigned, not only set: a reload with an attention model after a recurrent one re-enables preemption preempt_recurrent = llama_model_is_recurrent(model_tgt); if (preempt_recurrent && params_base.preempt_ram_mib != 0) { @@ -3579,7 +3576,7 @@ struct server_context_impl { if (slot.is_processing()) { n_processing_slots++; } - // [TAG_PREEMPT] a transfer counts with the parked: none of them decodes, and a client excusing a silent stream needs all three + // [TAG_PREEMPT] Transfers count as parked: none of them decodes. if (slot.preempt_is_out()) { n_preempted_slots++; } @@ -3841,7 +3838,7 @@ struct server_context_impl { void abort_all_slots(const std::string & reason) { for (auto & slot : slots) { - // [TAG_PREEMPT] a parked slot, or one with a copy in flight, took no part in what failed and comes back when there is room + // [TAG_PREEMPT] Parked or copying slots took no part in the failure. if (slot.is_processing() && !slot.preempt_is_out()) { send_error(slot, reason, ERROR_TYPE_SERVER); slot.release(); @@ -3880,14 +3877,14 @@ struct server_context_impl { #endif - // LLAMA_SERVER_PREEMPT_EVERY=N: preempt every generating slot every N tokens, pressure or not, so the determinism test can blame any difference on the preemption + // LLAMA_SERVER_PREEMPT_EVERY=N: preempt every generating slot every N tokens, for the determinism test. int32_t preempt_test_every = 0; std::string preempt_test_policy = "smallest"; // LLAMA_SERVER_PREEMPT_POLICY, see load_model - // [TAG_PREEMPT_ASYNC] whether parks go through a transfer; false with --no-preempt-async or a backend that cannot copy asynchronously + // [TAG_PREEMPT_ASYNC] False with --no-preempt-async or a backend without async copies. bool preempt_async_ok = false; - // [TAG_EXACT_CONCURRENCY] cells the pool hands out at a time, read once at load: 1 ordinarily, the page size under exact concurrency. LLAMA_SERVER_PREEMPT_GRANULARITY overrides it. + // [TAG_EXACT_CONCURRENCY] Pool allocation granularity: 1, or the page size under exact concurrency; LLAMA_SERVER_PREEMPT_GRANULARITY overrides. int32_t preempt_alloc_granularity = 1; int32_t preempt_n_cells(int32_t n_tokens) const { @@ -3898,7 +3895,7 @@ struct server_context_impl { return preempt_n_cells_step_g(n_tokens, n_step, preempt_alloc_granularity); } - // LLAMA_SERVER_PREEMPT_PLANNER=off (test knob): no parking ahead of the decode, leaving only the KV-full retry ladder + // LLAMA_SERVER_PREEMPT_PLANNER=off (test knob): only the KV-full retry ladder. bool preempt_planner_off = false; // LLAMA_SERVER_PREEMPT_RESUME=head or pass, read at load, per context @@ -3908,7 +3905,7 @@ struct server_context_impl { bool preempt_batch_abandoned = false; - // [TAG_PREEMPT_ASYNC] a context shift was recorded this round; it is applied in place inside the next llama_decode + // [TAG_PREEMPT_ASYNC] A context shift is pending; it is applied in place inside the next llama_decode. bool preempt_shift_pending = false; int32_t preempt_n_spec_max() const { @@ -3917,7 +3914,7 @@ struct server_context_impl { bool preempt_ram_kind_logged = false; - // [TAG_PREEMPT] the fall back to a recompute park is logged once, not per park + // [TAG_PREEMPT] Logged once, not per park. bool preempt_recompute_logged = false; void preempt_log_ram_kind(const server_slot & slot) { @@ -3926,7 +3923,7 @@ struct server_context_impl { } if (llama_state_seq_copy_buf_capacity(slot.preempt_cpy_tgt.get()) == 0) { - return; // nothing held, so nothing to report yet + return; } preempt_ram_kind_logged = true; @@ -3942,7 +3939,7 @@ struct server_context_impl { return 0; } - // a recompute park moved the prompt out of the slot, so the tokens it comes back with bound the draft, not the empty prompt: read as empty, a 2000-token sequence in a 2048-cell pool was charged a whole draft and failed as impossible + // A recompute park emptied the prompt, so bound the draft by preempt_tokens; reading the empty prompt once failed a fitting sequence as impossible. const int32_t n_tokens = std::max(slot.prompt.n_tokens(), slot.preempt_n_input()); res = std::min(res, slot.n_ctx - n_tokens - 2); @@ -3964,7 +3961,7 @@ struct server_context_impl { return res; } - // [TAG_PREEMPT_ASYNC] a restored slot keeps its pinned buffer, so that idle capacity is given back largest first when a park does not fit under --preempt-ram + // [TAG_PREEMPT_ASYNC] Restored slots keep pinned buffers; free the largest first when a park does not fit --preempt-ram. void preempt_reclaim_idle_ram(size_t budget, size_t extra, const server_slot & keep) { for (;;) { if (preempt_ram_used() + extra <= budget) { @@ -4009,7 +4006,7 @@ struct server_context_impl { bool preempt_fits_budget(const server_slot & slot) { const size_t budget = preempt_ram_budget(); - // what this slot already holds is counted by preempt_ram_used() and reused, so a park costs only the rest + // Capacity this slot already holds is reused, so the park costs only the rest. const size_t held = slot.preempt_state_size(); const size_t need = slot.preempt_state_required(); const size_t extra = need > held ? need - held : 0; @@ -4040,10 +4037,10 @@ struct server_context_impl { return n_keep; } - // a slot just given a task still mirrors the previous request's prompt, so what it holds and what it asks for both count from preempt_n_keep() + // A freshly assigned slot still mirrors the previous prompt, so count from preempt_n_keep(). int32_t preempt_n_retained(const server_slot & slot) const { if (slot.preempt_recompute) { - return (int32_t) slot.preempt_tokens.size(); // parked by dropping its cells: it comes back needing all of them at once + return (int32_t) slot.preempt_tokens.size(); // a recompute park needs all its cells back at once } if (slot.state == SLOT_STATE_STARTED && slot.task) { @@ -4053,7 +4050,7 @@ struct server_context_impl { return slot.prompt.n_tokens(); } - // [TAG_PREEMPT] the cells the media chunks pending at n_have take: pre_decode() runs a whole chunk through llama_decode() calls of its own, which no kv-full retry covers, so the planner reserves the lot before it is decoded + // [TAG_PREEMPT] Cells for media chunks pending at n_have: pre_decode() runs them outside any kv-full retry, so reserve them up front. int32_t preempt_n_mtmd_pending(const server_slot & slot, int32_t n_have) const { if (!slot.task || !slot.task->tokens.has_mtmd) { return 0; @@ -4089,22 +4086,22 @@ struct server_context_impl { res += n_mtmd > 0 ? n_mtmd : std::max(1, std::min((int32_t) llama_n_batch(ctx_tgt), n_left)); } - // [TAG_EXACT_CONCURRENCY] a restore takes fresh pages and its tail page is charged in full; undercounting admits a resume find_slot cannot satisfy + // [TAG_EXACT_CONCURRENCY] A restore takes fresh pages and its tail page counts in full; undercounting admits a resume find_slot cannot satisfy. return preempt_n_cells(res); } int32_t preempt_kv_used() const { int32_t res = 0; - // n_cmpl > 1: a family shares the prompt's cells through seq_cp, so it is charged once, to the first resident member + // n_cmpl > 1 siblings share the prompt's cells via seq_cp, so charge them once. std::vector charged; for (const auto & slot : slots) { if (slot.state == SLOT_STATE_PREEMPTED) { - continue; // parked: its cells are in host RAM, not in the pool + continue; // parked: its cells are in host RAM } - // [TAG_PREEMPT_ASYNC] deliberately not skipped: a slot with a copy in flight holds cells either way, and skipping it would hand the same cells out twice + // [TAG_PREEMPT_ASYNC] Not skipped: a slot mid-copy still holds cells, and skipping it would hand them out twice. if (slot.state == SLOT_STATE_WAIT_OTHER) { res += preempt_n_cells(slot.prompt.n_tokens()); @@ -4128,10 +4125,10 @@ struct server_context_impl { return res; } - // [TAG_PREEMPT_ASYNC] the room the pool is kept clear of, so everything still decoding has somewhere to put its tokens until a park lands; a resume candidate is charged the same runway + // [TAG_PREEMPT_ASYNC] Room kept free so running slots can keep decoding until a park lands; resume candidates are charged the same. int32_t preempt_n_margin(int32_t n_additional_running = 0) const { if (!preempt_async_ok) { - // [TAG_EXACT_CONCURRENCY] a margin of eight cells is no margin where a step can cost a whole page + // [TAG_EXACT_CONCURRENCY] One step can cost a whole page. return preempt_n_cells(PREEMPT_N_MARGIN); } @@ -4143,7 +4140,7 @@ struct server_context_impl { } } - // [TAG_EXACT_CONCURRENCY] round the runway up to a page, once and not per slot, which would keep a page per slot out of the users' reach + // [TAG_EXACT_CONCURRENCY] Round up once, not per slot, or a page per slot is wasted. return preempt_n_cells( PREEMPT_N_MARGIN + n_running * (1 + preempt_n_spec_max()) * PREEMPT_N_ASYNC_STEPS); } @@ -4156,11 +4153,11 @@ struct server_context_impl { int32_t res_mm = 0; int32_t n_pmt = 0; - // [TAG_EXACT_CONCURRENCY] reserve the cells the next step ADDS, not its tokens: the used figure already rounds every tail page up, and only a page crossing can empty the pool + // [TAG_EXACT_CONCURRENCY] Reserve the cells the next step adds: used already rounds tail pages up, so only a page crossing costs. for (const auto & slot : slots) { const int32_t n_cur = slot.prompt.n_tokens(); - // [TAG_PREEMPT_ASYNC] a restoring slot decodes as soon as its copy lands, so it is charged the step of the state it goes back to, or that first step preempts somebody else + // [TAG_PREEMPT_ASYNC] A restoring slot decodes as soon as its copy lands, so charge the step of the state it returns to. const slot_state state = slot.state == SLOT_STATE_RESTORING ? slot.state_before_preempt : slot.state; switch (state) { @@ -4172,7 +4169,7 @@ struct server_context_impl { case SLOT_STATE_STARTED: case SLOT_STATE_PROCESSING_PROMPT: { - // [TAG_PREEMPT] a prompt held back for a parked head takes no step until the head is back + // [TAG_PREEMPT] A prompt held for a parked head takes no step. if (preempt_held(slot)) { break; } @@ -4180,7 +4177,7 @@ struct server_context_impl { const int32_t n_have = preempt_n_retained(slot); const int32_t n_mtmd = preempt_n_mtmd_pending(slot, n_have); - // a media chunk is decoded whole, past the batch cap below and past the kv-full retry + // a media chunk is decoded whole, past the batch cap and the kv-full retry if (n_mtmd > 0) { res_mm += preempt_n_cells_step(n_have, n_mtmd); break; @@ -4199,7 +4196,7 @@ struct server_context_impl { return res + res_mm + std::min(res_pmt, preempt_n_cells(n_batch) + std::max(0, n_pmt - 1) * (preempt_alloc_granularity - 1)); } - // [TAG_PREEMPT] trim a just-started slot to the prefix it keeps first, or it is copied out, charged and sized by the previous request's prompt + // [TAG_PREEMPT] Trim a just-started slot to its kept prefix first, or it is sized by the previous request's prompt. bool preempt_normalize_started_all() { bool res = false; @@ -4229,7 +4226,7 @@ struct server_context_impl { return; } - // a memory that cannot remove part of a sequence aborts on a partial removal, so drop the whole stale sequence + // A memory without partial removal aborts on one, so drop the whole stale sequence. const bool partial_ok = ctx_tgt_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_PART && (!ctx_dft || ctx_dft_seq_rm_type == COMMON_CONTEXT_SEQ_RM_TYPE_PART); @@ -4243,7 +4240,7 @@ struct server_context_impl { slot.mem.seq_rm(slot.id, slot.prompt.tokens.pos_next(), -1); } - // `recompute` asks for a fallback: with no victim the host budget can hold, the same policy picks again and the park drops the cells instead of copying them. `n_deficit` is the room the caller is short of: one victim that covers it alone is parked rather than several smaller ones. + // `recompute`: no victim fits the host budget, so pick again and drop cells instead of copying. `n_deficit`: a single victim covering it is preferred over several smaller ones. server_slot * preempt_pick_victim(bool * recompute = nullptr, int32_t n_deficit = 0) { server_slot * leader = nullptr; int32_t n_running = 0; @@ -4263,14 +4260,14 @@ struct server_context_impl { } if (n_running < 2) { - // one conversation that does not fit alone is a real overflow, not a scheduling problem + // a conversation that does not fit alone is a real overflow return nullptr; } - // the test knob asking for the largest has to be able to pick it, so it exempts nobody + // the largest-policy test knob exempts nobody const server_slot * exempt = preempt_test_policy == "largest" ? nullptr : leader; - // the deficit is only weighed under the default policy: the others exist to pin down the order + // only the default policy weighs the deficit; the others pin the order if (preempt_test_policy != "smallest") { n_deficit = 0; } @@ -4286,7 +4283,7 @@ struct server_context_impl { return victim; } - // [TAG_PREEMPT] the room a park gives back: the slot's cells and the step it would have taken next + // [TAG_PREEMPT] Room a park frees: the slot's cells plus its next step. int32_t preempt_n_freed(const server_slot & slot) const { const int32_t n_cur = slot.prompt.n_tokens(); @@ -4306,7 +4303,7 @@ struct server_context_impl { } bool preempt_victim_eligible(server_slot & slot, const server_slot * exempt, bool recompute) { - // before the batch is built every slot is at a token boundary; one holding no cells is still worth parking + // Before the batch is built every slot is at a token boundary; a slot holding no cells is still worth parking. if (slot.state != SLOT_STATE_GENERATING && slot.state != SLOT_STATE_PROCESSING_PROMPT && slot.state != SLOT_STATE_STARTED) { @@ -4317,16 +4314,16 @@ struct server_context_impl { return false; } - // a held prompt with no cells takes no step either, so parking it gives nothing back + // a held prompt with no cells frees nothing if (preempt_held(slot) && slot.prompt.n_tokens() == 0) { return false; } if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { - return false; // n_cmpl > 1 slots share one sequence, out of scope here + return false; // n_cmpl > 1 slots share one sequence } - // a started slot the STARTED block is about to reject gets its error on its own pass: a park notice would open the stream and turn that 4xx into 200 plus an in-stream error + // A started slot about to be rejected gets its own 4xx; a park notice would turn it into 200 plus an in-stream error. if (slot.state == SLOT_STATE_STARTED) { std::string msg; error_type type = ERROR_TYPE_SERVER; @@ -4346,7 +4343,7 @@ struct server_context_impl { server_slot * preempt_pick_victim_pass(const server_slot * exempt, bool recompute, int32_t n_deficit = 0) { server_slot * victim = nullptr; - // the single victim that covers the deficit with the least, among the unstarved first + // the smallest single victim covering the deficit, unstarved first server_slot * cover[2] = { nullptr, nullptr }; for (auto & slot : slots) { @@ -4374,7 +4371,7 @@ struct server_context_impl { } } - // a starved slot covering the deficit is only taken where the order above would take a starved one anyway + // a starved slot is only taken where the order would take one anyway const bool victim_starved = victim && victim->n_preempt >= PREEMPT_N_STARVED; if (cover[0]) { @@ -4404,7 +4401,7 @@ struct server_context_impl { return a.prompt.n_tokens() < b.prompt.n_tokens(); } - // [TAG_PREEMPT] the oldest parked slot once it has waited PREEMPT_ROTATE_US: from then on no prompt that has never been resident may take the cells it needs + // [TAG_PREEMPT] The oldest parked slot once it has waited PREEMPT_ROTATE_US; then no never-resident prompt may take its cells. const server_slot * preempt_reserved_for = nullptr; void preempt_update_reservation() { @@ -4419,7 +4416,7 @@ struct server_context_impl { preempt_reserved_for = head && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_US ? head : nullptr; } - // [TAG_PREEMPT] a prompt waits while the reservation stands: a request that has never been resident, either not started or started after the head was parked. A re-prefill and a resumed prompt are parked slots coming back, and an empty or rejected prompt takes no cells, so those go on. + // [TAG_PREEMPT] A never-resident prompt waits while the head's reservation stands. Re-prefills, resumed prompts, and empty or rejected prompts go on. bool preempt_held(const server_slot & slot) const { if (!preempt_reserved_for || &slot == preempt_reserved_for || !slot.task) { return false; @@ -4458,7 +4455,7 @@ struct server_context_impl { preempt_reserved_for->id, (ggml_time_us() - preempt_reserved_for->t_preempt_us) / 1e6); } - // [TAG_PREEMPT] a slot back from a park is not rotated out again before it has decoded PREEMPT_ROTATE_MIN_GEN tokens, or one token and PREEMPT_ROTATE_US, so two slots cannot hand the cells back and forth without progress + // [TAG_PREEMPT] A resumed slot is not rotated out before PREEMPT_ROTATE_MIN_GEN tokens (or one token and PREEMPT_ROTATE_US), so two slots cannot swap cells without progress. bool preempt_served(const server_slot & slot) const { if (slot.n_preempt == 0) { return true; @@ -4480,11 +4477,11 @@ struct server_context_impl { return false; } - // [TAG_PREEMPT] park a slot: a synchronous park is finished here, an asynchronous one only issued, and update_preempt_copies() counts it when its copy lands. The notice goes with the save, not the cell release: preempt_save() has already detached the slot, so a release-time notice would leave the copy's silence unexplained. + // [TAG_PREEMPT] Sync parks finish here, async ones are counted by update_preempt_copies() when they land. The notice is sent with the save, since the slot is already detached and silent. bool preempt_park(server_slot & slot, int64_t t_start, bool recompute = false) { slot.t_preempt_copy_us = t_start; - // [TAG_PREEMPT_ASYNC] reserve ahead only where the budget still holds another state of that size afterwards: preempt_state_size() charges the slack, which must not crowd out the next park + // [TAG_PREEMPT_ASYNC] Reserve ahead only if the budget still fits another state that size: the slack is charged and must not block the next park. if (!recompute && slot.preempt_is_async()) { const size_t held = slot.preempt_state_size(); const size_t grown = slot.preempt_state_grown(); @@ -4492,7 +4489,7 @@ struct server_context_impl { slot.preempt_grow = preempt_ram_used() - held + 2 * grown <= preempt_ram_budget(); } - // [TAG_PREEMPT] a budget check grants permission to allocate, not a successful allocation: preempt_save() unwinds and waits for whatever it issued, so the same victim can still be parked by dropping its cells + // [TAG_PREEMPT] Budget checks do not guarantee the allocation; preempt_save() unwinds on failure, so fall back to a recompute park. if (!recompute && !slot.preempt_save()) { SLT_WRN(slot, "%s", "the park could not take the host memory the budget allowed, so it drops its cells instead and the resume re-prefills its tokens\n"); @@ -4507,7 +4504,7 @@ struct server_context_impl { if (!preempt_recompute_logged) { preempt_recompute_logged = true; - // [TAG_EXACT_CONCURRENCY] a state that comes back from host memory is the state that left; one rebuilt by re-prefilling is the same on CPU and differs in the last bits on CUDA, where a prefill of a token and a decode of it take different kernels + // [TAG_EXACT_CONCURRENCY] A host-restored state is identical; a re-prefilled one differs in the last bits on CUDA, where prefill and decode use different kernels. if (common_exact_concurrency()) { SRV_WRN("%s", "exact concurrency: a re-prefilled sequence is not guaranteed byte-identical to one that was never parked; raise --preempt-ram until every parked sequence fits it\n"); } @@ -4542,7 +4539,7 @@ struct server_context_impl { preempt_kv_used(), n_ctx); } - // [TAG_PREEMPT] a resume whose copy has landed; announced here rather than where the restore was issued, this being the first moment the slot can be scheduled again + // [TAG_PREEMPT] Announced on landing, the first moment the slot can be scheduled. void preempt_restored(server_slot & slot, const char * note) { metrics.n_resume++; @@ -4571,7 +4568,7 @@ struct server_context_impl { } } - // [TAG_PREEMPT_ASYNC] wait for every copy in flight before a shift: the shift is one in-place graph over the whole K cache, so a copy beside it reads or writes half-shifted cells + // [TAG_PREEMPT_ASYNC] Wait for all copies before a shift: it is one in-place graph over the whole K cache. void preempt_wait_for_shift() { if (!preempt_shift_pending) { return; @@ -4595,7 +4592,7 @@ struct server_context_impl { } } - // [TAG_PREEMPT] run the recorded shift here rather than leave it to the next llama_decode(): a park in between would serialize the positions the shift has already moved together with the K values it has not, and removing the sequence would drop the pending deltas with it + // [TAG_PREEMPT] Run the pending shift now: a park before the next decode would save moved positions with unshifted K, and removing the sequence drops the pending deltas. void preempt_apply_shift() { if (!preempt_shift_pending) { return; @@ -4644,14 +4641,14 @@ struct server_context_impl { preempt_reserved_for = nullptr; if (!params_base.kv_unified || slots.size() < 2) { - return; // with a cache per slot, no slot can take another one's cells + return; // a cache per slot: no slot can take another's cells } if (!llama_get_memory(ctx_tgt)) { - return; // no cache at all (an embedding model): nothing to run out of, nothing to park + return; // no cache (embedding model): nothing to park } - // [TAG_PREEMPT] --preempt-ram 0 parks nothing, so with nothing out there is nothing to scan + // [TAG_PREEMPT] With --preempt-ram 0 and nothing parked there is nothing to scan. if (params_base.preempt_ram_mib == 0 && !preempt_any_out()) { return; } @@ -4659,7 +4656,7 @@ struct server_context_impl { update_preempt_copies(); if (params_base.preempt_ram_mib == 0 || preempt_recurrent) { - return; // --preempt-ram 0, or a recurrent cache: the KV-full retry ladder, as before + return; // --preempt-ram 0 or a recurrent cache: retry ladder only } const int32_t n_cells = n_ctx; @@ -4706,7 +4703,7 @@ struct server_context_impl { continue; } - // room for the sequence and for the next step of everything running, the candidate included, or a resume immediately preempts somebody; with nobody resident an exact fit is let in + // Room for the sequence and everyone's next step, or the resume preempts somebody at once; with nobody resident an exact fit is allowed. for (;;) { const int32_t occupied = preempt_kv_used() + preempt_kv_reserve(); const int32_t margin = occupied == 0 ? 0 : preempt_n_margin(1); @@ -4731,11 +4728,11 @@ struct server_context_impl { } } - // nothing fits: a resident holds the room for as long as it generates, and one cycling through context shifts for good, so one is parked once the head has waited its turn + // Nothing fits: once the head has waited its turn, park a resident, since one may hold the room indefinitely. if (!best) { server_slot * head = parked.front(); - // [TAG_PREEMPT_ASYNC] a park still copying holds its cells, so a rotation now would only park another resident on top + // [TAG_PREEMPT_ASYNC] A park still copying holds its cells, so rotating now would park a second resident. if (!preempt_copies_in_flight() && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_US) { const int32_t occupied = preempt_kv_used() + preempt_kv_reserve(); const int32_t need = preempt_n_need(*head) + preempt_n_margin(1); @@ -4747,7 +4744,7 @@ struct server_context_impl { auto rotate_pick = [&](bool with_recompute) { for (auto & slot : slots) { - // [TAG_PREEMPT] any resident that has had its service since its last resume, the longest included, and a held prompt that sits on cells + // [TAG_PREEMPT] Residents that have had their service since resuming, and held prompts sitting on cells. const bool held = preempt_held(slot) && slot.prompt.n_tokens() > 0; if (!held && (slot.state != SLOT_STATE_GENERATING || !preempt_served(slot))) { @@ -4758,13 +4755,12 @@ struct server_context_impl { continue; } - // the head's own bytes are not credited as leaving: the resident is parked before the head is restored and freed, so both states are held at once + // The head's bytes are not credited: the resident is parked before the head is freed, so both states are held at once. if (!with_recompute && !preempt_fits_budget(slot)) { budget_refused = true; continue; } - // the fewest cells that make room, else the most const int32_t n_freed = preempt_n_freed(slot); const int32_t n_pick = pick ? preempt_n_freed(*pick) : 0; @@ -4781,7 +4777,7 @@ struct server_context_impl { rotate_pick(false); - // [TAG_PREEMPT] a resident the budget cannot swap out is rotated by dropping its cells, as ordinary victim selection does: waiting instead has no bound, a resident that keeps shifting need never finish. The head waits longer for this than for a swap: the rotated resident pays a whole re-prefill, and under exact concurrency it stops being the sequence that was parked + // [TAG_PREEMPT] A resident the budget cannot swap is rotated by dropping its cells, since waiting has no bound. The head waits longer for this, as it costs the resident a full re-prefill. if (!pick && budget_refused && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_RECOMPUTE_US) { rotate_pick(true); @@ -4817,7 +4813,7 @@ struct server_context_impl { slot.n_preempt); } - // [TAG_PREEMPT_ASYNC] a synchronous park has released its cells, so the head is re-examined now; an asynchronous one on the pass that sees the copy land + // [TAG_PREEMPT_ASYNC] Sync parks freed their cells, so re-examine the head now; async ones on the pass that sees the copy land. if (slot.state == SLOT_STATE_PREEMPTED) { best = head; } @@ -4866,7 +4862,7 @@ struct server_context_impl { metrics.n_resume++; - // [TAG_PREEMPT] the synchronous restore returns with the slot already back in its old state, so issue and landing are the same moment here + // [TAG_PREEMPT] A synchronous restore lands as it is issued. send_preempt_notice(*best, false, recompute); if (recompute) { @@ -4894,7 +4890,7 @@ struct server_context_impl { continue; } - // the budget refusing is the recompute park's case, so the knob reaches it too + // the budget refusing is the recompute case, so the knob covers it const bool recompute = !preempt_fits_budget(slot); if (preempt_park(slot, ggml_time_us(), recompute)) { @@ -4905,7 +4901,7 @@ struct server_context_impl { } if (preempt_planner_off) { - return; // test knob: leave the pool to the retry ladder and its last resort + return; // test knob: leave the pool to the retry ladder } for (;;) { @@ -4919,7 +4915,7 @@ struct server_context_impl { continue; } - // [TAG_PREEMPT_ASYNC] a park issued and not landed holds cells that are already spoken for, so waiting for it is quicker than parking somebody else + // [TAG_PREEMPT_ASYNC] An issued park will free cells, so waiting for it beats parking somebody else. if (preempt_copies_in_flight()) { if (n_used > n_cells) { if (preempt_wait_in_flight()) { @@ -4944,7 +4940,7 @@ struct server_context_impl { const int64_t t_start = ggml_time_us(); if (!preempt_park(*victim, t_start, recompute)) { - break; // could not park it; the existing retry ladder is still behind us + break; // the retry ladder is still behind us } if (victim->state == SLOT_STATE_PREEMPTING) { @@ -4956,7 +4952,7 @@ struct server_context_impl { preempt_kv_used(), n_cells, n_used, victim->n_preempt); - // [TAG_PREEMPT_ASYNC] short of the lookahead only, the step still fits and leaving is the point; out of room for it the cells are held until the copy lands, so the retry ladder ends every request instead of waiting + // [TAG_PREEMPT_ASYNC] Short only of the lookahead, the step still fits; short of the step itself, wait for the copy or the retry ladder ends every request. if (n_used + preempt_n_margin() > n_cells) { continue; } @@ -4982,7 +4978,7 @@ struct server_context_impl { } } - // the checks a request has to pass before its prompt is processed; true when it is rejected. An empty prompt is not here: it is a final response, not an error. + // Checks a request must pass before its prompt is processed; true if rejected. An empty prompt is a final response, not an error. bool task_prompt_rejected(const server_task & task, std::string & msg, error_type & type) const { // TODO: support memory-less logits computation if (task.need_logits() && !llama_get_memory(ctx_tgt)) { @@ -4991,14 +4987,14 @@ struct server_context_impl { return true; } - // as launch_slot_with_task(), ahead of it: a sibling parked behind a running one used to fail inside a stream that had already opened 200 + // Mirrors launch_slot_with_task(), run earlier so a sibling is not rejected inside an already opened 200 stream. if (!task.tokens.validate(ctx_tgt)) { msg = "Prompt contains invalid tokens"; type = ERROR_TYPE_INVALID_REQUEST; return true; } - // as server_slot::can_split(), from the task alone + // Mirrors server_slot::can_split(), from the task alone. const auto pooling = llama_pooling_type(ctx_tgt); const bool can_split = !task.need_embd() || @@ -5037,7 +5033,6 @@ struct server_context_impl { return true; } - // the outputs of a decision are read from one batch const int32_t n_batch = llama_n_batch(ctx_tgt); const int32_t n_decision_first = task.type == SERVER_TASK_TYPE_DECISION ? task.decision.pos_first() : -1; if (n_decision_first >= 0 && task.n_tokens() - n_decision_first > n_batch) { @@ -5101,10 +5096,10 @@ struct server_context_impl { } try { - // [TAG_PREEMPT] make the pool fit the step about to be built, measured after any context shift; inside the guard because a shift or a park can throw + // [TAG_PREEMPT] Fit the pool to the next step, after any context shift; inside the guard since a shift or park can throw. pre_decode_shift(); - // before update_preemption(), and not only before the decode: a slot must never be parked with a shift still pending on its cells + // A slot must never be parked with a shift pending on its cells. preempt_apply_shift(); update_preemption(); @@ -5143,7 +5138,7 @@ struct server_context_impl { int32_t off_next = 0; int32_t n_batch = llama_n_batch(ctx_tgt); - // [TAG_PREEMPT_ASYNC] and once more here: a shift --cache-reuse asks for is found inside pre_decode(), after the wait above + // [TAG_PREEMPT_ASYNC] A --cache-reuse shift is found inside pre_decode(), after the wait above. preempt_wait_for_shift(); for (int32_t off = 0; off < batch.size(); off = off_next) { @@ -5413,7 +5408,7 @@ struct server_context_impl { return; // batch is full, skip remaining slots } - // [TAG_PREEMPT] a parked slot is processing but has nothing in the cache to batch until it is restored + // [TAG_PREEMPT] A parked slot has nothing in the cache to batch. if (!slot.is_processing() || slot.preempt_is_out()) { return; } @@ -5429,7 +5424,7 @@ struct server_context_impl { return; } - // [TAG_PREEMPT] a parked head that has waited its turn is not overtaken by a prompt that has never been resident + // [TAG_PREEMPT] A never-resident prompt does not overtake a parked head that has waited its turn. if (preempt_held(slot)) { preempt_log_held(slot); return; @@ -5439,7 +5434,7 @@ struct server_context_impl { if (slot.state == SLOT_STATE_PROCESSING_PROMPT || slot.state == SLOT_STATE_STARTED) { const auto & input_tokens = slot.preempt_input(); - // [TAG_PREEMPT] what the prompt step works towards: the re-prefill list of a park that dropped its cells, the request otherwise + // [TAG_PREEMPT] The re-prefill list of a recompute park, else the request's prompt. const int32_t n_input_tokens = slot.preempt_n_input(); // used to determine the number of tokens added to the batch for the current slot @@ -5493,7 +5488,7 @@ struct server_context_impl { } if (slot.can_split()) { - // the size of a decision is checked in slot_prompt_rejected, its first position bounds the reuse below + // the decision size is checked in slot_prompt_rejected; its first position bounds the reuse below const int32_t n_decision_first = slot.task->type == SERVER_TASK_TYPE_DECISION ? slot.task->decision.pos_first() : -1; const bool is_stateless_task = slot.task->type == SERVER_TASK_TYPE_EMBEDDING || slot.task->type == SERVER_TASK_TYPE_RERANK; @@ -5738,7 +5733,7 @@ struct server_context_impl { } } - // [TAG_EXACT_CONCURRENCY] a prompt is isolated into ubatches of its own, so it gets the shapes it would get alone only if what it adds here is a whole number of ubatches: otherwise a neighbour's decoded token shortens the last one, and 512,512,512,509 is not 512,512,512,512 + // [TAG_EXACT_CONCURRENCY] A prompt gets its standalone ubatch shapes only if it adds whole ubatches here; otherwise a neighbour's token shortens the last one. int32_t n_batch_cur = n_batch; if (common_exact_concurrency() && slot.can_split() && !slot.prompt.tokens.has_mtmd) { @@ -5751,7 +5746,7 @@ struct server_context_impl { if (n_take > 0) { n_batch_cur = (int32_t) batch.size() + n_take; } else { - // the waiting ends: common_exact_batch_geometry() refused a batch that cannot hold a whole ubatch beside a decode step of every slot, and the prompts ahead of this one in the same batch are finite + // Waiting ends: common_exact_batch_geometry() refused a batch too small for a whole ubatch beside every decode, and the prompts ahead are finite. SLT_DBG(slot, "exact concurrency: %d of %d batch tokens left, short of a %d-token ubatch: the prefill waits\n", n_avail, n_batch, n_ubatch); return; @@ -5807,7 +5802,7 @@ struct server_context_impl { // make checkpoints only for completion tasks do_checkpoint = do_checkpoint && slot.task->type == SERVER_TASK_TYPE_COMPLETION; - // a re-prefill walks its own list, which the request's message spans do not index + // a re-prefill walks its own list, which the message spans do not index do_checkpoint = do_checkpoint && !slot.preempt_reprefill; // make a checkpoint of the parts of the memory that cannot be rolled back. @@ -5839,7 +5834,7 @@ struct server_context_impl { break; } - // [TAG_PREEMPT_ASYNC] the chunk decodes whole, past the kv-full retry, so a park the planner issued for it has to land first + // [TAG_PREEMPT_ASYNC] The chunk decodes whole, past the kv-full retry, so a park issued for it must land first. while (preempt_wait_in_flight()) { } @@ -5864,7 +5859,7 @@ struct server_context_impl { metrics_queue_prompt(n_tokens_out); - // [TAG_PREEMPT] a re-prefill puts back what a park dropped: real compute, counted above, but it is not the request's prompt + // [TAG_PREEMPT] A re-prefill is real compute but not the request's prompt. if (!slot.preempt_reprefill) { slot.stats.n_prompt_processed += n_tokens_out; slot.stats.update_prompt_last(); @@ -5924,7 +5919,7 @@ struct server_context_impl { } slot.prompt.tokens.push_back(cur_tok); - // [TAG_EXACT_CONCURRENCY] a token that was decoded goes back through the arithmetic that decoded it: one per step, in the narrow set beside the other decodes. Re-prefilled wide it went through batched arithmetic, and the output diverged at the second park + // [TAG_EXACT_CONCURRENCY] Re-prefill an already decoded token one per step beside the other decodes, as it was decoded; batching it wide diverged the output at the second park. if (slot.preempt_reprefill && common_exact_concurrency() && slot.prompt.n_tokens() >= slot.task->n_tokens()) { break; } @@ -5978,14 +5973,14 @@ struct server_context_impl { GGML_ASSERT(batch.size() > 0); // extract the logits only for the last token - // [TAG_PREEMPT] except a re-prefill's under a backend sampler: that token was sampled before the park and post_decode throws the output away, but the sampler runs on every output of its sequence and, at one output per sequence, draws its uniform from the stream's own RNG, which would come back a draw ahead + // [TAG_PREEMPT] Except a re-prefill's last token under a backend sampler: it was sampled before the park, and sampling again would advance the stream's RNG by one draw. if (!(slot.preempt_reprefill && slot.backend_sampler && !slot.can_speculate())) { batch.set_output(batch.size() - 1, true); } slot.i_batch = batch.size() - 1; - // [TAG_PREEMPT] a re-prefill only puts back what the park dropped: the sampler and the counters carry on from where the park found them + // [TAG_PREEMPT] The sampler and counters carry on from where the park left them. if (!slot.preempt_reprefill) { slot.stats.n_gen = 0; @@ -6090,7 +6085,7 @@ struct server_context_impl { return true; } - // [TAG_PREEMPT_ASYNC] a recurrent memory keeps no fixed row per sequence: find_slot() gathers the active ones into contiguous rows, so a decode beside a park moves or overwrites the row the copy is still reading. A hybrid carries that half too, and so can the draft. + // [TAG_PREEMPT_ASYNC] Recurrent memory compacts active sequences in find_slot(), so a decode beside a park can move the row being copied. This applies to hybrids and the draft too. static bool preempt_state_relocates(const llama_model * model) { return model && (llama_model_is_recurrent(model) || llama_model_is_hybrid(model)); } @@ -6099,13 +6094,13 @@ struct server_context_impl { return preempt_state_relocates(model_tgt) || preempt_state_relocates(model_dft); } - // [TAG_PREEMPT_ASYNC] whether a park can happen at all and go asynchronously + // [TAG_PREEMPT_ASYNC] Whether a park can happen at all and go asynchronously. bool preempt_async_possible() const { return params_base.preempt_async && params_base.kv_unified && params_base.preempt_ram_mib != 0 && slots.size() >= 2 && llama_get_memory(ctx_tgt) && !preempt_state_relocates(); } - // [TAG_PREEMPT] read by clients deciding whether to rely on parking; notices is the version of the in-stream notice protocol + // [TAG_PREEMPT] For clients deciding whether to rely on parking; notices is the in-stream notice protocol version. json preempt_props() const { return json { { "enabled", params_base.kv_unified && slots.size() >= 2 && params_base.preempt_ram_mib != 0 && @@ -6122,7 +6117,7 @@ struct server_context_impl { return params_base.kv_unified && params_base.preempt_ram_mib != 0 && !preempt_recurrent && slots.size() >= 2 && llama_get_memory(ctx_tgt); } - // [TAG_PREEMPT] the retry ladder ran out: give the batch up, rewind every resident to the token boundary the cache is at and park the smallest. A media chunk mid-prompt keeps the old path. + // [TAG_PREEMPT] Retry ladder exhausted: give up the batch, rewind residents to the cache's token boundary and park the smallest. A media chunk mid-prompt keeps the old path. bool preempt_last_resort(int32_t off) { if (!preempt_last_resort_possible()) { return false; @@ -6135,7 +6130,7 @@ struct server_context_impl { continue; } - // a media chunk decodes whole through calls of its own, so a resident still inside its prompt cannot be rewound to a token boundary; one that is generating can + // A resident mid-prompt on a media chunk cannot be rewound to a token boundary; a generating one can. if (slot.prompt.tokens.has_mtmd && slot.state != SLOT_STATE_GENERATING) { return false; } @@ -6144,7 +6139,7 @@ struct server_context_impl { } if (n_running < 2) { - return false; // one conversation that does not fit alone is a real overflow + return false; // a conversation that does not fit alone is a real overflow } for (auto & slot : slots) { @@ -6181,7 +6176,7 @@ struct server_context_impl { n_parked++; - // [TAG_PREEMPT_ASYNC] the cells are wanted now, not next iteration: wait for the copy, which releases them + // [TAG_PREEMPT_ASYNC] The cells are needed now: wait for the copy. if (victim->state == SLOT_STATE_PREEMPTING) { while (preempt_wait_in_flight()) { } @@ -6201,7 +6196,7 @@ struct server_context_impl { } if (n_parked == 0) { - return false; // nothing could be parked: the error path clears what the rewind left + return false; // nothing parked: the error path cleans up the rewind } SRV_WRN("last resort: batch given up at off = %d, %d slot(s) parked, kv %d/%d resident\n", @@ -6264,20 +6259,20 @@ struct server_context_impl { }); if (ret != 0) { - // [TAG_PREEMPT_ASYNC] halving the batch returns no cells, so wait for an issued park first, or the ladder runs down to n_batch == 1 and ends every request + // [TAG_PREEMPT_ASYNC] Halving frees no cells, so wait for an issued park first or the ladder ends every request. if (ret == 1 && preempt_wait_in_flight()) { SRV_WRN("%s", "waited for an in-flight park before retrying the decode\n"); - return false; // retry at the same batch size, with the cells it freed + return false; // retry at the same batch size } { std::string err; - // [TAG_PREEMPT] a slot's sampled token and its draft have to stay in one view, so halving would split the group and make the verify step throw + // [TAG_PREEMPT] Halving would split a slot's sampled token from its draft and make the verify step throw. if (ret == 1 && n_batch > 1 && preempt_last_resort_possible() && batch_has_spec_groups()) { if (try_clear_idle_slots()) { SRV_WRN("%s", "failed to find free space in the KV cache, retrying after purging an idle slot\n"); - return false; // retry at the same width + return false; // retry at the same width } n_batch = 1; @@ -6417,7 +6412,7 @@ struct server_context_impl { } if (slot.state == SLOT_STATE_DONE_PROMPT) { - // [TAG_PREEMPT] the re-prefill is back in the cache; the token this slot had already sampled is decoded next, so nothing is sampled here + // [TAG_PREEMPT] The re-prefill is back; the already sampled token is decoded next, so do not sample. if (slot.preempt_reprefill) { slot.preempt_reprefill_done(); return; @@ -6719,7 +6714,7 @@ struct server_context_impl { n_prompt_tokens++; auto & slot = slots[t.id_slot]; - // [TAG_PREEMPT] replayed tokens stay out of the slot's prompt count, they were counted when the request first processed its prompt + // [TAG_PREEMPT] Replayed tokens were already counted as prompt. if (slot.stats.is_set() && !slot.preempt_reprefill) { slot.stats.n_prompt_processed++; } @@ -6738,7 +6733,7 @@ struct server_context_impl { for (int i = off; i < off + n_tokens; ++i) { const auto & t = batch.tokens[i]; auto & slot = slots[t.id_slot]; - // [TAG_PREEMPT] a re-prefill must not move the prompt/generation boundary: n_gen carries across the park, so the generation time would then cover only the tokens after it + // [TAG_PREEMPT] A re-prefill must not move the prompt/generation boundary, since n_gen carries across the park. if (t.is_prompt && slot.stats.is_set() && !slot.preempt_reprefill) { slot.stats.set_prompt_last(t_now); } @@ -6955,7 +6950,7 @@ std::unique_ptr server_routes::handle_completions_impl( task.params.oaicompat_cmpl_id = completion_id; task.params.oaicompat_model = meta->model_name; - // [TAG_EXACT_CONCURRENCY] exact mode gives a page to a single sequence, so refuse an n_cmpl > 1 child here, where it becomes a 400 rather than at seq_cp + // [TAG_EXACT_CONCURRENCY] Exact mode gives each page to one sequence, so reject n_cmpl > 1 here as a 400 rather than fail at seq_cp. if (task.params.n_cmpl > 1 && common_exact_concurrency()) { throw std::runtime_error( "n > 1 is not supported while LLAMA_EXACT_CONCURRENCY is set: each " @@ -6974,7 +6969,7 @@ std::unique_ptr server_routes::handle_completions_impl( tasks.push_back(std::move(task)); } - // [TAG_PREEMPT] every prompt of the request, before any of them is queued: one member can be parked, and its notice opens the stream, before another member is rejected + // [TAG_PREEMPT] Validate all prompts before queueing: a parked member's notice opens the stream before another could be rejected. { json error; @@ -7016,7 +7011,7 @@ std::unique_ptr server_routes::handle_completions_impl( for (size_t i = 1; i < arr.size(); i++) { choices.push_back(std::move(arr[i]["choices"][0])); } - // [TAG_PREEMPT] one response stands for every prompt (or choice), so its counters are the sum of each result's: a park of any member is the request's + // [TAG_PREEMPT] One response covers every prompt, so its counters sum all results. if (arr[0].contains("preempt")) { int64_t n_parks = 0; int64_t n_recomputes = 0; @@ -7041,9 +7036,9 @@ std::unique_ptr server_routes::handle_completions_impl( // in streaming mode, the first error must be treated as non-stream response // this is to match the OAI API behavior // ref: https://github.com/ggml-org/llama.cpp/pull/16486#discussion_r2419657309 - // [TAG_PREEMPT] a slot can be parked before any token exists, so those notices are kept and sent in front of the first real result + // [TAG_PREEMPT] A slot can be parked before any token exists, so its notices are sent before the first result. std::string preempt_prefix; - std::set parked_idx; // prompts of this request that are parked right now + std::set parked_idx; auto first_result = rd.next(req.should_stop); if (first_result != nullptr && dynamic_cast(first_result.get()) != nullptr) { const auto * notice = static_cast(first_result.get()); @@ -7136,7 +7131,7 @@ std::unique_ptr server_routes::handle_completions_impl( // receive subsequent results bool timeout = false; int64_t start_time = ggml_time_ms(); - // [TAG_PREEMPT] a parked slot produces nothing, so ping at least every 2 s whether or not --sse-ping asked for one, and name it; a shorter interval asked for is kept + // [TAG_PREEMPT] A parked slot is silent, so ping at least every 2 s regardless of --sse-ping; a shorter requested interval is kept. const int64_t ping_cfg = sse_ping_interval > 0 ? (int64_t) sse_ping_interval * 1000 : -1; const int64_t ping_ms = parked ? (ping_cfg > 0 ? std::min(ping_cfg, PREEMPT_KEEPALIVE_MS) : PREEMPT_KEEPALIVE_MS) : ping_cfg; auto result = rd.next([&timeout, &start_time, ping_ms, &effective_should_stop]() { @@ -7182,7 +7177,7 @@ std::unique_ptr server_routes::handle_completions_impl( ); json res_json = result->to_json(); if (res_json.is_null()) { - // [TAG_PREEMPT] the empty signal a prompt sends before its first token has nothing to add once a notice has opened the stream + // [TAG_PREEMPT] Skip the pre-token empty signal once a notice opened the stream. return true; } if (res_type == TASK_RESPONSE_TYPE_ANTHROPIC) { @@ -7317,9 +7312,9 @@ static json get_res_props(const server_context_meta & meta, const common_params { "endpoint_slots", params.endpoint_slots }, { "endpoint_props", params.endpoint_props }, { "endpoint_metrics", params.endpoint_metrics }, - // [TAG_EXACT_CONCURRENCY] a client that asked for the mode reads here whether this process runs it: a build that ignores the variable starts all the same + // [TAG_EXACT_CONCURRENCY] Tells clients whether the mode is active, since a build ignoring the variable still starts. { "exact_concurrency", common_exact_concurrency() }, - // [TAG_PREEMPT] whether this process parks sequences under pressure and how + // [TAG_PREEMPT] Whether and how this process parks sequences under pressure. { "preempt", meta.preempt }, { "ui", params.ui }, { "ui_settings", meta.json_ui_settings }, diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp index 8ddcdc27dda1..4291fd8a5281 100644 --- a/tools/server/server-decision.cpp +++ b/tools/server/server-decision.cpp @@ -1233,7 +1233,7 @@ json server_decision_context::format_answer(const server_decision_question & que // std::vector server_decision_group_tasks(std::vector && tasks, size_t n_slots) { - // [TAG_EXACT_CONCURRENCY] a child continues from the parent's cells through seq_cp, which exact mode refuses (a page belongs to one sequence): every task keeps its whole prompt + // [TAG_EXACT_CONCURRENCY] Exact mode refuses seq_cp (a page belongs to one sequence), so every task keeps its whole prompt. if (common_exact_concurrency()) { return std::move(tasks); } diff --git a/tools/server/server-queue.cpp b/tools/server/server-queue.cpp index b37ccebe11f8..bf7cd68e6a79 100644 --- a/tools/server/server-queue.cpp +++ b/tools/server/server-queue.cpp @@ -448,7 +448,7 @@ server_task_result_ptr server_response::recv(const std::unordered_set & id_ } server_task_result_ptr server_response::recv_with_timeout(const std::unordered_set & id_tasks, int timeout) { - // [TAG_PREEMPT] the timeout is a deadline, not a per-wait duration: send() notify_all()s for every result of every task, and with wait_for() each wakeup restarted the wait + // [TAG_PREEMPT] The timeout is a deadline: send() wakes all waiters for every result, and wait_for() restarted the wait on each wakeup. const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout); while (true) { @@ -530,7 +530,7 @@ void server_response_reader::post_tasks(std::vector && tasks, const id_tasks = server_task::get_list_id(tasks); states.reserve(tasks.size()); size_t index = 0; - // [TAG_PREEMPT] several prompts, or several completions of one prompt, all number their results, and their preempt notices have to say which one they belong to + // [TAG_PREEMPT] Multiple prompts or completions number their results, and preempt notices must say which one they belong to. const bool batched = id_tasks.size() > 1; for (auto & task : tasks) { task.index = index++; diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 941fad0e552d..5a842a8a166c 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -444,7 +444,7 @@ struct server_task_result_cmpl_final : server_task_result { json to_json_anthropic_stream(); }; -// [TAG_PREEMPT] out-of-band notice for a streaming task whose slot was parked or restored, sent as an SSE comment (": preempted", ": resumed") every existing client ignores +// [TAG_PREEMPT] Notice for a streaming task whose slot was parked or restored, sent as an SSE comment (": preempted", ": resumed") that clients ignore. struct server_task_result_preempt_notice : server_task_result { bool parked = false; // true when the slot was just parked, false when restored bool recomputed = false; // this resume re-prefilled its tokens instead of restoring saved bytes diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 2ece78eef16e..17e200439e34 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -12,14 +12,14 @@ import requests from utils import * -# Preemption on a unified KV pool: one slot is parked, its sequence copied to host RAM and its cells released, instead of every slot being terminated. Needs --kv-unified. +# Preemption on a unified KV pool: one slot is parked in host RAM instead of every slot being terminated. Needs --kv-unified. server = ServerPreset.tinyllama2() _ASYNC_BANNER = "parking and resuming asynchronously" _scratch = [] # files a test wrote, removed after it -_cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES") # put back after a test that hides the GPUs +_cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES") # restored after a test that hides the GPUs _PROMPT_A = "Once upon a time there was a brave knight who" _PROMPT_B = "The quick brown fox jumps over the lazy dog and" @@ -32,7 +32,7 @@ def create_server(): server = ServerPreset.tinyllama2() server.n_slots = 2 server.kv_unified = True - # the server parks only when asked: --preempt-ram defaults to 0, and this suite is about parking + # --preempt-ram defaults to 0, so parking must be enabled. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" server.server_slots = True server.server_metrics = True @@ -93,7 +93,7 @@ def _complete(n_predict: int, prompt="Hi how are you", id_slot: int = -1, delay: timeout: float = DEFAULT_REQUEST_TIMEOUT): time.sleep(delay) if after_slot_busy is not None: - # sent once that slot is processing, so the request queues behind it whatever the host's speed + # Sent once that slot is processing, so the request queues behind it regardless of host speed. for _ in range(200): slots = server.make_request("GET", "/slots").body if any(s["id"] == after_slot_busy and s["is_processing"] for s in slots): @@ -159,7 +159,7 @@ def _assert_completed(results, n_predict: int): def _assert_nothing_parked(text: str): - # the park log lines, not the bare word: a verbose log prints every slot's "is_preempted" + # Match park log lines, not the bare word: verbose logs print every slot's "is_preempted". assert not any(m in text for m in _PARK_MARKERS), "nothing could be parked here" @@ -213,9 +213,9 @@ def test_forced_parks_do_not_change_the_output(mode): @pytest.mark.parametrize("knob", ["planner", "pages", "async", "last-resort", "last-resort-unlimited"]) def test_two_generations_that_do_not_fit_together_both_finish(knob): - # each request fits the pool alone (960 and 600 of 1024 cells) but not together; without preemption both end with "Context size has been exceeded" + # Each request fits the pool alone (960 and 600 of 1024 cells) but not together. if knob == "pages": - # a block allocator gives a whole block to one sequence, so the planner has to count cells: counting tokens it sees room the allocator cannot find + # A block allocator gives each block to one sequence, so the planner must count cells, not tokens. os.environ["LLAMA_SERVER_PREEMPT_GRANULARITY"] = "64" if knob.startswith("last-resort"): os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" @@ -224,8 +224,7 @@ def test_two_generations_that_do_not_fit_together_both_finish(knob): n_ctx = 1024 (_start_async if knob == "async" else _start)(n_ctx=n_ctx) - # the lengths, not the client's speed, decide the overlap: two equal requests fired together did not overlap on a Windows runner, the first finished before the second arrived, and the last resort never saw the two residents it needs. - # the follower is sent once the leader is seen processing, so it holds its cells while the leader grows into the rest of the pool + # Lengths, not client speed, must force the overlap: equal requests fired together did not overlap on a Windows runner. n_predict = (460, 400) results = _complete_overlapping(n_predict, (500, 200)) @@ -258,12 +257,12 @@ def test_a_request_that_cannot_be_helped_gets_the_context_error_and_the_server_l if knob == "ram-0": os.environ["LLAMA_ARG_PREEMPT_RAM"] = "0" else: - # a family member is not a victim for the other, so a two-completion request gets the error it would get alone + # Family members are not victims for each other, so a two-completion request gets the same error as alone. os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" _start(n_ctx=256) if knob == "ram-0": - # the overflow has to be a matter of lengths: two equal requests fired together did not overlap on a Windows runner, and each one fits the pool alone + # The overflow must come from lengths, since equal concurrent requests did not overlap on a Windows runner. assert any(res.status_code != 200 for res in _complete_overlapping((110, 100), (120, 60))) else: res = server.make_request("POST", "/completion", data={ @@ -291,7 +290,6 @@ def test_a_server_that_never_asked_for_parking_behaves_as_upstream(): assert "preemption:" not in text, "a server that did not ask for parking announced it" assert _ASYNC_BANNER not in text, "the async park path was set up without being asked for" - # as above, the two have to be resident together for the pool to overflow at all assert any(res.status_code != 200 for res in _complete_overlapping((110, 100), (120, 60))) text = _log() @@ -330,17 +328,17 @@ def test_a_late_prompt_and_a_generating_slot_both_finish(planner): for res, n_predict in zip(results, (n_predict_a, n_predict_b)): assert res.status_code == 200, res.body assert res.body["timings"]["predicted_n"] == n_predict - # the chunk in the batch given up is processed once after the rewind, never twice + # The chunk in the abandoned batch is processed once after the rewind, never twice. assert results[1].body["timings"]["prompt_n"] == n_b def test_a_prompt_parked_before_its_first_token_is_issued_whole(): - # both prompts are too close to n_ctx to leave the usual margin, so the second is parked before it takes a cell and has to come back once the first has finished + # Both prompts are too close to n_ctx for the usual margin, so the second is parked before taking a cell and resumes after the first finishes. _start(n_ctx=256, n_batch=256) n_prompt = 240 n_predict = 4 - # two different prompts: with the same one, the second can be served from the first one's cached cells after it finishes, and prompt_n is then 1 + # Different prompts: with the same one the second could reuse the first's cached cells and prompt_n would be 1. together = _complete_all(n_predict, [_prompt_of(n_prompt, _PROMPT_A), _prompt_of(n_prompt, _PROMPT_B)]) assert "cannot fit the pool" not in _log() @@ -350,10 +348,10 @@ def test_a_prompt_parked_before_its_first_token_is_issued_whole(): def test_a_resident_cycling_through_context_shifts_is_rotated_out_for_a_parked_head(): - # with context shift on a resident would hold its cells for as long as it generates, so once the head has waited its turn the resident is parked and the two take turns + # With context shift a resident never frees its cells, so once the head has waited it is parked and the two take turns. _start(n_slots=3, n_ctx=384, enable_ctx_shift=True) - # the rotation waits on a clock, not on a token count, so the generation has to be long enough on a fast host; that is a lot of tokens for a slow one, and it takes turns with two others, so it is given more than the usual wait + # Rotation is clock-based, so a fast host needs a long generation, and a slow host then needs a longer wait. n_predict = 9000 _assert_completed(_complete_all(n_predict, (_PROMPT_A, _PROMPT_B, _PROMPT_C), timeout=1800), n_predict) @@ -363,11 +361,11 @@ def test_a_resident_cycling_through_context_shifts_is_rotated_out_for_a_parked_h def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): - # the budget grants permission to allocate, not a successful allocation: a failed save used to stop the planner and leave the pool to overflow, although the same victim could be parked by dropping its cells + # A failed save used to stop the planner and let the pool overflow, though the victim could still be parked by dropping its cells. os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" _start(n_ctx=1024, n_slots=2) - # lengths decide the overlap, not the host's speed: two 171-cell requests fired together did not overlap on a Windows runner, so nothing was parked. The leader ends at 960 of 1024 cells, so the second is parked whatever the client's lag + # The leader ends at 960 of 1024 cells, so the second is parked regardless of client lag. leader = _prompt_of(500, _PROMPT_A) other = _prompt_of(200, _PROMPT_B) with ThreadPoolExecutor(1) as pool: @@ -386,18 +384,18 @@ def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): def test_a_resident_that_cannot_be_swapped_out_is_rotated_by_recompute(): - # 1 MiB holds no snapshot, so rotation refused every resident and only logged that the head waits: a resident that keeps context-shifting need never finish, and the head waited behind it for good + # 1 MiB holds no snapshot, so rotation used to refuse every resident and the head waited forever behind a context-shifting one. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" _start(n_ctx=2048, n_slots=2, n_batch=2048, enable_ctx_shift=True) - # a small n_discard keeps the resident near the end of the pool, so its state never fits the budget + # A small n_discard keeps the resident near the end of the pool, so its state never fits the budget. def unending_request(): return server.make_request("POST", "/completion", data={ "n_predict": 100000, "prompt": _PROMPT_A, "n_keep": 1, "n_discard": 64, "ignore_eos": True, "temperature": 0.0, "seed": 42, }, timeout=600) - # the server is stopped below with this request still in flight, so the disconnect it then sees is expected and must not surface as an unhandled thread exception + # The server is stopped with this request in flight, so the disconnect is expected. unending = [] def run_unending(): @@ -410,7 +408,7 @@ def run_unending(): t.start() try: - # the resident has to be at the pool's limit and cycling before a second prompt cannot fit beside it + # The resident must be at the pool's limit and cycling before a second prompt cannot fit. for _ in range(3000): if "slot context shift" in _log(): break @@ -437,7 +435,7 @@ def run_unending(): def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): - # a cancelled request can reach release() with a park or a resume still running, where the host buffer is freed and the cells handed on, so both have to wait for the copy + # A cancelled request can reach release() with a copy running, so release must wait for it. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start_async(n_ctx=512) @@ -447,7 +445,7 @@ def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): "n_predict": 96, "prompt": _PROMPT_A, "ignore_eos": True, "temperature": 0.0, "seed": 42, }, timeout=0.05 + 0.1 * i) except Exception: - pass # the point is the drop, not the response + pass for _ in range(600): res = server.make_request("GET", "/slots") @@ -468,16 +466,16 @@ def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): def test_a_started_slot_is_counted_by_the_cells_it_holds_not_by_the_prompt_it_keeps(): - # the last request waits for slot 0 and is started on it holding the first request's cells; counted by the prompt it keeps instead, the pool looks free and a parked slot is restored into cells that are still taken + # The last request starts on slot 0 holding the first request's cells; counting only its kept prompt made the pool look free and a restore landed on taken cells. _start(n_ctx=1024, n_slots=3) - # the lengths, not the host's speed, decide who is parked: the three prompts (500 + 200 + 200) fit the 1024 cells, so both of the others are parked holding at least their whole prompt once slot 0 grows into the rest, and slot 0 is the largest slot throughout, which the planner never picks as a victim. Slot 0 ends holding 960 of the 1024 cells, too few left for either parked slot to come back + # 500 + 200 + 200 fit 1024 cells, so both small slots are parked with their whole prompt once slot 0 grows; slot 0 stays largest and ends at 960 cells, too few for either to return. ids = _prompt_of(500, _PROMPT_C) with ThreadPoolExecutor(4) as pool: first = pool.submit(_complete, 460, ids, 0) _wait_processing([0]) - # queued behind slot 0 whatever the host's speed, and a real prefix of what slot 0 holds: it starts on 960 cells while keeping 8 of them + # Queued behind slot 0 and a real prefix of what it holds: it starts on 960 cells keeping 8. follower = pool.submit(_complete, 8, ids[:8], 0) long_ones = [pool.submit(_complete, 400, _prompt_of(200, _PROMPT_A), 1), pool.submit(_complete, 400, _prompt_of(200, _PROMPT_B), 2)] @@ -506,7 +504,7 @@ def test_a_recurrent_model_is_served_without_preemption(): os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" server.start(timeout_seconds=300) - # not "Once upon a time": what this Q2_K model decodes from it on CUDA carries bytes the content parser refuses, master included, which is not what this test measures + # Not "Once upon a time": on CUDA this Q2_K model decodes bytes the content parser refuses, also on master. results = _complete_all(64, ["The quick brown fox", "Hello world"]) _assert_completed(results, 64) @@ -536,11 +534,11 @@ def _stream_completion(n_predict: int, prompt: str | list[int]) -> tuple[list[st @pytest.mark.parametrize("planner", ["on", "off"]) def test_a_budget_that_holds_no_sequence_parks_by_dropping_the_cells(planner): - # 1 MiB holds neither sequence, so no victim fits the budget: the park drops the cells and the resume re-prefills the tokens, instead of the pool overflowing and ending both; the last resort falls back the same way + # 1 MiB fits neither sequence, so the park drops the cells and the resume re-prefills; the last resort falls back the same way. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" if planner == "off": os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" - # one batch for the re-prefill: a prompt of this length in 32-token batches hangs the CUDA build with graphs on, master included, so that is not what this test measures + # One batch for the re-prefill: this prompt in 32-token batches hangs the CUDA build with graphs on, also on master. _start(n_ctx=3840, n_batch=2048) n_predict = 2000 @@ -565,7 +563,7 @@ def test_a_budget_that_holds_no_sequence_parks_by_dropping_the_cells(planner): def test_a_media_chunk_is_reserved_whole_before_it_is_decoded(): - # a chunk is decoded whole inside one iteration, through decodes the kv-full retry does not cover: unless the planner reserves every cell it takes, the second of two image requests that each fit alone fails part way through its chunk + # A media chunk decodes whole outside the kv-full retry, so unless the planner reserves all its cells the second of two image requests fails mid-chunk. os.environ["LLAMA_MEDIA_MARKER"] = "<__media__>" server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" server.model_hf_file = None @@ -589,15 +587,15 @@ def test_a_media_chunk_is_reserved_whole_before_it_is_decoded(): def test_an_mtp_draft_stays_inside_the_reservation_it_was_priced_for(): - # near the end of the pool the planner prices one draft token and one sampled token, but the draft loop stopped against the configured window and could attempt positions past the reservation + # Near the end of the pool the draft loop could attempt positions past the planner's reservation. path = os.environ.get("LLAMA_SERVER_TEST_MTP_MODEL") if not path: pytest.skip("set LLAMA_SERVER_TEST_MTP_MODEL to a gguf carrying an MTP head") # ty: ignore[too-many-positional-arguments] server.model_file = path server.model_hf_repo = server.model_hf_file = None server.spec_type = "draft-mtp" - os.environ["LLAMA_ARG_SPEC_DRAFT_P_MIN"] = "0.0" # nothing but the bounds stops the draft loop - os.environ["LLAMA_ARG_LOG_VERBOSITY"] = "5" # the wrapper says so when it truncates what an implementation returned + os.environ["LLAMA_ARG_SPEC_DRAFT_P_MIN"] = "0.0" # only the bounds stop the draft loop + os.environ["LLAMA_ARG_LOG_VERBOSITY"] = "5" # logs when the wrapper truncates a draft _start(n_ctx=2048, n_slots=2, n_batch=2048, n_gpu_layer=99, spec_draft_n_max=128, spec_draft_n_min=1) n_prompt = 2045 @@ -617,7 +615,7 @@ def test_an_mtp_draft_stays_inside_the_reservation_it_was_priced_for(): def test_a_hybrid_model_parks_synchronously(): - # the recurrent half of a hybrid gathers the active sequences into contiguous rows on every batch, so a copy running beside the decode could read a row another sequence has been moved into + # A hybrid's recurrent half compacts active sequences each batch, so a concurrent copy could read a moved row. path = os.environ.get("LLAMA_SERVER_TEST_HYBRID_MODEL") if not path: pytest.skip("set LLAMA_SERVER_TEST_HYBRID_MODEL to a hybrid attention/recurrent gguf") # ty: ignore[too-many-positional-arguments] @@ -638,7 +636,7 @@ def test_a_hybrid_model_parks_synchronously(): _assert_recovered(text, "preempted on request") -# [TAG_EXACT_CONCURRENCY] the paged pool places a cell from the sequence and the position alone, so a layout that gives several tokens one position cannot be served +# [TAG_EXACT_CONCURRENCY] The paged pool places a cell by sequence and position, so layouts with shared positions cannot be served. def _mrope_model() -> str: path = os.environ.get("LLAMA_SERVER_TEST_MROPE_MODEL") @@ -648,12 +646,12 @@ def _mrope_model() -> str: def test_exact_concurrency_refuses_an_mrope_model_with_a_projector(): - # every token of one image shares a temporal position under M-RoPE, so the pool would give the second one the first one's cell + # Under M-RoPE all tokens of one image share a temporal position. path = _mrope_model() with tempfile.TemporaryDirectory() as tmp: mmproj = os.path.join(tmp, "mmproj.gguf") with open(mmproj, "wb") as f: - f.write(b"GGUF" + struct.pack(" list: def test_exact_concurrency_prefills_a_prompt_in_the_ubatches_it_would_get_alone(): - # generated tokens enter the batch first and a prompt took what was left, so its ubatches were 512,512,512,509 beside three decoders and 512,512,512,512 alone: isolating the sequences does not make the shapes equal by itself - # geometry: -b 2048 -ub 512 -np 4, so the batch holds a whole ubatch beside a decode step of every slot (516 tokens), which is what common_exact_batch_geometry() requires of a start + # Generated tokens enter the batch first, so a prompt got ubatches 512,512,512,509 beside three decoders and 512,512,512,512 alone. + # -b 2048 -ub 512 -np 4: the batch holds a whole ubatch plus one decode per slot (516 tokens), as common_exact_batch_geometry() requires. path = os.environ.get("LLAMA_SERVER_TEST_EXACT_MODEL") if not path: pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") # ty: ignore[too-many-positional-arguments] @@ -734,7 +732,7 @@ def prefill(first_token: int) -> list: assert res.status_code == 200, res.body assert res.body["timings"]["prompt_n"] == 3500 text = _log()[mark:] - # a decode step is one token per slot, so the prompt's own ubatches are the wide ones + # Decode steps are one token per slot, so the wide ubatches are the prompt's. return [w for w in _ubatch_widths(text) if w > 3] alone = prefill(1000) @@ -770,7 +768,7 @@ def decoder(i): def test_slots_reports_a_transferring_slot_apart_from_a_parked_one(): - # a copy out still owns its cells and a restore has already taken them back, so a reader counting residency has to keep counting both; only a fully parked slot holds nothing + # Slots copying out or restoring still hold cells; only a fully parked slot holds nothing. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "1" _start_async(n_ctx=256) @@ -809,7 +807,7 @@ def _shift_completion(n_predict: int): def test_a_park_right_after_a_context_shift_does_not_change_the_output(): - # the shift moves the positions and leaves the K transformation for the next decode, so a park in between used to save the new positions with the old K + # A shift defers the K transform to the next decode, so a park in between used to save new positions with old K. os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "0" os.environ["LLAMA_ARG_PREEMPT_RAM"] = "0" _start(n_ctx=256, n_batch=32, n_ubatch=32, enable_ctx_shift=True, cache_ram=0) @@ -821,7 +819,7 @@ def test_a_park_right_after_a_context_shift_does_not_change_the_output(): n_prompt = reference.body["timings"]["prompt_n"] server.stop() - # park on the step the shift lands on: the pool holds n_ctx cells, so the first shift is that many tokens in + # The pool holds n_ctx cells, so the first shift is that many tokens in. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = str(256 - n_prompt) _start() @@ -838,7 +836,7 @@ def test_a_park_right_after_a_context_shift_does_not_change_the_output(): def test_a_sibling_prompt_with_an_invalid_token_is_refused_before_anything_streams(): - # validated with the others ahead of posting: parked behind a running sibling, it used to fail inside a stream that had already opened 200 + # Validated before posting: parked behind a running sibling, it used to fail inside an already opened 200 stream. _start(n_ctx=256, n_slots=2, n_batch=256) res = server.make_request("POST", "/completion", data={ @@ -852,7 +850,7 @@ def test_a_sibling_prompt_with_an_invalid_token_is_refused_before_anything_strea def test_a_recompute_park_bounds_its_draft_by_the_tokens_it_comes_back_with(): - # a recompute park moves the prompt out of the slot, and the draft was bounded by the empty prompt: 2000 tokens and a whole draft could not fit a 2048-cell pool "even alone", failing a request that fits + # A recompute park empties the prompt, and bounding the draft by it failed a 2000-token request in a 2048-cell pool as impossible. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "1" server.spec_type = "ngram-mod" @@ -873,7 +871,7 @@ def test_a_recompute_park_bounds_its_draft_by_the_tokens_it_comes_back_with(): def test_props_says_whether_exact_concurrency_is_running(): - # a client that asked for the mode reads the answer here: a build that ignores the variable starts all the same + # A build ignoring the variable still starts, so clients read the answer here. _start(n_ctx=256) res = server.make_request("GET", "/props") assert res.status_code == 200 @@ -891,7 +889,7 @@ def test_props_reports_exact_concurrency_on(): def test_a_recompute_park_under_exact_concurrency_says_it_is_not_byte_identical(): - # a state that comes back from host memory is the state that left; one rebuilt by re-prefilling differs in the last bits on CUDA, so the mode says so the first time it happens + # A re-prefilled state differs in the last bits on CUDA, so the mode reports it the first time. server.model_file = _mrope_model() server.model_hf_repo = server.model_hf_file = None os.environ["LLAMA_EXACT_CONCURRENCY"] = "1" @@ -907,10 +905,10 @@ def test_a_recompute_park_under_exact_concurrency_says_it_is_not_byte_identical( def test_a_recompute_park_is_reported_to_the_client_and_to_metrics(): - # a recompute resume re-prefills instead of restoring the saved bytes, so it is not the continuation the parked state would have given: the request, /slots and /metrics all say how often that happened + # A recompute resume is not bit-identical to the saved state; the request, /slots and /metrics report how often it happened. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" - # a sequence this long holds more than the 1 MiB budget, so every park drops its cells + # This sequence exceeds the 1 MiB budget, so every park drops its cells. _start(n_ctx=2048, n_batch=2048) n_predict = 24 @@ -922,7 +920,6 @@ def test_a_recompute_park_is_reported_to_the_client_and_to_metrics(): assert final["preempt"]["parks"] >= 2, final["preempt"] assert final["preempt"]["recomputes"] == final["preempt"]["parks"], final["preempt"] - # the notice comes right after the resume it belongs to resumed = [i for i, c in enumerate(comments) if c.startswith(": resumed")] assert len(resumed) == final["preempt"]["recomputes"], comments for i in resumed: @@ -932,7 +929,6 @@ def test_a_recompute_park_is_reported_to_the_client_and_to_metrics(): assert metrics["preempt_recompute_total"] == final["preempt"]["recomputes"] assert metrics["preempt_recompute_total"] == metrics["n_preempt_total"] - # a request that is never parked says so plain = server.make_request("POST", "/completion", data={ "n_predict": 4, "prompt": _PROMPT_B, "temperature": 0.0, "seed": 42, }) @@ -941,7 +937,7 @@ def test_a_recompute_park_is_reported_to_the_client_and_to_metrics(): def test_a_recompute_restore_does_not_count_its_replay_as_prompt(): - # the re-prefill puts back what the park dropped: counted as prompt it would move the prompt/generation boundary, and since n_gen carries across the park the generation time would then cover only the tokens after the last re-prefill + # Counting the re-prefill as prompt would move the prompt/generation boundary, and the generation time would cover only tokens after the last re-prefill. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=2048, n_batch=2048) @@ -956,12 +952,11 @@ def test_a_recompute_restore_does_not_count_its_replay_as_prompt(): timings = res.body["timings"] assert timings["prompt_n"] == n_prompt, timings assert timings["predicted_n"] == n_predict, timings - # every re-prefill happens inside the generation, so the generation holds the longer time of the two + # Every re-prefill happens during generation, so the generation time is the longer. assert timings["predicted_ms"] > timings["prompt_ms"], timings def test_slots_reports_the_recomputes_of_the_current_task(): - # a reader watching the slots sees the same count the request is given at the end os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=2048, n_batch=2048) @@ -990,7 +985,7 @@ def test_slots_reports_the_recomputes_of_the_current_task(): def test_a_swap_park_is_not_reported_as_a_recompute(): - # the same park with room for its bytes keeps the sequence it saved, and the client is told so + # With room for its bytes the park keeps the saved sequence, and the client is told so. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512) @@ -1022,7 +1017,7 @@ def _stream_responses(n_predict: int, prompt: str) -> dict: def test_a_streamed_response_carries_the_preempt_record_where_a_plain_one_does(): - # what a client keeps from a streamed /v1/responses is data["response"], so the record has to be in that object, the same place the non-streamed body carries it + # Clients keep data["response"] from a streamed /v1/responses, so the record must be there, as in the non-streamed body. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512) @@ -1039,7 +1034,7 @@ def test_a_streamed_response_carries_the_preempt_record_where_a_plain_one_does() def test_two_image_chats_that_outgrow_the_parking_budget_both_finish(): - # a media chunk could not be parked by recompute, so with the host budget spent nothing could be parked at all and the pool overflowing ended both chats. The chunk comes back the way it went in: re-encoded off the task, its cells reserved whole + # Media chunks could not be recompute-parked, so with no budget the pool overflowed and ended both chats. Now the chunk is re-encoded from the task with its cells reserved whole. os.environ["LLAMA_MEDIA_MARKER"] = "<__media__>" os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" @@ -1066,8 +1061,8 @@ def test_two_image_chats_that_outgrow_the_parking_budget_both_finish(): def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): - # a park with no budget for the state drops the cells of a prompt that is still being processed, and the resume starts that prefill again from nothing: what it had counted before the park has to go with the cells, or the request reports more prompt tokens than it has - # the park is made to fail its host allocation, so it drops the cells instead: the state of a half processed prompt is small enough to fit any budget + # A recompute park mid-prefill restarts the prefill, so the prompt count before the park must be dropped too. + # The park's host allocation is forced to fail, so it drops the cells instead. os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" _start(n_ctx=2048, n_batch=256) @@ -1075,7 +1070,7 @@ def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): t = threading.Thread(target=lambda: resident.append(_complete(1900, _PROMPT_A)), daemon=True) t.start() - # the pool has to be nearly full before the second prompt starts, so that it is that prefill which runs out of cells + # The pool must be nearly full before the second prompt starts, so its prefill runs out of cells. deadline = time.time() + 90 while t.is_alive() and time.time() < deadline: slots = server.make_request("GET", "/slots").body @@ -1094,7 +1089,7 @@ def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): assert "error" not in final, final assert comments and comments[0] == ": preempted", comments - # a park that dropped fewer cells than the resume has tokens to put back is a park taken mid-prefill, which is the case this test is about + # A park that dropped fewer cells than the resume puts back was taken mid-prefill, the case under test. parks = [(int(cells), int(again)) for cells, again in re.findall( r"preempted: (\d+) cells dropped .*? (\d+) tokens to re-prefill", _log())] assert any(0 < cells < again for cells, again in parks), parks @@ -1140,12 +1135,12 @@ def _serve_with_training_context(n_ctx_train: int): def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): - # a parked head of 7300 cells needs nearly the whole pool, and short requests that fit kept arriving and finishing, two queued per slot, so a resident was always there and the head waited for as long as the stream lasted. Once the head has waited its turn, a prompt that has never been resident waits for it. - # 1 MiB holds no short request's state, so none is rotated out for the head before PREEMPT_ROTATE_RECOMPUTE_US: what brings the head back early is the reservation alone + # A 7300-cell parked head used to wait forever while short requests kept a resident present. Once the head has waited its turn, never-resident prompts wait for it. + # 1 MiB holds no short request's state, so only the reservation brings the head back before PREEMPT_ROTATE_RECOMPUTE_US. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" - # parks the head while it generates; a short request never gets that far + # Parks the head while it generates. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "48" - # the scheduling under test is host code; on CUDA a prompt chunk across position 2048 of this context-extended model hangs llama_decode, the pin's base included, so the server runs on the CPU + # On CUDA a prompt chunk across position 2048 of this model hangs llama_decode (also on base), so run on CPU; the code under test is host-side. os.environ["CUDA_VISIBLE_DEVICES"] = "" _serve_with_training_context(8192) _start(n_ctx=8192, n_slots=4, n_batch=1024) @@ -1153,7 +1148,7 @@ def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): short_prompt = _prompt_of(1700, _PROMPT_B) head_prompt = _prompt_of(7200, _PROMPT_A) n_short, n_head = 32, 100 - # a starved head waits for as long as the stream lasts, so any bound catches it; the head prefills its 7200 tokens three times (two parks, no room to keep them), which took 46 s on a CPU CI runner and 92 s on a Windows one + # A starved head waits forever, so any bound catches it; the head prefills 7200 tokens three times, 46 s on a CPU runner and 92 s on Windows. t_stream_max = 240.0 stop = threading.Event() @@ -1197,7 +1192,7 @@ def stream(id_slot): assert "Context size has been exceeded" not in text assert not stopped_early, f"the head was still waiting when the stream was stopped after {t_stream_max} s" assert "prompt held:" in text, "no prompt was held back for the head" - # the head comes back once the residents in front of it have finished, about one quantum after each park + # The head returns once the residents ahead of it finish, about one quantum after each park. waits = [float(w) for w in re.findall(r"id +3 \| task \d+ \| resumed after ([\d.]+) s", text)] assert waits, "the head was never parked and resumed" assert max(waits) < 10.0, f"the head waited {waits} s behind requests that came after it" @@ -1205,7 +1200,7 @@ def stream(id_slot): @pytest.mark.slow def test_a_long_resident_that_never_shifts_is_rotated_out_for_an_aged_head(): - # only a resident cycling through context shifts used to be rotated, so a long generation that fits the pool held it to the end, and the parked slot waited for all of it + # Only context-shifting residents used to be rotated, so a long generation that fit held the pool and the parked slot waited for all of it. _serve_with_training_context(16384) _start(n_ctx=16384, n_slots=2, n_batch=2048) @@ -1215,7 +1210,7 @@ def run(name, n_predict, prompt, id_slot): res = _raw_completion(n_predict, prompt, id_slot, timeout=900) done[name] = (time.time(), res) - # A leads B by 564 cells throughout, so B is the one parked once the two fill the pool; A then has about 7600 tokens to go, far longer than the 2 s a parked head waits + # A leads B by 564 cells, so B is parked once the pool fills, and A then runs far longer than the 2 s a parked head waits. a = threading.Thread(target=run, args=("a", 16000, _prompt_of(64, _PROMPT_A), 0)) a.start() deadline = time.time() + 300 @@ -1239,7 +1234,7 @@ def run(name, n_predict, prompt, id_slot): def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small_ones(): - # the second chunk of a long prompt is short of about 600 cells: smallest first parked both 400-token residents, where the 1400-token one covers the shortfall alone + # The second chunk is about 600 cells short: smallest-first parked both 400-token residents, where the 1400-token one alone covers it. _serve_with_training_context(8192) _start(n_ctx=4864, n_slots=4, n_batch=2048) @@ -1249,7 +1244,7 @@ def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small with ThreadPoolExecutor(4) as pool: residents = [pool.submit(_raw_completion, 300, p, i) for i, p in enumerate(small + [medium])] - # every resident is generating before the leader arrives, so the leader's second chunk is what the pool is short of + # Every resident is generating before the leader arrives, so the leader's second chunk is the shortfall. deadline = time.time() + 60 while time.time() < deadline: slots = server.make_request("GET", "/slots").body @@ -1274,7 +1269,7 @@ def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small @pytest.mark.parametrize("ram", ["8192", "0", "unset"]) def test_props_reports_the_preemption_setup(ram): - # a client deciding whether to rely on parking reads this instead of guessing from the version + # Clients read this instead of guessing from the version. if ram == "unset": os.environ.pop("LLAMA_ARG_PREEMPT_RAM", None) else: @@ -1311,7 +1306,7 @@ def test_props_reports_the_planning_granularity(): def test_a_growing_sequence_keeps_its_pinned_buffer_across_parks(): - # the pinned buffer was sized to the exact state, so every park of a sequence that had grown since the last one unpinned it and pinned a new one, which costs about as long as the copy itself + # Pinned buffers sized exactly were re-pinned on every park of a grown sequence, costing about as much as the copy. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start_async(n_ctx=2048) @@ -1327,7 +1322,7 @@ def test_a_growing_sequence_keeps_its_pinned_buffer_across_parks(): def test_a_multi_prompt_oai_completion_counts_the_parks_of_every_prompt(): - # an array prompt is one ordinary task per prompt, each parked on its own; the OAI response merges them into one object, so its counters are the sum, as /completion reports them per prompt + # An array prompt is one task per prompt, each parked separately; the OAI response merges them, so its counters are the sum. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start() diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py index 561641d2cc70..282c71901b29 100644 --- a/tools/server/tests/unit/test_preempt_notify.py +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -8,7 +8,7 @@ import requests from utils import * -# [TAG_PREEMPT] a streaming client is told when its slot is parked and restored, as SSE comments every existing client ignores; a keepalive every 2 s keeps proxies from giving up +# [TAG_PREEMPT] Streaming clients get SSE comment notices on park and restore, and a 2 s keepalive keeps proxies from giving up. server = ServerPreset.tinyllama2() @@ -172,7 +172,7 @@ def _prefill_payload(path: str, prompt: str, n_predict: int) -> dict: @pytest.mark.parametrize("path", ["/completion", "/v1/chat/completions", "/v1/responses", "/v1/messages"]) def test_a_park_during_prompt_processing_opens_the_stream_with_the_notice(path): - # a park before the first token is the case a client cannot tell from a stall, so the notice goes out with the response headers rather than waiting for a chunk that is not coming + # A park before the first token looks like a stall, so its notice goes out with the response headers. server.server_slots = True _start(n_ctx=2048, n_batch=256) @@ -184,7 +184,7 @@ def _resident(): t = threading.Thread(target=_resident, daemon=True) t.start() - # the pool has to be nearly full before the second prompt starts, so that its prefill is what runs out of cells + # The pool must be nearly full before the second prompt starts, so its prefill runs out of cells. # the resident grows by decoding: 1400 tokens took over 12 s on a loaded CI runner deadline = time.time() + 90 while t.is_alive() and time.time() < deadline: @@ -235,7 +235,7 @@ def test_a_stream_parked_before_its_first_token_starts_with_the_notice(): def test_an_oversized_prompt_is_errored_instead_of_parked(): - # a slot just given a task has not passed the prompt checks yet, and a notice opens the stream, so parking it would turn a plain error response into 200 plus an in-stream one + # A newly assigned slot has not passed prompt checks, and a notice opens the stream, so parking it would turn an error response into 200 plus an in-stream error. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512, n_batch=512) @@ -246,7 +246,7 @@ def test_an_oversized_prompt_is_errored_instead_of_parked(): def test_a_rotation_tells_both_streams_and_a_head_parked_past_the_budget_is_kept_alive(): - # --preempt-ram 2 MiB holds one parked state but not a resident's and the head's at once, so that rotation is refused and the head waits parked for longer than the 2 s keepalive + # 2 MiB holds one parked state but not two, so rotation is refused and the head stays parked past the 2 s keepalive. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "2" _start(n_slots=3, n_ctx=2048, enable_ctx_shift=True) @@ -271,7 +271,7 @@ def test_a_rotation_tells_both_streams_and_a_head_parked_past_the_budget_is_kept def test_every_notice_of_a_multi_prompt_stream_names_the_prompt_it_is_about(): - # one request, two prompts: a client reading the shared stream can only tell the notices apart by their index, so index 0 has to be spelled out like any other + # Clients sharing a stream tell notices apart by index, so index 0 must be explicit too. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512) @@ -285,7 +285,7 @@ def test_every_notice_of_a_multi_prompt_stream_names_the_prompt_it_is_about(): def test_an_oversized_sibling_prompt_is_errored_before_a_valid_one_is_parked(): - # a request can carry several prompts; a valid one can be parked and its notice opens the stream, so the sibling that does not fit has to be found before any of them is queued + # A valid prompt's park notice opens the stream, so a sibling that does not fit must be rejected before any is queued. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" _start(n_ctx=256, n_slots=3, n_batch=512) From e8ad1ccc24f31f361f5e8aade241b288c975c837 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 02:42:40 -0700 Subject: [PATCH 027/109] server: keep the non-causal decision check in the prompt validator The validator that replaced the prefill checks treated every decision task as splittable, while server_slot::can_split() does not split a decision over a non-causal context. A non-causal decision longer than n_ubatch then reached llama_decode() and aborted the server instead of returning the batch size error. Both now use one helper. Adds an override_kv option to the test harness. --- tools/server/server-context.cpp | 67 +++++++++---------- .../server/tests/unit/test_preempt_models.py | 43 ++++++++++++ tools/server/tests/utils.py | 3 + 3 files changed, 78 insertions(+), 35 deletions(-) create mode 100644 tools/server/tests/unit/test_preempt_models.py diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 9398b6e10219..1281a8616a92 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -316,6 +316,36 @@ struct server_batch { } }; +// whether the prompt of a task may be split over several ubatches +static bool task_can_split(const server_task & task, llama_context * ctx) { + // a decision over a non-causal context reads the whole prompt in one batch + if (task.type == SERVER_TASK_TYPE_DECISION && !llama_get_causal_attn(ctx)) { + return false; + } + // MTP supports splitting - uses task.need_embd() not the slot's need_embd() + if (!task.need_embd()) { + return true; + } + // if the context does not have a memory module then all embeddings have to be computed within a single ubatch + if (!llama_get_memory(ctx)) { + return false; + } + // context can be chunked/split if the pooling type is LAST + const auto pooling = llama_pooling_type(ctx); + if (pooling == LLAMA_POOLING_TYPE_LAST) { + return true; + } + // causal rerankers read the last token and have a KV cache, so they can also be chunked/split. + if (pooling == LLAMA_POOLING_TYPE_RANK && llama_get_causal_attn(ctx)) { + return true; + } + // a decision task reads its outputs from the last batch + if (task.type == SERVER_TASK_TYPE_DECISION) { + return true; + } + return false; +} + struct server_slot { int id; @@ -972,32 +1002,7 @@ struct server_slot { bool can_split() const { GGML_ASSERT(task); - // a decision over a non-causal context reads the whole prompt in one batch - if (task->type == SERVER_TASK_TYPE_DECISION && !llama_get_causal_attn(ctx_tgt)) { - return false; - } - // MTP supports splitting - uses task->need_embd() not need_embd() - if (!task->need_embd()) { - return true; - } - // if the context does not have a memory module then all embeddings have to be computed within a single ubatch - if (!llama_get_memory(ctx_tgt)) { - return false; - } - // context can be chunked/split if the pooling type is LAST - const auto pooling = llama_pooling_type(ctx_tgt); - if (pooling == LLAMA_POOLING_TYPE_LAST) { - return true; - } - // causal rerankers read the last token and have a KV cache, so they can also be chunked/split. - if (pooling == LLAMA_POOLING_TYPE_RANK && llama_get_causal_attn(ctx_tgt)) { - return true; - } - // a decision task reads its outputs from the last batch - if (task->type == SERVER_TASK_TYPE_DECISION) { - return true; - } - return false; + return task_can_split(*task, ctx_tgt); } bool can_batch_with(server_slot & other_slot) const { @@ -4994,15 +4999,7 @@ struct server_context_impl { return true; } - // Mirrors server_slot::can_split(), from the task alone. - const auto pooling = llama_pooling_type(ctx_tgt); - const bool can_split = - !task.need_embd() || - (llama_get_memory(ctx_tgt) && - (pooling == LLAMA_POOLING_TYPE_LAST || (pooling == LLAMA_POOLING_TYPE_RANK && llama_get_causal_attn(ctx_tgt)) || - task.type == SERVER_TASK_TYPE_DECISION)); - - if (!can_split) { + if (!task_can_split(task, ctx_tgt)) { const int32_t n_ubatch = llama_n_ubatch(ctx_tgt); if (task.n_tokens() > n_ubatch) { diff --git a/tools/server/tests/unit/test_preempt_models.py b/tools/server/tests/unit/test_preempt_models.py new file mode 100644 index 000000000000..9402c59555a6 --- /dev/null +++ b/tools/server/tests/unit/test_preempt_models.py @@ -0,0 +1,43 @@ +import os +import pytest +from utils import * + +# Requests and models outside the parking path that the preemption change must leave as upstream serves them. + +server = ServerPreset.tinyllama2() + +START_TIMEOUT = 300 # the preload can be slow on a loaded host + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinyllama2() + yield + os.environ.pop("LLAMA_ARG_PREEMPT_RAM", None) + + +@pytest.mark.parametrize("preempt_ram", [None, "1024"]) +def test_a_non_causal_decision_longer_than_the_ubatch_is_refused_and_the_server_lives(preempt_ram): + global server + server = ServerPreset.tinyopenjev() + server.override_kv = ["qwen35.attention.causal=bool:false"] + server.n_ctx = 1024 + server.n_slots = 2 + server.kv_unified = True + server.n_batch = 256 + server.n_ubatch = 32 + if preempt_ram is not None: + os.environ["LLAMA_ARG_PREEMPT_RAM"] = preempt_ram + server.start(timeout_seconds=START_TIMEOUT) + res = server.make_request("POST", "/v1/systemone", data={ + "state": "Hello " * 30, + "questions": {"q": { + "type": "choice", + "instructions": "Is this a greeting?", + "criteria": {"yes": "a greeting", "no": "something else"}, + }}, + }) + assert res.status_code == 500 + assert "too large to process" in res.body["error"]["message"] + assert server.make_request("GET", "/health").status_code == 200 diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index 76e7b2bf4823..ab65c29bce5a 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -125,6 +125,7 @@ class ServerProcess: mcp_servers_config: str | None = None mcp_servers_json: str | None = None cors_origins: str | None = None + override_kv: List[str] | None = None # session variables process: subprocess.Popen | None = None @@ -187,6 +188,8 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.extend(["--models-preset", self.models_preset]) if self.cors_origins: server_args.extend(["--cors-origins", self.cors_origins]) + for kv in self.override_kv or []: + server_args.extend(["--override-kv", kv]) if self.n_batch: server_args.extend(["--batch-size", self.n_batch]) if self.n_ubatch: From 2df2ed0d40fe637278b8f1b54829c3850d01740d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 02:43:02 -0700 Subject: [PATCH 028/109] server: trim started slots before purging idle caches for KV pressure The planner charged a started slot's previous prompt cells together with the chunk of its new prompt, so a pool that never filled looked short and an idle slot's cache was purged (and with two residents a slot was parked). Trim started slots to their kept prefix before believing the shortfall, and keep idle caches while the next step fits and purging them would only cover the planning margin: a purge is instant, so it waits until the cells are needed, as without preemption. --- tools/server/server-context.cpp | 23 ++++++++++++++++++ tools/server/tests/unit/test_preempt.py | 32 +++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 9398b6e10219..14bdf0d53d0c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4125,6 +4125,19 @@ struct server_context_impl { return res; } + // Cells try_clear_idle_slots() can free. + int32_t preempt_n_idle_cells() const { + int32_t res = 0; + + for (const auto & slot : slots) { + if (!slot.is_processing()) { + res += preempt_n_cells(slot.prompt.n_tokens()); + } + } + + return res; + } + // [TAG_PREEMPT_ASYNC] Room kept free so running slots can keep decoding until a park lands; resume candidates are charged the same. int32_t preempt_n_margin(int32_t n_additional_running = 0) const { if (!preempt_async_ok) { @@ -4911,6 +4924,16 @@ struct server_context_impl { break; } + // [TAG_PREEMPT] A started slot still holds its previous prompt: trim it before the shortfall is believed. + if (preempt_normalize_started_all()) { + continue; + } + + // [TAG_PREEMPT] The step fits and purging idle slots would cover the margin: purging is instant, so keep their caches until the step needs the cells. + if (n_used <= n_cells && n_used - preempt_n_idle_cells() + preempt_n_margin() <= n_cells) { + break; + } + if (try_clear_idle_slots()) { continue; } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 17e200439e34..ca9fd7ca6eaa 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1338,3 +1338,35 @@ def test_a_multi_prompt_oai_completion_counts_the_parks_of_every_prompt(): assert len(merged.body["choices"]) == 2 assert merged.body["preempt"]["parks"] == sum(c["parks"] for c in counts), (merged.body["preempt"], counts) assert merged.body["preempt"]["recomputes"] == sum(c["recomputes"] for c in counts), (merged.body["preempt"], counts) + + +def _cached(n_predict: int, prompt: list, id_slot: int): + return server.make_request("POST", "/completion", data={ + "n_predict": n_predict, "prompt": prompt, "id_slot": id_slot, "cache_prompt": True, + "ignore_eos": True, "temperature": 0.0, "seed": 42, + }) + + +def test_a_started_slot_replacing_its_prompt_does_not_purge_an_idle_slot(): + # 200 of 256 cells are ever held; charging the started slot's old 100 cells beside its new 100 purged slot 1, so its rerun re-prefilled. + _start(n_ctx=256, n_batch=128, n_ubatch=64, cache_ram=0) + results = [_cached(1, [tok] * 100, slot) for slot, tok in ((0, 11), (1, 12), (0, 13), (1, 12))] + for res in results: + assert res.status_code == 200, res.body + assert results[3].body["timings"]["prompt_n"] == 1, results[3].body["timings"] + text = _log() + assert "purging slot" not in text + _assert_nothing_parked(text) + + +def test_an_idle_slot_inside_the_margin_keeps_its_cache(): + # 120 idle and 132 generating cells fit 256 with room for the step; purging slot 0 only to keep the planning margin made its rerun re-prefill. + _start(n_ctx=256, n_batch=128, n_ubatch=64, cache_ram=0) + first = [11] * 120 + assert _cached(1, first, 0).status_code == 200 + assert _cached(12, [12] * 120, 1).status_code == 200 + res = _cached(1, first, 0) + assert res.status_code == 200, res.body + assert res.body["timings"]["prompt_n"] == 1, res.body["timings"] + assert "purging slot" not in _log() + From c1af185a6a741e19bd17cb29be0aab4ce7e0cebc Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 02:43:02 -0700 Subject: [PATCH 029/109] server tests: a started slot that fits once trimmed parks nobody Covers the false park of a generating slot that the untrimmed count of a started slot caused; fixed by the previous commit. --- tools/server/tests/unit/test_preempt.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index ca9fd7ca6eaa..b8dcb745ee02 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1370,3 +1370,24 @@ def test_an_idle_slot_inside_the_margin_keeps_its_cache(): assert res.body["timings"]["prompt_n"] == 1, res.body["timings"] assert "purging slot" not in _log() + +def test_a_started_slot_that_fits_once_trimmed_parks_nobody(): + # Slot 0 keeps 300 of its 600 old cells: 300 + 336 + 60 + 310 fit 1024, but the untrimmed count parked the generating slot and purged slot 2. + _start(n_ctx=1024, n_slots=3, n_batch=512, n_ubatch=512, cache_ram=0) + old = [100 + i % 50 for i in range(600)] + idle = [300 + i % 30 for i in range(60)] + assert _cached(1, old, 0).status_code == 200 + assert _cached(1, idle, 2).status_code == 200 + with ThreadPoolExecutor(1) as pool: + gen = pool.submit(_cached, 220, [200 + i for i in range(90)], 1) + _wait_processing([1]) + started = _cached(4, old[:300] + [400 + i % 100 for i in range(336)], 0) + generating = gen.result() + for res in (started, generating): + assert res.status_code == 200, res.body + assert res.body["preempt"]["parks"] == 0, res.body["preempt"] + rerun = _cached(1, idle, 2) + assert rerun.body["timings"]["cache_n"] == 59, rerun.body["timings"] + text = _log() + assert "purging slot" not in text + _assert_nothing_parked(text) From 2f25fc91b3b5db5418ae561b83ce675f8a0fe346 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:07:11 -0700 Subject: [PATCH 030/109] ggml-cuda: refuse paged FLASH_ATTN_EXT shapes the paged kernel does not run With a page table the CUDA backend always dispatches the one-column F16 vector kernel for 256-wide heads, but supports_op answered from the unpaged kernel choice. It accepted shapes the paged dispatch then aborts on (64-wide heads, BF16 K/V, softcap) and refused supported ones on archs where the unpaged choice for the batch size is none. Answer for the paged kernel directly. Adds test-backend-ops cases for the refused shapes. --- ggml/src/ggml-cuda/fattn.cu | 15 +++++++++++++++ tests/test-backend-ops.cpp | 8 ++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 09ede03fecba..b9bbd66df929 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -824,5 +824,20 @@ void ggml_cuda_flash_attn_ext(ggml_backend_cuda_context & ctx, ggml_tensor * dst } bool ggml_cuda_flash_attn_ext_supported(int device, const ggml_tensor * dst) { + // [TAG_EXACT_CONCURRENCY] the paged path always runs the one-column F16 vector kernel, whatever the batch size or arch + if (const ggml_tensor * pages = ggml_cuda_fattn_pages(dst)) { +#ifndef FLASH_ATTN_AVAILABLE + return false; +#endif // FLASH_ATTN_AVAILABLE + float softcap; + memcpy(&softcap, (const float *) dst->op_params + 2, sizeof(softcap)); + + return dst->src[0]->ne[0] == 256 && dst->src[1]->ne[0] == 256 && dst->src[2]->ne[0] == 256 && + dst->src[1]->type == GGML_TYPE_F16 && dst->src[2]->type == GGML_TYPE_F16 && + dst->src[3] && dst->src[0]->ne[3] == 1 && dst->src[0]->ne[2] % dst->src[1]->ne[2] == 0 && + pages->type == GGML_TYPE_I32 && ggml_is_contiguous(pages) && pages->ne[1] == dst->src[0]->ne[1] && + softcap == 0.0f; + } + return ggml_cuda_get_best_fattn_kernel(device, dst) != BEST_FATTN_KERNEL_NONE; } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 7deb7139982a..be8f30591642 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -8505,8 +8505,8 @@ struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { // same attention as the CPU mask reference, but visiting nonadjacent pages in a different order struct test_flash_attn_ext_pages : public test_flash_attn_ext { - test_flash_attn_ext_pages(int64_t batch) : - test_flash_attn_ext(256, 256, 2, {8, 1}, 1024, batch) {} + test_flash_attn_ext_pages(int64_t batch, int64_t hs = 256, ggml_type type_KV = GGML_TYPE_F16, float logit_softcap = 0.0f) : + test_flash_attn_ext(hs, hs, 2, {8, 1}, 1024, batch, true, false, 0.0f, logit_softcap, GGML_PREC_F32, type_KV, type_KV) {} std::string vars() override { return test_flash_attn_ext::vars() + ",exact_pages=1"; } @@ -11717,6 +11717,10 @@ static std::vector> make_test_cases_eval() { for (int64_t batch : {1, 4, 12}) { test_cases.emplace_back(new test_flash_attn_ext_pages(batch)); } + // shapes the paged kernel does not cover: a backend must refuse them, not abort + test_cases.emplace_back(new test_flash_attn_ext_pages(4, 64)); + test_cases.emplace_back(new test_flash_attn_ext_pages(4, 256, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_flash_attn_ext_pages(4, 256, GGML_TYPE_F16, 30.0f)); test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0)); test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_F16)); test_cases.emplace_back(new test_flash_attn_ext(72, 72, 4, {1, 1}, 96, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_Q8_0)); From 491d98cc2a5c77ce5d08a0db1fded0a3fe1a3e8d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:07:11 -0700 Subject: [PATCH 031/109] tests: skip devices without events in test-event-query A GGML_CUDA_NO_PEER_COPY build reports caps.events = false and creates no events, so the query test failed there although parking correctly falls back to synchronous copies. Also require the query on ROCm and MUSA. --- tests/test-event-query.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/test-event-query.cpp b/tests/test-event-query.cpp index 8a34cdddf90c..33da176f10d6 100644 --- a/tests/test-event-query.cpp +++ b/tests/test-event-query.cpp @@ -17,11 +17,20 @@ int main() { const char * reg_name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)); const bool supported = ggml_backend_dev_supports_event_query(dev); - printf("%s (%s): event query %s\n", ggml_backend_dev_name(dev), reg_name, supported ? "yes" : "no"); + ggml_backend_dev_props props; + ggml_backend_dev_get_props(dev, &props); + + printf("%s (%s): events %s, event query %s\n", ggml_backend_dev_name(dev), reg_name, + props.caps.events ? "yes" : "no", supported ? "yes" : "no"); + + // a build without events (GGML_CUDA_NO_PEER_COPY) parks synchronously, so there is nothing to query + if (!props.caps.events) { + continue; + } if (!supported) { - if (strcmp(reg_name, "CUDA") == 0) { - fprintf(stderr, "%s is a CUDA device without a non-blocking event query\n", ggml_backend_dev_name(dev)); + if (strcmp(reg_name, "CUDA") == 0 || strcmp(reg_name, "ROCm") == 0 || strcmp(reg_name, "MUSA") == 0) { + fprintf(stderr, "%s is a %s device without a non-blocking event query\n", ggml_backend_dev_name(dev), reg_name); rc = 1; } continue; From 32c67409b322875a5cec4063ce87d436d67898b0 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:07:11 -0700 Subject: [PATCH 032/109] tests: build the server helper tests only when the server is built test-server-tokens and test-server-decision-exact link server-context, which tools/ adds only with LLAMA_BUILD_SERVER, so a build with tools and tests on but the server off failed to link them. --- tests/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 20a985b1cec7..a1e90f16a182 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -363,8 +363,8 @@ llama_build_and_test(test-mtmd-impl.cpp LINK mtmd) # [TAG_EXACT_CONCURRENCY] the batch shape the mode requires, checked without a model llama_build_and_test(test-exact-geometry.cpp) -# server helpers that need no model -if (LLAMA_BUILD_TOOLS) +# server helpers that need no model; server-context exists only where tools/ adds the server +if (LLAMA_BUILD_TOOLS AND LLAMA_BUILD_SERVER AND NOT EMSCRIPTEN) llama_build_and_test(test-server-tokens.cpp) target_link_libraries(test-server-tokens PRIVATE server-context mtmd) target_include_directories(test-server-tokens PRIVATE ${PROJECT_SOURCE_DIR}/tools/server ${PROJECT_SOURCE_DIR}/tools/mtmd) From 8c704c6e39375b11a0a57be8dfd042f2c5bae472 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:07:12 -0700 Subject: [PATCH 033/109] tests: cover integrated GPUs in test-exact-buft --- tests/test-exact-buft.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test-exact-buft.cpp b/tests/test-exact-buft.cpp index c89fec423ac7..bead5f365f59 100644 --- a/tests/test-exact-buft.cpp +++ b/tests/test-exact-buft.cpp @@ -24,7 +24,8 @@ int main() { for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { ggml_backend_dev_t dev = ggml_backend_dev_get(i); - if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU) { + // an integrated GPU (Jetson, GB10, Strix Halo) is a CUDA/ROCm device too + if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU && ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_IGPU) { continue; } From becae25b30eb09effd050101588f66cf260adbac Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:17:27 -0700 Subject: [PATCH 034/109] server: keep a resumed re-prefill's reservation until it is done A recompute park is admitted back only when its whole sequence fits, but once resumed it was charged only its next prompt chunk, so restores queued behind it took the room and the planner parked it again part way through the re-prefill, wasting the work. Charge the rest of the re-prefill while it runs, and treat a slot mid re-prefill like a starved one when choosing a victim. --- tools/server/server-context.cpp | 23 ++++++++++++++---- tools/server/tests/unit/test_preempt.py | 31 +++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 14bdf0d53d0c..1ff4ca119e50 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4198,6 +4198,12 @@ struct server_context_impl { const int32_t n_left = slot.preempt_n_input() - n_have; + // [TAG_PREEMPT] A re-prefill keeps the room it was resumed into, or later restores take it and park it again with no progress. + if (slot.preempt_reprefill) { + res += preempt_n_cells_step(n_have, std::max(0, n_left) + 1 + preempt_n_spec(slot)); + break; + } + res_pmt += preempt_n_cells_step(n_have, std::max(1, std::min(n_batch, n_left))); n_pmt++; } break; @@ -4309,7 +4315,11 @@ struct server_context_impl { const int32_t n_mtmd = preempt_n_mtmd_pending(slot, n_have); const int32_t n_left = slot.preempt_n_input() - n_have; - res += preempt_n_cells_step(n_have, n_mtmd > 0 ? n_mtmd : std::max(1, std::min((int32_t) llama_n_batch(ctx_tgt), n_left))); + if (n_mtmd == 0 && slot.preempt_reprefill) { + res += preempt_n_cells_step(n_have, std::max(0, n_left) + 1 + preempt_n_spec(slot)); // as preempt_kv_reserve() charges it + } else { + res += preempt_n_cells_step(n_have, n_mtmd > 0 ? n_mtmd : std::max(1, std::min((int32_t) llama_n_batch(ctx_tgt), n_left))); + } } return res; @@ -4353,6 +4363,11 @@ struct server_context_impl { return true; } + // A slot mid re-prefill has produced nothing since it was dropped, so it is protected like a starved one. + static bool preempt_starved(const server_slot & slot) { + return slot.n_preempt >= PREEMPT_N_STARVED || slot.preempt_reprefill; + } + server_slot * preempt_pick_victim_pass(const server_slot * exempt, bool recompute, int32_t n_deficit = 0) { server_slot * victim = nullptr; @@ -4364,8 +4379,8 @@ struct server_context_impl { continue; } - const bool starved = slot.n_preempt >= PREEMPT_N_STARVED; - const bool starved_cur = victim && victim->n_preempt >= PREEMPT_N_STARVED; + const bool starved = preempt_starved(slot); + const bool starved_cur = victim && preempt_starved(*victim); if (!victim || (starved_cur && !starved) || @@ -4385,7 +4400,7 @@ struct server_context_impl { } // a starved slot is only taken where the order would take one anyway - const bool victim_starved = victim && victim->n_preempt >= PREEMPT_N_STARVED; + const bool victim_starved = victim && preempt_starved(*victim); if (cover[0]) { return cover[0]; diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index b8dcb745ee02..21790bf00fe6 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1391,3 +1391,34 @@ def test_a_started_slot_that_fits_once_trimmed_parks_nobody(): text = _log() assert "purging slot" not in text _assert_nothing_parked(text) + + +def _reparked_mid_reprefill(text: str) -> list: + """(slot, cells parked, tokens it was re-prefilling) for every park that hit a slot before its re-prefill finished.""" + pending, res = {}, [] + for line in text.splitlines(): + m = re.search(r"id +(\d+) \| task \d+ \| resumed after [\d.]+ s: (\d+) tokens to re-prefill", line) + if m: + pending[m.group(1)] = int(m.group(2)) + continue + m = re.search(r"id +(\d+) \| task \d+ \| (?:preempted|rotated out)[^:]*: (\d+) cells", line) + if m and m.group(1) in pending: + need = pending.pop(m.group(1)) + if int(m.group(2)) < need: + res.append((m.group(1), int(m.group(2)), need)) + return res + + +def test_a_resumed_re_prefill_keeps_its_room_until_it_is_done(): + # The second park falls back to recompute; its resume was admitted for the whole sequence, but the restores behind it took the room and parked it again part way through. + os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "2" + _start(n_ctx=1024, n_slots=4, n_batch=128, n_ubatch=128) + prompts = [[10 + 20 * i + k % 20 for k in range(40)] for i in range(4)] + with ThreadPoolExecutor(4) as pool: + results = list(pool.map(lambda i: server.make_request("POST", "/completion", data={ + "n_predict": 900, "prompt": prompts[i], "id_slot": i, "cache_prompt": False, + "ignore_eos": True, "temperature": 0.0, "seed": 42}), range(4))) + _assert_completed(results, 900) + text = _log() + assert "tokens to re-prefill on resume" in text, "nothing was parked by dropping its cells" + assert _reparked_mid_reprefill(text) == [] From 45f0067e17b2572b029a7457a628c7e7c6e25e29 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:21:25 -0700 Subject: [PATCH 035/109] server: do not let n_cmpl > 1 requests turn an overflow into an error for every slot Slots of an n_cmpl > 1 request share the prompt's cells and cannot be parked. The victim choice still exempted the largest slot, so an n=1 request beside such a family was protected while nothing else was eligible, and the overflow ended every slot. Exempt nobody when the largest slot is in a family, park the leader when the only other residents are family slots, and when nothing can be parked end only the family holding the most cells instead of every resident. --- tools/server/server-context.cpp | 85 ++++++++++++++++++++++++- tools/server/tests/unit/test_preempt.py | 40 ++++++++++++ 2 files changed, 122 insertions(+), 3 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 1ff4ca119e50..f2b318598e8b 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4283,14 +4283,25 @@ struct server_context_impl { return nullptr; } - // the largest-policy test knob exempts nobody - const server_slot * exempt = preempt_test_policy == "largest" ? nullptr : leader; + // the largest-policy test knob exempts nobody; an n_cmpl > 1 leader cannot be parked anyway, so exempting it keeps nobody else safe + const server_slot * exempt = preempt_test_policy == "largest" || preempt_is_family(*leader) ? nullptr : leader; // only the default policy weighs the deficit; the others pin the order if (preempt_test_policy != "smallest") { n_deficit = 0; } + server_slot * victim = preempt_pick_victim_pass_any(exempt, recompute, n_deficit); + + // [TAG_PREEMPT] Beside n_cmpl > 1 slots the leader may be the only slot that can be parked; parking it lets them finish. + if (!victim && exempt && preempt_any_family_running()) { + victim = preempt_pick_victim_pass_any(nullptr, recompute, n_deficit); + } + + return victim; + } + + server_slot * preempt_pick_victim_pass_any(const server_slot * exempt, bool * recompute, int32_t n_deficit) { server_slot * victim = preempt_pick_victim_pass(exempt, false, n_deficit); if (!victim && recompute) { @@ -4302,6 +4313,20 @@ struct server_context_impl { return victim; } + static bool preempt_is_family(const server_slot & slot) { + return slot.task && (slot.task->is_parent() || slot.task->is_child()); + } + + bool preempt_any_family_running() const { + for (const auto & slot : slots) { + if (slot.is_processing() && !slot.preempt_is_out() && preempt_is_family(slot)) { + return true; + } + } + + return false; + } + // [TAG_PREEMPT] Room a park frees: the slot's cells plus its next step. int32_t preempt_n_freed(const server_slot & slot) const { const int32_t n_cur = slot.prompt.n_tokens(); @@ -6234,7 +6259,7 @@ struct server_context_impl { } if (n_parked == 0) { - return false; // nothing parked: the error path cleans up the rewind + return preempt_fail_largest_family(); // nothing parked: the error path cleans up the rewind } SRV_WRN("last resort: batch given up at off = %d, %d slot(s) parked, kv %d/%d resident\n", @@ -6243,6 +6268,60 @@ struct server_context_impl { return true; } + // [TAG_PREEMPT] n_cmpl > 1 slots cannot be parked: when nothing else can be, end only the family holding the most cells, not every slot. + bool preempt_fail_largest_family() { + auto family_of = [](const server_slot & slot) { + return slot.task->is_parent() ? slot.task->id : slot.task->id_parent; + }; + + auto running = [](const server_slot & slot) { + return slot.is_processing() && !slot.preempt_is_out(); + }; + + int family = -1; + int32_t n_cells = 0; + + for (const auto & slot : slots) { + if (!running(slot) || !preempt_is_family(slot)) { + continue; + } + + int32_t n = 0; + + for (const auto & other : slots) { + if (running(other) && preempt_is_family(other) && family_of(other) == family_of(slot)) { + n += other.prompt.n_tokens(); + } + } + + if (family < 0 || n > n_cells) { + family = family_of(slot); + n_cells = n; + } + } + + bool others = false; + + for (const auto & slot : slots) { + others |= running(slot) && (!preempt_is_family(slot) || family_of(slot) != family); + } + + if (family < 0 || !others) { + return false; + } + + for (auto & slot : slots) { + if (running(slot) && preempt_is_family(slot) && family_of(slot) == family) { + SLT_WRN(slot, "%s", "the n_cmpl > 1 request holding the most cells cannot be parked, ending it alone\n"); + send_error(slot, "Context size has been exceeded."); + slot.release(); + slot.prompt_clear(); + } + } + + return true; + } + bool batch_has_spec_groups() const { for (const auto & slot : slots) { if (!slot.spec_i_batch.empty()) { diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 21790bf00fe6..40a5de852dfb 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1422,3 +1422,43 @@ def test_a_resumed_re_prefill_keeps_its_room_until_it_is_done(): text = _log() assert "tokens to re-prefill on resume" in text, "nothing was parked by dropping its cells" assert _reparked_mid_reprefill(text) == [] + + +def _oai_n(prompt: list, n: int, max_tokens: int): + return server.make_request("POST", "/v1/completions", data={ + "prompt": prompt, "n": n, "max_tokens": max_tokens, "ignore_eos": True, + "temperature": 0.0, "seed": 42, "cache_prompt": False, + }) + + +def test_a_single_request_beside_an_n_2_request_is_parked_so_both_finish(): + # 900 + 700 cells overflow 1024 while each fits alone; the n=1 slot was the exempt leader and the n=2 slots cannot be parked, so every slot failed. + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128) + with ThreadPoolExecutor(1) as pool: + single = pool.submit(_cached, 300, [100 + k % 50 for k in range(600)], 0) + _wait_processing([0]) + family = _oai_n([200 + k % 50 for k in range(200)], 2, 250) + single = single.result() + assert single.status_code == 200, single.body + assert single.body["timings"]["predicted_n"] == 300 + assert family.status_code == 200, family.body + assert [c["finish_reason"] for c in family.body["choices"]] == ["length", "length"] + _assert_recovered(_log()) + + +def test_two_n_2_requests_that_do_not_fit_together_end_only_one(): + # Neither n=2 request can be parked; ending every slot also ended the one that fits alone. + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + _start(n_ctx=1024, n_slots=4, n_batch=128, n_ubatch=128) + with ThreadPoolExecutor(2) as pool: + first = pool.submit(_oai_n, [100 + k % 50 for k in range(200)], 2, 250) + deadline = time.time() + 30 + while time.time() < deadline and sum(s["is_processing"] for s in server.make_request("GET", "/slots").body) < 2: + time.sleep(0.005) + second = pool.submit(_oai_n, [200 + k % 50 for k in range(200)], 2, 250) + results = [first.result(), second.result()] + assert sorted(r.status_code for r in results) == [200, 500], [r.body for r in results] + ok = next(r for r in results if r.status_code == 200) + assert [c["finish_reason"] for c in ok.body["choices"]] == ["length", "length"] + assert "ending it alone" in _log() From 7432429208cc74bfc89479c59425f3a3b59903da Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:23:49 -0700 Subject: [PATCH 036/109] server: do not re-size a park state the budget already refused Every budget check sized the candidate's state, which walks the whole KV pool, and a rotation blocked by --preempt-ram repeated the check every server iteration. Remember the last refusal: a slot whose sequence only grew, holding no more capacity, with no less RAM in use and nothing idle to reclaim, is refused again without sizing. An unlimited budget skips the sizing entirely. --- tools/server/server-context.cpp | 39 +++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index f2b318598e8b..ca8076f6149c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -480,6 +480,11 @@ struct server_slot { bool preempt_hold_logged = false; bool preempt_grow = false; // the next park may pin a buffer larger than the sequence + // [TAG_PREEMPT] Last budget refusal: tokens, held capacity and RAM in use then; -1 when none. + mutable int32_t preempt_refused_n = -1; + mutable size_t preempt_refused_held = 0; + mutable size_t preempt_refused_used = 0; + // [TAG_PREEMPT] Service since the last resume, so two slots rotating for each other both make progress. int64_t t_preempt_resume_us = 0; int32_t n_gen_resume = 0; @@ -930,6 +935,7 @@ struct server_slot { t_preempt_resume_us = 0; n_gen_resume = 0; preempt_hold_logged = false; + preempt_refused_n = -1; llama_set_sampler(ctx_tgt, id, nullptr); backend_sampler = false; @@ -4006,14 +4012,43 @@ struct server_context_impl { bool preempt_fits_budget(const server_slot & slot) { const size_t budget = preempt_ram_budget(); + if (budget == SIZE_MAX) { + return true; // unlimited: no need to size the state + } + // Capacity this slot already holds is reused, so the park costs only the rest. - const size_t held = slot.preempt_state_size(); + const size_t held = slot.preempt_state_size(); + + // [TAG_PREEMPT] Sizing walks the pool; a state that only grew cannot fit where it did not, unless RAM was freed. + if (slot.preempt_refused_n >= 0 && slot.prompt.n_tokens() >= slot.preempt_refused_n && + held <= slot.preempt_refused_held && preempt_ram_used() >= slot.preempt_refused_used && + !preempt_idle_ram_reclaimable(slot)) { + return false; + } + const size_t need = slot.preempt_state_required(); const size_t extra = need > held ? need - held : 0; preempt_reclaim_idle_ram(budget, extra, slot); - return preempt_ram_used() + extra <= budget; + const bool res = preempt_ram_used() + extra <= budget; + + slot.preempt_refused_n = res ? -1 : slot.prompt.n_tokens(); + slot.preempt_refused_held = held; + slot.preempt_refused_used = preempt_ram_used(); + + return res; + } + + // preempt_reclaim_idle_ram() could free host RAM for `keep`. + bool preempt_idle_ram_reclaimable(const server_slot & keep) const { + for (const auto & other : slots) { + if (&other != &keep && !other.preempt_is_out() && other.preempt_state_size() > 0) { + return true; + } + } + + return false; } void preempt_trim_ram(server_slot & slot) { From 0edf9c8748b8e123fe0e51e371c6bd9184d5e774 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:26:01 -0700 Subject: [PATCH 037/109] server: do not rotate out a resident for nothing A slot that was never parked counted as served from its first token, so a long prefill could be rotated out one token after it finished. Count its service from its first token like a resumed slot's. And a rotation pick that frees too little alone was parked even when every candidate together could not make room for the head, leaving it parked beside the head while the pool sat underused; skip the rotation then. --- tools/server/server-context.cpp | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index ca8076f6149c..cca5247da327 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4545,14 +4545,13 @@ struct server_context_impl { // [TAG_PREEMPT] A resumed slot is not rotated out before PREEMPT_ROTATE_MIN_GEN tokens (or one token and PREEMPT_ROTATE_US), so two slots cannot swap cells without progress. bool preempt_served(const server_slot & slot) const { - if (slot.n_preempt == 0) { - return true; - } - const int32_t n_gen = (int32_t) slot.stats.n_gen - slot.n_gen_resume; + // a slot never parked counts from its first token, or a long prefill is rotated out after one token + const int64_t t_from = slot.n_preempt == 0 ? slot.stats.t_prompt_last : slot.t_preempt_resume_us; + return n_gen >= PREEMPT_ROTATE_MIN_GEN || - (n_gen > 0 && ggml_time_us() - slot.t_preempt_resume_us >= PREEMPT_ROTATE_US); + (n_gen > 0 && ggml_time_us() - t_from >= PREEMPT_ROTATE_US); } bool preempt_any_out() const { @@ -4829,8 +4828,11 @@ struct server_context_impl { bool pick_enough = false; bool budget_refused = false; bool recompute = false; + int32_t n_freed_all = 0; auto rotate_pick = [&](bool with_recompute) { + n_freed_all = 0; + for (auto & slot : slots) { // [TAG_PREEMPT] Residents that have had their service since resuming, and held prompts sitting on cells. const bool held = preempt_held(slot) && slot.prompt.n_tokens() > 0; @@ -4852,6 +4854,8 @@ struct server_context_impl { const int32_t n_freed = preempt_n_freed(slot); const int32_t n_pick = pick ? preempt_n_freed(*pick) : 0; + n_freed_all += n_freed; + const bool enough = occupied - n_freed + need <= n_cells; if (!pick || @@ -4863,11 +4867,20 @@ struct server_context_impl { } }; + // [TAG_PREEMPT] Short alone, a pick is only a first step: if every candidate together cannot make room, it would wait parked beside the head for nothing. + auto drop_futile = [&]() { + if (pick && !pick_enough && occupied - n_freed_all + need > n_cells) { + pick = nullptr; + } + }; + rotate_pick(false); + drop_futile(); // [TAG_PREEMPT] A resident the budget cannot swap is rotated by dropping its cells, since waiting has no bound. The head waits longer for this, as it costs the resident a full re-prefill. if (!pick && budget_refused && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_RECOMPUTE_US) { rotate_pick(true); + drop_futile(); recompute = pick != nullptr; } From 54ac4ad38b7e93f794caeed8bce8477593c2fe9a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:26:47 -0700 Subject: [PATCH 038/109] server: land in-flight restores before the last-resort park The last resort skips slots whose asynchronous restore is still copying, though they already hold their cells. With one other resident it saw a single running slot and ended it as a real overflow, while parking the restored slot would have made room. Wait for those restores to land first, as a context shift does. --- tools/server/server-context.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index cca5247da327..6246815c3dee 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -6234,6 +6234,19 @@ struct server_context_impl { return false; } + // [TAG_PREEMPT_ASYNC] A restoring slot holds its cells but is skipped below, so land it first: it may be the only other resident. + for (auto & slot : slots) { + if (slot.state != SLOT_STATE_RESTORING) { + continue; + } + + slot.preempt_copy_wait(); + + if (slot.preempt_restore_poll()) { + preempt_restored(slot, " (waited for, as a last resort)"); + } + } + int32_t n_running = 0; for (auto & slot : slots) { From a8eae5b7f027fdc381b4664db0c647b78851032d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:48:55 -0700 Subject: [PATCH 039/109] server: send the preempt record only when the server can park Every completion response gained a "preempt": {"parks": 0, "recomputes": 0} object, including on servers started without --preempt-ram, where nothing can ever be parked. Send it only when parking is possible, which is what /props preempt.enabled reports, so a server that did not ask for parking answers with upstream's response shape. --- tools/server/README.md | 2 +- tools/server/server-context.cpp | 1 + tools/server/server-task.cpp | 41 ++++++++++++++----- tools/server/server-task.h | 1 + .../server/tests/unit/test_preempt_models.py | 40 ++++++++++++++++++ 5 files changed, 73 insertions(+), 12 deletions(-) diff --git a/tools/server/README.md b/tools/server/README.md index d60593d28ad7..be03ac2fb4ec 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -676,7 +676,7 @@ These words will not be included in the completion, so make sure to add them to - `tokens_cached`: Number of tokens from the prompt which could be re-used from previous completion - `tokens_evaluated`: Number of tokens evaluated in total from the prompt - `truncated`: Boolean indicating if the context size was exceeded during generation, i.e. the number of tokens provided in the prompt (`tokens_evaluated`) plus tokens generated (`tokens predicted`) exceeded the context size (`n_ctx`) -- `preempt`: How the request was served while the unified KV cache was full (see `--preempt-ram`). `parks` is how often the request was parked to make room for another, and `recomputes` is how many of those parks dropped the sequence's cells because `--preempt-ram` was spent, so that the resume re-prefilled its tokens instead of restoring the bytes that were saved. A re-prefilled sequence continues from the same tokens, but its numerics are not guaranteed identical to the sequence that left, `LLAMA_EXACT_CONCURRENCY` included: raise `--preempt-ram` until `recomputes` stays 0 where that matters. Both fields are present in the final response of a streamed completion as well, and on the OpenAI-compatible endpoints: the final chunk of a streamed `/v1/chat/completions`, the `message_delta` event of `/v1/messages`, and the response object of `/v1/responses` streamed or not, which in a stream is the `response` of the `response.completed` event. +- `preempt`: How the request was served while the unified KV cache was full (see `--preempt-ram`), sent only by a server that can park (a unified KV cache, two or more slots and a non-zero `--preempt-ram`, as `/props` `preempt.enabled` reports). `parks` is how often the request was parked to make room for another, and `recomputes` is how many of those parks dropped the sequence's cells because `--preempt-ram` was spent, so that the resume re-prefilled its tokens instead of restoring the bytes that were saved. A re-prefilled sequence continues from the same tokens, but its numerics are not guaranteed identical to the sequence that left, `LLAMA_EXACT_CONCURRENCY` included: raise `--preempt-ram` until `recomputes` stays 0 where that matters. Both fields are present in the final response of a streamed completion as well, and on the OpenAI-compatible endpoints: the final chunk of a streamed `/v1/chat/completions`, the `message_delta` event of `/v1/messages`, and the response object of `/v1/responses` streamed or not, which in a stream is the `response` of the `response.completed` event. While a request is streaming, the server sends SSE comment lines that a client reading raw lines can act on and every SSE event consumer ignores: diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 1281a8616a92..2956436788d4 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2982,6 +2982,7 @@ struct server_context_impl { res->post_sampling_probs = slot.task->params.post_sampling_probs; res->n_preempt = slot.n_preempt; res->n_recompute = slot.n_recompute; + res->preempt_report = preempt_last_resort_possible(); res->verbose = slot.task->params.verbose; res->stream = slot.task->params.stream; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index b22371f863c8..2f5c93ec6ca7 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -347,8 +347,10 @@ json server_task_result_cmpl_final::to_json_non_oaicompat() { {"stopping_word", stopping_word}, {"tokens_cached", n_tokens_cached}, {"timings", stats.to_json()}, - {"preempt", preempt_to_json()}, }; + if (preempt_report) { + res["preempt"] = preempt_to_json(); + } if (!stream && !probs_output.empty()) { res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs); } @@ -407,7 +409,9 @@ json server_task_result_cmpl_final::to_json_oaicompat() { } if (stats.is_set()) { res["timings"] = stats.to_json(); - res["preempt"] = preempt_to_json(); + if (preempt_report) { + res["preempt"] = preempt_to_json(); + } } return res; @@ -456,7 +460,9 @@ json server_task_result_cmpl_final::to_json_oaicompat_chat() { } if (stats.is_set()) { res["timings"] = stats.to_json(); - res["preempt"] = preempt_to_json(); + if (preempt_report) { + res["preempt"] = preempt_to_json(); + } } return res; @@ -518,7 +524,9 @@ json server_task_result_cmpl_final::to_json_oaicompat_chat_stream() { if (stats.is_set()) { deltas.back()["timings"] = stats.to_json(); - deltas.back()["preempt"] = preempt_to_json(); + if (preempt_report) { + deltas.back()["preempt"] = preempt_to_json(); + } } // extra fields for debugging purposes @@ -595,8 +603,10 @@ json server_task_result_cmpl_final::to_json_oaicompat_resp() { {"total_tokens", n_decoded + n_prompt_tokens}, {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }}, }}, - {"preempt", preempt_to_json()}, }; + if (preempt_report) { + res["preempt"] = preempt_to_json(); + } return res; } @@ -707,12 +717,15 @@ json server_task_result_cmpl_final::to_json_oaicompat_resp_stream() { {"total_tokens", n_decoded + n_prompt_tokens}, {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }}, }}, - // [TAG_PREEMPT] inside the response object, where the non-streaming body carries it: that object is what a client keeps from the stream - {"preempt", preempt_to_json()}, }}, }} }); + // [TAG_PREEMPT] inside the response object, where the non-streaming body carries it: that object is what a client keeps from the stream + if (preempt_report) { + server_sent_events.back().at("data").at("response")["preempt"] = preempt_to_json(); + } + if (stats.is_set()) { server_sent_events.back().at("data")["timings"] = stats.to_json(); } @@ -731,8 +744,10 @@ json server_task_result_cmpl_final::to_json_oaicompat_asr() { {"total_tokens", n_decoded + n_prompt_tokens}, {"input_tokens_details", json { {"cached_tokens", n_prompt_tokens_cache} }}, }}, - {"preempt", preempt_to_json()}, }; + if (preempt_report) { + event["preempt"] = preempt_to_json(); + } return event; } @@ -797,8 +812,10 @@ json server_task_result_cmpl_final::to_json_anthropic() { {"input_tokens", n_prompt_tokens - n_prompt_tokens_cache}, {"output_tokens", n_decoded} }}, - {"preempt", preempt_to_json()} }; + if (preempt_report) { + res["preempt"] = preempt_to_json(); + } return res; } @@ -977,10 +994,12 @@ json server_task_result_cmpl_final::to_json_anthropic_stream() { }}, {"usage", { {"output_tokens", n_decoded} - }}, - {"preempt", preempt_to_json()} + }} }} }); + if (preempt_report) { + events.back()["data"]["preempt"] = preempt_to_json(); + } events.push_back({ {"event", "message_stop"}, diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 5a842a8a166c..bdd5c1d37d84 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -388,6 +388,7 @@ struct server_task_result_cmpl_final : server_task_result { // [TAG_PREEMPT] how the request was served: how often it was parked, and how many of those parks re-prefilled instead of restoring saved bytes int32_t n_preempt = 0; int32_t n_recompute = 0; + bool preempt_report = false; // the server can park, so the response carries the record json preempt_to_json() const; diff --git a/tools/server/tests/unit/test_preempt_models.py b/tools/server/tests/unit/test_preempt_models.py index 9402c59555a6..35856547d5db 100644 --- a/tools/server/tests/unit/test_preempt_models.py +++ b/tools/server/tests/unit/test_preempt_models.py @@ -41,3 +41,43 @@ def test_a_non_causal_decision_longer_than_the_ubatch_is_refused_and_the_server_ assert res.status_code == 500 assert "too large to process" in res.body["error"]["message"] assert server.make_request("GET", "/health").status_code == 200 + + +def _final_bodies(): + """The final record of a completion on every endpoint that reports how the request was served.""" + msgs = [{"role": "user", "content": "Hello"}] + bodies = {} + res = server.make_request("POST", "/completion", data={"prompt": "Hello", "n_predict": 4}) + bodies["completion"] = res.body + res = server.make_request("POST", "/v1/completions", data={"prompt": "Hello", "max_tokens": 4}) + bodies["oai_completion"] = res.body + res = server.make_request("POST", "/v1/chat/completions", data={"messages": msgs, "max_tokens": 4}) + bodies["chat"] = res.body + res = server.make_request("POST", "/v1/responses", data={"input": "Hello", "max_output_tokens": 4}) + bodies["responses"] = res.body + res = server.make_request("POST", "/v1/messages", data={"messages": msgs, "max_tokens": 4}) + bodies["messages"] = res.body + events = list(server.make_stream_request("POST", "/v1/chat/completions", data={ + "messages": msgs, "max_tokens": 4, "stream": True, "stream_options": {"include_usage": True}})) + bodies["chat_stream"] = events[-1] + events = list(server.make_stream_request("POST", "/v1/responses", data={ + "input": "Hello", "max_output_tokens": 4, "stream": True})) + bodies["responses_stream"] = [e for e in events if e.get("type") == "response.completed"][0]["response"] + return bodies + + +@pytest.mark.parametrize("preempt_ram", [None, "1024"]) +def test_the_preempt_record_is_sent_only_by_a_server_that_can_park(preempt_ram): + global server + server.n_slots = 2 + server.kv_unified = True + server.jinja = True + if preempt_ram is not None: + os.environ["LLAMA_ARG_PREEMPT_RAM"] = preempt_ram + server.start(timeout_seconds=START_TIMEOUT) + for name, body in _final_bodies().items(): + if preempt_ram is None: + assert "preempt" not in body, name + else: + assert body["preempt"] == {"parks": 0, "recomputes": 0}, name + From ea8b7b9d0516c2081a6bf7377e3f468f5162d212 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:49:23 -0700 Subject: [PATCH 040/109] server: leave a context shift to the decode when nothing can be parked preempt_apply_shift() ran llama_memory_update() and its graph_reserve() ahead of every decode that followed a context shift or cache-reuse shift, also on servers that cannot park. That moved the K-shift out of the decode timer and, when another slot shifted in pre_decode(), ran the update and reserve twice instead of once. Apply it early only when a park can happen before the decode. --- tools/server/server-context.cpp | 6 ++++ .../server/tests/unit/test_preempt_models.py | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 2956436788d4..093f5111a5a8 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4604,6 +4604,12 @@ struct server_context_impl { return; } + // nothing can be parked: leave the shift to llama_decode(), which applies it together with any later one + if (!preempt_last_resort_possible()) { + preempt_shift_pending = false; + return; + } + preempt_wait_for_shift(); llama_memory_update(ctx_tgt); diff --git a/tools/server/tests/unit/test_preempt_models.py b/tools/server/tests/unit/test_preempt_models.py index 35856547d5db..c0ae36281c2b 100644 --- a/tools/server/tests/unit/test_preempt_models.py +++ b/tools/server/tests/unit/test_preempt_models.py @@ -81,3 +81,32 @@ def test_the_preempt_record_is_sent_only_by_a_server_that_can_park(preempt_ram): else: assert body["preempt"] == {"parks": 0, "recomputes": 0}, name + +@pytest.mark.parametrize("preempt_ram", [None, "1024"]) +def test_a_context_shift_is_left_to_the_decode_unless_parking_is_on(preempt_ram, tmp_path): + global server + server.n_ctx = 256 + server.n_slots = 2 + server.kv_unified = True + server.enable_ctx_shift = True + server.debug = True + server.temperature = 0.0 + server.log_path = str(tmp_path / "server.log") + if preempt_ram is not None: + os.environ["LLAMA_ARG_PREEMPT_RAM"] = preempt_ram + server.start(timeout_seconds=START_TIMEOUT) + res = server.make_request("POST", "/completion", data={"prompt": "Once upon a time", "n_predict": 320}) + assert res.status_code == 200 + assert res.body["truncated"] is True + server.stop() + + text = open(server.log_path).read() + after = text[text.index("slot context shift"):] + i_decode = after.index("n_batch (effective)") + i_update = after.index("applying K-shift") + if preempt_ram is None: + # as upstream: the K-shift runs inside llama_decode() + assert i_decode < i_update + else: + # a park before the decode must see shifted K, so the shift runs first + assert i_update < i_decode From 295957ca7a4b118e19dfe838179e35deefd3f987 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:51:06 -0700 Subject: [PATCH 041/109] server: do not exempt a slot that has only just started The cost policy exempts the largest resident from parking. A request that had just been assigned to a slot was measured by the cells the slot kept from an earlier conversation, so a follow-up on a long cached prefix became that leader before decoding anything and an older request already streaming to its client was parked for it. Pick the leader among slots past the started state when there are any. --- tools/server/server-context.cpp | 6 +++++- tools/server/tests/unit/test_preempt.py | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 6246815c3dee..f573a9671572 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4303,11 +4303,15 @@ struct server_context_impl { preempt_normalize_started(slot); } + // [TAG_PREEMPT] A started slot is not the leader: the cells it keeps are an earlier request's, and exempting them would park an older request already running. for (auto & slot : slots) { if (slot.is_processing() && !slot.preempt_is_out()) { n_running++; - if (!leader || slot.prompt.n_tokens() > leader->prompt.n_tokens()) { + const bool started = slot.state == SLOT_STATE_STARTED; + const bool started_cur = leader && leader->state == SLOT_STATE_STARTED; + + if (!leader || (started_cur && !started) || (started == started_cur && slot.prompt.n_tokens() > leader->prompt.n_tokens())) { leader = &slot; } } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 40a5de852dfb..977a902e00b3 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1462,3 +1462,23 @@ def test_two_n_2_requests_that_do_not_fit_together_end_only_one(): ok = next(r for r in results if r.status_code == 200) assert [c["finish_reason"] for c in ok.body["choices"]] == ["length", "length"] assert "ending it alone" in _log() + + +def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generating_one(): + # Slot 1 keeps 600 cells of an earlier conversation; its follow-up started beside a generating request, was the largest, became the exempt leader, and the older request was parked for it. + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + _start(n_ctx=1024, n_slots=2, n_batch=128, n_ubatch=128, cache_ram=0) + earlier = [200 + k % 50 for k in range(600)] + assert _cached(1, earlier, 1).status_code == 200 + with ThreadPoolExecutor(1) as pool: + older = pool.submit(_cached, 600, [100 + k % 50 for k in range(40)], 0) + deadline = time.time() + 60 + while time.time() < deadline and _n_decoded(_slot_view(0)) < 280: + time.sleep(0.002) + newer = _cached(4, earlier + [300 + k % 50 for k in range(300)], 1) + older = older.result() + for res, n_predict in ((older, 600), (newer, 4)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + assert older.body["preempt"]["parks"] == 0, "the older generating request was parked for a newer one" + assert newer.body["preempt"]["parks"] > 0 From 1bb79707270077165f28d980523b46e0b03faaff Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:32:58 -0700 Subject: [PATCH 042/109] server: add --preempt-policy fcfs next to the cost-based victim choice fcfs parks the most recently arrived running request with no exemption, so the oldest always runs; it resumes parked requests in arrival order, and the oldest parked request holds its room against newer prompts at once instead of after the rotation delay. A resident older than the head is rotated out only if it context-shifts, since it may never end. cost is the existing rule and stays the default, set by COMMON_PREEMPT_POLICY_DEFAULT. Idle slots are still purged before any running slot is parked under either policy. LLAMA_SERVER_PREEMPT_POLICY=fcfs or cost selects the policy when LLAMA_ARG_PREEMPT_POLICY is unset; its other values remain test knobs of the cost rule. /props reports the policy in use. --- common/arg.cpp | 12 +++++ common/common.h | 4 ++ tools/server/README.md | 1 + tools/server/server-context.cpp | 69 ++++++++++++++++++++++--- tools/server/tests/unit/test_preempt.py | 63 +++++++++++++++++++++- 5 files changed, 140 insertions(+), 9 deletions(-) diff --git a/common/arg.cpp b/common/arg.cpp index b4ae21e4a9fe..f8828817693b 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -1747,6 +1747,18 @@ common_params_context common_params_parser_init(common_params & params, llama_ex 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; + } + ).set_env("LLAMA_ARG_PREEMPT_POLICY").set_examples({LLAMA_EXAMPLE_SERVER})); add_opt(common_arg( {"-kvu", "--kv-unified"}, {"-no-kvu", "--no-kv-unified"}, diff --git a/common/common.h b/common/common.h index 6e2ca06f902e..8f2ae0319800 100644 --- a/common/common.h +++ b/common/common.h @@ -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: "cost" (park the cheapest slot, the largest exempt) or "fcfs" (park the newest arrival) +#define COMMON_PREEMPT_POLICY_DEFAULT "cost" + #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) @@ -640,6 +643,7 @@ struct common_params { 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" std::string public_path = ""; // NOLINT std::string api_prefix = ""; // NOLINT diff --git a/tools/server/README.md b/tools/server/README.md index d60593d28ad7..27ba701ce71d 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -168,6 +168,7 @@ For the full list of features, please refer to [server's changelog](https://gith | `-cram, --cache-ram N` | set the maximum cache size in MiB (default: 8192, -1 - no limit, 0 - disable)[(more info)](https://github.com/ggml-org/llama.cpp/pull/16391)
(env: LLAMA_ARG_CACHE_RAM) | | `--preempt-ram N` | 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: 0 - disabled, -1 - no limit)
(env: LLAMA_ARG_PREEMPT_RAM) | | `--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)
(env: LLAMA_ARG_PREEMPT_ASYNC) | +| `--preempt-policy {fcfs,cost}` | 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: cost)
(env: LLAMA_ARG_PREEMPT_POLICY) | | `-kvu, --kv-unified, -no-kvu, --no-kv-unified` | use single unified KV buffer shared across all sequences (default: enabled if number of slots is auto)
(env: LLAMA_ARG_KV_UNIFIED) | | `--cache-idle-slots, --no-cache-idle-slots` | save idle slots to the prompt cache on new task, and clear them when using unified KV (default: enabled, requires cache-ram)
(env: LLAMA_ARG_CACHE_IDLE_SLOTS) | | `--context-shift, --no-context-shift` | whether to use context shift on infinite text generation (default: disabled)
(env: LLAMA_ARG_CONTEXT_SHIFT) | diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index f573a9671572..7c17186fbebd 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2142,9 +2142,19 @@ struct server_context_impl { const char * LLAMA_SERVER_PREEMPT_EVERY = getenv("LLAMA_SERVER_PREEMPT_EVERY"); preempt_test_every = LLAMA_SERVER_PREEMPT_EVERY ? atoi(LLAMA_SERVER_PREEMPT_EVERY) : 0; - // LLAMA_SERVER_PREEMPT_POLICY: smallest (default), largest, youngest or oldest. + preempt_fcfs = params_base.preempt_policy == "fcfs"; + + // LLAMA_SERVER_PREEMPT_POLICY: fcfs or cost, as --preempt-policy when LLAMA_ARG_PREEMPT_POLICY is unset; or a cost test knob: smallest (default), largest, youngest or oldest. const char * LLAMA_SERVER_PREEMPT_POLICY = getenv("LLAMA_SERVER_PREEMPT_POLICY"); - preempt_test_policy = LLAMA_SERVER_PREEMPT_POLICY ? LLAMA_SERVER_PREEMPT_POLICY : "smallest"; + preempt_test_policy = "smallest"; + + if (LLAMA_SERVER_PREEMPT_POLICY && (strcmp(LLAMA_SERVER_PREEMPT_POLICY, "fcfs") == 0 || strcmp(LLAMA_SERVER_PREEMPT_POLICY, "cost") == 0)) { + if (!getenv("LLAMA_ARG_PREEMPT_POLICY")) { + preempt_fcfs = strcmp(LLAMA_SERVER_PREEMPT_POLICY, "fcfs") == 0; + } + } else if (LLAMA_SERVER_PREEMPT_POLICY) { + preempt_test_policy = LLAMA_SERVER_PREEMPT_POLICY; + } if (preempt_test_policy != "smallest") { SRV_WRN("LLAMA_SERVER_PREEMPT_POLICY = %s (test knob: victim choice for comparison only)\n", preempt_test_policy.c_str()); @@ -3887,6 +3897,9 @@ struct server_context_impl { int32_t preempt_test_every = 0; std::string preempt_test_policy = "smallest"; // LLAMA_SERVER_PREEMPT_POLICY, see load_model + // [TAG_PREEMPT] --preempt-policy fcfs: park the newest arrival, resume and reserve in arrival order. + bool preempt_fcfs = false; + // [TAG_PREEMPT_ASYNC] False with --no-preempt-async or a backend without async copies. bool preempt_async_ok = false; @@ -4322,6 +4335,10 @@ struct server_context_impl { return nullptr; } + if (preempt_fcfs) { + return preempt_pick_victim_fcfs(recompute); + } + // the largest-policy test knob exempts nobody; an n_cmpl > 1 leader cannot be parked anyway, so exempting it keeps nobody else safe const server_slot * exempt = preempt_test_policy == "largest" || preempt_is_family(*leader) ? nullptr : leader; @@ -4352,6 +4369,27 @@ struct server_context_impl { return victim; } + // [TAG_PREEMPT] The most recently arrived resident, with no exemption: the oldest always runs. Copied if the budget holds it, else dropped. + server_slot * preempt_pick_victim_fcfs(bool * recompute) { + server_slot * victim = nullptr; + + for (auto & slot : slots) { + if (preempt_victim_eligible(slot, nullptr, true) && (!victim || slot.task->id > victim->task->id)) { + victim = &slot; + } + } + + if (victim && !preempt_fits_budget(*victim)) { + if (!recompute) { + return nullptr; + } + + *recompute = true; + } + + return victim; + } + static bool preempt_is_family(const server_slot & slot) { return slot.task && (slot.task->is_parent() || slot.task->is_child()); } @@ -4500,12 +4538,18 @@ struct server_context_impl { const server_slot * head = nullptr; for (const auto & slot : slots) { - if (slot.state == SLOT_STATE_PREEMPTED && (!head || slot.t_preempt_us < head->t_preempt_us)) { + if (slot.state == SLOT_STATE_PREEMPTED && (!head || preempt_resumes_before(slot, *head))) { head = &slot; } } - preempt_reserved_for = head && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_US ? head : nullptr; + // under fcfs the oldest parked request holds its room against newer ones at once + preempt_reserved_for = head && (preempt_fcfs || ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_US) ? head : nullptr; + } + + // [TAG_PREEMPT] Resume order: arrival under fcfs, park time under cost. + bool preempt_resumes_before(const server_slot & a, const server_slot & b) const { + return preempt_fcfs ? a.task->id < b.task->id : a.t_preempt_us < b.t_preempt_us; } // [TAG_PREEMPT] A never-resident prompt waits while the head's reservation stands. Re-prefills, resumed prompts, and empty or rejected prompts go on. @@ -4518,6 +4562,10 @@ struct server_context_impl { return false; } + if (preempt_fcfs && slot.task->id < preempt_reserved_for->task->id) { + return false; + } + if (slot.state == SLOT_STATE_STARTED) { if (slot.preempt_input().empty()) { return false; @@ -4530,7 +4578,8 @@ struct server_context_impl { } if (slot.state == SLOT_STATE_PROCESSING_PROMPT) { - return slot.stats.t_start > preempt_reserved_for->t_preempt_us; + return preempt_fcfs ? slot.task->id > preempt_reserved_for->task->id + : slot.stats.t_start > preempt_reserved_for->t_preempt_us; } return false; @@ -4769,12 +4818,12 @@ struct server_context_impl { break; } - std::sort(parked.begin(), parked.end(), [head_of_line](const server_slot * a, const server_slot * b) { + std::sort(parked.begin(), parked.end(), [this, head_of_line](const server_slot * a, const server_slot * b) { if (!head_of_line && a->n_preempt != b->n_preempt) { return a->n_preempt > b->n_preempt; } - return a->t_preempt_us < b->t_preempt_us; + return preempt_resumes_before(*a, *b); }); if (head_of_line) { @@ -4849,6 +4898,11 @@ struct server_context_impl { continue; } + // [TAG_PREEMPT] Under fcfs an older resident is rotated only if it context-shifts, as it may never end. + if (preempt_fcfs && !held && slot.task->id < head->task->id && slot.n_ctx_shift == 0) { + continue; + } + // The head's bytes are not credited: the resident is parked before the head is freed, so both states are held at once. if (!with_recompute && !preempt_fits_budget(slot)) { budget_refused = true; @@ -6225,6 +6279,7 @@ struct server_context_impl { { "notices", 2 }, { "recurrent", preempt_recurrent }, { "granularity", preempt_alloc_granularity }, + { "policy", preempt_fcfs ? "fcfs" : "cost" }, }; } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 977a902e00b3..d9ae4fc0ded3 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -53,7 +53,7 @@ def create_server(): "LLAMA_SERVER_PREEMPT_PLANNER", "LLAMA_ARG_PREEMPT_RAM", "LLAMA_ARG_PREEMPT_ASYNC", "LLAMA_SERVER_PREEMPT_FAIL_SAVE", "LLAMA_ARG_SPEC_DRAFT_P_MIN", "LLAMA_ARG_LOG_VERBOSITY", "LLAMA_BATCH_DEBUG", "LLAMA_ARG_CTX_CHECKPOINTS", - "LLAMA_MEDIA_MARKER", "LLAMA_EXACT_CONCURRENCY"): + "LLAMA_MEDIA_MARKER", "LLAMA_EXACT_CONCURRENCY", "LLAMA_ARG_PREEMPT_POLICY"): os.environ.pop(name, None) @@ -1279,7 +1279,7 @@ def test_props_reports_the_preemption_setup(ram): res = server.make_request("GET", "/props") assert res.status_code == 200 preempt = res.body["preempt"] - assert sorted(preempt) == ["async", "enabled", "granularity", "notices", "ram_mib", "recurrent"] + assert sorted(preempt) == ["async", "enabled", "granularity", "notices", "policy", "ram_mib", "recurrent"] assert preempt["enabled"] is (ram == "8192") assert preempt["ram_mib"] == (8192 if ram == "8192" else 0) assert preempt["async"] is False or ram == "8192" @@ -1287,6 +1287,7 @@ def test_props_reports_the_preemption_setup(ram): assert preempt["notices"] == 2 assert preempt["recurrent"] is False assert preempt["granularity"] == 1 + assert preempt["policy"] == "cost" def test_props_reports_preemption_off_without_a_unified_cache(): @@ -1482,3 +1483,61 @@ def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generati assert res.body["timings"]["predicted_n"] == n_predict assert older.body["preempt"]["parks"] == 0, "the older generating request was parked for a newer one" assert newer.body["preempt"]["parks"] > 0 + + +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_the_policy_decides_whether_the_newest_or_the_cheapest_slot_is_parked(policy): + # The older request is smaller: cost parks it and exempts the larger one, fcfs parks the newer one. Both first purge the idle slot. + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy + _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128, cache_ram=0) + assert server.make_request("GET", "/props").body["preempt"]["policy"] == policy + assert _cached(1, [300 + k % 50 for k in range(150)], 2).status_code == 200 + with ThreadPoolExecutor(1) as pool: + older = pool.submit(_cached, 600, [100 + k % 50 for k in range(40)], 0) + deadline = time.time() + 60 + while time.time() < deadline and _n_decoded(_slot_view(0)) < 20: + time.sleep(0.005) + newer = _cached(500, [200 + k % 50 for k in range(300)], 1) + older = older.result() + for res, n_predict in ((older, 600), (newer, 500)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + parked, exempt = (newer, older) if policy == "fcfs" else (older, newer) + assert exempt.body["preempt"]["parks"] == 0 + assert parked.body["preempt"]["parks"] > 0 + text = _log() + assert 0 <= text.find("purging slot 2") < text.find("preempted:"), "a running slot was parked while an idle one held cells" + + +def test_fcfs_resumes_parked_requests_in_arrival_order(): + # The newest is parked first, so park time and arrival disagree: the older of the two parked requests comes back first. + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = "fcfs" + _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128) + with ThreadPoolExecutor(3) as pool: + futures = [] + for i, n_predict in enumerate((700, 450, 450)): + futures.append(pool.submit(_cached, n_predict, [100 * (i + 1) + k % 50 for k in range(40)], i)) + _wait_processing([i]) + results = [f.result() for f in futures] + for res, n_predict in zip(results, (700, 450, 450)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + assert results[0].body["preempt"]["parks"] == 0, "the oldest request was parked" + text = _log() + resumed = [int(m) for m in re.findall(r"id +(\d+) \| task \d+ \| resumed after", text)] + assert resumed, "nothing was parked" + parked = [int(m) for m in re.findall(r"id +(\d+) \| task \d+ \| preempted:", text)] + assert parked[0] == 2, parked + if 1 in parked: + assert resumed.index(1) < resumed.index(2), resumed + + +def test_the_old_policy_knob_selects_fcfs(): + os.environ["LLAMA_SERVER_PREEMPT_POLICY"] = "fcfs" + try: + _start(n_ctx=256) + assert server.make_request("GET", "/props").body["preempt"]["policy"] == "fcfs" + finally: + os.environ.pop("LLAMA_SERVER_PREEMPT_POLICY", None) From 9667e0521f76b4454f240d241f6998beedee5db2 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:55:46 -0700 Subject: [PATCH 043/109] server: resume a prompt dropped in its prefill only when it fits whole A prompt parked by dropping its cells restarts from its first token, but its resume was admitted as soon as one chunk fitted. Under fcfs the newest request is the victim, so a long prompt beside an older generating request was prefilled, dropped and resumed again until the older one ended (80 parks in the added test). Size its return by the whole prompt, as a dropped generating sequence already is. --- tools/server/server-context.cpp | 2 +- tools/server/tests/unit/test_preempt.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 7c17186fbebd..be7fd1f6f47c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4088,7 +4088,7 @@ struct server_context_impl { // A freshly assigned slot still mirrors the previous prompt, so count from preempt_n_keep(). int32_t preempt_n_retained(const server_slot & slot) const { if (slot.preempt_recompute) { - return (int32_t) slot.preempt_tokens.size(); // a recompute park needs all its cells back at once + return slot.preempt_n_input(); // a recompute park needs all its cells back at once; a prompt dropped in its prefill restarts, so it waits for room for all of it } if (slot.state == SLOT_STATE_STARTED && slot.task) { diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index d9ae4fc0ded3..96e303848ec0 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1541,3 +1541,24 @@ def test_the_old_policy_knob_selects_fcfs(): assert server.make_request("GET", "/props").body["preempt"]["policy"] == "fcfs" finally: os.environ.pop("LLAMA_SERVER_PREEMPT_POLICY", None) + + +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_a_prompt_dropped_in_its_prefill_waits_until_it_fits_whole(policy): + # The newer prompt is parked by dropping its cells part way through its prefill; resumed as soon as one chunk fitted, it was prefilled and dropped again until the older request ended. + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy + _serve_with_training_context(8192) + _start(n_ctx=4096, n_slots=2, n_batch=256, n_ubatch=256, cache_ram=0) + with ThreadPoolExecutor(1) as pool: + older = pool.submit(_cached, 1500, [100 + k % 50 for k in range(1500)], 0) + deadline = time.time() + 120 + while time.time() < deadline and _n_decoded(_slot_view(0)) < 100: + time.sleep(0.005) + newer = _cached(4, [200 + k % 50 for k in range(2500)], 1) + older = older.result() + for res, n_predict in ((older, 1500), (newer, 4)): + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == n_predict + parked = older if older.body["preempt"]["parks"] > 0 else newer + assert parked.body["preempt"]["parks"] == 1, (older.body["preempt"], newer.body["preempt"]) From d4531b9b8f61ca76df48a9c3de5452e8bc3bea65 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 03:55:57 -0700 Subject: [PATCH 044/109] server tests: check the policy in use in the fcfs tests --- tools/server/tests/unit/test_preempt.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 96e303848ec0..2a3811bc6f3d 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1515,6 +1515,7 @@ def test_fcfs_resumes_parked_requests_in_arrival_order(): os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" os.environ["LLAMA_ARG_PREEMPT_POLICY"] = "fcfs" _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128) + assert server.make_request("GET", "/props").body["preempt"]["policy"] == "fcfs" with ThreadPoolExecutor(3) as pool: futures = [] for i, n_predict in enumerate((700, 450, 450)): @@ -1550,6 +1551,7 @@ def test_a_prompt_dropped_in_its_prefill_waits_until_it_fits_whole(policy): os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _serve_with_training_context(8192) _start(n_ctx=4096, n_slots=2, n_batch=256, n_ubatch=256, cache_ram=0) + assert server.make_request("GET", "/props").body["preempt"]["policy"] == policy with ThreadPoolExecutor(1) as pool: older = pool.submit(_cached, 1500, [100 + k % 50 for k in range(1500)], 0) deadline = time.time() + 120 From c2cfc8dc12fc790a77d5c21eaabf92807b5d9b72 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 05:03:18 -0700 Subject: [PATCH 045/109] server: stop time-slicing residents that end by themselves Every 2 s a parked head rotated out any served resident, so oversubscribed chats with bounded output took turns parking and restoring their whole sequence: four 3000-token chats with 1024 output tokens in an 8192-cell pool took 1049 parks on CPU (38 and 73 on a GPU run), and decoded slower than running them two at a time. A resident that neither context-shifts nor generates without a bound now finishes, as under vLLM; one with more than 4096 tokens left still yields to a head that has waited 30 s, and context-shifting or unbounded residents rotate as before. The same workload now parks 3 times. --- tools/server/server-context.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index be7fd1f6f47c..7fc346393681 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -159,6 +159,8 @@ constexpr int64_t PREEMPT_FAIL_US = 60ll * 1000 * 1000; // Only applies afte constexpr int64_t PREEMPT_ROTATE_US = 2ll * 1000 * 1000; // A parked head waiting this long gets a resident rotated out for it, and new prompts wait. constexpr int64_t PREEMPT_ROTATE_RECOMPUTE_US = 30ll * 1000 * 1000; // After this long the head may also rotate a resident that would need a re-prefill. constexpr int32_t PREEMPT_ROTATE_MIN_GEN = 32; // Tokens a resumed slot decodes before it can be rotated out again. +constexpr int64_t PREEMPT_ROTATE_BOUNDED_US = 30ll * 1000 * 1000; // A resident that will end by itself (no context shift, bounded output) is rotated only for a head parked this long, +constexpr int32_t PREEMPT_ROTATE_MIN_LEFT = 4096; // and only while it has more than this many tokens left to generate. // [TAG_PREEMPT_ASYNC] An async park frees cells only when its copy lands, so it must start this many steps before the pool runs out. constexpr int32_t PREEMPT_N_ASYNC_STEPS = 8; @@ -4903,6 +4905,12 @@ struct server_context_impl { continue; } + // [TAG_PREEMPT] Time-slicing residents that end by themselves only trades park copies for nothing; a long one still yields to a head that waited long. + if (!held && slot.n_ctx_shift == 0 && slot.n_remaining() >= 0 && + (slot.n_remaining() <= PREEMPT_ROTATE_MIN_LEFT || ggml_time_us() - head->t_preempt_us < PREEMPT_ROTATE_BOUNDED_US)) { + continue; + } + // The head's bytes are not credited: the resident is parked before the head is freed, so both states are held at once. if (!with_recompute && !preempt_fits_budget(slot)) { budget_refused = true; From de339402da11e4786e177b3728da9718f2ab070a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 05:04:30 -0700 Subject: [PATCH 046/109] server tests: oversubscribed bounded chats are not time-sliced --- tools/server/tests/unit/test_preempt.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 2a3811bc6f3d..92c94ec35de5 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1564,3 +1564,17 @@ def test_a_prompt_dropped_in_its_prefill_waits_until_it_fits_whole(policy): assert res.body["timings"]["predicted_n"] == n_predict parked = older if older.body["preempt"]["parks"] > 0 else newer assert parked.body["preempt"]["parks"] == 1, (older.body["preempt"], newer.body["preempt"]) + + +def test_oversubscribed_bounded_chats_are_not_time_sliced(): + # Four chats of 200 + 800 tokens need twice the pool; residents that end by themselves used to be rotated out every 2 s, parking and restoring whole sequences over and over. + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + _start(n_ctx=2048, n_slots=4, n_batch=256, n_ubatch=256, cache_ram=0) + with ThreadPoolExecutor(4) as pool: + results = list(pool.map(lambda i: _cached(800, [50 + 100 * i + k % 50 for k in range(200)], i), range(4))) + _assert_completed(results, 800) + text = _log() + assert "Context size has been exceeded" not in text + assert "rotated out after" not in text + parks = sum(r.body["preempt"]["parks"] for r in results) + assert 1 <= parks <= 4, parks From 317ef28b2a62dd5815c0fbf2de2613d5760be21d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 05:08:23 -0700 Subject: [PATCH 047/109] server tests: run test_preempt_models with two threads A server that spins every hardware thread missed the request timeout on a loaded machine. --- tools/server/tests/unit/test_preempt_models.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/server/tests/unit/test_preempt_models.py b/tools/server/tests/unit/test_preempt_models.py index c0ae36281c2b..d5aae120c3fb 100644 --- a/tools/server/tests/unit/test_preempt_models.py +++ b/tools/server/tests/unit/test_preempt_models.py @@ -13,6 +13,7 @@ def create_server(): global server server = ServerPreset.tinyllama2() + server.n_threads = 2 yield os.environ.pop("LLAMA_ARG_PREEMPT_RAM", None) @@ -21,6 +22,7 @@ def create_server(): def test_a_non_causal_decision_longer_than_the_ubatch_is_refused_and_the_server_lives(preempt_ram): global server server = ServerPreset.tinyopenjev() + server.n_threads = 2 server.override_kv = ["qwen35.attention.causal=bool:false"] server.n_ctx = 1024 server.n_slots = 2 From 4bdbeb10eb0ca85d2e4a8c46d6d0653697f36fe4 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 05:57:12 -0700 Subject: [PATCH 048/109] server: resume a parked slot only into room its bounded residents will not need The resume check left room for the parked sequence and everyone's next step, so in an oversubscribed pool a slot came back as soon as one fitted and was parked again a few hundred tokens later when the residents grew. When every resident has an output limit, also require that all of them can reach it beside the resumed slot. Unbounded or n_cmpl > 1 residents keep the old check. Four 3000-token chats with 1024 output tokens in an 8192-cell pool now park 3 times instead of 8. The cost case of the policy test no longer asserts which slot is parked: that depends on the host's speed. --- tools/server/server-context.cpp | 38 ++++++++++++++++++++++++- tools/server/tests/unit/test_preempt.py | 15 ++++++---- 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 7fc346393681..7f317744c090 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4175,6 +4175,38 @@ struct server_context_impl { return res; } + // [TAG_PREEMPT] Cells a slot holds once its output limit is reached; -1 if it has no limit. + int32_t preempt_n_final(const server_slot & slot) const { + if (!slot.task || slot.n_remaining() < 0) { + return -1; + } + + const int32_t n_cur = std::max(slot.prompt.n_tokens(), slot.state == SLOT_STATE_GENERATING ? 0 : slot.preempt_n_input()); + + return preempt_n_cells(std::min(slot.n_ctx, n_cur + slot.n_remaining() + 1)); + } + + // Cells the residents hold once each reaches its output limit; -1 if one has no limit, or shares cells with a sibling. + int32_t preempt_kv_projected() const { + int32_t res = 0; + + for (const auto & slot : slots) { + if (!slot.is_processing() || slot.state == SLOT_STATE_PREEMPTED) { + continue; + } + + const int32_t n = preempt_n_final(slot); + + if (n < 0 || preempt_is_family(slot) || slot.state == SLOT_STATE_WAIT_OTHER) { + return -1; + } + + res += n; + } + + return res; + } + // Cells try_clear_idle_slots() can free. int32_t preempt_n_idle_cells() const { int32_t res = 0; @@ -4850,8 +4882,12 @@ struct server_context_impl { const int32_t occupied = preempt_kv_used() + preempt_kv_reserve(); const int32_t margin = occupied == 0 ? 0 : preempt_n_margin(1); + // [TAG_PREEMPT] With every resident bounded, also wait until all of them can reach their output limit beside it, or the growth parks someone again. + const int32_t projected = occupied == 0 ? 0 : preempt_kv_projected(); + for (auto * slot : parked) { - if (occupied + preempt_n_need(*slot) + margin <= n_cells) { + if (occupied + preempt_n_need(*slot) + margin <= n_cells && + (projected < 0 || preempt_n_final(*slot) < 0 || projected + preempt_n_final(*slot) + margin <= n_cells)) { best = slot; break; } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 92c94ec35de5..1a562b3b7d7a 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1487,7 +1487,7 @@ def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generati @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_the_policy_decides_whether_the_newest_or_the_cheapest_slot_is_parked(policy): - # The older request is smaller: cost parks it and exempts the larger one, fcfs parks the newer one. Both first purge the idle slot. + # fcfs parks the newer request and never the older one; cost parks whichever is cheaper at the time, which depends on the host's speed. Both first purge the idle slot. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128, cache_ram=0) @@ -1503,9 +1503,11 @@ def test_the_policy_decides_whether_the_newest_or_the_cheapest_slot_is_parked(po for res, n_predict in ((older, 600), (newer, 500)): assert res.status_code == 200, res.body assert res.body["timings"]["predicted_n"] == n_predict - parked, exempt = (newer, older) if policy == "fcfs" else (older, newer) - assert exempt.body["preempt"]["parks"] == 0 - assert parked.body["preempt"]["parks"] > 0 + if policy == "fcfs": + assert older.body["preempt"]["parks"] == 0 + assert newer.body["preempt"]["parks"] > 0 + else: + assert older.body["preempt"]["parks"] + newer.body["preempt"]["parks"] > 0 text = _log() assert 0 <= text.find("purging slot 2") < text.find("preempted:"), "a running slot was parked while an idle one held cells" @@ -1576,5 +1578,6 @@ def test_oversubscribed_bounded_chats_are_not_time_sliced(): text = _log() assert "Context size has been exceeded" not in text assert "rotated out after" not in text - parks = sum(r.body["preempt"]["parks"] for r in results) - assert 1 <= parks <= 4, parks + parks = [r.body["preempt"]["parks"] for r in results] + assert 1 <= sum(parks) <= 4, parks + assert max(parks) == 1, f"a chat was resumed into room the residents still needed and parked again: {parks}" From 9354766cce9121f03e2f90728544cf9aa53b8898 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 07:15:50 -0700 Subject: [PATCH 049/109] server: under fcfs, queue a rotated-out slot behind the head it made room for fcfs resumes parked slots in arrival order. A resident rotated out for a parked head is usually older than it, so it came straight back ahead of the head, and a context-shifting resident that the budget could only rotate by recompute was dropped and re-prefilled every few hundred milliseconds while the head never ran. Give the rotated slot a resume rank just behind the head's. --- tools/server/server-context.cpp | 11 ++++++++++- tools/server/tests/unit/test_preempt.py | 5 ++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 7f317744c090..db52f273ab4f 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -481,6 +481,7 @@ struct server_slot { bool preempt_rotation_refused = false; bool preempt_hold_logged = false; bool preempt_grow = false; // the next park may pin a buffer larger than the sequence + int64_t preempt_rank = -1; // fcfs resume order once rotated out, -1 = by arrival // [TAG_PREEMPT] Last budget refusal: tokens, held capacity and RAM in use then; -1 when none. mutable int32_t preempt_refused_n = -1; @@ -937,6 +938,7 @@ struct server_slot { t_preempt_resume_us = 0; n_gen_resume = 0; preempt_hold_logged = false; + preempt_rank = -1; preempt_refused_n = -1; llama_set_sampler(ctx_tgt, id, nullptr); @@ -4583,7 +4585,12 @@ struct server_context_impl { // [TAG_PREEMPT] Resume order: arrival under fcfs, park time under cost. bool preempt_resumes_before(const server_slot & a, const server_slot & b) const { - return preempt_fcfs ? a.task->id < b.task->id : a.t_preempt_us < b.t_preempt_us; + return preempt_fcfs ? preempt_rank(a) < preempt_rank(b) : a.t_preempt_us < b.t_preempt_us; + } + + // [TAG_PREEMPT] fcfs order: twice the task id, or just behind the head a slot was rotated out for, or it would resume at once ahead of it. + static int64_t preempt_rank(const server_slot & slot) { + return slot.preempt_rank >= 0 ? slot.preempt_rank : 2 * (int64_t) slot.task->id; } // [TAG_PREEMPT] A never-resident prompt waits while the head's reservation stands. Re-prefills, resumed prompts, and empty or rejected prompts go on. @@ -5000,6 +5007,8 @@ struct server_context_impl { if (pick && preempt_park(*pick, t_start, recompute)) { server_slot & slot = *pick; + slot.preempt_rank = std::max(preempt_rank(slot), preempt_rank(*head) + 1); + if (slot.preempt_recompute) { SLT_WRN(slot, "rotated out after %d context shifts: %d cells dropped, %d tokens to re-prefill on resume, a head parked %.1f s takes its turn%s, preemptions %d\n", slot.n_ctx_shift, n_rotated, diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 1a562b3b7d7a..7f507ad8004a 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -383,9 +383,12 @@ def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): assert res.body["timings"]["predicted_n"] == n_predict -def test_a_resident_that_cannot_be_swapped_out_is_rotated_by_recompute(): +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_a_resident_that_cannot_be_swapped_out_is_rotated_by_recompute(policy): # 1 MiB holds no snapshot, so rotation used to refuse every resident and the head waited forever behind a context-shifting one. + # Under fcfs the rotated-out resident is older than the head, and resumed ahead of it at once until it queued behind it. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _start(n_ctx=2048, n_slots=2, n_batch=2048, enable_ctx_shift=True) # A small n_discard keeps the resident near the end of the pool, so its state never fits the budget. From cafbdedfdab2a89f580cbf31c8cb729aef5fe073 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 07:46:31 -0700 Subject: [PATCH 050/109] server: rotate a resident that ends by itself only if it would hold the head long The rule from the previous change rotated a bounded resident only with more than 4096 tokens left, so a resident with 3000 tokens to go at a slow rate held a parked head for minutes, and fcfs never rotated an older bounded resident at all. Estimate each resident's time to its end from its rate since it last resumed, capped by the context when it cannot shift. Once the head has waited 30 s, rotate one that would run another 30 s, under both policies. Residents that context-shift, or may shift with no output limit, still rotate after 2 s, and under fcfs a resident newer than the head always may. Bounded chats that end soon are still not time-sliced. The slow rotation test now runs under both policies and checks that the parked request's wait is bounded instead of which request ends first. --- tools/server/server-context.cpp | 39 ++++++++++++++++++------- tools/server/tests/unit/test_preempt.py | 19 +++++++----- 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index db52f273ab4f..6faaac3beb48 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -159,8 +159,7 @@ constexpr int64_t PREEMPT_FAIL_US = 60ll * 1000 * 1000; // Only applies afte constexpr int64_t PREEMPT_ROTATE_US = 2ll * 1000 * 1000; // A parked head waiting this long gets a resident rotated out for it, and new prompts wait. constexpr int64_t PREEMPT_ROTATE_RECOMPUTE_US = 30ll * 1000 * 1000; // After this long the head may also rotate a resident that would need a re-prefill. constexpr int32_t PREEMPT_ROTATE_MIN_GEN = 32; // Tokens a resumed slot decodes before it can be rotated out again. -constexpr int64_t PREEMPT_ROTATE_BOUNDED_US = 30ll * 1000 * 1000; // A resident that will end by itself (no context shift, bounded output) is rotated only for a head parked this long, -constexpr int32_t PREEMPT_ROTATE_MIN_LEFT = 4096; // and only while it has more than this many tokens left to generate. +constexpr int64_t PREEMPT_ROTATE_BOUNDED_US = 30ll * 1000 * 1000; // A resident that will end by itself is rotated only for a head parked this long, and only if it would run longer than this again. // [TAG_PREEMPT_ASYNC] An async park frees cells only when its copy lands, so it must start this many steps before the pool runs out. constexpr int32_t PREEMPT_N_ASYNC_STEPS = 8; @@ -4648,6 +4647,28 @@ struct server_context_impl { (n_gen > 0 && ggml_time_us() - t_from >= PREEMPT_ROTATE_US); } + // [TAG_PREEMPT] Time until a resident ends by itself, at its rate since it last resumed; -1 if it may never end (it context-shifts, or may shift with no output limit). + int64_t preempt_us_to_end(const server_slot & slot) const { + if (slot.n_ctx_shift > 0 || (params_base.ctx_shift && slot.n_remaining() < 0)) { + return -1; + } + + int64_t n_left = slot.n_remaining() >= 0 ? slot.n_remaining() : INT32_MAX; + + if (!params_base.ctx_shift) { + n_left = std::min(n_left, std::max(0, slot.n_ctx - slot.prompt.n_tokens())); + } + + const int32_t n_gen = (int32_t) slot.stats.n_gen - slot.n_gen_resume; + const int64_t t_from = slot.n_preempt == 0 ? slot.stats.t_prompt_last : slot.t_preempt_resume_us; + + if (n_gen <= 0) { + return INT64_MAX; + } + + return (int64_t) std::min((double) n_left * (double) (ggml_time_us() - t_from) / n_gen, (double) INT64_MAX / 2); + } + bool preempt_any_out() const { for (const auto & slot : slots) { if (slot.preempt_is_out()) { @@ -4943,15 +4964,13 @@ struct server_context_impl { continue; } - // [TAG_PREEMPT] Under fcfs an older resident is rotated only if it context-shifts, as it may never end. - if (preempt_fcfs && !held && slot.task->id < head->task->id && slot.n_ctx_shift == 0) { - continue; - } + // [TAG_PREEMPT] Time-slicing residents that end by themselves only trades park copies for nothing; one that would still hold the head long yields once the head has waited long. Under fcfs a resident newer than the head always yields. + if (!held && !(preempt_fcfs && preempt_rank(slot) > preempt_rank(*head))) { + const int64_t t_end = preempt_us_to_end(slot); - // [TAG_PREEMPT] Time-slicing residents that end by themselves only trades park copies for nothing; a long one still yields to a head that waited long. - if (!held && slot.n_ctx_shift == 0 && slot.n_remaining() >= 0 && - (slot.n_remaining() <= PREEMPT_ROTATE_MIN_LEFT || ggml_time_us() - head->t_preempt_us < PREEMPT_ROTATE_BOUNDED_US)) { - continue; + if (t_end >= 0 && (ggml_time_us() - head->t_preempt_us < PREEMPT_ROTATE_BOUNDED_US || t_end < PREEMPT_ROTATE_BOUNDED_US)) { + continue; + } } // The head's bytes are not credited: the resident is parked before the head is freed, so both states are held at once. diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 7f507ad8004a..1ea72a3cef56 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1202,18 +1202,21 @@ def stream(id_slot): @pytest.mark.slow -def test_a_long_resident_that_never_shifts_is_rotated_out_for_an_aged_head(): +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_a_long_resident_that_never_shifts_is_rotated_out_for_an_aged_head(policy): # Only context-shifting residents used to be rotated, so a long generation that fit held the pool and the parked slot waited for all of it. + # A resident that ends by itself is rotated once the head has waited 30 s and it would run 30 s more, so the head's wait is bounded either way. + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _serve_with_training_context(16384) _start(n_ctx=16384, n_slots=2, n_batch=2048) done = {} def run(name, n_predict, prompt, id_slot): - res = _raw_completion(n_predict, prompt, id_slot, timeout=900) + res = _raw_completion(n_predict, prompt, id_slot, timeout=1800) done[name] = (time.time(), res) - # A leads B by 564 cells, so B is parked once the pool fills, and A then runs far longer than the 2 s a parked head waits. + # A leads B by 564 cells, so B is parked once the pool fills. a = threading.Thread(target=run, args=("a", 16000, _prompt_of(64, _PROMPT_A), 0)) a.start() deadline = time.time() + 300 @@ -1221,8 +1224,8 @@ def run(name, n_predict, prompt, id_slot): time.sleep(0.01) b = threading.Thread(target=run, args=("b", 8000, _prompt_of(1500, _PROMPT_B), 1)) b.start() - a.join(900) - b.join(900) + a.join(1800) + b.join(1800) for name in ("a", "b"): assert done[name][1].status_code == 200, done[name][1].body @@ -1232,8 +1235,10 @@ def run(name, n_predict, prompt, id_slot): text = _log() assert "Context size has been exceeded" not in text assert "slot context shift" not in text - assert "rotated out after 0 context shifts" in text, "the long resident was never rotated out" - assert done["b"][0] < done["a"][0], "the parked slot only came back once the long resident had finished" + waits = [float(w) for w in re.findall(r"id +1 \| task \d+ \| resumed after ([\d.]+) s", text)] + assert waits, "the second request was never parked" + # 30 s before a rotation is considered, plus at most 30 s of the resident's own estimated remainder. + assert max(waits) < 90.0, f"the parked request waited {waits} s behind a resident that ends by itself" def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small_ones(): From 323e93ffcfaf0487442333942fc15982d344c3f8 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 08:03:16 -0700 Subject: [PATCH 051/109] server: make fcfs the default preemption policy fcfs matched or beat cost on the oversubscribed workloads measured, and parks the newest arrival instead of an older request. cost stays available with --preempt-policy cost. The preemption tests now keep a LLAMA_ARG_PREEMPT_POLICY set by the caller between tests, so the whole file can run under either policy, and the props and old-knob tests follow it. --- common/common.h | 4 ++-- tools/server/README.md | 2 +- tools/server/tests/unit/test_preempt.py | 14 ++++++++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/common/common.h b/common/common.h index 8f2ae0319800..2a62a2334a1f 100644 --- a/common/common.h +++ b/common/common.h @@ -38,8 +38,8 @@ #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: "cost" (park the cheapest slot, the largest exempt) or "fcfs" (park the newest arrival) -#define COMMON_PREEMPT_POLICY_DEFAULT "cost" +// --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) diff --git a/tools/server/README.md b/tools/server/README.md index 27ba701ce71d..0a827b56a99c 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -168,7 +168,7 @@ For the full list of features, please refer to [server's changelog](https://gith | `-cram, --cache-ram N` | set the maximum cache size in MiB (default: 8192, -1 - no limit, 0 - disable)[(more info)](https://github.com/ggml-org/llama.cpp/pull/16391)
(env: LLAMA_ARG_CACHE_RAM) | | `--preempt-ram N` | 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: 0 - disabled, -1 - no limit)
(env: LLAMA_ARG_PREEMPT_RAM) | | `--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)
(env: LLAMA_ARG_PREEMPT_ASYNC) | -| `--preempt-policy {fcfs,cost}` | 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: cost)
(env: LLAMA_ARG_PREEMPT_POLICY) | +| `--preempt-policy {fcfs,cost}` | 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: fcfs)
(env: LLAMA_ARG_PREEMPT_POLICY) | | `-kvu, --kv-unified, -no-kvu, --no-kv-unified` | use single unified KV buffer shared across all sequences (default: enabled if number of slots is auto)
(env: LLAMA_ARG_KV_UNIFIED) | | `--cache-idle-slots, --no-cache-idle-slots` | save idle slots to the prompt cache on new task, and clear them when using unified KV (default: enabled, requires cache-ram)
(env: LLAMA_ARG_CACHE_IDLE_SLOTS) | | `--context-shift, --no-context-shift` | whether to use context shift on infinite text generation (default: disabled)
(env: LLAMA_ARG_CONTEXT_SHIFT) | diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 1ea72a3cef56..f90e934a9863 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -20,6 +20,7 @@ _scratch = [] # files a test wrote, removed after it _cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES") # restored after a test that hides the GPUs +_policy = os.environ.get("LLAMA_ARG_PREEMPT_POLICY") # restored after a test that picks one, so the suite can run under either _PROMPT_A = "Once upon a time there was a brave knight who" _PROMPT_B = "The quick brown fox jumps over the lazy dog and" @@ -55,6 +56,8 @@ def create_server(): "LLAMA_BATCH_DEBUG", "LLAMA_ARG_CTX_CHECKPOINTS", "LLAMA_MEDIA_MARKER", "LLAMA_EXACT_CONCURRENCY", "LLAMA_ARG_PREEMPT_POLICY"): os.environ.pop(name, None) + if _policy is not None: + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = _policy def _start(**kwargs): @@ -1295,7 +1298,7 @@ def test_props_reports_the_preemption_setup(ram): assert preempt["notices"] == 2 assert preempt["recurrent"] is False assert preempt["granularity"] == 1 - assert preempt["policy"] == "cost" + assert preempt["policy"] == (_policy or "fcfs") def test_props_reports_preemption_off_without_a_unified_cache(): @@ -1545,11 +1548,14 @@ def test_fcfs_resumes_parked_requests_in_arrival_order(): assert resumed.index(1) < resumed.index(2), resumed -def test_the_old_policy_knob_selects_fcfs(): - os.environ["LLAMA_SERVER_PREEMPT_POLICY"] = "fcfs" +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_the_old_policy_knob_selects_the_policy(policy): + # The old test knob is an alias only while LLAMA_ARG_PREEMPT_POLICY is unset. + os.environ.pop("LLAMA_ARG_PREEMPT_POLICY", None) + os.environ["LLAMA_SERVER_PREEMPT_POLICY"] = policy try: _start(n_ctx=256) - assert server.make_request("GET", "/props").body["preempt"]["policy"] == "fcfs" + assert server.make_request("GET", "/props").body["preempt"]["policy"] == policy finally: os.environ.pop("LLAMA_SERVER_PREEMPT_POLICY", None) From e3f32b8e7f2d8cb0afe49595943ec6fed241a513 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 12:40:21 -0700 Subject: [PATCH 052/109] server: let --preempt-policy outrank the old LLAMA_SERVER_PREEMPT_POLICY knob --- common/arg.cpp | 3 ++- common/common.h | 1 + tools/server/server-context.cpp | 4 ++-- tools/server/tests/unit/test_preempt.py | 14 ++++++++++++++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/common/arg.cpp b/common/arg.cpp index f8828817693b..41fc43455583 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -1756,7 +1756,8 @@ common_params_context common_params_parser_init(common_params & params, llama_ex if (value != "fcfs" && value != "cost") { throw std::invalid_argument("invalid value"); } - params.preempt_policy = 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( diff --git a/common/common.h b/common/common.h index 2a62a2334a1f..a2555c3af1cd 100644 --- a/common/common.h +++ b/common/common.h @@ -644,6 +644,7 @@ struct common_params { 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 std::string public_path = ""; // NOLINT std::string api_prefix = ""; // NOLINT diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 1ef2185bddd7..1255609d953c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2152,12 +2152,12 @@ struct server_context_impl { preempt_fcfs = params_base.preempt_policy == "fcfs"; - // LLAMA_SERVER_PREEMPT_POLICY: fcfs or cost, as --preempt-policy when LLAMA_ARG_PREEMPT_POLICY is unset; or a cost test knob: smallest (default), largest, youngest or oldest. + // LLAMA_SERVER_PREEMPT_POLICY: fcfs or cost, as --preempt-policy when neither that flag nor LLAMA_ARG_PREEMPT_POLICY was given; or a cost test knob: smallest (default), largest, youngest or oldest. const char * LLAMA_SERVER_PREEMPT_POLICY = getenv("LLAMA_SERVER_PREEMPT_POLICY"); preempt_test_policy = "smallest"; if (LLAMA_SERVER_PREEMPT_POLICY && (strcmp(LLAMA_SERVER_PREEMPT_POLICY, "fcfs") == 0 || strcmp(LLAMA_SERVER_PREEMPT_POLICY, "cost") == 0)) { - if (!getenv("LLAMA_ARG_PREEMPT_POLICY")) { + if (!params_base.preempt_policy_set) { preempt_fcfs = strcmp(LLAMA_SERVER_PREEMPT_POLICY, "fcfs") == 0; } } else if (LLAMA_SERVER_PREEMPT_POLICY) { diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index f90e934a9863..db5ab0f7ae76 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1560,6 +1560,20 @@ def test_the_old_policy_knob_selects_the_policy(policy): os.environ.pop("LLAMA_SERVER_PREEMPT_POLICY", None) +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_the_command_line_policy_wins_over_the_old_knob(policy, monkeypatch): + # The old knob only stands in for an unset policy: --preempt-policy outranks it like any environment value. + os.environ.pop("LLAMA_ARG_PREEMPT_POLICY", None) + os.environ["LLAMA_SERVER_PREEMPT_POLICY"] = "cost" if policy == "fcfs" else "fcfs" + popen = subprocess.Popen + monkeypatch.setattr(subprocess, "Popen", lambda args, *a, **k: popen([*args, "--preempt-policy", policy], *a, **k)) + try: + _start(n_ctx=256) + assert server.make_request("GET", "/props").body["preempt"]["policy"] == policy + finally: + os.environ.pop("LLAMA_SERVER_PREEMPT_POLICY", None) + + @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_a_prompt_dropped_in_its_prefill_waits_until_it_fits_whole(policy): # The newer prompt is parked by dropping its cells part way through its prefill; resumed as soon as one chunk fitted, it was prefilled and dropped again until the older request ended. From f6439767158bbcf415a1d7832639616afb9c2ec3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 13:02:15 -0700 Subject: [PATCH 053/109] llama: emit state runs without allocating, and refuse a decode width the backends cannot take --- src/llama-context.cpp | 41 +++++++++++++++-------------------- src/llama-impl.cpp | 6 +++++ tests/test-exact-geometry.cpp | 5 +++++ 3 files changed, 29 insertions(+), 23 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index a067ff12161a..d2b124c5e264 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -3024,46 +3024,41 @@ static size_t llama_io_run_size(const std::vector & infos, size_t i, siz // [TAG_STATE_COALESCE] Equal runs at a constant stride (sequences interleaved in a unified cache) are one strided copy. template static void llama_io_emit(const std::vector & infos, size_t first, size_t last, emit_t emit) { - std::vector> runs; - + // one pass and no allocation: this also runs from the host I/O destructors, where a bad_alloc would terminate for (size_t i = first; i < last; ) { - const size_t end = llama_io_run_end(infos, i); - - runs.emplace_back(i, end); - - i = end; - } - - for (size_t r = 0; r < runs.size(); ) { - const auto & head = infos[runs[r].first]; - - const size_t size = llama_io_run_size(infos, runs[r].first, runs[r].second); + const size_t end = llama_io_run_end(infos, i); + const auto & head = infos[i]; + const size_t size = llama_io_run_size(infos, i, end); size_t n_copies = 1; size_t stride_tensor = 0; size_t stride_data = 0; + size_t next = end; - if (r + 1 < runs.size()) { - const auto & next = infos[runs[r + 1].first]; + if (end < last) { + const auto & second = infos[end]; + const size_t second_end = llama_io_run_end(infos, end); - if (next.tensor == head.tensor && next.offset > head.offset && next.ptr > head.ptr && - llama_io_run_size(infos, runs[r + 1].first, runs[r + 1].second) == size) { - stride_tensor = next.offset - head.offset; - stride_data = (size_t) (next.ptr - head.ptr); + if (second.tensor == head.tensor && second.offset > head.offset && second.ptr > head.ptr && + llama_io_run_size(infos, end, second_end) == size) { + stride_tensor = second.offset - head.offset; + stride_data = (size_t) (second.ptr - head.ptr); // a strided copy may not have its rows overlap, on either side if (stride_tensor >= size && stride_data >= size) { - while (r + n_copies < runs.size()) { - const auto & cur = infos[runs[r + n_copies].first]; + while (next < last) { + const auto & cur = infos[next]; + const size_t cur_end = llama_io_run_end(infos, next); if (cur.tensor != head.tensor || cur.offset != head.offset + n_copies * stride_tensor || cur.ptr != head.ptr + n_copies * stride_data || - llama_io_run_size(infos, runs[r + n_copies].first, runs[r + n_copies].second) != size) { + llama_io_run_size(infos, next, cur_end) != size) { break; } n_copies++; + next = cur_end; } } } @@ -3071,7 +3066,7 @@ static void llama_io_emit(const std::vector & infos, size_t first, size_ emit(head.tensor, head.ptr, head.offset, size, n_copies, stride_tensor, stride_data); - r += n_copies; + i = next; } } diff --git a/src/llama-impl.cpp b/src/llama-impl.cpp index 99fe83823c1e..9147316112da 100644 --- a/src/llama-impl.cpp +++ b/src/llama-impl.cpp @@ -334,6 +334,12 @@ static bool llama_exact_width_within_explicit_bound(uint32_t n_cols) { } bool llama_set_exact_decode_width(uint32_t n_cols) { + // the backends take the width as an int; a wider one would reach them negative and be ignored, while the maximum kept it + if (n_cols > (uint32_t) INT32_MAX) { + LLAMA_LOG_ERROR("%s: a decode width of %u columns is too wide to report\n", __func__, n_cols); + return false; + } + if (!llama_exact_width_within_explicit_bound(n_cols)) { return false; } diff --git a/tests/test-exact-geometry.cpp b/tests/test-exact-geometry.cpp index 56f399216b70..57b332765e10 100644 --- a/tests/test-exact-geometry.cpp +++ b/tests/test-exact-geometry.cpp @@ -45,6 +45,11 @@ int main() { assert(common_exact_batch_geometry(512, 512, 0, &n_min)); assert(n_min == 512); + // a width the backends cannot take as an int is refused, and does not pin the maximum above every later width + const uint32_t width = llama_exact_decode_width(); + assert(!llama_set_exact_decode_width((uint32_t) INT32_MAX + 1)); + assert(llama_exact_decode_width() == width); + printf("%s: all tests passed\n", __func__); return 0; From 37254a781ab1f6077bda85a9e4e4202822095866 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 13:25:44 -0700 Subject: [PATCH 054/109] Trim comments --- tools/server/server-context.cpp | 15 --------------- tools/server/tests/unit/test_preempt.py | 6 ------ tools/server/tests/unit/test_preempt_notify.py | 1 - 3 files changed, 22 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 1255609d953c..7c8883d36e00 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -3601,7 +3601,6 @@ struct server_context_impl { if (slot.is_processing()) { n_processing_slots++; } - // [TAG_PREEMPT] Transfers count as parked: none of them decodes. if (slot.preempt_is_out()) { n_preempted_slots++; } @@ -3909,7 +3908,6 @@ struct server_context_impl { // [TAG_PREEMPT] --preempt-policy fcfs: park the newest arrival, resume and reserve in arrival order. bool preempt_fcfs = false; - // [TAG_PREEMPT_ASYNC] False with --no-preempt-async or a backend without async copies. bool preempt_async_ok = false; // [TAG_EXACT_CONCURRENCY] Pool allocation granularity: 1, or the page size under exact concurrency; LLAMA_SERVER_PREEMPT_GRANULARITY overrides. @@ -3942,7 +3940,6 @@ struct server_context_impl { bool preempt_ram_kind_logged = false; - // [TAG_PREEMPT] Logged once, not per park. bool preempt_recompute_logged = false; void preempt_log_ram_kind(const server_slot & slot) { @@ -4214,7 +4211,6 @@ struct server_context_impl { return res; } - // Cells try_clear_idle_slots() can free. int32_t preempt_n_idle_cells() const { int32_t res = 0; @@ -4445,7 +4441,6 @@ struct server_context_impl { return false; } - // [TAG_PREEMPT] Room a park frees: the slot's cells plus its next step. int32_t preempt_n_freed(const server_slot & slot) const { const int32_t n_cur = slot.prompt.n_tokens(); @@ -4480,7 +4475,6 @@ struct server_context_impl { return false; } - // a held prompt with no cells frees nothing if (preempt_held(slot) && slot.prompt.n_tokens() == 0) { return false; } @@ -4514,7 +4508,6 @@ struct server_context_impl { server_slot * preempt_pick_victim_pass(const server_slot * exempt, bool recompute, int32_t n_deficit = 0) { server_slot * victim = nullptr; - // the smallest single victim covering the deficit, unstarved first server_slot * cover[2] = { nullptr, nullptr }; for (auto & slot : slots) { @@ -4862,7 +4855,6 @@ struct server_context_impl { return; // no cache (embedding model): nothing to park } - // [TAG_PREEMPT] With --preempt-ram 0 and nothing parked there is nothing to scan. if (params_base.preempt_ram_mib == 0 && !preempt_any_out()) { return; } @@ -5105,7 +5097,6 @@ struct server_context_impl { metrics.n_resume++; - // [TAG_PREEMPT] A synchronous restore lands as it is issued. send_preempt_notice(*best, false, recompute); if (recompute) { @@ -5653,7 +5644,6 @@ struct server_context_impl { return; // batch is full, skip remaining slots } - // [TAG_PREEMPT] A parked slot has nothing in the cache to batch. if (!slot.is_processing() || slot.preempt_is_out()) { return; } @@ -6225,7 +6215,6 @@ struct server_context_impl { slot.i_batch = batch.size() - 1; - // [TAG_PREEMPT] The sampler and counters carry on from where the park left them. if (!slot.preempt_reprefill) { slot.stats.n_gen = 0; @@ -6339,7 +6328,6 @@ struct server_context_impl { return preempt_state_relocates(model_tgt) || preempt_state_relocates(model_dft); } - // [TAG_PREEMPT_ASYNC] Whether a park can happen at all and go asynchronously. bool preempt_async_possible() const { return params_base.preempt_async && params_base.kv_unified && params_base.preempt_ram_mib != 0 && slots.size() >= 2 && llama_get_memory(ctx_tgt) && !preempt_state_relocates(); @@ -6435,7 +6423,6 @@ struct server_context_impl { n_parked++; - // [TAG_PREEMPT_ASYNC] The cells are needed now: wait for the copy. if (victim->state == SLOT_STATE_PREEMPTING) { while (preempt_wait_in_flight()) { } @@ -7324,7 +7311,6 @@ std::unique_ptr server_routes::handle_completions_impl( for (size_t i = 1; i < arr.size(); i++) { choices.push_back(std::move(arr[i]["choices"][0])); } - // [TAG_PREEMPT] One response covers every prompt, so its counters sum all results. if (arr[0].contains("preempt")) { int64_t n_parks = 0; int64_t n_recomputes = 0; @@ -7627,7 +7613,6 @@ static json get_res_props(const server_context_meta & meta, const common_params { "endpoint_metrics", params.endpoint_metrics }, // [TAG_EXACT_CONCURRENCY] Tells clients whether the mode is active, since a build ignoring the variable still starts. { "exact_concurrency", common_exact_concurrency() }, - // [TAG_PREEMPT] Whether and how this process parks sequences under pressure. { "preempt", meta.preempt }, { "ui", params.ui }, { "ui_settings", meta.json_ui_settings }, diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index db5ab0f7ae76..ab592bcd5bd5 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -33,7 +33,6 @@ def create_server(): server = ServerPreset.tinyllama2() server.n_slots = 2 server.kv_unified = True - # --preempt-ram defaults to 0, so parking must be enabled. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" server.server_slots = True server.server_metrics = True @@ -738,7 +737,6 @@ def prefill(first_token: int) -> list: assert res.status_code == 200, res.body assert res.body["timings"]["prompt_n"] == 3500 text = _log()[mark:] - # Decode steps are one token per slot, so the wide ubatches are the prompt's. return [w for w in _ubatch_widths(text) if w > 3] alone = prefill(1000) @@ -825,7 +823,6 @@ def test_a_park_right_after_a_context_shift_does_not_change_the_output(): n_prompt = reference.body["timings"]["prompt_n"] server.stop() - # The pool holds n_ctx cells, so the first shift is that many tokens in. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = str(256 - n_prompt) _start() @@ -1068,7 +1065,6 @@ def test_two_image_chats_that_outgrow_the_parking_budget_both_finish(): def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): # A recompute park mid-prefill restarts the prefill, so the prompt count before the park must be dropped too. - # The park's host allocation is forced to fail, so it drops the cells instead. os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" _start(n_ctx=2048, n_batch=256) @@ -1144,7 +1140,6 @@ def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): # A 7300-cell parked head used to wait forever while short requests kept a resident present. Once the head has waited its turn, never-resident prompts wait for it. # 1 MiB holds no short request's state, so only the reservation brings the head back before PREEMPT_ROTATE_RECOMPUTE_US. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" - # Parks the head while it generates. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "48" # On CUDA a prompt chunk across position 2048 of this model hangs llama_decode (also on base), so run on CPU; the code under test is host-side. os.environ["CUDA_VISIBLE_DEVICES"] = "" @@ -1280,7 +1275,6 @@ def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small @pytest.mark.parametrize("ram", ["8192", "0", "unset"]) def test_props_reports_the_preemption_setup(ram): - # Clients read this instead of guessing from the version. if ram == "unset": os.environ.pop("LLAMA_ARG_PREEMPT_RAM", None) else: diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py index 282c71901b29..415717dc112a 100644 --- a/tools/server/tests/unit/test_preempt_notify.py +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -23,7 +23,6 @@ def create_server(): server = ServerPreset.tinyllama2() server.n_slots = 2 server.kv_unified = True - # the server parks only when asked: --preempt-ram defaults to 0, and this suite is about parking os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" server.temperature = 0.0 server.seed = 42 From 2456bf85e33154687f61db648099a3a827aaf040 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 21:52:10 -0700 Subject: [PATCH 055/109] server: do not hold an n>1 prompt already on cells behind a parked head An n_cmpl > 1 prompt cannot be parked or rotated, so under fcfs it parked the older request it overflowed and was then held behind it, while the head waited for the cells the prompt sat on. Neither request finished. --- tools/server/server-context.cpp | 5 +++++ tools/server/tests/unit/test_preempt.py | 23 +++++++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 7c8883d36e00..082fa44207e1 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4601,6 +4601,11 @@ struct server_context_impl { return false; } + // [TAG_PREEMPT] An n_cmpl > 1 prompt on cells cannot be parked or rotated, so holding it keeps the head from the cells it sits on. + if (preempt_is_family(slot) && slot.prompt.n_tokens() > 0) { + return false; + } + if (preempt_fcfs && slot.task->id < preempt_reserved_for->task->id) { return false; } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index ab592bcd5bd5..5787e7ac7022 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1430,11 +1430,11 @@ def test_a_resumed_re_prefill_keeps_its_room_until_it_is_done(): assert _reparked_mid_reprefill(text) == [] -def _oai_n(prompt: list, n: int, max_tokens: int): +def _oai_n(prompt: list, n: int, max_tokens: int, timeout: float = DEFAULT_REQUEST_TIMEOUT): return server.make_request("POST", "/v1/completions", data={ "prompt": prompt, "n": n, "max_tokens": max_tokens, "ignore_eos": True, "temperature": 0.0, "seed": 42, "cache_prompt": False, - }) + }, timeout=timeout) def test_a_single_request_beside_an_n_2_request_is_parked_so_both_finish(): @@ -1470,6 +1470,25 @@ def test_two_n_2_requests_that_do_not_fit_together_end_only_one(): assert "ending it alone" in _log() +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_an_n_2_prompt_that_parked_an_older_request_is_not_held_behind_it(policy): + # The n=2 prompt cannot be parked, so the older request is parked for it; fcfs then held the prompt behind that head, which waited for the cells the prompt sat on. + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy + _start(n_ctx=1024, n_slots=3, n_batch=128, cache_ram=0) + with ThreadPoolExecutor(1) as pool: + single = pool.submit(_raw_completion, 300, [100 + k % 50 for k in range(600)], 0, 90) + deadline = time.time() + 60 + while time.time() < deadline and _n_decoded(_slot_view(0)) <= 4: + time.sleep(0.002) + family = _oai_n([200 + k % 50 for k in range(800)], 2, 1, timeout=90) + single = single.result() + assert single.status_code == 200, single.body + assert single.body["timings"]["predicted_n"] == 300 + assert family.status_code == 200, family.body + assert [c["finish_reason"] for c in family.body["choices"]] == ["length", "length"] + _assert_recovered(_log()) + + def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generating_one(): # Slot 1 keeps 600 cells of an earlier conversation; its follow-up started beside a generating request, was the largest, became the exempt leader, and the older request was parked for it. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" From 6e277f5dc70d923473f2db569e629f66930ca639 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 21:52:10 -0700 Subject: [PATCH 056/109] server: charge the rotation margin on what stays resident after it A parked head that fits the pool only with nobody else resident was never rotated in, since the margin for the residents was charged even when the rotation would remove all of them. Allow the exact fit the restore already allows once the pool would be empty. --- tools/server/server-context.cpp | 14 +++++++-- tools/server/tests/unit/test_preempt.py | 38 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 082fa44207e1..c8bf6a7bac4a 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4950,7 +4950,15 @@ struct server_context_impl { // [TAG_PREEMPT_ASYNC] A park still copying holds its cells, so rotating now would park a second resident. if (!preempt_copies_in_flight() && ggml_time_us() - head->t_preempt_us >= PREEMPT_ROTATE_US) { const int32_t occupied = preempt_kv_used() + preempt_kv_reserve(); - const int32_t need = preempt_n_need(*head) + preempt_n_margin(1); + const int32_t need = preempt_n_need(*head); + const int32_t margin = preempt_n_margin(1); + + // [TAG_PREEMPT] The margin is charged on what stays resident after the rotation; with nobody left an exact fit is allowed, as on restore. + auto room_after = [&](int32_t n_freed) { + const int32_t n_left = occupied - n_freed; + + return n_left + need + (n_left <= 0 ? 0 : margin) <= n_cells; + }; server_slot * pick = nullptr; bool pick_enough = false; @@ -4993,7 +5001,7 @@ struct server_context_impl { n_freed_all += n_freed; - const bool enough = occupied - n_freed + need <= n_cells; + const bool enough = room_after(n_freed); if (!pick || (enough && !pick_enough) || @@ -5006,7 +5014,7 @@ struct server_context_impl { // [TAG_PREEMPT] Short alone, a pick is only a first step: if every candidate together cannot make room, it would wait parked beside the head for nothing. auto drop_futile = [&]() { - if (pick && !pick_enough && occupied - n_freed_all + need > n_cells) { + if (pick && !pick_enough && !room_after(n_freed_all)) { pick = nullptr; } }; diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 5787e7ac7022..ec6931e6595c 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -362,6 +362,44 @@ def test_a_resident_cycling_through_context_shifts_is_rotated_out_for_a_parked_h assert "slot context shift" in text +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_a_parked_head_that_needs_the_whole_pool_is_rotated_in(policy): + # 506 of 512 cells fit only with nobody else resident; the rotation still charged the residents' margin, so a resident that context-shifts forever kept the pool. + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy + _start(n_ctx=512, n_batch=512, cache_ram=0, enable_ctx_shift=True, n_predict=-1) + head = _prompt_of(506, _PROMPT_B) + alone = _raw_completion(1, head, 1, timeout=60) + assert alone.status_code == 200, alone.body + + stop = threading.Event() + + def lead(): + with requests.post(server.make_url("/completion"), json={ + "n_predict": -1, "prompt": _prompt_of(320, _PROMPT_A), "id_slot": 0, "cache_prompt": False, + "ignore_eos": True, "temperature": 0.0, "seed": 42, "stream": True, + }, stream=True, timeout=120) as res: + for _ in res.iter_lines(): + if stop.is_set(): + break + + leader = threading.Thread(target=lead, daemon=True) + leader.start() + try: + deadline = time.time() + 60 + while time.time() < deadline and _n_decoded(_slot_view(0)) <= 40: + time.sleep(0.005) + # Rotation waits 2 s for the head; without it the head waits for a leader that never ends. + res = _raw_completion(1, head, 1, timeout=60) + finally: + stop.set() + leader.join(30) + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == 1 + text = _log() + assert "Context size has been exceeded" not in text + assert "rotated out after" in text + + def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): # A failed save used to stop the planner and let the pool overflow, though the victim could still be parked by dropping its cells. os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" From c0e5d8ee2c68768a8673a5bc81d232f80a2f8f87 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 22:49:03 -0700 Subject: [PATCH 057/109] llama, server: record the transfer fence only when a transfer is issued The fence a transfer waits on was recorded after every decode once the server had made its transfers at startup, so an idle server with async parking recorded an event per token without ever parking. Record it as a park or restore is issued instead, which orders the copy after all compute queued so far, the same guarantee as before. The server also scanned every slot each iteration to learn that nothing was parked; a flag set by every park and cleared by the first scan that finds nobody out lets the disabled and idle paths skip it. --- src/llama-context.cpp | 16 ++++------------ src/llama-context.h | 4 ++-- tools/server/server-context.cpp | 26 +++++++++++++++++++++----- 3 files changed, 27 insertions(+), 19 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index d2b124c5e264..e2858e3c7cae 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1844,10 +1844,6 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } } - if (!state_copy_fences.empty()) { - state_seq_copy_fence(); - } - return 0; } @@ -2308,10 +2304,6 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // wait for the computation to finish (automatically done when obtaining the model output) //synchronize(); - if (!state_copy_fences.empty()) { - state_seq_copy_fence(); - } - return 0; } @@ -3731,7 +3723,7 @@ struct llama_state_seq_copy { } } - // Order the copies after compute already queued: the copy stream waits for the fence recorded at the end of every decode. + // Order the copies after compute already queued: the copy stream waits for the fence recorded as the transfer is issued. void order_after(const std::map & fences) { for (auto & it : devs) { const auto fence = fences.find(it.first); @@ -4120,7 +4112,7 @@ llama_state_seq_copy * llama_context::state_seq_copy_init() { cpy->can_pin = cpy->host_buffer_type() != ggml_backend_cpu_buffer_type(); - // One fence per device, shared by all transfers and recorded after every decode; installed after the checks so a refused transfer leaves nothing. + // One fence per device, shared by all transfers and recorded when one is issued; installed after the checks so a refused transfer leaves nothing. std::vector fences_new; for (const auto & it : cpy->devs) { @@ -4143,8 +4135,6 @@ llama_state_seq_copy * llama_context::state_seq_copy_init() { fences_new.push_back(it.first); } - state_seq_copy_fence(); - state_copies.insert(cpy.get()); cpy->counted = true; @@ -4165,6 +4155,7 @@ size_t llama_context::state_seq_copy_get(llama_state_seq_copy & cpy, size_t size } const int64_t t_sync = ggml_time_us(); + state_seq_copy_fence(); cpy.order_after(state_copy_fences); cpy.t_sync_us = ggml_time_us() - t_sync; @@ -4200,6 +4191,7 @@ size_t llama_context::state_seq_copy_set(llama_state_seq_copy & cpy, size_t size // A graph in flight may still read these cells (masked), so the copy stream waits for compute, see order_after(). const int64_t t_sync = ggml_time_us(); + state_seq_copy_fence(); cpy.order_after(state_copy_fences); cpy.t_sync_us = ggml_time_us() - t_sync; diff --git a/src/llama-context.h b/src/llama-context.h index ce7792845464..0e195fd111c6 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -174,7 +174,7 @@ struct llama_context { size_t state_seq_copy_get(llama_state_seq_copy & cpy, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags); size_t state_seq_copy_set(llama_state_seq_copy & cpy, size_t size, llama_seq_id dest_seq_id, llama_state_seq_flags flags); - // [TAG_STATE_ASYNC] mark the point the compute streams have reached, for the copies to wait for; recorded after every decode and encode once a transfer exists + // [TAG_STATE_ASYNC] mark the point the compute streams have reached, for the copies to wait for; recorded as each transfer is issued, so a decode records nothing void state_seq_copy_fence(); void state_seq_copy_release(llama_state_seq_copy * cpy); @@ -412,7 +412,7 @@ struct llama_context { ggml_backend_t backend_cpu = nullptr; std::vector backends; - // [TAG_STATE_ASYNC] one event per device that copies asynchronously, recorded on the compute stream at the end of every decode; see state_seq_copy_fence() + // [TAG_STATE_ASYNC] one event per device that copies asynchronously, recorded on the compute stream as a transfer is issued; see state_seq_copy_fence() std::map state_copy_fences; // Live transfers; the fences go with the last one, and freeing the context drains live transfers first. diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index c8bf6a7bac4a..6e65d4082562 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2038,7 +2038,7 @@ struct server_context_impl { } }; - // [TAG_PREEMPT_ASYNC] One transfer per context: each owns a backend and installs the fences the context records after every decode. + // [TAG_PREEMPT_ASYNC] One transfer per context: each owns a backend and installs the fences the context records as a transfer is issued. if (preempt_async_possible()) { slot.preempt_cpy_tgt = llama_state_seq_copy_make(ctx_tgt); @@ -4673,13 +4673,22 @@ struct server_context_impl { return (int64_t) std::min((double) n_left * (double) (ggml_time_us() - t_from) / n_gen, (double) INT64_MAX / 2); } - bool preempt_any_out() const { + // [TAG_PREEMPT] Set by every park and cleared by the first scan that finds nobody out, so an idle or disabled server skips the slot scans. + bool preempt_maybe_out = false; + + bool preempt_any_out() { + if (!preempt_maybe_out) { + return false; + } + for (const auto & slot : slots) { if (slot.preempt_is_out()) { return true; } } + preempt_maybe_out = false; + return false; } @@ -4687,6 +4696,8 @@ struct server_context_impl { bool preempt_park(server_slot & slot, int64_t t_start, bool recompute = false) { slot.t_preempt_copy_us = t_start; + preempt_maybe_out = true; + // [TAG_PREEMPT_ASYNC] Reserve ahead only if the budget still fits another state that size: the slack is charged and must not block the next park. if (!recompute && slot.preempt_is_async()) { const size_t held = slot.preempt_state_size(); @@ -4860,11 +4871,15 @@ struct server_context_impl { return; // no cache (embedding model): nothing to park } - if (params_base.preempt_ram_mib == 0 && !preempt_any_out()) { + const bool any_out = preempt_any_out(); + + if (params_base.preempt_ram_mib == 0 && !any_out) { return; } - update_preempt_copies(); + if (any_out) { + update_preempt_copies(); + } if (params_base.preempt_ram_mib == 0 || preempt_recurrent) { return; // --preempt-ram 0 or a recurrent cache: retry ladder only @@ -4874,7 +4889,8 @@ struct server_context_impl { const bool head_of_line = preempt_resume_head; - for (;;) { + // nobody parked: nothing to resume + while (any_out) { preempt_update_reservation(); std::vector parked; From abf60fd32306554c46e0285a1e65f83927edf2d1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 14 Oct 2026 22:54:37 -0700 Subject: [PATCH 058/109] server: do not park on a cache whose sequences do not share cells DeepSeek V4 keeps its raw and compressed streams per sequence even under --kv-unified, but the planner summed every slot's cells as one pool, so two prompts that each fit their own cache had one parked for nothing. Add llama_memory_shares_cells(): true when the cache has one stream, false for a stream per sequence, recurrent states and the DeepSeek V4 cache; the iswa, DSA, MSA and hybrid caches answer for their attention cache, and a module that does not say inherits true. Planning, the last-resort park and /props preempt.enabled stay off when it is false. --- include/llama.h | 4 +++ src/llama-context.cpp | 8 +++++ src/llama-kv-cache-dsa-iswa.h | 2 ++ src/llama-kv-cache-dsa.h | 2 ++ src/llama-kv-cache-dsv4.h | 2 ++ src/llama-kv-cache-iswa.h | 2 ++ src/llama-kv-cache-msa.h | 2 ++ src/llama-kv-cache.h | 2 ++ src/llama-memory-hybrid-iswa.h | 2 ++ src/llama-memory-hybrid.cpp | 4 +++ src/llama-memory-hybrid.h | 2 ++ src/llama-memory-recurrent.h | 2 ++ src/llama-memory.h | 3 ++ tools/server/server-context.cpp | 17 +++++++--- tools/server/tests/unit/test_preempt.py | 45 +++++++++++++++++++++++++ 15 files changed, 95 insertions(+), 4 deletions(-) diff --git a/include/llama.h b/include/llama.h index d2576b5dd935..019ef1c86df3 100644 --- a/include/llama.h +++ b/include/llama.h @@ -824,6 +824,10 @@ extern "C" { // n contiguous tokens then occupy round_up(n, granularity) cells; a sequence left with holes still holds every block one live cell is in LLAMA_API uint32_t llama_memory_alloc_granularity(llama_memory_t mem); + // [TAG_PREEMPT] true when the sequences draw on one pool of cells, so one sequence's growth takes room from the others + // false for a recurrent state, a cache with a stream per sequence, or one that keeps its own streams per sequence whatever the unified flag says + LLAMA_API bool llama_memory_shares_cells(llama_memory_t mem); + // [TAG_PREEMPT] run the in-place update a seq_add() recorded, which llama_decode() would otherwise run at the start of the next batch // takes the context because the update is a graph; returns true when one was run LLAMA_API bool llama_memory_update(struct llama_context * ctx); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index e2858e3c7cae..0eb283e6cd61 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -5259,6 +5259,14 @@ uint32_t llama_memory_alloc_granularity(llama_memory_t mem) { return mem->alloc_granularity(); } +bool llama_memory_shares_cells(llama_memory_t mem) { + if (!mem) { + return false; + } + + return mem->shares_cells(); +} + bool llama_memory_update(llama_context * ctx) { if (!ctx) { return false; diff --git a/src/llama-kv-cache-dsa-iswa.h b/src/llama-kv-cache-dsa-iswa.h index 28cf95bf0518..c0a3215bc6f9 100644 --- a/src/llama-kv-cache-dsa-iswa.h +++ b/src/llama-kv-cache-dsa-iswa.h @@ -45,6 +45,8 @@ class llama_kv_cache_dsa_iswa : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return kv_dsa->shares_cells(); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache-dsa.h b/src/llama-kv-cache-dsa.h index e74fc4d9100f..ae46efc78943 100644 --- a/src/llama-kv-cache-dsa.h +++ b/src/llama-kv-cache-dsa.h @@ -47,6 +47,8 @@ class llama_kv_cache_dsa : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return kv_mla->shares_cells(); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache-dsv4.h b/src/llama-kv-cache-dsv4.h index ce39867c0342..ee3abe4aae54 100644 --- a/src/llama-kv-cache-dsv4.h +++ b/src/llama-kv-cache-dsv4.h @@ -120,6 +120,8 @@ class llama_kv_cache_dsv4 : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return false; } // a raw and compressed stream per sequence, even when unified + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache-iswa.h b/src/llama-kv-cache-iswa.h index 7dab6eaa82c8..980f6526511d 100644 --- a/src/llama-kv-cache-iswa.h +++ b/src/llama-kv-cache-iswa.h @@ -65,6 +65,8 @@ class llama_kv_cache_iswa : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return kv_base->shares_cells(); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache-msa.h b/src/llama-kv-cache-msa.h index f09b6d32b044..9478a8fc0293 100644 --- a/src/llama-kv-cache-msa.h +++ b/src/llama-kv-cache-msa.h @@ -44,6 +44,8 @@ class llama_kv_cache_msa : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return kv_base->shares_cells(); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index c5fe9e675add..f56e72f459a4 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -133,6 +133,8 @@ class llama_kv_cache : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return get_n_stream() == 1; } // one stream: every sequence draws on the same cells + // [TAG_EXACT_CONCURRENCY] the page size under exact mode, 1 otherwise uint32_t alloc_granularity() const override; diff --git a/src/llama-memory-hybrid-iswa.h b/src/llama-memory-hybrid-iswa.h index c9d3f9f57c50..69161eb10ad1 100644 --- a/src/llama-memory-hybrid-iswa.h +++ b/src/llama-memory-hybrid-iswa.h @@ -58,6 +58,8 @@ class llama_memory_hybrid_iswa : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return mem_attn->shares_cells(); } // the recurrent half holds one state per sequence + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index dc5c872b3bd4..66137605099b 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -150,6 +150,10 @@ uint32_t llama_memory_hybrid::alloc_granularity() const { return mem_attn->alloc_granularity(); } +bool llama_memory_hybrid::shares_cells() const { + return mem_attn->shares_cells(); +} + void llama_memory_hybrid::clear(bool data) { mem_attn->clear(data); mem_recr->clear(data); diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 70ba19ca3239..b514abb50a0e 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -60,6 +60,8 @@ class llama_memory_hybrid : public llama_memory_i { uint32_t alloc_granularity() const override; + bool shares_cells() const override; + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 08489a4bee4c..c9329396457a 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -61,6 +61,8 @@ class llama_memory_recurrent : public llama_memory_i { bool get_can_shift() const override; + bool shares_cells() const override { return false; } // one state per sequence + // state write/load void state_write(llama_io_write_i & io, llama_seq_id seq_id = -1, llama_state_seq_flags flags = 0) const override; diff --git a/src/llama-memory.h b/src/llama-memory.h index 4df3ca9e452d..1b090054e3fd 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -104,6 +104,9 @@ struct llama_memory_i { // [TAG_EXACT_CONCURRENCY] Allocation granularity: n tokens occupy round_up(n, granularity) cells. Not pure virtual, so old modules inherit 1. virtual uint32_t alloc_granularity() const { return 1; } + // [TAG_PREEMPT] True when the sequences draw on one pool of cells, so one sequence's growth takes room from the others. Not pure virtual, so old modules inherit true. + virtual bool shares_cells() const { return true; } + // // ops // diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 6e65d4082562..413c98bd37d0 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2186,6 +2186,13 @@ struct server_context_impl { if (preempt_recurrent && params_base.preempt_ram_mib != 0) { SRV_WRN("%s", "preemption: off, the recurrent cache holds one state per sequence whatever its length, so there is no cell pool to run out of\n"); } + + // [TAG_PREEMPT] A cache with its own cells per sequence (DeepSeek V4, even when unified): parking one frees nothing another sequence could use. + preempt_unshared = !preempt_recurrent && llama_get_memory(ctx_tgt) && !llama_memory_shares_cells(llama_get_memory(ctx_tgt)); + + if (preempt_unshared && params_base.kv_unified && params_base.preempt_ram_mib != 0) { + SRV_WRN("%s", "preemption: off, this cache keeps its own cells per sequence even when unified, so parking one frees no room for another\n"); + } } { @@ -3929,6 +3936,8 @@ struct server_context_impl { bool preempt_recurrent = false; + bool preempt_unshared = false; // the sequences do not draw on one pool of cells + bool preempt_batch_abandoned = false; // [TAG_PREEMPT_ASYNC] A context shift is pending; it is applied in place inside the next llama_decode. @@ -4881,8 +4890,8 @@ struct server_context_impl { update_preempt_copies(); } - if (params_base.preempt_ram_mib == 0 || preempt_recurrent) { - return; // --preempt-ram 0 or a recurrent cache: retry ladder only + if (params_base.preempt_ram_mib == 0 || preempt_recurrent || preempt_unshared) { + return; // --preempt-ram 0, or no shared pool of cells: retry ladder only } const int32_t n_cells = n_ctx; @@ -6366,7 +6375,7 @@ struct server_context_impl { json preempt_props() const { return json { { "enabled", params_base.kv_unified && slots.size() >= 2 && params_base.preempt_ram_mib != 0 && - !preempt_recurrent && ctx_tgt && llama_get_memory(ctx_tgt) }, + !preempt_recurrent && !preempt_unshared && ctx_tgt && llama_get_memory(ctx_tgt) }, { "ram_mib", params_base.preempt_ram_mib }, { "async", preempt_async_ok }, { "notices", 2 }, @@ -6377,7 +6386,7 @@ struct server_context_impl { } bool preempt_last_resort_possible() const { - return params_base.kv_unified && params_base.preempt_ram_mib != 0 && !preempt_recurrent && slots.size() >= 2 && llama_get_memory(ctx_tgt); + return params_base.kv_unified && params_base.preempt_ram_mib != 0 && !preempt_recurrent && !preempt_unshared && slots.size() >= 2 && llama_get_memory(ctx_tgt); } // [TAG_PREEMPT] Retry ladder exhausted: give up the batch, rewind residents to the cache's token boundary and park the smallest. A media chunk mid-prompt keeps the old path. diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index ec6931e6595c..4d91810d3c13 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -679,6 +679,51 @@ def test_a_hybrid_model_parks_synchronously(): _assert_recovered(text, "preempted on request") +def _generated_model(arch: str, name: str) -> str: + """A model made by test-llama-archs beside the server binary; LLAMA_SERVER_TEST_GENERATED_MODELS names a directory that already holds it.""" + have = os.environ.get("LLAMA_SERVER_TEST_GENERATED_MODELS") + if have: + return os.path.join(have, f"{name}.gguf") + gen = os.path.join(os.path.dirname(os.environ.get("LLAMA_SERVER_BIN_PATH", "../../../build/bin/llama-server")), + "test-llama-archs.exe" if os.name == "nt" else "test-llama-archs") + if not os.path.exists(gen): + pytest.skip("build test-llama-archs, or set LLAMA_SERVER_TEST_GENERATED_MODELS to a directory of its models") # ty: ignore[too-many-positional-arguments] + out = tempfile.mkdtemp() + subprocess.run([gen, "-a", f"^{arch}$", "-s", "2981215097", "-o", out], check=True, capture_output=True, timeout=300) + fd, path = tempfile.mkstemp(suffix=".gguf") + os.close(fd) + _scratch.append(path) + os.replace(os.path.join(out, f"{name}.gguf"), path) + for f in os.listdir(out): + os.remove(os.path.join(out, f)) + os.rmdir(out) + return path + + +@pytest.mark.parametrize("arch,name,shared", [("deepseek4", "deepseek4-moe", False), ("llama", "llama-dense", True)]) +def test_only_a_cache_whose_sequences_share_cells_is_parked(arch, name, shared): + # DeepSeek V4 keeps a cache per sequence even under --kv-unified: two prompts that overflow n_ctx together each fit their own, and a park freed nothing the other could use. + # The llama control shares one pool, so the same pair overflows it and one is parked. + server.model_file = _generated_model(arch, name) + server.model_hf_repo = server.model_hf_file = None + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + _start(n_ctx=256, n_batch=128, n_ubatch=64, fa="on", n_gpu_layer=0) + assert server.make_request("GET", "/props").body["preempt"]["enabled"] is shared + + results = parallel_function_calls([(_raw_completion, (80, [1] * 140)) for _ in range(2)]) + _assert_completed(results, 80) + parks = [(res.body.get("preempt") or {}).get("parks", 0) for res in results] + + text = _log() + assert "Context size has been exceeded" not in text + if shared: + assert sum(parks) >= 1, parks + _assert_recovered(text) + else: + assert parks == [0, 0], parks + _assert_nothing_parked(text) + + # [TAG_EXACT_CONCURRENCY] The paged pool places a cell by sequence and position, so layouts with shared positions cannot be served. def _mrope_model() -> str: From ce0965c6da6c496ab387a482da14fa0454b15a71 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 00:01:37 -0700 Subject: [PATCH 059/109] server tests: warm up before timing a recompute restore On a GPU the first large prefill pays one-time backend setup and costs more than the warm re-prefills plus decodes, so comparing generation time with prompt time failed there. Warm up on other text first. --- tools/server/tests/unit/test_preempt.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 4d91810d3c13..3cf59408eaae 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1030,12 +1030,15 @@ def test_a_recompute_restore_does_not_count_its_replay_as_prompt(): n_prompt = 1950 n_predict = 24 + # A first prefill this size pays one-time backend setup, which on a GPU outweighs the warm re-prefills: warm up on other text first. + assert _complete(n_predict, _prompt_of(n_prompt, _PROMPT_A)).status_code == 200 res = _complete(n_predict, _prompt_of(n_prompt, _PROMPT_C)) assert res.status_code == 200, res.body assert res.body["preempt"]["recomputes"] >= 1, res.body["preempt"] timings = res.body["timings"] + assert timings["cache_n"] == 0, timings assert timings["prompt_n"] == n_prompt, timings assert timings["predicted_n"] == n_predict, timings # Every re-prefill happens during generation, so the generation time is the longer. From bc04bd433cc905ac44307c1441e676b78f9c9644 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 01:57:00 -0700 Subject: [PATCH 060/109] server: follow a slot that falls back to synchronous parks in the margin and /props A park buffer can come back pageable after the load-time probe pinned 1 MiB, and that slot then parks synchronously. The context kept reporting async and charging the async margin regardless. Recompute both from the slots: the async margin while any slot still parks asynchronously, /props async only while every slot does. LLAMA_SERVER_PREEMPT_PAGEABLE=N forces the Nth async park's buffer pageable for the test. --- tools/server/server-context.cpp | 38 +++++++++++++++++++++++-- tools/server/tests/unit/test_preempt.py | 18 +++++++++++- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 413c98bd37d0..c7d3c78e4eea 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -175,6 +175,17 @@ static bool preempt_fail_save() { return n_left > 0 && --n_left == 0; } +// [TAG_PREEMPT_ASYNC] Test knob: LLAMA_SERVER_PREEMPT_PAGEABLE=N treats the Nth async park's buffer as pageable, as a large allocation can be. +static bool preempt_force_pageable() { + static int32_t n_left = []() { + const char * val = getenv("LLAMA_SERVER_PREEMPT_PAGEABLE"); + + return val ? std::max(0, atoi(val)) : 0; + }(); + + return n_left > 0 && --n_left == 0; +} + using llama_state_seq_copy_ptr = std::shared_ptr; static llama_state_seq_copy_ptr llama_state_seq_copy_make(llama_context * ctx) { @@ -749,7 +760,8 @@ struct server_slot { // [TAG_PREEMPT_ASYNC] A large buffer can still come back pageable, and copies into pageable memory block, so this slot parks synchronously from now on. const bool pageable = !llama_state_seq_copy_buf_is_pinned(preempt_cpy_tgt.get()) || - (size_dft > 0 && !llama_state_seq_copy_buf_is_pinned(preempt_cpy_dft.get())); + (size_dft > 0 && !llama_state_seq_copy_buf_is_pinned(preempt_cpy_dft.get())) || + preempt_force_pageable(); if (pageable) { SLT_WRN(*this, "the host memory for a %.3f MiB park is pageable, so this slot parks synchronously from now on\n", @@ -2114,6 +2126,8 @@ struct server_context_impl { slot.preempt_cpy_dft.reset(); } } + + preempt_async_all = preempt_async_ok; } { @@ -3915,7 +3929,18 @@ struct server_context_impl { // [TAG_PREEMPT] --preempt-policy fcfs: park the newest arrival, resume and reserve in arrival order. bool preempt_fcfs = false; - bool preempt_async_ok = false; + bool preempt_async_ok = false; // some slot still parks asynchronously: keep the async margin + bool preempt_async_all = false; // every slot does, as /props reports + + void preempt_async_refresh() { + preempt_async_ok = false; + preempt_async_all = !slots.empty(); + + for (const auto & slot : slots) { + preempt_async_ok = preempt_async_ok || slot.preempt_is_async(); + preempt_async_all = preempt_async_all && slot.preempt_is_async(); + } + } // [TAG_EXACT_CONCURRENCY] Pool allocation granularity: 1, or the page size under exact concurrency; LLAMA_SERVER_PREEMPT_GRANULARITY overrides. int32_t preempt_alloc_granularity = 1; @@ -4715,6 +4740,8 @@ struct server_context_impl { slot.preempt_grow = preempt_ram_used() - held + 2 * grown <= preempt_ram_budget(); } + const bool was_async = slot.preempt_is_async(); + // [TAG_PREEMPT] Budget checks do not guarantee the allocation; preempt_save() unwinds on failure, so fall back to a recompute park. if (!recompute && !slot.preempt_save()) { SLT_WRN(slot, "%s", "the park could not take the host memory the budget allowed, so it drops its cells instead and the resume re-prefills its tokens\n"); @@ -4722,6 +4749,11 @@ struct server_context_impl { recompute = true; } + // [TAG_PREEMPT_ASYNC] A slot whose buffer came back pageable parks synchronously from now on: the margin and /props follow the slots left. + if (was_async && !slot.preempt_is_async()) { + preempt_async_refresh(); + } + if (recompute) { if (!slot.preempt_save_recompute()) { return false; @@ -6377,7 +6409,7 @@ struct server_context_impl { { "enabled", params_base.kv_unified && slots.size() >= 2 && params_base.preempt_ram_mib != 0 && !preempt_recurrent && !preempt_unshared && ctx_tgt && llama_get_memory(ctx_tgt) }, { "ram_mib", params_base.preempt_ram_mib }, - { "async", preempt_async_ok }, + { "async", preempt_async_all }, { "notices", 2 }, { "recurrent", preempt_recurrent }, { "granularity", preempt_alloc_granularity }, diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 3cf59408eaae..87b1bf6ab5c5 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -51,7 +51,7 @@ def create_server(): os.remove(_scratch.pop()) for name in ("LLAMA_SERVER_PREEMPT_EVERY", "LLAMA_SERVER_PREEMPT_GRANULARITY", "LLAMA_SERVER_PREEMPT_PLANNER", "LLAMA_ARG_PREEMPT_RAM", "LLAMA_ARG_PREEMPT_ASYNC", - "LLAMA_SERVER_PREEMPT_FAIL_SAVE", "LLAMA_ARG_SPEC_DRAFT_P_MIN", "LLAMA_ARG_LOG_VERBOSITY", + "LLAMA_SERVER_PREEMPT_FAIL_SAVE", "LLAMA_SERVER_PREEMPT_PAGEABLE", "LLAMA_ARG_SPEC_DRAFT_P_MIN", "LLAMA_ARG_LOG_VERBOSITY", "LLAMA_BATCH_DEBUG", "LLAMA_ARG_CTX_CHECKPOINTS", "LLAMA_MEDIA_MARKER", "LLAMA_EXACT_CONCURRENCY", "LLAMA_ARG_PREEMPT_POLICY"): os.environ.pop(name, None) @@ -1413,6 +1413,22 @@ def test_a_growing_sequence_keeps_its_pinned_buffer_across_parks(): assert 1 <= len(sizes) <= 4, f"{len(sizes)} pinned allocations for {parks} parks" +def test_a_slot_whose_park_buffer_comes_back_pageable_is_no_longer_reported_async(): + # The load-time probe pins 1 MiB, but a larger buffer can still be pageable: that slot parks synchronously, and /props must say so. + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + os.environ["LLAMA_SERVER_PREEMPT_PAGEABLE"] = "1" + _start_async(n_ctx=512) + assert server.make_request("GET", "/props").body["preempt"]["async"] is True + + res = _complete(32) + assert res.status_code == 200, res.body + assert res.body["timings"]["predicted_n"] == 32 + assert res.body["preempt"]["parks"] > 0, res.body["preempt"] + + assert "is pageable, so this slot parks synchronously from now on" in _log() + assert server.make_request("GET", "/props").body["preempt"]["async"] is False + + def test_a_multi_prompt_oai_completion_counts_the_parks_of_every_prompt(): # An array prompt is one task per prompt, each parked separately; the OAI response merges them, so its counters are the sum. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" From d1766ccb53d00a6313b3658a75b9f013919265e8 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 03:36:09 -0700 Subject: [PATCH 061/109] server: report the live async state in /props /props is served from metadata copied at load, so a slot that fell back to synchronous parks still showed preempt.async true there. Keep the state in an atomic the HTTP thread reads. --- tools/server/server-context.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 053f79e056f9..bf44a4a4656a 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1521,6 +1521,9 @@ struct server_context_impl { server_queue queue_tasks; server_response queue_results; + // [TAG_PREEMPT_ASYNC] Whether every slot still parks asynchronously, for the HTTP thread: /props is served from metadata copied at load. + std::atomic preempt_async_live { false }; + // note: chat_params must not be refreshed upon existing sleeping state server_chat_params chat_params; @@ -2128,7 +2131,8 @@ struct server_context_impl { } } - preempt_async_all = preempt_async_ok; + preempt_async_all = preempt_async_ok; + preempt_async_live = preempt_async_all; } { @@ -3940,6 +3944,7 @@ struct server_context_impl { bool preempt_async_ok = false; // some slot still parks asynchronously: keep the async margin bool preempt_async_all = false; // every slot does, as /props reports + void preempt_async_refresh() { preempt_async_ok = false; preempt_async_all = !slots.empty(); @@ -3948,6 +3953,8 @@ struct server_context_impl { preempt_async_ok = preempt_async_ok || slot.preempt_is_async(); preempt_async_all = preempt_async_all && slot.preempt_is_async(); } + + preempt_async_live = preempt_async_all; } // [TAG_EXACT_CONCURRENCY] Pool allocation granularity: 1, or the page size under exact concurrency; LLAMA_SERVER_PREEMPT_GRANULARITY overrides. @@ -7874,7 +7881,12 @@ void server_routes::init_routes() { std::unique_lock lock(mutex_cache); res->ok(cached_props); } else { - res->ok(get_res_props(*meta, params, false)); + json props = get_res_props(*meta, params, false); + // [TAG_PREEMPT_ASYNC] A slot can fall back to synchronous parks after load, which the copied metadata does not see. + if (props["preempt"].contains("async")) { + props["preempt"]["async"] = ctx_server.preempt_async_live.load(); + } + res->ok(props); } return res; }; From 3c7e71f14749189a0f9cfd8630c0fb7851b52ac3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 04:58:26 -0700 Subject: [PATCH 062/109] Trim comments in the preemption and exact concurrency tests --- tests/llama-context/cases-kv.cpp | 1 - tests/test-backend-ops.cpp | 3 - tests/test-event-query.cpp | 2 - tests/test-exact-buft.cpp | 8 +- tests/test-exact-geometry.cpp | 10 -- tests/test-exact-pages.cpp | 18 ---- tests/test-exact-weights.cpp | 3 - tests/test-rpc-paged-fa.cpp | 7 -- tests/test-server-decision-exact.cpp | 4 +- tests/test-server-tokens.cpp | 47 ++++----- tests/test-state-seq-copy.cpp | 5 - tools/server/tests/unit/test_preempt.py | 95 ++----------------- .../server/tests/unit/test_preempt_models.py | 5 +- .../server/tests/unit/test_preempt_notify.py | 11 --- 14 files changed, 28 insertions(+), 191 deletions(-) diff --git a/tests/llama-context/cases-kv.cpp b/tests/llama-context/cases-kv.cpp index 83e4d99df48e..bfce9e23f977 100644 --- a/tests/llama-context/cases-kv.cpp +++ b/tests/llama-context/cases-kv.cpp @@ -628,7 +628,6 @@ struct case_state_restore_fragmented : ctx_test { return case_result::fail(); } - // a fragmented restore may stage a whole device tensor, so the neighbours are checked byte for byte too std::vector neighbours_before[2]; if (!get_seq_state(ctx.get(), 0, LLAMA_STATE_SEQ_FLAGS_NONE, neighbours_before[0]) || !get_seq_state(ctx.get(), 2, LLAMA_STATE_SEQ_FLAGS_NONE, neighbours_before[1])) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 967baa1347f8..390de83dcfac 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -8517,7 +8517,6 @@ struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { } }; -// same attention as the CPU mask reference, but visiting nonadjacent pages in a different order struct test_flash_attn_ext_pages : public test_flash_attn_ext { test_flash_attn_ext_pages(int64_t batch, int64_t hs = 256, ggml_type type_KV = GGML_TYPE_F16, float logit_softcap = 0.0f) : test_flash_attn_ext(hs, hs, 2, {8, 1}, 1024, batch, true, false, 0.0f, logit_softcap, GGML_PREC_F32, type_KV, type_KV) {} @@ -10753,7 +10752,6 @@ static std::vector> make_test_cases_eval() { } } - // MoE projections at the token counts a decode ubatch forms; 17 tokens is past the width exact concurrency pins for (ggml_type type_a : {GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_Q8_0, GGML_TYPE_F16}) { for (int n : {1, 2, 4, 8, 17}) { test_cases.emplace_back(new test_mul_mat_id(type_a, GGML_TYPE_F32, 16, 8, true, 512, n, 2048)); @@ -11749,7 +11747,6 @@ static std::vector> make_test_cases_eval() { for (int64_t batch : {1, 4, 12}) { test_cases.emplace_back(new test_flash_attn_ext_pages(batch)); } - // shapes the paged kernel does not cover: a backend must refuse them, not abort test_cases.emplace_back(new test_flash_attn_ext_pages(4, 64)); test_cases.emplace_back(new test_flash_attn_ext_pages(4, 256, GGML_TYPE_BF16)); test_cases.emplace_back(new test_flash_attn_ext_pages(4, 256, GGML_TYPE_F16, 30.0f)); diff --git a/tests/test-event-query.cpp b/tests/test-event-query.cpp index 33da176f10d6..56d5cf5793b9 100644 --- a/tests/test-event-query.cpp +++ b/tests/test-event-query.cpp @@ -1,5 +1,4 @@ // [TAG_EXACT_CONCURRENCY] the non-blocking event query is found through the registry; CUDA must report it, else every async park poll blocks. -// On every device that reports it, a recorded event that was waited for reads as complete. #include "ggml-backend.h" @@ -23,7 +22,6 @@ int main() { printf("%s (%s): events %s, event query %s\n", ggml_backend_dev_name(dev), reg_name, props.caps.events ? "yes" : "no", supported ? "yes" : "no"); - // a build without events (GGML_CUDA_NO_PEER_COPY) parks synchronously, so there is nothing to query if (!props.caps.events) { continue; } diff --git a/tests/test-exact-buft.cpp b/tests/test-exact-buft.cpp index bead5f365f59..02d714ef0eb5 100644 --- a/tests/test-exact-buft.cpp +++ b/tests/test-exact-buft.cpp @@ -1,5 +1,4 @@ -// [TAG_EXACT_CONCURRENCY] which buffer types the mode accepts a weight in, as used by the context weight check and the lora refusal. -// A host buffer is refused: its ops move to the GPU only once the batch is wide enough, so results depend on the step width. +// [TAG_EXACT_CONCURRENCY] A host buffer is refused: its ops move to the GPU only once the batch is wide enough, so results depend on the step width. #include "ggml-backend.h" @@ -13,10 +12,8 @@ int main() { ggml_backend_load_all(); - // nothing placed anywhere is nothing to trust assert(!llama_exact_buft_invariant(nullptr)); - // the plain CPU buffer, and the pinned host buffer a GPU backend offers, are both host memory assert(!llama_exact_buft_invariant(ggml_backend_cpu_buffer_type())); bool checked_gpu = false; @@ -24,7 +21,6 @@ int main() { for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { ggml_backend_dev_t dev = ggml_backend_dev_get(i); - // an integrated GPU (Jetson, GB10, Strix Halo) is a CUDA/ROCm device too if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU && ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_IGPU) { continue; } @@ -33,7 +29,6 @@ int main() { const bool invariant = reg && llama_exact_backend_name(ggml_backend_reg_name(reg)); - // a device's own buffer follows its backend, and its host buffer never does assert(llama_exact_buft_invariant(ggml_backend_dev_buffer_type(dev)) == invariant); if (auto * host = ggml_backend_dev_host_buffer_type(dev)) { @@ -43,7 +38,6 @@ int main() { checked_gpu = checked_gpu || invariant; } - // the registry names the mode trusts, whatever this build has assert(llama_exact_backend_name("CUDA")); assert(llama_exact_backend_name("ROCm")); assert(llama_exact_backend_name("MUSA")); diff --git a/tests/test-exact-geometry.cpp b/tests/test-exact-geometry.cpp index 57b332765e10..4c1d1ff7001a 100644 --- a/tests/test-exact-geometry.cpp +++ b/tests/test-exact-geometry.cpp @@ -1,4 +1,3 @@ -// [TAG_EXACT_CONCURRENCY] the batch must hold one whole ubatch beside a decode step of every slot, so a prefill gets the ubatches it would get alone. #include "common.h" @@ -10,42 +9,33 @@ int main() { int n_min = 0; - // the reported minimum is the ubatch plus the decode step, whether or not the batch reaches it assert(common_exact_batch_geometry(2048, 512, 4, &n_min)); assert(n_min == 516); - // the case that used to warn and carry on: one decoder beside the prompt leaves it 511 tokens assert(!common_exact_batch_geometry(512, 512, 1, &n_min)); assert(n_min == 513); assert(!common_exact_batch_geometry(512, 512, 2, &n_min)); assert(n_min == 514); - // exactly enough, and one short of it assert(common_exact_batch_geometry(514, 512, 2, &n_min) && n_min == 514); assert(!common_exact_batch_geometry(513, 512, 2, &n_min) && n_min == 514); - // a single slot with no draft still needs room for its own decoded token assert(!common_exact_batch_geometry(512, 512, 1)); assert(common_exact_batch_geometry(1024, 512, 1)); - // an unset ubatch is the whole batch, which then cannot hold a decode step as well assert(!common_exact_batch_geometry(2048, 0, 4, &n_min)); assert(n_min == 2052); - // a ubatch larger than the batch is clamped to it, so it cannot pass either assert(!common_exact_batch_geometry(512, 4096, 1, &n_min)); assert(n_min == 513); - // n_batch = min(n_ctx, -b) and n_ubatch = min(n_batch, -ub), so a 256-cell context leaves no column for a decode step. assert(!common_exact_batch_geometry(256, 256, 2, &n_min)); assert(n_min == 258); - // no slot decoding at all: the prompt has the batch to itself assert(common_exact_batch_geometry(512, 512, 0, &n_min)); assert(n_min == 512); - // a width the backends cannot take as an int is refused, and does not pin the maximum above every later width const uint32_t width = llama_exact_decode_width(); assert(!llama_set_exact_decode_width((uint32_t) INT32_MAX + 1)); assert(llama_exact_decode_width() == width); diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index c65bebc8b5de..69cd322a1cdf 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -1,5 +1,4 @@ // [TAG_EXACT_CONCURRENCY] tests the paged KV pool removal and restore paths, with LLAMA_KV_CACHE_DEBUG=1 cross-checking page ownership every ubatch. -// Needs a CUDA build with 256-wide heads and a fully offloaded F16 cache; without one the test reports what it skipped and passes. #include "arg.h" #include "common.h" @@ -21,7 +20,6 @@ static bool decode_range(llama_context * ctx, llama_seq_id seq, llama_pos first, batch.clear(); for (int i = 0; i < 64 && p <= last; ++i, ++p) { - // every decode asks for one set of logits, so none of them is a batch with no output batch.add(1, p, seq, i == 63 || p == last); } @@ -31,7 +29,6 @@ static bool decode_range(llama_context * ctx, llama_seq_id seq, llama_pos first, return ok; } -// Windows has no setenv static void set_env_default(const char * name, const char * value) { if (getenv(name)) { return; @@ -44,7 +41,6 @@ static void set_env_default(const char * name, const char * value) { } int main(int argc, char ** argv) { - // read before the model is loaded: both are latched on first use set_env_default("LLAMA_EXACT_CONCURRENCY", "1"); set_env_default("LLAMA_KV_CACHE_DEBUG", "1"); @@ -62,7 +58,6 @@ int main(int argc, char ** argv) { return 1; } - // after the parser, which requires the default here params.n_gpu_layers = 999; ggml_backend_load_all(); @@ -84,13 +79,11 @@ int main(int argc, char ** argv) { return 1; } - // positions 0..599 of sequence 0: three pages, the last one part full if (!decode_range(ctx, 0, 0, 599)) { fprintf(stderr, "%s : failed to fill sequence 0\n", __func__); return 1; } - // a page belongs to one sequence, so a cross-sequence copy is refused whole and both sequences stay as they were. llama_memory_seq_cp(mem, 0, 1, -1, -1); if (llama_memory_seq_pos_max(mem, 1) != -1 || llama_memory_seq_pos_max(mem, 0) != 599) { @@ -99,7 +92,6 @@ int main(int argc, char ** argv) { return 1; } - // removing a rejected speculative tail that is not there must leave the pool and its ownership alone. if (!llama_memory_seq_rm(mem, 0, 600, -1) || llama_memory_seq_pos_max(mem, 0) != 599) { fprintf(stderr, "%s : a removal past the tail changed the sequence, its end is %d\n", __func__, llama_memory_seq_pos_max(mem, 0)); @@ -111,8 +103,6 @@ int main(int argc, char ** argv) { return 1; } - // holes: positions 1 to 510 go and 0, 511 to 655 stay, so the first two pages each keep a live cell and stay reserved. - // A hybrid memory refuses to remove the middle of a sequence, so there is nothing to check then. const bool holes = llama_memory_seq_rm(mem, 0, 1, 511); if (holes && llama_memory_seq_pos_max(mem, 0) != 655) { @@ -123,19 +113,16 @@ int main(int argc, char ** argv) { printf("%s : interior removal %s\n", __func__, holes ? "left holes" : "was refused, skipping the hole case"); - // sequence 1 fills the 5 pages left of 8, since sequence 0 holds 3 including holes and a partial tail page. if (!decode_range(ctx, 1, 0, 5*PAGE - 1)) { fprintf(stderr, "%s : failed to fill the pages sequence 0 does not hold\n", __func__); return 1; } - // one page more than is left must be refused, not taken from a page that still has a live cell. if (decode_range(ctx, 1, 5*PAGE, 5*PAGE)) { fprintf(stderr, "%s : the pool allocated a page that sequence 0 still holds\n", __func__); return 1; } - // a whole sequence goes back to the pool as whole pages, holes included if (!llama_memory_seq_rm(mem, 0, -1, -1) || llama_memory_seq_pos_max(mem, 0) != -1) { fprintf(stderr, "%s : sequence 0 is still in the pool after a full removal\n", __func__); return 1; @@ -146,14 +133,11 @@ int main(int argc, char ** argv) { return 1; } - // the pool is full again if (decode_range(ctx, 1, 8*PAGE, 8*PAGE)) { fprintf(stderr, "%s : the pool allocated a ninth page\n", __func__); return 1; } - // a restored cell with a negative position has no page, so the restore fails while the unpatched state still restores. - // Layout after the magic and sequence id: n_stream, cell_count, then the first cell's position. { std::vector state(llama_state_seq_get_size(ctx, 1)); state.resize(llama_state_seq_get_data(ctx, state.data(), state.size(), 1)); @@ -189,7 +173,6 @@ int main(int argc, char ** argv) { return 1; } - // a whole-context state cannot be restored in this mode, so size, copy and session save all fail and leave no file. std::vector whole(state.size() + 4096); if (llama_state_get_size(ctx) != 0 || llama_state_get_data(ctx, whole.data(), whole.size()) != 0) { @@ -211,7 +194,6 @@ int main(int argc, char ** argv) { return 1; } - // the restore stays refused through the same error return if (llama_state_set_data(ctx, state.data(), state.size()) != 0) { fprintf(stderr, "%s : a whole-context state was restored\n", __func__); return 1; diff --git a/tests/test-exact-weights.cpp b/tests/test-exact-weights.cpp index 0244424226b2..ee7aa9ec972c 100644 --- a/tests/test-exact-weights.cpp +++ b/tests/test-exact-weights.cpp @@ -1,5 +1,4 @@ // [TAG_EXACT_CONCURRENCY] The context refuses a non-layer weight (output_norm) kept on host by an override, and accepts the same model fully offloaded. -// Needs a batch-invariant GPU backend; without one the test reports what it skipped and passes. #include "llama.h" #include "ggml-backend.h" @@ -8,7 +7,6 @@ #include #include -// Windows has no setenv static void set_env_default(const char * name, const char * value) { if (getenv(name)) { return; @@ -47,7 +45,6 @@ static bool context_ok(const char * path, const llama_model_tensor_buft_override } int main(int argc, char ** argv) { - // read before the model is loaded: latched on first use set_env_default("LLAMA_EXACT_CONCURRENCY", "1"); const char * path = nullptr; diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp index 81187a88ec63..058965ccdfce 100644 --- a/tests/test-rpc-paged-fa.cpp +++ b/tests/test-rpc-paged-fa.cpp @@ -1,5 +1,4 @@ // [TAG_EXACT_CONCURRENCY] an RPC server must refuse a FLASH_ATTN_EXT with a page table (src[5]), since a client can send any graph. -// The server and each client run in child processes, so a refused graph only drops that client. #include "ggml.h" #include "ggml-alloc.h" @@ -32,7 +31,6 @@ static bool port_open(int port) { return ok; } -// runs in a child: one FLASH_ATTN_EXT over a single 256-cell page, computed on the server [[noreturn]] static void send_graph(const std::string & endpoint, bool paged) { alarm(120); @@ -67,14 +65,12 @@ static bool port_open(int port) { ggml_backend_graph_compute(backend, gf); - // the read is the round trip that sees whether the server kept the connection std::vector res(ggml_nelements(out)); ggml_backend_tensor_get(out, res.data(), 0, ggml_nbytes(out)); _exit(0); } -// exit status of one client, or -signal static int run_client(const std::string & endpoint, bool paged) { const pid_t pid = fork(); if (pid == 0) { @@ -110,11 +106,8 @@ int main() { fprintf(stderr, "the RPC server did not start on %s\n", endpoint.c_str()); rc = 1; } else { - // an unpaged graph computes, which shows the harness works const int plain = run_client(endpoint, false); - // a paged one is refused, so the client loses its connection and its read fails const int paged = run_client(endpoint, true); - // and the server is still there for the next client const int after = run_client(endpoint, false); printf("unpaged: %d, paged: %d, unpaged after: %d\n", plain, paged, after); diff --git a/tests/test-server-decision-exact.cpp b/tests/test-server-decision-exact.cpp index 7466298bfcbc..a81b4a788d87 100644 --- a/tests/test-server-decision-exact.cpp +++ b/tests/test-server-decision-exact.cpp @@ -1,5 +1,4 @@ -// [TAG_EXACT_CONCURRENCY] decision questions with a shared prefix are grouped through seq_cp, which exact mode refuses. -// So in exact mode no grouping happens and every task keeps its whole prompt. +// [TAG_EXACT_CONCURRENCY] decision questions with a shared prefix are grouped through seq_cp, which exact mode refuses, so no grouping happens. #include "server-decision.h" @@ -17,7 +16,6 @@ static server_task make_task(int id, const llama_tokens & tokens) { } int main() { - // latched on first use, so set before anything reads it #ifdef _WIN32 _putenv_s("LLAMA_EXACT_CONCURRENCY", "1"); #else diff --git a/tests/test-server-tokens.cpp b/tests/test-server-tokens.cpp index 65290ec4174e..c23db2e18609 100644 --- a/tests/test-server-tokens.cpp +++ b/tests/test-server-tokens.cpp @@ -29,28 +29,27 @@ struct chunk_writer { } }; -// nx*ny tokens of one image, max(nx, ny) positions under M-RoPE static mtmd::input_chunk_ptr make_image_chunk(uint32_t nx, uint32_t ny) { chunk_writer w; - w.put(2); // MTMD_SERIALIZATION_VERSION + w.put(2); w.put(MTMD_INPUT_CHUNK_TYPE_IMAGE); - w.put(0); // tokens_text - w.put(1); // tokens_image follows + w.put(0); + w.put(1); w.put(nx); w.put(ny); - w.put(1); // MTMD_POS_TYPE_MROPE - w.put(0); // image_idx - w.put(1); // n_temporal_merge - w.put_str("test-image"); // id - w.put(0); // batch_f32.is_audio - w.put(1); // one entry - w.put(0); // entry.add_viewsep - w.put(0); // entry.add_newline - w.put(0); // entry.lead_pad - w.put(1); // entry.nx - w.put(1); // entry.ny - w.put(0); // no tokens_audio + w.put(1); + w.put(0); + w.put(1); + w.put_str("test-image"); + w.put(0); + w.put(1); + w.put(0); + w.put(0); + w.put(0); + w.put(1); + w.put(1); + w.put(0); mtmd::input_chunk_ptr chunk(mtmd_input_chunk_load(w.buf.data(), w.buf.size())); @@ -59,7 +58,6 @@ static mtmd::input_chunk_ptr make_image_chunk(uint32_t nx, uint32_t ny) { return chunk; } -// 10 text tokens, an image of 256 tokens and 16 positions, 20 text tokens, then n_gen generated tokens static server_tokens make_prompt(size_t n_gen, const mtmd_input_chunk * chunk) { server_tokens res; @@ -88,7 +86,6 @@ int main() { assert(mtmd_input_chunk_get_n_tokens(chunk.get()) == 256); assert(mtmd_input_chunk_get_n_pos (chunk.get()) == 16); - // a cut in the generated tail: the cache reports 86 positions, which is 326 tokens { server_tokens prompt = make_prompt(40, chunk.get()); @@ -101,7 +98,6 @@ int main() { assert(n_cached == 326); assert(prompt.pos_next(n_cached) == pos_cached); - // the same number taken for a token count falls inside the image bool threw = false; try { @@ -113,14 +109,13 @@ int main() { assert(threw && "a position used as a token count cuts the image in half"); } - // the same prompt with a longer tail, cut inside the generated tokens { server_tokens prompt = make_prompt(300, chunk.get()); assert(prompt.size() == 586); assert(prompt.pos_next() == 346); - const llama_pos pos_cached = 106; // 10 text + 16 image + 20 text + 60 generated + const llama_pos pos_cached = 106; const size_t n_cached = prompt.size_up_to_pos(pos_cached); assert(n_cached == 346); @@ -132,27 +127,24 @@ int main() { assert(prompt.pos_next() == pos_cached); } - // a cut before the image, and one at its first token: both are token boundaries { server_tokens prompt = make_prompt(0, chunk.get()); assert(prompt.size_up_to_pos(10) == 10); assert(prompt.pos_next(10) == 10); - // the image ends at position 26 and token 266 assert(prompt.size_up_to_pos(26) == 266); assert(prompt.pos_next(266) == 26); } - // a cut inside the image: the conversion cannot land there, and stepping back reaches the chunk's first token { server_tokens prompt = make_prompt(0, chunk.get()); - const llama_pos pos_cached = 20; // inside the image, which spans positions 10..25 + const llama_pos pos_cached = 20; size_t n_cached = prompt.size_up_to_pos(pos_cached); - assert(n_cached == 266); // rounded up to the whole chunk + assert(n_cached == 266); while (n_cached > 0 && prompt.pos_next(n_cached) > pos_cached) { n_cached--; @@ -161,11 +153,10 @@ int main() { assert(n_cached == 10); assert(prompt.pos_next(n_cached) == 10); - prompt.keep_first(n_cached); // would throw if it cut the image in half + prompt.keep_first(n_cached); assert(prompt.size() == 10); } - // an empty cache has to be handled by the caller: the walk always consumes its first token { server_tokens prompt = make_prompt(4, chunk.get()); diff --git a/tests/test-state-seq-copy.cpp b/tests/test-state-seq-copy.cpp index 5a9f9a49047a..b90b2efe9433 100644 --- a/tests/test-state-seq-copy.cpp +++ b/tests/test-state-seq-copy.cpp @@ -1,4 +1,3 @@ -// [TAG_STATE_ASYNC] Async state transfer guards: an oversized size is refused since the transfer owns the buffer, and ON_DEVICE is refused since copies go via host. #include "arg.h" #include "common.h" @@ -42,7 +41,6 @@ int main(int argc, char ** argv) { return 1; } - // two sequences interleaved, so the cells of each are a comb rather than one block, which is what the transfer is built for std::vector tokens(60, 1); common_batch batch(ctx); @@ -60,7 +58,6 @@ int main(int argc, char ** argv) { llama_state_seq_copy * cpy = llama_state_seq_copy_init(ctx); - // a recurrent state does not stay in one row, so these models are refused a transfer whatever the backend can do if (llama_model_is_recurrent(llama_init->model()) || llama_model_is_hybrid(llama_init->model())) { CHECK(cpy == nullptr); fprintf(stderr, "%s : a recurrent or hybrid model is refused a transfer, as it must be\n", __func__); @@ -77,7 +74,6 @@ int main(int argc, char ** argv) { CHECK(size > 0); - // nothing is allocated yet, so nothing is page-locked yet, whatever the backend offers CHECK(llama_state_seq_copy_buf_is_pinned(cpy) == false); CHECK(llama_state_seq_copy_buf(cpy) == nullptr); @@ -102,7 +98,6 @@ int main(int argc, char ** argv) { fprintf(stderr, "%s : oversized, empty and ON_DEVICE transfers are all refused\n", __func__); - // a transfer that fails part way must post nothing: the caller is told it failed and is free to reuse the buffer at once CHECK(llama_state_seq_copy_get(cpy, size - 1, seq_id, LLAMA_STATE_SEQ_FLAGS_NONE) == 0); CHECK(llama_state_seq_copy_n_copies(cpy) == 0); CHECK(llama_state_seq_copy_done(cpy)); diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 87b1bf6ab5c5..3d9ce9c9b999 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -12,15 +12,14 @@ import requests from utils import * -# Preemption on a unified KV pool: one slot is parked in host RAM instead of every slot being terminated. Needs --kv-unified. server = ServerPreset.tinyllama2() _ASYNC_BANNER = "parking and resuming asynchronously" -_scratch = [] # files a test wrote, removed after it -_cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES") # restored after a test that hides the GPUs -_policy = os.environ.get("LLAMA_ARG_PREEMPT_POLICY") # restored after a test that picks one, so the suite can run under either +_scratch = [] +_cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES") +_policy = os.environ.get("LLAMA_ARG_PREEMPT_POLICY") _PROMPT_A = "Once upon a time there was a brave knight who" _PROMPT_B = "The quick brown fox jumps over the lazy dog and" @@ -95,7 +94,6 @@ def _complete(n_predict: int, prompt="Hi how are you", id_slot: int = -1, delay: timeout: float = DEFAULT_REQUEST_TIMEOUT): time.sleep(delay) if after_slot_busy is not None: - # Sent once that slot is processing, so the request queues behind it regardless of host speed. for _ in range(200): slots = server.make_request("GET", "/slots").body if any(s["id"] == after_slot_busy and s["is_processing"] for s in slots): @@ -161,7 +159,6 @@ def _assert_completed(results, n_predict: int): def _assert_nothing_parked(text: str): - # Match park log lines, not the bare word: verbose logs print every slot's "is_preempted". assert not any(m in text for m in _PARK_MARKERS), "nothing could be parked here" @@ -215,9 +212,7 @@ def test_forced_parks_do_not_change_the_output(mode): @pytest.mark.parametrize("knob", ["planner", "pages", "async", "last-resort", "last-resort-unlimited"]) def test_two_generations_that_do_not_fit_together_both_finish(knob): - # Each request fits the pool alone (960 and 600 of 1024 cells) but not together. if knob == "pages": - # A block allocator gives each block to one sequence, so the planner must count cells, not tokens. os.environ["LLAMA_SERVER_PREEMPT_GRANULARITY"] = "64" if knob.startswith("last-resort"): os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" @@ -226,7 +221,6 @@ def test_two_generations_that_do_not_fit_together_both_finish(knob): n_ctx = 1024 (_start_async if knob == "async" else _start)(n_ctx=n_ctx) - # Lengths, not client speed, must force the overlap: equal requests fired together did not overlap on a Windows runner. n_predict = (460, 400) results = _complete_overlapping(n_predict, (500, 200)) @@ -259,12 +253,10 @@ def test_a_request_that_cannot_be_helped_gets_the_context_error_and_the_server_l if knob == "ram-0": os.environ["LLAMA_ARG_PREEMPT_RAM"] = "0" else: - # Family members are not victims for each other, so a two-completion request gets the same error as alone. os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" _start(n_ctx=256) if knob == "ram-0": - # The overflow must come from lengths, since equal concurrent requests did not overlap on a Windows runner. assert any(res.status_code != 200 for res in _complete_overlapping((110, 100), (120, 60))) else: res = server.make_request("POST", "/completion", data={ @@ -330,17 +322,14 @@ def test_a_late_prompt_and_a_generating_slot_both_finish(planner): for res, n_predict in zip(results, (n_predict_a, n_predict_b)): assert res.status_code == 200, res.body assert res.body["timings"]["predicted_n"] == n_predict - # The chunk in the abandoned batch is processed once after the rewind, never twice. assert results[1].body["timings"]["prompt_n"] == n_b def test_a_prompt_parked_before_its_first_token_is_issued_whole(): - # Both prompts are too close to n_ctx for the usual margin, so the second is parked before taking a cell and resumes after the first finishes. _start(n_ctx=256, n_batch=256) n_prompt = 240 n_predict = 4 - # Different prompts: with the same one the second could reuse the first's cached cells and prompt_n would be 1. together = _complete_all(n_predict, [_prompt_of(n_prompt, _PROMPT_A), _prompt_of(n_prompt, _PROMPT_B)]) assert "cannot fit the pool" not in _log() @@ -350,10 +339,8 @@ def test_a_prompt_parked_before_its_first_token_is_issued_whole(): def test_a_resident_cycling_through_context_shifts_is_rotated_out_for_a_parked_head(): - # With context shift a resident never frees its cells, so once the head has waited it is parked and the two take turns. _start(n_slots=3, n_ctx=384, enable_ctx_shift=True) - # Rotation is clock-based, so a fast host needs a long generation, and a slow host then needs a longer wait. n_predict = 9000 _assert_completed(_complete_all(n_predict, (_PROMPT_A, _PROMPT_B, _PROMPT_C), timeout=1800), n_predict) @@ -364,7 +351,6 @@ def test_a_resident_cycling_through_context_shifts_is_rotated_out_for_a_parked_h @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_a_parked_head_that_needs_the_whole_pool_is_rotated_in(policy): - # 506 of 512 cells fit only with nobody else resident; the rotation still charged the residents' margin, so a resident that context-shifts forever kept the pool. os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _start(n_ctx=512, n_batch=512, cache_ram=0, enable_ctx_shift=True, n_predict=-1) head = _prompt_of(506, _PROMPT_B) @@ -388,7 +374,6 @@ def lead(): deadline = time.time() + 60 while time.time() < deadline and _n_decoded(_slot_view(0)) <= 40: time.sleep(0.005) - # Rotation waits 2 s for the head; without it the head waits for a leader that never ends. res = _raw_completion(1, head, 1, timeout=60) finally: stop.set() @@ -401,11 +386,9 @@ def lead(): def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): - # A failed save used to stop the planner and let the pool overflow, though the victim could still be parked by dropping its cells. os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" _start(n_ctx=1024, n_slots=2) - # The leader ends at 960 of 1024 cells, so the second is parked regardless of client lag. leader = _prompt_of(500, _PROMPT_A) other = _prompt_of(200, _PROMPT_B) with ThreadPoolExecutor(1) as pool: @@ -425,20 +408,16 @@ def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_a_resident_that_cannot_be_swapped_out_is_rotated_by_recompute(policy): - # 1 MiB holds no snapshot, so rotation used to refuse every resident and the head waited forever behind a context-shifting one. - # Under fcfs the rotated-out resident is older than the head, and resumed ahead of it at once until it queued behind it. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _start(n_ctx=2048, n_slots=2, n_batch=2048, enable_ctx_shift=True) - # A small n_discard keeps the resident near the end of the pool, so its state never fits the budget. def unending_request(): return server.make_request("POST", "/completion", data={ "n_predict": 100000, "prompt": _PROMPT_A, "n_keep": 1, "n_discard": 64, "ignore_eos": True, "temperature": 0.0, "seed": 42, }, timeout=600) - # The server is stopped with this request in flight, so the disconnect is expected. unending = [] def run_unending(): @@ -451,7 +430,6 @@ def run_unending(): t.start() try: - # The resident must be at the pool's limit and cycling before a second prompt cannot fit. for _ in range(3000): if "slot context shift" in _log(): break @@ -478,7 +456,6 @@ def run_unending(): def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): - # A cancelled request can reach release() with a copy running, so release must wait for it. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start_async(n_ctx=512) @@ -509,16 +486,13 @@ def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): def test_a_started_slot_is_counted_by_the_cells_it_holds_not_by_the_prompt_it_keeps(): - # The last request starts on slot 0 holding the first request's cells; counting only its kept prompt made the pool look free and a restore landed on taken cells. _start(n_ctx=1024, n_slots=3) - # 500 + 200 + 200 fit 1024 cells, so both small slots are parked with their whole prompt once slot 0 grows; slot 0 stays largest and ends at 960 cells, too few for either to return. ids = _prompt_of(500, _PROMPT_C) with ThreadPoolExecutor(4) as pool: first = pool.submit(_complete, 460, ids, 0) _wait_processing([0]) - # Queued behind slot 0 and a real prefix of what it holds: it starts on 960 cells keeping 8. follower = pool.submit(_complete, 8, ids[:8], 0) long_ones = [pool.submit(_complete, 400, _prompt_of(200, _PROMPT_A), 1), pool.submit(_complete, 400, _prompt_of(200, _PROMPT_B), 2)] @@ -577,7 +551,6 @@ def _stream_completion(n_predict: int, prompt: str | list[int]) -> tuple[list[st @pytest.mark.parametrize("planner", ["on", "off"]) def test_a_budget_that_holds_no_sequence_parks_by_dropping_the_cells(planner): - # 1 MiB fits neither sequence, so the park drops the cells and the resume re-prefills; the last resort falls back the same way. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" if planner == "off": os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" @@ -606,7 +579,6 @@ def test_a_budget_that_holds_no_sequence_parks_by_dropping_the_cells(planner): def test_a_media_chunk_is_reserved_whole_before_it_is_decoded(): - # A media chunk decodes whole outside the kv-full retry, so unless the planner reserves all its cells the second of two image requests fails mid-chunk. os.environ["LLAMA_MEDIA_MARKER"] = "<__media__>" server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" server.model_hf_file = None @@ -630,15 +602,14 @@ def test_a_media_chunk_is_reserved_whole_before_it_is_decoded(): def test_an_mtp_draft_stays_inside_the_reservation_it_was_priced_for(): - # Near the end of the pool the draft loop could attempt positions past the planner's reservation. path = os.environ.get("LLAMA_SERVER_TEST_MTP_MODEL") if not path: pytest.skip("set LLAMA_SERVER_TEST_MTP_MODEL to a gguf carrying an MTP head") # ty: ignore[too-many-positional-arguments] server.model_file = path server.model_hf_repo = server.model_hf_file = None server.spec_type = "draft-mtp" - os.environ["LLAMA_ARG_SPEC_DRAFT_P_MIN"] = "0.0" # only the bounds stop the draft loop - os.environ["LLAMA_ARG_LOG_VERBOSITY"] = "5" # logs when the wrapper truncates a draft + os.environ["LLAMA_ARG_SPEC_DRAFT_P_MIN"] = "0.0" + os.environ["LLAMA_ARG_LOG_VERBOSITY"] = "5" _start(n_ctx=2048, n_slots=2, n_batch=2048, n_gpu_layer=99, spec_draft_n_max=128, spec_draft_n_min=1) n_prompt = 2045 @@ -658,7 +629,6 @@ def test_an_mtp_draft_stays_inside_the_reservation_it_was_priced_for(): def test_a_hybrid_model_parks_synchronously(): - # A hybrid's recurrent half compacts active sequences each batch, so a concurrent copy could read a moved row. path = os.environ.get("LLAMA_SERVER_TEST_HYBRID_MODEL") if not path: pytest.skip("set LLAMA_SERVER_TEST_HYBRID_MODEL to a hybrid attention/recurrent gguf") # ty: ignore[too-many-positional-arguments] @@ -702,8 +672,6 @@ def _generated_model(arch: str, name: str) -> str: @pytest.mark.parametrize("arch,name,shared", [("deepseek4", "deepseek4-moe", False), ("llama", "llama-dense", True)]) def test_only_a_cache_whose_sequences_share_cells_is_parked(arch, name, shared): - # DeepSeek V4 keeps a cache per sequence even under --kv-unified: two prompts that overflow n_ctx together each fit their own, and a park freed nothing the other could use. - # The llama control shares one pool, so the same pair overflows it and one is parked. server.model_file = _generated_model(arch, name) server.model_hf_repo = server.model_hf_file = None os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" @@ -724,7 +692,6 @@ def test_only_a_cache_whose_sequences_share_cells_is_parked(arch, name, shared): _assert_nothing_parked(text) -# [TAG_EXACT_CONCURRENCY] The paged pool places a cell by sequence and position, so layouts with shared positions cannot be served. def _mrope_model() -> str: path = os.environ.get("LLAMA_SERVER_TEST_MROPE_MODEL") @@ -734,12 +701,11 @@ def _mrope_model() -> str: def test_exact_concurrency_refuses_an_mrope_model_with_a_projector(): - # Under M-RoPE all tokens of one image share a temporal position. path = _mrope_model() with tempfile.TemporaryDirectory() as tmp: mmproj = os.path.join(tmp, "mmproj.gguf") with open(mmproj, "wb") as f: - f.write(b"GGUF" + struct.pack(" list: def test_exact_concurrency_prefills_a_prompt_in_the_ubatches_it_would_get_alone(): - # Generated tokens enter the batch first, so a prompt got ubatches 512,512,512,509 beside three decoders and 512,512,512,512 alone. - # -b 2048 -ub 512 -np 4: the batch holds a whole ubatch plus one decode per slot (516 tokens), as common_exact_batch_geometry() requires. path = os.environ.get("LLAMA_SERVER_TEST_EXACT_MODEL") if not path: pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") # ty: ignore[too-many-positional-arguments] @@ -855,7 +816,6 @@ def decoder(i): def test_slots_reports_a_transferring_slot_apart_from_a_parked_one(): - # Slots copying out or restoring still hold cells; only a fully parked slot holds nothing. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "1" _start_async(n_ctx=256) @@ -894,7 +854,6 @@ def _shift_completion(n_predict: int): def test_a_park_right_after_a_context_shift_does_not_change_the_output(): - # A shift defers the K transform to the next decode, so a park in between used to save new positions with old K. os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "0" os.environ["LLAMA_ARG_PREEMPT_RAM"] = "0" _start(n_ctx=256, n_batch=32, n_ubatch=32, enable_ctx_shift=True, cache_ram=0) @@ -922,7 +881,6 @@ def test_a_park_right_after_a_context_shift_does_not_change_the_output(): def test_a_sibling_prompt_with_an_invalid_token_is_refused_before_anything_streams(): - # Validated before posting: parked behind a running sibling, it used to fail inside an already opened 200 stream. _start(n_ctx=256, n_slots=2, n_batch=256) res = server.make_request("POST", "/completion", data={ @@ -936,7 +894,6 @@ def test_a_sibling_prompt_with_an_invalid_token_is_refused_before_anything_strea def test_a_recompute_park_bounds_its_draft_by_the_tokens_it_comes_back_with(): - # A recompute park empties the prompt, and bounding the draft by it failed a 2000-token request in a 2048-cell pool as impossible. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "1" server.spec_type = "ngram-mod" @@ -957,7 +914,6 @@ def test_a_recompute_park_bounds_its_draft_by_the_tokens_it_comes_back_with(): def test_props_says_whether_exact_concurrency_is_running(): - # A build ignoring the variable still starts, so clients read the answer here. _start(n_ctx=256) res = server.make_request("GET", "/props") assert res.status_code == 200 @@ -975,7 +931,6 @@ def test_props_reports_exact_concurrency_on(): def test_a_recompute_park_under_exact_concurrency_says_it_is_not_byte_identical(): - # A re-prefilled state differs in the last bits on CUDA, so the mode reports it the first time. server.model_file = _mrope_model() server.model_hf_repo = server.model_hf_file = None os.environ["LLAMA_EXACT_CONCURRENCY"] = "1" @@ -991,10 +946,8 @@ def test_a_recompute_park_under_exact_concurrency_says_it_is_not_byte_identical( def test_a_recompute_park_is_reported_to_the_client_and_to_metrics(): - # A recompute resume is not bit-identical to the saved state; the request, /slots and /metrics report how often it happened. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" - # This sequence exceeds the 1 MiB budget, so every park drops its cells. _start(n_ctx=2048, n_batch=2048) n_predict = 24 @@ -1023,14 +976,12 @@ def test_a_recompute_park_is_reported_to_the_client_and_to_metrics(): def test_a_recompute_restore_does_not_count_its_replay_as_prompt(): - # Counting the re-prefill as prompt would move the prompt/generation boundary, and the generation time would cover only tokens after the last re-prefill. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=2048, n_batch=2048) n_prompt = 1950 n_predict = 24 - # A first prefill this size pays one-time backend setup, which on a GPU outweighs the warm re-prefills: warm up on other text first. assert _complete(n_predict, _prompt_of(n_prompt, _PROMPT_A)).status_code == 200 res = _complete(n_predict, _prompt_of(n_prompt, _PROMPT_C)) @@ -1041,7 +992,6 @@ def test_a_recompute_restore_does_not_count_its_replay_as_prompt(): assert timings["cache_n"] == 0, timings assert timings["prompt_n"] == n_prompt, timings assert timings["predicted_n"] == n_predict, timings - # Every re-prefill happens during generation, so the generation time is the longer. assert timings["predicted_ms"] > timings["prompt_ms"], timings @@ -1074,7 +1024,6 @@ def test_slots_reports_the_recomputes_of_the_current_task(): def test_a_swap_park_is_not_reported_as_a_recompute(): - # With room for its bytes the park keeps the saved sequence, and the client is told so. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512) @@ -1106,7 +1055,6 @@ def _stream_responses(n_predict: int, prompt: str) -> dict: def test_a_streamed_response_carries_the_preempt_record_where_a_plain_one_does(): - # Clients keep data["response"] from a streamed /v1/responses, so the record must be there, as in the non-streamed body. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512) @@ -1123,7 +1071,6 @@ def test_a_streamed_response_carries_the_preempt_record_where_a_plain_one_does() def test_two_image_chats_that_outgrow_the_parking_budget_both_finish(): - # Media chunks could not be recompute-parked, so with no budget the pool overflowed and ended both chats. Now the chunk is re-encoded from the task with its cells reserved whole. os.environ["LLAMA_MEDIA_MARKER"] = "<__media__>" os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" @@ -1150,7 +1097,6 @@ def test_two_image_chats_that_outgrow_the_parking_budget_both_finish(): def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): - # A recompute park mid-prefill restarts the prefill, so the prompt count before the park must be dropped too. os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" _start(n_ctx=2048, n_batch=256) @@ -1158,7 +1104,6 @@ def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): t = threading.Thread(target=lambda: resident.append(_complete(1900, _PROMPT_A)), daemon=True) t.start() - # The pool must be nearly full before the second prompt starts, so its prefill runs out of cells. deadline = time.time() + 90 while t.is_alive() and time.time() < deadline: slots = server.make_request("GET", "/slots").body @@ -1177,7 +1122,6 @@ def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): assert "error" not in final, final assert comments and comments[0] == ": preempted", comments - # A park that dropped fewer cells than the resume puts back was taken mid-prefill, the case under test. parks = [(int(cells), int(again)) for cells, again in re.findall( r"preempted: (\d+) cells dropped .*? (\d+) tokens to re-prefill", _log())] assert any(0 < cells < again for cells, again in parks), parks @@ -1223,8 +1167,6 @@ def _serve_with_training_context(n_ctx_train: int): def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): - # A 7300-cell parked head used to wait forever while short requests kept a resident present. Once the head has waited its turn, never-resident prompts wait for it. - # 1 MiB holds no short request's state, so only the reservation brings the head back before PREEMPT_ROTATE_RECOMPUTE_US. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "48" # On CUDA a prompt chunk across position 2048 of this model hangs llama_decode (also on base), so run on CPU; the code under test is host-side. @@ -1235,7 +1177,6 @@ def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): short_prompt = _prompt_of(1700, _PROMPT_B) head_prompt = _prompt_of(7200, _PROMPT_A) n_short, n_head = 32, 100 - # A starved head waits forever, so any bound catches it; the head prefills 7200 tokens three times, 46 s on a CPU runner and 92 s on Windows. t_stream_max = 240.0 stop = threading.Event() @@ -1279,7 +1220,6 @@ def stream(id_slot): assert "Context size has been exceeded" not in text assert not stopped_early, f"the head was still waiting when the stream was stopped after {t_stream_max} s" assert "prompt held:" in text, "no prompt was held back for the head" - # The head returns once the residents ahead of it finish, about one quantum after each park. waits = [float(w) for w in re.findall(r"id +3 \| task \d+ \| resumed after ([\d.]+) s", text)] assert waits, "the head was never parked and resumed" assert max(waits) < 10.0, f"the head waited {waits} s behind requests that came after it" @@ -1288,8 +1228,6 @@ def stream(id_slot): @pytest.mark.slow @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_a_long_resident_that_never_shifts_is_rotated_out_for_an_aged_head(policy): - # Only context-shifting residents used to be rotated, so a long generation that fit held the pool and the parked slot waited for all of it. - # A resident that ends by itself is rotated once the head has waited 30 s and it would run 30 s more, so the head's wait is bounded either way. os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _serve_with_training_context(16384) _start(n_ctx=16384, n_slots=2, n_batch=2048) @@ -1300,7 +1238,6 @@ def run(name, n_predict, prompt, id_slot): res = _raw_completion(n_predict, prompt, id_slot, timeout=1800) done[name] = (time.time(), res) - # A leads B by 564 cells, so B is parked once the pool fills. a = threading.Thread(target=run, args=("a", 16000, _prompt_of(64, _PROMPT_A), 0)) a.start() deadline = time.time() + 300 @@ -1321,12 +1258,10 @@ def run(name, n_predict, prompt, id_slot): assert "slot context shift" not in text waits = [float(w) for w in re.findall(r"id +1 \| task \d+ \| resumed after ([\d.]+) s", text)] assert waits, "the second request was never parked" - # 30 s before a rotation is considered, plus at most 30 s of the resident's own estimated remainder. assert max(waits) < 90.0, f"the parked request waited {waits} s behind a resident that ends by itself" def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small_ones(): - # The second chunk is about 600 cells short: smallest-first parked both 400-token residents, where the 1400-token one alone covers it. _serve_with_training_context(8192) _start(n_ctx=4864, n_slots=4, n_batch=2048) @@ -1336,7 +1271,6 @@ def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small with ThreadPoolExecutor(4) as pool: residents = [pool.submit(_raw_completion, 300, p, i) for i, p in enumerate(small + [medium])] - # Every resident is generating before the leader arrives, so the leader's second chunk is the shortfall. deadline = time.time() + 60 while time.time() < deadline: slots = server.make_request("GET", "/slots").body @@ -1398,7 +1332,6 @@ def test_props_reports_the_planning_granularity(): def test_a_growing_sequence_keeps_its_pinned_buffer_across_parks(): - # Pinned buffers sized exactly were re-pinned on every park of a grown sequence, costing about as much as the copy. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start_async(n_ctx=2048) @@ -1414,7 +1347,6 @@ def test_a_growing_sequence_keeps_its_pinned_buffer_across_parks(): def test_a_slot_whose_park_buffer_comes_back_pageable_is_no_longer_reported_async(): - # The load-time probe pins 1 MiB, but a larger buffer can still be pageable: that slot parks synchronously, and /props must say so. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" os.environ["LLAMA_SERVER_PREEMPT_PAGEABLE"] = "1" _start_async(n_ctx=512) @@ -1430,7 +1362,6 @@ def test_a_slot_whose_park_buffer_comes_back_pageable_is_no_longer_reported_asyn def test_a_multi_prompt_oai_completion_counts_the_parks_of_every_prompt(): - # An array prompt is one task per prompt, each parked separately; the OAI response merges them, so its counters are the sum. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start() @@ -1456,7 +1387,6 @@ def _cached(n_predict: int, prompt: list, id_slot: int): def test_a_started_slot_replacing_its_prompt_does_not_purge_an_idle_slot(): - # 200 of 256 cells are ever held; charging the started slot's old 100 cells beside its new 100 purged slot 1, so its rerun re-prefilled. _start(n_ctx=256, n_batch=128, n_ubatch=64, cache_ram=0) results = [_cached(1, [tok] * 100, slot) for slot, tok in ((0, 11), (1, 12), (0, 13), (1, 12))] for res in results: @@ -1468,7 +1398,6 @@ def test_a_started_slot_replacing_its_prompt_does_not_purge_an_idle_slot(): def test_an_idle_slot_inside_the_margin_keeps_its_cache(): - # 120 idle and 132 generating cells fit 256 with room for the step; purging slot 0 only to keep the planning margin made its rerun re-prefill. _start(n_ctx=256, n_batch=128, n_ubatch=64, cache_ram=0) first = [11] * 120 assert _cached(1, first, 0).status_code == 200 @@ -1480,7 +1409,6 @@ def test_an_idle_slot_inside_the_margin_keeps_its_cache(): def test_a_started_slot_that_fits_once_trimmed_parks_nobody(): - # Slot 0 keeps 300 of its 600 old cells: 300 + 336 + 60 + 310 fit 1024, but the untrimmed count parked the generating slot and purged slot 2. _start(n_ctx=1024, n_slots=3, n_batch=512, n_ubatch=512, cache_ram=0) old = [100 + i % 50 for i in range(600)] idle = [300 + i % 30 for i in range(60)] @@ -1518,7 +1446,6 @@ def _reparked_mid_reprefill(text: str) -> list: def test_a_resumed_re_prefill_keeps_its_room_until_it_is_done(): - # The second park falls back to recompute; its resume was admitted for the whole sequence, but the restores behind it took the room and parked it again part way through. os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "2" _start(n_ctx=1024, n_slots=4, n_batch=128, n_ubatch=128) prompts = [[10 + 20 * i + k % 20 for k in range(40)] for i in range(4)] @@ -1540,7 +1467,6 @@ def _oai_n(prompt: list, n: int, max_tokens: int, timeout: float = DEFAULT_REQUE def test_a_single_request_beside_an_n_2_request_is_parked_so_both_finish(): - # 900 + 700 cells overflow 1024 while each fits alone; the n=1 slot was the exempt leader and the n=2 slots cannot be parked, so every slot failed. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128) with ThreadPoolExecutor(1) as pool: @@ -1556,7 +1482,6 @@ def test_a_single_request_beside_an_n_2_request_is_parked_so_both_finish(): def test_two_n_2_requests_that_do_not_fit_together_end_only_one(): - # Neither n=2 request can be parked; ending every slot also ended the one that fits alone. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" _start(n_ctx=1024, n_slots=4, n_batch=128, n_ubatch=128) with ThreadPoolExecutor(2) as pool: @@ -1574,7 +1499,6 @@ def test_two_n_2_requests_that_do_not_fit_together_end_only_one(): @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_an_n_2_prompt_that_parked_an_older_request_is_not_held_behind_it(policy): - # The n=2 prompt cannot be parked, so the older request is parked for it; fcfs then held the prompt behind that head, which waited for the cells the prompt sat on. os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _start(n_ctx=1024, n_slots=3, n_batch=128, cache_ram=0) with ThreadPoolExecutor(1) as pool: @@ -1592,7 +1516,6 @@ def test_an_n_2_prompt_that_parked_an_older_request_is_not_held_behind_it(policy def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generating_one(): - # Slot 1 keeps 600 cells of an earlier conversation; its follow-up started beside a generating request, was the largest, became the exempt leader, and the older request was parked for it. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" _start(n_ctx=1024, n_slots=2, n_batch=128, n_ubatch=128, cache_ram=0) earlier = [200 + k % 50 for k in range(600)] @@ -1613,7 +1536,6 @@ def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generati @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_the_policy_decides_whether_the_newest_or_the_cheapest_slot_is_parked(policy): - # fcfs parks the newer request and never the older one; cost parks whichever is cheaper at the time, which depends on the host's speed. Both first purge the idle slot. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128, cache_ram=0) @@ -1639,7 +1561,6 @@ def test_the_policy_decides_whether_the_newest_or_the_cheapest_slot_is_parked(po def test_fcfs_resumes_parked_requests_in_arrival_order(): - # The newest is parked first, so park time and arrival disagree: the older of the two parked requests comes back first. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" os.environ["LLAMA_ARG_PREEMPT_POLICY"] = "fcfs" _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128) @@ -1665,7 +1586,6 @@ def test_fcfs_resumes_parked_requests_in_arrival_order(): @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_the_old_policy_knob_selects_the_policy(policy): - # The old test knob is an alias only while LLAMA_ARG_PREEMPT_POLICY is unset. os.environ.pop("LLAMA_ARG_PREEMPT_POLICY", None) os.environ["LLAMA_SERVER_PREEMPT_POLICY"] = policy try: @@ -1677,7 +1597,6 @@ def test_the_old_policy_knob_selects_the_policy(policy): @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_the_command_line_policy_wins_over_the_old_knob(policy, monkeypatch): - # The old knob only stands in for an unset policy: --preempt-policy outranks it like any environment value. os.environ.pop("LLAMA_ARG_PREEMPT_POLICY", None) os.environ["LLAMA_SERVER_PREEMPT_POLICY"] = "cost" if policy == "fcfs" else "fcfs" popen = subprocess.Popen @@ -1691,7 +1610,6 @@ def test_the_command_line_policy_wins_over_the_old_knob(policy, monkeypatch): @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_a_prompt_dropped_in_its_prefill_waits_until_it_fits_whole(policy): - # The newer prompt is parked by dropping its cells part way through its prefill; resumed as soon as one chunk fitted, it was prefilled and dropped again until the older request ended. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _serve_with_training_context(8192) @@ -1712,7 +1630,6 @@ def test_a_prompt_dropped_in_its_prefill_waits_until_it_fits_whole(policy): def test_oversubscribed_bounded_chats_are_not_time_sliced(): - # Four chats of 200 + 800 tokens need twice the pool; residents that end by themselves used to be rotated out every 2 s, parking and restoring whole sequences over and over. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" _start(n_ctx=2048, n_slots=4, n_batch=256, n_ubatch=256, cache_ram=0) with ThreadPoolExecutor(4) as pool: diff --git a/tools/server/tests/unit/test_preempt_models.py b/tools/server/tests/unit/test_preempt_models.py index d5aae120c3fb..0408128698d4 100644 --- a/tools/server/tests/unit/test_preempt_models.py +++ b/tools/server/tests/unit/test_preempt_models.py @@ -2,11 +2,10 @@ import pytest from utils import * -# Requests and models outside the parking path that the preemption change must leave as upstream serves them. server = ServerPreset.tinyllama2() -START_TIMEOUT = 300 # the preload can be slow on a loaded host +START_TIMEOUT = 300 @pytest.fixture(autouse=True) @@ -107,8 +106,6 @@ def test_a_context_shift_is_left_to_the_decode_unless_parking_is_on(preempt_ram, i_decode = after.index("n_batch (effective)") i_update = after.index("applying K-shift") if preempt_ram is None: - # as upstream: the K-shift runs inside llama_decode() assert i_decode < i_update else: - # a park before the decode must see shifted K, so the shift runs first assert i_update < i_decode diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py index 415717dc112a..008a3d7dc0a0 100644 --- a/tools/server/tests/unit/test_preempt_notify.py +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -8,7 +8,6 @@ import requests from utils import * -# [TAG_PREEMPT] Streaming clients get SSE comment notices on park and restore, and a 2 s keepalive keeps proxies from giving up. server = ServerPreset.tinyllama2() @@ -171,7 +170,6 @@ def _prefill_payload(path: str, prompt: str, n_predict: int) -> dict: @pytest.mark.parametrize("path", ["/completion", "/v1/chat/completions", "/v1/responses", "/v1/messages"]) def test_a_park_during_prompt_processing_opens_the_stream_with_the_notice(path): - # A park before the first token looks like a stall, so its notice goes out with the response headers. server.server_slots = True _start(n_ctx=2048, n_batch=256) @@ -183,8 +181,6 @@ def _resident(): t = threading.Thread(target=_resident, daemon=True) t.start() - # The pool must be nearly full before the second prompt starts, so its prefill runs out of cells. - # the resident grows by decoding: 1400 tokens took over 12 s on a loaded CI runner deadline = time.time() + 90 while t.is_alive() and time.time() < deadline: slots = requests.get(f"http://{server.server_host}:{server.server_port}/slots").json() @@ -214,13 +210,11 @@ def _resident(): assert comments and comments[0][1] == ": preempted", [line for _, line in seen[:4]] assert datas, "the request never produced a chunk" - # sent when the slot was parked, not batched with the chunk that came later assert comments[0][0] + 0.05 < datas[0][0], [(round(at, 3), line[:24]) for at, line in seen[:4]] assert any(line == ": resumed" for _, line in comments), [line for _, line in comments[:4]] def test_a_stream_parked_before_its_first_token_starts_with_the_notice(): - # n_batch: the whole prompt in one batch, so the planner sees its size at once _start(n_ctx=512, n_batch=512) status, _, lines = _behind_a_resident(_completion_payload(32, " ".join([_PROMPT_B] * 14))) @@ -234,7 +228,6 @@ def test_a_stream_parked_before_its_first_token_starts_with_the_notice(): def test_an_oversized_prompt_is_errored_instead_of_parked(): - # A newly assigned slot has not passed prompt checks, and a notice opens the stream, so parking it would turn an error response into 200 plus an in-stream error. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512, n_batch=512) @@ -245,12 +238,10 @@ def test_an_oversized_prompt_is_errored_instead_of_parked(): def test_a_rotation_tells_both_streams_and_a_head_parked_past_the_budget_is_kept_alive(): - # 2 MiB holds one parked state but not two, so rotation is refused and the head stays parked past the 2 s keepalive. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "2" _start(n_slots=3, n_ctx=2048, enable_ctx_shift=True) n_predict = 12000 - # the default 2 s keepalive equals the rotation window, so a park could end before its ping; ask for 1 s instead. results = _stream_all(n_predict, (_PROMPT_A, _PROMPT_B, _PROMPT_C), sse_ping_interval=1) n_parked = n_keepalive = 0 for comments, datas in results: @@ -270,7 +261,6 @@ def test_a_rotation_tells_both_streams_and_a_head_parked_past_the_budget_is_kept def test_every_notice_of_a_multi_prompt_stream_names_the_prompt_it_is_about(): - # Clients sharing a stream tell notices apart by index, so index 0 must be explicit too. os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start(n_ctx=512) @@ -284,7 +274,6 @@ def test_every_notice_of_a_multi_prompt_stream_names_the_prompt_it_is_about(): def test_an_oversized_sibling_prompt_is_errored_before_a_valid_one_is_parked(): - # A valid prompt's park notice opens the stream, so a sibling that does not fit must be rejected before any is queued. os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" _start(n_ctx=256, n_slots=3, n_batch=512) From a9f91605aabd475bf1bc7183baed3cad417c7c42 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 07:56:01 -0700 Subject: [PATCH 063/109] llama : keep branches off 32-byte boundaries on x86 On cores with the JCC erratum microcode (Skylake through Cascade Lake) a jump that crosses or ends on a 32-byte boundary is not cached in the decoded uop cache. Where the per-token sampler loops land moves with any change to the code linked before them, which cost 1-2% of server decode speed with no change to the code that runs: padding base b11642 by 16 bytes reproduced it, and padding this branch by 16 bytes removed it. Build libllama with -Wa,-mbranches-within-32B-boundaries (GCC with binutils as) or -mbranches-within-32B-boundaries (clang, whose integrated assembler refuses the -Wa form) where the compiler accepts it, so its speed no longer depends on the layout. MSVC and non-x86 targets are left as they are. --- src/CMakeLists.txt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 97250c2e8856..ebff20b98e5f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -69,6 +69,24 @@ target_include_directories(llama PRIVATE . ${CMAKE_CURRENT_BINARY_DIR}) target_include_directories(llama PUBLIC ../include) target_compile_features (llama PRIVATE cxx_std_17) # don't bump +# [TAG_JCC_ALIGN] On x86 cores with the JCC erratum microcode (Skylake through Cascade Lake), a jump that crosses or ends on +# a 32-byte boundary is not cached in the decoded uop cache, so a hot loop that lands on one runs slower. Where a loop lands +# moves with any unrelated change to the code linked before it: the per-token sampler loops over the vocabulary did, costing +# 1-2% of server decode speed with no change to the code that runs. Keeping branches off those boundaries removes that. +if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64|i[3-6]86)$" AND NOT MSVC) + include(CheckCXXCompilerFlag) + # GCC passes it to binutils as; clang's integrated assembler takes it only as a driver flag + check_cxx_compiler_flag("-Wa,-mbranches-within-32B-boundaries" LLAMA_CXX_HAS_JCC_ALIGN) + if (LLAMA_CXX_HAS_JCC_ALIGN) + target_compile_options(llama PRIVATE -Wa,-mbranches-within-32B-boundaries) + else() + check_cxx_compiler_flag("-mbranches-within-32B-boundaries" LLAMA_CXX_HAS_JCC_ALIGN_DRIVER) + if (LLAMA_CXX_HAS_JCC_ALIGN_DRIVER) + target_compile_options(llama PRIVATE -mbranches-within-32B-boundaries) + endif() + endif() +endif() + target_link_libraries(llama PUBLIC ggml) if (BUILD_SHARED_LIBS) From 3ef8b53a20ff4f4b103881f00f2af54fc5d4d09e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 11:37:49 -0700 Subject: [PATCH 064/109] llama : shorten the JCC alignment comment --- src/CMakeLists.txt | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ebff20b98e5f..d70300120794 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -69,10 +69,7 @@ target_include_directories(llama PRIVATE . ${CMAKE_CURRENT_BINARY_DIR}) target_include_directories(llama PUBLIC ../include) target_compile_features (llama PRIVATE cxx_std_17) # don't bump -# [TAG_JCC_ALIGN] On x86 cores with the JCC erratum microcode (Skylake through Cascade Lake), a jump that crosses or ends on -# a 32-byte boundary is not cached in the decoded uop cache, so a hot loop that lands on one runs slower. Where a loop lands -# moves with any unrelated change to the code linked before it: the per-token sampler loops over the vocabulary did, costing -# 1-2% of server decode speed with no change to the code that runs. Keeping branches off those boundaries removes that. +# [TAG_JCC_ALIGN] JCC-erratum x86 cores skip the uop cache for jumps on 32-byte boundaries; keep them off, or decode speed depends on code layout. if (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64|i[3-6]86)$" AND NOT MSVC) include(CheckCXXCompilerFlag) # GCC passes it to binutils as; clang's integrated assembler takes it only as a driver flag From 3a68a5c33a7dbcedeb48fa1e69954a349742bc50 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 12:29:35 -0700 Subject: [PATCH 065/109] spec : keep the per-call LiliCorr bound clear of the walk's loop header --- common/speculative.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/common/speculative.cpp b/common/speculative.cpp index 6d06a588d730..5eecd865d65d 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -1342,13 +1342,14 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { int32_t predecessor = 0; for (int32_t i = 1; i < n_block_tokens; ++i) { + const float * row = lattice + (size_t) (beg + i) * n_embd_dec; + const int32_t top_k = is_dflash2 ? selector_top_k : lilicorr_top_k; + const float * scores = row + top_k + (size_t) predecessor * top_k; // a LiliCorr block has a fixed size, so the per-call bound from the caller's remaining context stops the walk instead + // (kept clear of the loop header, which ggml-org#30520 rewrites) if (dp.n_max > 0 && (int32_t) result.size() >= dp.n_max) { break; } - const float * row = lattice + (size_t) (beg + i) * n_embd_dec; - const int32_t top_k = is_dflash2 ? selector_top_k : lilicorr_top_k; - const float * scores = row + top_k + (size_t) predecessor * top_k; predecessor = (int32_t) std::distance(scores, std::max_element(scores, scores + top_k)); From f57ea1b98c1473956d65064990c00c2f739d2dbf Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 15 Oct 2026 14:27:11 -0700 Subject: [PATCH 066/109] server tests: name the repeated --override-kv list apart from upstream's single override_kv --- tools/server/tests/unit/test_preempt_models.py | 2 +- tools/server/tests/utils.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/server/tests/unit/test_preempt_models.py b/tools/server/tests/unit/test_preempt_models.py index 0408128698d4..fdb9cad46332 100644 --- a/tools/server/tests/unit/test_preempt_models.py +++ b/tools/server/tests/unit/test_preempt_models.py @@ -22,7 +22,7 @@ def test_a_non_causal_decision_longer_than_the_ubatch_is_refused_and_the_server_ global server server = ServerPreset.tinyopenjev() server.n_threads = 2 - server.override_kv = ["qwen35.attention.causal=bool:false"] + server.override_kvs = ["qwen35.attention.causal=bool:false"] server.n_ctx = 1024 server.n_slots = 2 server.kv_unified = True diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index a5f6286c7cff..486157586915 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -126,7 +126,7 @@ class ServerProcess: mcp_servers_config: str | None = None mcp_servers_json: str | None = None cors_origins: str | None = None - override_kv: List[str] | None = None + override_kvs: List[str] | None = None # session variables process: subprocess.Popen | None = None @@ -189,7 +189,7 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.extend(["--models-preset", self.models_preset]) if self.cors_origins: server_args.extend(["--cors-origins", self.cors_origins]) - for kv in self.override_kv or []: + for kv in self.override_kvs or []: server_args.extend(["--override-kv", kv]) if self.n_batch: server_args.extend(["--batch-size", self.n_batch]) From dde3e20a23b44a39f4c4b54623a25069984639af Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 18 Oct 2026 04:07:37 -0700 Subject: [PATCH 067/109] server: never park the oldest under fcfs, and drop a started slot trimmed below its sliding window Beside prompts held for a parked slot, the oldest running request could be the only fcfs candidate. Parked at the end of the window, it was also first to resume, so it ping-ponged forever and nothing finished. The fcfs picker now skips the oldest, as the cost policy already skips its leader. Trimming a started slot to the prefix its new request keeps removed every cell a sliding window still held, leaving an empty sequence that claimed tokens; the reuse check then aborted with pos_min == -1. Such a slot now drops the stale sequence and prefills again. --- tools/server/server-context.cpp | 19 ++++++++- tools/server/tests/unit/test_preempt.py | 52 +++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index bf44a4a4656a..58113fecf258 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4391,6 +4391,12 @@ struct server_context_impl { slot.prompt.tokens.keep_first(n_keep); slot.mem.seq_rm(slot.id, slot.prompt.tokens.pos_next(), -1); + + // [TAG_PREEMPT] A sliding window holds only the newest cells: cut below them, nothing of the prefix is left, and the reuse check aborts on an empty sequence that claims tokens. + if (n_keep > 0 && llama_memory_seq_pos_min(llama_get_memory(ctx_tgt), slot.id) == -1) { + slot.prompt.tokens.clear(); + slot.mem.seq_rm(slot.id, -1, -1); + } } // `recompute`: no victim fits the host budget, so pick again and drop cells instead of copying. `n_deficit`: a single victim covering it is preferred over several smaller ones. @@ -4455,12 +4461,21 @@ struct server_context_impl { return victim; } - // [TAG_PREEMPT] The most recently arrived resident, with no exemption: the oldest always runs. Copied if the budget holds it, else dropped. + // [TAG_PREEMPT] The most recently arrived resident, never the oldest, which always runs. Copied if the budget holds it, else dropped. server_slot * preempt_pick_victim_fcfs(bool * recompute) { + // [TAG_PREEMPT] Beside held prompts the oldest can be the only eligible slot; parked, it is resumed first, so it would ping-pong at the window's end instead of finishing. + const server_slot * oldest = nullptr; + + for (const auto & slot : slots) { + if (slot.is_processing() && !slot.preempt_is_out() && slot.task && (!oldest || slot.task->id < oldest->task->id)) { + oldest = &slot; + } + } + server_slot * victim = nullptr; for (auto & slot : slots) { - if (preempt_victim_eligible(slot, nullptr, true) && (!victim || slot.task->id > victim->task->id)) { + if (&slot != oldest && preempt_victim_eligible(slot, nullptr, true) && (!victim || slot.task->id > victim->task->id)) { victim = &slot; } } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 3d9ce9c9b999..cca358982f88 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1584,6 +1584,58 @@ def test_fcfs_resumes_parked_requests_in_arrival_order(): assert resumed.index(1) < resumed.index(2), resumed +@pytest.mark.parametrize("policy", ["fcfs", "cost"]) +def test_the_oldest_runs_to_the_end_of_the_window_beside_a_held_prompt(policy): + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy + _start(n_ctx=256, n_slots=3, n_batch=64, n_ubatch=64, cache_ram=0) + with ThreadPoolExecutor(2) as pool: + # a livelock never ends, so the bound is the test's verdict; it is generous for a loaded host + oldest = pool.submit(lambda: server.make_request("POST", "/completion", timeout=180, data={ + "n_predict": 1000, "prompt": [100 + k % 50 for k in range(20)], "id_slot": 0, "cache_prompt": True, + "ignore_eos": True, "temperature": 0.0, "seed": 42})) + deadline = time.time() + 180 + while time.time() < deadline and _n_decoded(_slot_view(0)) < 130: + time.sleep(0.02) + # the oldest must also be the largest, or the cost policy rightly parks it for the next prompt + assert _n_decoded(_slot_view(0)) >= 130, "the oldest did not reach the window's last quarter in time" + # does not fit beside the oldest, so it is parked holding nothing and is owed the cells first + parked = pool.submit(_cached, 16, [200 + k % 50 for k in range(125)], 1) + assert _wait_preempted() + # held behind the parked one: a running slot, but no candidate, so the oldest is the only one left to pick + held = _cached(16, [300 + k % 50 for k in range(30)], 2) + oldest = oldest.result() + parked = parked.result() + for res in (oldest, parked, held): + assert res.status_code == 200, res.body + assert oldest.body["stop_type"] == "limit", oldest.body + assert oldest.body["preempt"]["parks"] == 0, "the oldest was parked at the end of the window" + assert parked.body["preempt"]["parks"] > 0 + + +def test_a_started_slot_trimmed_below_its_sliding_window_prefills_again(): + server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" + server.model_hf_file = None + server.model_alias = "tinygemma3" + server.override_kvs = ["gemma3.attention.sliding_window=int:32"] + _start(n_ctx=512, n_slots=2, n_batch=64, n_ubatch=64, cache_ram=0, n_threads=4) + stale = [100 + k % 50 for k in range(200)] + assert _cached(1, stale, 1).status_code == 200 + with ThreadPoolExecutor(1) as pool: + busy = pool.submit(_cached, 400, [300 + k % 50 for k in range(40)], 0) + deadline = time.time() + 180 + while time.time() < deadline and _n_decoded(_slot_view(0)) < 230: + time.sleep(0.02) + assert _n_decoded(_slot_view(0)) >= 230, "the busy slot did not fill the pool in time" + # 40 tokens in common, far below the 32 newest cells the window kept of the stale 200 + res = _cached(16, stale[:40] + [400 + k % 50 for k in range(60)], 1) + busy = busy.result() + for r in (res, busy): + assert r.status_code == 200, r.body + text = _log() + assert "trimmed to the" in text, "the started slot was not trimmed, so the case was not reached" + assert "should not happen" not in text + + @pytest.mark.parametrize("policy", ["fcfs", "cost"]) def test_the_old_policy_knob_selects_the_policy(policy): os.environ.pop("LLAMA_ARG_PREEMPT_POLICY", None) From 51d53d59fcaaa1f15790164fad76f4fe16631999 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 18 Oct 2026 04:14:37 -0700 Subject: [PATCH 068/109] server: let fcfs park the oldest when only it can make room for a running n_cmpl > 1 request An n_cmpl > 1 request shares one sequence and cannot be parked, so beside one the oldest may be the only candidate; parking it lets both finish, as the cost policy already does with its leader. A held prompt takes no cells, so it does not open the exemption. --- tools/server/server-context.cpp | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 58113fecf258..4a79141c857e 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4472,11 +4472,27 @@ struct server_context_impl { } } - server_slot * victim = nullptr; + const auto pick = [&](const server_slot * exempt) { + server_slot * res = nullptr; - for (auto & slot : slots) { - if (&slot != oldest && preempt_victim_eligible(slot, nullptr, true) && (!victim || slot.task->id > victim->task->id)) { - victim = &slot; + for (auto & slot : slots) { + if (&slot != exempt && preempt_victim_eligible(slot, nullptr, true) && (!res || slot.task->id > res->task->id)) { + res = &slot; + } + } + + return res; + }; + + server_slot * victim = pick(oldest); + + // [TAG_PREEMPT] Beside n_cmpl > 1 slots the oldest may be the only slot that can be parked; parking it lets them finish. A held one would not take the cells, so it does not count. + if (!victim && oldest) { + for (const auto & slot : slots) { + if (slot.is_processing() && !slot.preempt_is_out() && preempt_is_family(slot) && !preempt_held(slot)) { + victim = pick(nullptr); + break; + } } } From fcb5f3319908a058c7fe6082a0b59aaeeda0a6c4 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 18 Oct 2026 04:32:02 -0700 Subject: [PATCH 069/109] server tests: give the oldest-at-the-window-end case a window long enough to see the park The tiny model fills a 256-cell window in milliseconds, so the parked prompt was often resumed before the test saw it. An 8192-cell window keeps the park open for seconds; the case is fcfs only, since a larger newcomer is rightly parked over under the cost policy. --- tools/server/tests/unit/test_preempt.py | 26 ++++++++++++------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index cca358982f88..363be1222a45 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1584,23 +1584,20 @@ def test_fcfs_resumes_parked_requests_in_arrival_order(): assert resumed.index(1) < resumed.index(2), resumed -@pytest.mark.parametrize("policy", ["fcfs", "cost"]) -def test_the_oldest_runs_to_the_end_of_the_window_beside_a_held_prompt(policy): - os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy - _start(n_ctx=256, n_slots=3, n_batch=64, n_ubatch=64, cache_ram=0) +def test_fcfs_runs_the_oldest_to_the_end_of_the_window_beside_a_held_prompt(): + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = "fcfs" + # a long window: the tiny model decodes thousands of tokens a second, and the park must last long enough to be seen + _serve_with_training_context(8192) + _start(n_ctx=8192, n_slots=3, n_batch=256, n_ubatch=256, cache_ram=0) with ThreadPoolExecutor(2) as pool: # a livelock never ends, so the bound is the test's verdict; it is generous for a loaded host - oldest = pool.submit(lambda: server.make_request("POST", "/completion", timeout=180, data={ - "n_predict": 1000, "prompt": [100 + k % 50 for k in range(20)], "id_slot": 0, "cache_prompt": True, + oldest = pool.submit(lambda: server.make_request("POST", "/completion", timeout=300, data={ + "n_predict": 100000, "prompt": [100 + k % 50 for k in range(20)], "id_slot": 0, "cache_prompt": True, "ignore_eos": True, "temperature": 0.0, "seed": 42})) - deadline = time.time() + 180 - while time.time() < deadline and _n_decoded(_slot_view(0)) < 130: - time.sleep(0.02) - # the oldest must also be the largest, or the cost policy rightly parks it for the next prompt - assert _n_decoded(_slot_view(0)) >= 130, "the oldest did not reach the window's last quarter in time" - # does not fit beside the oldest, so it is parked holding nothing and is owed the cells first - parked = pool.submit(_cached, 16, [200 + k % 50 for k in range(125)], 1) - assert _wait_preempted() + _wait_processing([0]) + # cannot fit beside the oldest as it grows, so it is parked and is owed the cells first + parked = pool.submit(_cached, 16, [200 + k % 50 for k in range(8100)], 1) + assert _wait_preempted(120), "the second request was never parked, so the case was not reached" # held behind the parked one: a running slot, but no candidate, so the oldest is the only one left to pick held = _cached(16, [300 + k % 50 for k in range(30)], 2) oldest = oldest.result() @@ -1610,6 +1607,7 @@ def test_the_oldest_runs_to_the_end_of_the_window_beside_a_held_prompt(policy): assert oldest.body["stop_type"] == "limit", oldest.body assert oldest.body["preempt"]["parks"] == 0, "the oldest was parked at the end of the window" assert parked.body["preempt"]["parks"] > 0 + assert "prompt held" in _log(), "no prompt was held behind the parked one, so the case was not reached" def test_a_started_slot_trimmed_below_its_sliding_window_prefills_again(): From 833fa33277edd9f33d4e34c138381299215fa44d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 18 Oct 2026 06:34:22 -0700 Subject: [PATCH 070/109] server tests: hold the window-end case until the oldest cannot share the pool, and allow one rotation On a slow runner the oldest had barely started when the long prompt arrived, so both fit and nothing was parked. Wait until it has decoded 100 tokens first. A slow host may also rotate the oldest out once for the head parked 30 s; bound the parks instead of requiring none, since the livelock parks thousands of times. --- tools/server/tests/unit/test_preempt.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 363be1222a45..b6499e008891 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1594,8 +1594,11 @@ def test_fcfs_runs_the_oldest_to_the_end_of_the_window_beside_a_held_prompt(): oldest = pool.submit(lambda: server.make_request("POST", "/completion", timeout=300, data={ "n_predict": 100000, "prompt": [100 + k % 50 for k in range(20)], "id_slot": 0, "cache_prompt": True, "ignore_eos": True, "temperature": 0.0, "seed": 42})) - _wait_processing([0]) - # cannot fit beside the oldest as it grows, so it is parked and is owed the cells first + deadline = time.time() + 180 + while time.time() < deadline and _n_decoded(_slot_view(0)) < 100: + time.sleep(0.02) + assert _n_decoded(_slot_view(0)) >= 100, "the oldest did not start generating in time" + # 120 cells and growing beside 8116: it cannot fit, so it is parked and is owed the cells first parked = pool.submit(_cached, 16, [200 + k % 50 for k in range(8100)], 1) assert _wait_preempted(120), "the second request was never parked, so the case was not reached" # held behind the parked one: a running slot, but no candidate, so the oldest is the only one left to pick @@ -1605,7 +1608,8 @@ def test_fcfs_runs_the_oldest_to_the_end_of_the_window_beside_a_held_prompt(): for res in (oldest, parked, held): assert res.status_code == 200, res.body assert oldest.body["stop_type"] == "limit", oldest.body - assert oldest.body["preempt"]["parks"] == 0, "the oldest was parked at the end of the window" + # a slow host may rotate the oldest out once for the head parked 30 s; the livelock parks it thousands of times + assert oldest.body["preempt"]["parks"] <= 2, f"the oldest was parked {oldest.body['preempt']['parks']} times" assert parked.body["preempt"]["parks"] > 0 assert "prompt held" in _log(), "no prompt was held behind the parked one, so the case was not reached" From de519a4726b35dbd08c421d2dc905b97b7ba1293 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 18 Oct 2026 09:31:34 -0700 Subject: [PATCH 071/109] server tests: run the window-end case on a 4096-cell window A loaded CI runner prefilled the 8100-token prompt in about two minutes and decoded the oldest far slower, so the 8192 window outlasted the 300 s bound with nothing parked twice. 4096 cells keep the park open for seconds on a fast host and bound the case at 600 s; a server without the fcfs fix still never finishes it. --- tools/server/tests/unit/test_preempt.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index b6499e008891..855372768554 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1586,20 +1586,21 @@ def test_fcfs_resumes_parked_requests_in_arrival_order(): def test_fcfs_runs_the_oldest_to_the_end_of_the_window_beside_a_held_prompt(): os.environ["LLAMA_ARG_PREEMPT_POLICY"] = "fcfs" - # a long window: the tiny model decodes thousands of tokens a second, and the park must last long enough to be seen - _serve_with_training_context(8192) - _start(n_ctx=8192, n_slots=3, n_batch=256, n_ubatch=256, cache_ram=0) + # a long window: the tiny model decodes thousands of tokens a second, and the park must last long enough to be seen; + # not longer, since a loaded CI runner prefills and decodes it hundreds of times slower + _serve_with_training_context(4096) + _start(n_ctx=4096, n_slots=3, n_batch=256, n_ubatch=256, cache_ram=0) with ThreadPoolExecutor(2) as pool: # a livelock never ends, so the bound is the test's verdict; it is generous for a loaded host - oldest = pool.submit(lambda: server.make_request("POST", "/completion", timeout=300, data={ + oldest = pool.submit(lambda: server.make_request("POST", "/completion", timeout=600, data={ "n_predict": 100000, "prompt": [100 + k % 50 for k in range(20)], "id_slot": 0, "cache_prompt": True, "ignore_eos": True, "temperature": 0.0, "seed": 42})) deadline = time.time() + 180 while time.time() < deadline and _n_decoded(_slot_view(0)) < 100: time.sleep(0.02) assert _n_decoded(_slot_view(0)) >= 100, "the oldest did not start generating in time" - # 120 cells and growing beside 8116: it cannot fit, so it is parked and is owed the cells first - parked = pool.submit(_cached, 16, [200 + k % 50 for k in range(8100)], 1) + # 120 cells and growing beside 4016: it cannot fit, so it is parked and is owed the cells first + parked = pool.submit(_cached, 16, [200 + k % 50 for k in range(4000)], 1) assert _wait_preempted(120), "the second request was never parked, so the case was not reached" # held behind the parked one: a running slot, but no candidate, so the oldest is the only one left to pick held = _cached(16, [300 + k % 50 for k in range(30)], 2) From 18b4ec5f17190e8f2cd0cad560214a938f200324 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 19 Oct 2026 10:52:49 -0700 Subject: [PATCH 072/109] ci: re-run the checks on this head From 27725121253031aa948860d9ee9f48899def1aaa Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 20 Oct 2026 19:32:04 -0700 Subject: [PATCH 073/109] server: match upstream's recv_with_timeout deadline hunk verbatim Upstream ggml-org#29707 (first in b11769) made the same deadline change to server_response::recv_with_timeout. Keeping our comment and blank line around the identical line turned it into an add/add conflict that additive_merge refuses (the same line added twice). With the hunk byte identical to upstream, older bases still get the deadline fix from this pin and b11769+ merge it as one change made on both sides. --- tools/server/server-queue.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/tools/server/server-queue.cpp b/tools/server/server-queue.cpp index bf7cd68e6a79..59407e2803ba 100644 --- a/tools/server/server-queue.cpp +++ b/tools/server/server-queue.cpp @@ -448,9 +448,7 @@ server_task_result_ptr server_response::recv(const std::unordered_set & id_ } server_task_result_ptr server_response::recv_with_timeout(const std::unordered_set & id_tasks, int timeout) { - // [TAG_PREEMPT] The timeout is a deadline: send() wakes all waiters for every result, and wait_for() restarted the wait on each wakeup. const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout); - while (true) { std::unique_lock lock(mutex_results); From 15b4e3bd090ce2ad6720afcb67ee2d1830447f78 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 20 Oct 2026 22:42:50 -0700 Subject: [PATCH 074/109] server: never pick a TTS or realtime transcription slot to park Upstream b11780/b11781 added slots that drive their own decode loop (process_tts_slots) or take their rows from an audio stream. Neither has a token prompt a recompute resume could replay, so keep them out of the victim set the same way n_cmpl > 1 slots are. --- tools/server/server-context.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index dfebf01faa98..6d7c5872ddea 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4795,6 +4795,11 @@ struct server_context_impl { return false; // n_cmpl > 1 slots share one sequence } + // TTS and realtime transcription slots feed their own decode loop, not a token prompt a resume could replay + if (slot.task && (slot.task->type == SERVER_TASK_TYPE_TTS || slot.task->type == SERVER_TASK_TYPE_TRANSCRIBE_RT)) { + return false; + } + // A started slot about to be rejected gets its own 4xx; a park notice would turn it into 200 plus an in-stream error. if (slot.state == SLOT_STATE_STARTED) { std::string msg; From 27ce31b8ffd562be557ebce9c3ae15e3f2d20dd1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 03:24:42 -0700 Subject: [PATCH 075/109] server: one parkable check for every victim and rotation selector Rotation skipped only n_cmpl > 1 slots, so it could pick a TTS or realtime transcription resident; parked by dropping its cells, that slot resumed into PROCESSING_PROMPT, which the prompt loop never advances for either type. server_task::preempt_resumable() now decides it for the ordinary victim check, rotation and the park-every-N test knob, and preempt_park() refuses a slot it rejects. --- tests/CMakeLists.txt | 3 +++ tests/test-server-preempt-kind.cpp | 39 ++++++++++++++++++++++++++++++ tools/server/server-context.cpp | 21 ++++++++++------ tools/server/server-task.h | 10 ++++++++ 4 files changed, 65 insertions(+), 8 deletions(-) create mode 100644 tests/test-server-preempt-kind.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 38ee7a5f7ccc..dc49bcfe6f4f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -374,6 +374,9 @@ if (LLAMA_BUILD_TOOLS AND LLAMA_BUILD_SERVER AND NOT EMSCRIPTEN) llama_build_and_test(test-server-decision-exact.cpp) target_link_libraries(test-server-decision-exact PRIVATE server-context mtmd) target_include_directories(test-server-decision-exact PRIVATE ${PROJECT_SOURCE_DIR}/tools/server ${PROJECT_SOURCE_DIR}/tools/mtmd) + llama_build_and_test(test-server-preempt-kind.cpp) + target_link_libraries(test-server-preempt-kind PRIVATE server-context mtmd) + target_include_directories(test-server-preempt-kind PRIVATE ${PROJECT_SOURCE_DIR}/tools/server ${PROJECT_SOURCE_DIR}/tools/mtmd) endif() # GGUF model data fetcher library for tests that need real model metadata diff --git a/tests/test-server-preempt-kind.cpp b/tests/test-server-preempt-kind.cpp new file mode 100644 index 000000000000..f3c1982cdbb1 --- /dev/null +++ b/tests/test-server-preempt-kind.cpp @@ -0,0 +1,39 @@ +// [TAG_PREEMPT] Which tasks a park may pick. Every victim and rotation selector asks server_task::preempt_resumable(): +// a TTS or realtime transcription slot feeds its own decode loop, so a resume could not replay it as a prompt. + +#include "server-task.h" + +#include + +#undef NDEBUG +#include + +static server_task make_task(server_task_type type) { + server_task task(type); + task.id = 1; + return task; +} + +int main() { + // a token prompt is replayed on resume + assert(make_task(SERVER_TASK_TYPE_COMPLETION).preempt_resumable()); + assert(make_task(SERVER_TASK_TYPE_INFILL).preempt_resumable()); + assert(make_task(SERVER_TASK_TYPE_EMBEDDING).preempt_resumable()); + assert(make_task(SERVER_TASK_TYPE_RERANK).preempt_resumable()); + assert(make_task(SERVER_TASK_TYPE_DECISION).preempt_resumable()); + + // their rows come from the vocoder loop or the audio stream, not from a prompt + assert(!make_task(SERVER_TASK_TYPE_TTS).preempt_resumable()); + assert(!make_task(SERVER_TASK_TYPE_TRANSCRIBE_RT).preempt_resumable()); + + // n_cmpl > 1 slots share one sequence + server_task parent = make_task(SERVER_TASK_TYPE_COMPLETION); + parent.add_child(parent.id, 2); + assert(parent.is_parent()); + assert(!parent.preempt_resumable()); + assert(parent.child_tasks[0].is_child()); + assert(!parent.child_tasks[0].preempt_resumable()); + + printf("ok: TTS, realtime transcription and n_cmpl > 1 tasks are never picked to park\n"); + return 0; +} diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 6d7c5872ddea..ba79a156be7c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4775,6 +4775,11 @@ struct server_context_impl { return res; } + // [TAG_PREEMPT] The one check every victim and rotation selector applies, and preempt_park() enforces: see server_task::preempt_resumable(). + static bool preempt_parkable(const server_slot & slot) { + return slot.task && slot.task->preempt_resumable(); + } + bool preempt_victim_eligible(server_slot & slot, const server_slot * exempt, bool recompute) { // Before the batch is built every slot is at a token boundary; a slot holding no cells is still worth parking. if (slot.state != SLOT_STATE_GENERATING && @@ -4791,12 +4796,7 @@ struct server_context_impl { return false; } - if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { - return false; // n_cmpl > 1 slots share one sequence - } - - // TTS and realtime transcription slots feed their own decode loop, not a token prompt a resume could replay - if (slot.task && (slot.task->type == SERVER_TASK_TYPE_TTS || slot.task->type == SERVER_TASK_TYPE_TRANSCRIBE_RT)) { + if (!preempt_parkable(slot)) { return false; } @@ -5011,6 +5011,11 @@ struct server_context_impl { // [TAG_PREEMPT] Sync parks finish here, async ones are counted by update_preempt_copies() when they land. The notice is sent with the save, since the slot is already detached and silent. bool preempt_park(server_slot & slot, int64_t t_start, bool recompute = false) { + if (!preempt_parkable(slot)) { + SLT_WRN(slot, "%s", "not parked: this slot cannot be resumed by replaying its prompt\n"); + return false; + } + slot.t_preempt_copy_us = t_start; preempt_maybe_out = true; @@ -5317,7 +5322,7 @@ struct server_context_impl { continue; } - if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { + if (!preempt_parkable(slot)) { continue; } @@ -5472,7 +5477,7 @@ struct server_context_impl { if (preempt_test_every > 0) { for (auto & slot : slots) { - if (slot.state != SLOT_STATE_GENERATING || + if (slot.state != SLOT_STATE_GENERATING || !preempt_parkable(slot) || (int32_t) slot.stats.n_gen < (slot.n_preempt + 1) * preempt_test_every) { continue; } diff --git a/tools/server/server-task.h b/tools/server/server-task.h index df7b7f3f87ac..4fde60a6c04a 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -322,6 +322,16 @@ struct server_task { return id_parent != -1; } + // [TAG_PREEMPT] Whether a slot running this task may be picked to park: TTS and realtime transcription feed their own decode loop, + // not a token prompt a resume could replay, and n_cmpl > 1 tasks share one sequence. Every victim and rotation selector asks this. + bool preempt_resumable() const { + if (is_parent() || is_child()) { + return false; + } + + return type != SERVER_TASK_TYPE_TTS && type != SERVER_TASK_TYPE_TRANSCRIBE_RT; + } + // embedding and rerank tasks always process their whole prompt, their state is never reused bool is_stateless() const { return type == SERVER_TASK_TYPE_EMBEDDING || type == SERVER_TASK_TYPE_RERANK; From b6be4a093f6a102599fdfcd0ce1c4926b0bb81f3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 04:26:59 -0700 Subject: [PATCH 076/109] cuda: claim a paged FLASH_ATTN_EXT only in the shapes the paged kernel launches supports_op did not check the page table width, whole 256-cell pages or the mask extent that the launch asserts or the kernel reads, so the scheduler could hand CUDA a paged op it then aborted on. One shape check now serves both. The load-time probe built K over one page but a table for the whole pool; it now builds the shape the graph builds. --- ggml/src/ggml-cuda/fattn.cu | 46 +++++++++------- src/llama-kv-cache.cpp | 3 +- tests/CMakeLists.txt | 3 + tests/test-paged-fa-supports.cpp | 95 ++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 20 deletions(-) create mode 100644 tests/test-paged-fa-supports.cpp diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index bf8bb64cd15c..a3a3ceb105d0 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -759,19 +759,34 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d return f16_extra.end - (uintptr_t) dst->data; } +// [TAG_EXACT_CONCURRENCY] The shapes the paged kernel can run: one-column F16 vector kernel, whole 256-cell pages, a table row of +// [count, page IDs...] per query and a mask row per query covering every cell. supports_op answers with this and the launch asserts it. +static bool ggml_cuda_fattn_paged_shape_ok(const ggml_tensor * dst) { + const ggml_tensor * Q = dst->src[0]; + const ggml_tensor * K = dst->src[1]; + const ggml_tensor * V = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * pages = ggml_cuda_fattn_pages(dst); + + float softcap; + memcpy(&softcap, (const float *) dst->op_params + 2, sizeof(softcap)); + + return pages && mask && + Q->ne[0] == 256 && K->ne[0] == 256 && V->ne[0] == 256 && + K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16 && + Q->ne[3] == 1 && Q->ne[2] % K->ne[2] == 0 && + K->ne[1] % FATTN_KQ_STRIDE == 0 && + mask->ne[0] >= K->ne[1] && mask->ne[1] >= Q->ne[1] && + pages->type == GGML_TYPE_I32 && ggml_is_contiguous(pages) && + pages->ne[0] == 1 + K->ne[1]/FATTN_KQ_STRIDE && pages->ne[1] == Q->ne[1] && + softcap == 0.0f; +} + void ggml_cuda_flash_attn_ext(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { ggml_cuda_set_device(ctx.device); - if (const ggml_tensor * pages = ggml_cuda_fattn_pages(dst)) { - GGML_ASSERT(dst->src[0]->ne[0] == 256 && dst->src[2]->ne[0] == 256); - GGML_ASSERT(dst->src[1]->type == GGML_TYPE_F16 && dst->src[2]->type == GGML_TYPE_F16); - GGML_ASSERT(dst->src[3] && dst->src[0]->ne[3] == 1); - GGML_ASSERT(pages->type == GGML_TYPE_I32 && ggml_is_contiguous(pages)); - GGML_ASSERT(pages->ne[0] == 1 + dst->src[1]->ne[1]/FATTN_KQ_STRIDE); - GGML_ASSERT(pages->ne[1] == dst->src[0]->ne[1]); - float softcap; - memcpy(&softcap, (const float *) dst->op_params + 2, sizeof(softcap)); - GGML_ASSERT(softcap == 0.0f); + if (ggml_cuda_fattn_pages(dst)) { + GGML_ASSERT(ggml_cuda_fattn_paged_shape_ok(dst)); fattn_kernel_t kernel = flash_attn_ext_vec<256, 1, GGML_TYPE_F16, GGML_TYPE_F16, false, true>; launch_fattn<256, 1, 1>(ctx, dst, kernel, 4, 0, 128, false, false, false, /*use_sparse =*/ false); return; @@ -824,18 +839,11 @@ void ggml_cuda_flash_attn_ext(ggml_backend_cuda_context & ctx, ggml_tensor * dst bool ggml_cuda_flash_attn_ext_supported(int device, const ggml_tensor * dst) { // [TAG_EXACT_CONCURRENCY] the paged path always runs the one-column F16 vector kernel, whatever the batch size or arch - if (const ggml_tensor * pages = ggml_cuda_fattn_pages(dst)) { + if (ggml_cuda_fattn_pages(dst)) { #ifndef FLASH_ATTN_AVAILABLE return false; #endif // FLASH_ATTN_AVAILABLE - float softcap; - memcpy(&softcap, (const float *) dst->op_params + 2, sizeof(softcap)); - - return dst->src[0]->ne[0] == 256 && dst->src[1]->ne[0] == 256 && dst->src[2]->ne[0] == 256 && - dst->src[1]->type == GGML_TYPE_F16 && dst->src[2]->type == GGML_TYPE_F16 && - dst->src[3] && dst->src[0]->ne[3] == 1 && dst->src[0]->ne[2] % dst->src[1]->ne[2] == 0 && - pages->type == GGML_TYPE_I32 && ggml_is_contiguous(pages) && pages->ne[1] == dst->src[0]->ne[1] && - softcap == 0.0f; + return ggml_cuda_fattn_paged_shape_ok(dst); } return ggml_cuda_get_best_fattn_kernel(device, dst) != BEST_FATTN_KERNEL_NONE; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 302c5e45c108..45a1c13bd0c4 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -101,7 +101,8 @@ static bool llama_dev_supports_paged_attn( bool res = true; - const int64_t n_kv = page_size; + // the graph's K/V span the whole pool and its page table is sized for it (get_n_kv(), build_input_pages()) + const int64_t n_kv = n_cells; for (const int64_t n_tokens : { (int64_t) 1, (int64_t) 4, (int64_t) 16, (int64_t) 512 }) { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, n_embd_head_k, n_tokens, n_head, 1); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index dc49bcfe6f4f..e28fdc6c12dd 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -325,6 +325,9 @@ endif() # [TAG_EXACT_CONCURRENCY] the event query a backend publishes through its registry is found and answers llama_build_and_test(test-event-query.cpp LINK ggml) +# [TAG_EXACT_CONCURRENCY] a paged FLASH_ATTN_EXT is claimed only in the shapes the paged kernel launches +llama_build_and_test(test-paged-fa-supports.cpp LINK ggml) + llama_build_and_test(test-tiled-mulmat.cpp LINK ggml) llama_build_and_test(test-model-load-cancel.cpp LABEL "model") llama_build_and_test(test-autorelease.cpp LABEL "model") diff --git a/tests/test-paged-fa-supports.cpp b/tests/test-paged-fa-supports.cpp new file mode 100644 index 000000000000..65a55481a9d2 --- /dev/null +++ b/tests/test-paged-fa-supports.cpp @@ -0,0 +1,95 @@ +// [TAG_EXACT_CONCURRENCY] A device that claims a paged FLASH_ATTN_EXT must be able to launch it: every shape the +// paged kernel refuses at launch has to be refused by supports_op first, so the scheduler never hands it one. + +#include "ggml.h" +#include "ggml-backend.h" + +#include +#include +#include + +struct paged_shape { + const char * name; + int64_t n_kv; // K/V cells + int64_t n_tokens; // queries + int64_t width; // page table row width, 1 + n_kv/256 is what the kernel indexes + int64_t mask_rows; // mask rows, one per query at least + int64_t mask_cols; // mask columns, one per K cell at least + bool valid; +}; + +static bool supports(ggml_backend_dev_t dev, const paged_shape & s) { + ggml_init_params ip = { + /*.mem_size =*/ ggml_tensor_overhead()*16 + ggml_graph_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context * ctx = ggml_init(ip); + + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 256, s.n_tokens, 8, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 256, s.n_kv, 2, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 256, s.n_kv, 2, 1); + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, s.mask_cols, s.mask_rows, 1, 1); + + ggml_tensor * op = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/sqrtf(256.0f), 0.0f, 0.0f); + ggml_prec_set_acc(op, GGML_PREC_F32); + op->src[5] = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, s.width, s.n_tokens); + + const bool res = ggml_backend_dev_supports_op(dev, op); + + ggml_free(ctx); + + return res; +} + +int main() { + ggml_backend_load_all(); + + const paged_shape shapes[] = { + { "1024 cells, 4 queries", 1024, 4, 5, 4, 1024, true }, + { "512 cells, 1 query", 512, 1, 3, 1, 512, true }, + { "table one page too narrow", 1024, 4, 4, 4, 1024, false }, + { "table one page too wide", 1024, 4, 6, 4, 1024, false }, + { "table of one column", 512, 4, 1, 4, 512, false }, + { "cells not a whole number of pages", 1000, 4, 4, 4, 1000, false }, + { "mask with fewer rows than queries", 1024, 4, 5, 3, 1024, false }, + { "mask narrower than the cells", 1024, 4, 5, 4, 768, false }, + }; + + int rc = 0; + int n_checked = 0; + + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + const char * reg_name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)); + + // only the CUDA backend reads the page table; the others are kept off this path by llama_exact_backend_name() + if (strcmp(reg_name, "CUDA") != 0) { + continue; + } + + if (!supports(dev, shapes[0])) { + printf("%s: no paged flash attention in this build, skipped\n", ggml_backend_dev_name(dev)); + continue; + } + + n_checked++; + + for (const auto & s : shapes) { + const bool got = supports(dev, s); + printf("%s: %-36s supports_op %d, launchable %d\n", ggml_backend_dev_name(dev), s.name, got, s.valid); + if (got != s.valid) { + rc = 1; + } + } + } + + if (n_checked == 0) { + printf("no CUDA device with paged flash attention, nothing to check\n"); + } else { + printf("%s\n", rc == 0 ? "ok: supports_op accepts exactly the paged shapes the kernel launches" : + "FAIL: supports_op and the paged launch disagree"); + } + + return rc; +} From 88c9cce28659080bcd690c2c024227fed5a421b3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 04:26:59 -0700 Subject: [PATCH 077/109] llama : refuse a negative position as an invalid batch under exact concurrency A fresh sequence at position -1 passed batch validation and reached the paged allocator's assertion. decode() now returns -1 for it, as for shared tokens. --- src/llama-context.cpp | 12 ++++++++++++ tests/test-exact-pages.cpp | 13 +++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 0eb283e6cd61..6e953f8800a3 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1968,6 +1968,18 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -1; } + // [TAG_EXACT_CONCURRENCY] a page is keyed by position/page size, so a negative position has no page: refuse it as invalid input + if (llama_exact_concurrency()) { + const llama_batch & batch = balloc->get_batch(); + + for (int32_t i = 0; i < batch.n_tokens; ++i) { + if (batch.pos[i] < 0) { + LLAMA_LOG_ERROR("%s: exact concurrency needs non-negative positions (token %d is at %d)\n", __func__, i, batch.pos[i]); + return -1; + } + } + } + const uint32_t n_tokens_all = balloc->get_n_tokens(); const uint32_t n_outputs_all = balloc->get_n_outputs(); diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index 69cd322a1cdf..40045ad76e8e 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -79,6 +79,19 @@ int main(int argc, char ** argv) { return 1; } + { + // a negative position is an invalid batch: decode refuses it, it never reaches the page allocator + common_batch batch(ctx); + batch.add(1, -1, 1, true); + + const int32_t ret = llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + + if (ret >= 0 || llama_memory_seq_pos_max(mem, 1) != -1) { + fprintf(stderr, "%s : a token at position -1 was not refused as an invalid batch (decode returned %d)\n", __func__, ret); + return 1; + } + } + if (!decode_range(ctx, 0, 0, 599)) { fprintf(stderr, "%s : failed to fill sequence 0\n", __func__); return 1; From 89233995c223d09987983e82c3202723f0fa1fc1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 04:26:59 -0700 Subject: [PATCH 078/109] server: never give up a batch holding a realtime transcription's audio rows The rows are consumed when the batch is built and the audio stream does not produce them again, so the last resort's rewind would drop them. It keeps the old path while such a slot is running. --- tools/server/server-context.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index ba79a156be7c..2a2b2ec4663c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -6851,6 +6851,13 @@ struct server_context_impl { return false; } + // [TAG_PREEMPT] A realtime transcription slot's audio rows are consumed when the batch is built and its stream does not produce them again, so the batch cannot be given up and rebuilt: keep the old path. + for (const auto & slot : slots) { + if (slot.is_processing() && !slot.preempt_is_out() && slot.audio_stream) { + return false; + } + } + // [TAG_PREEMPT_ASYNC] A restoring slot holds its cells but is skipped below, so land it first: it may be the only other resident. for (auto & slot : slots) { if (slot.state != SLOT_STATE_RESTORING) { From 5149d088269b936d2fd10657aa2beb14e6da10ee Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 04:26:59 -0700 Subject: [PATCH 079/109] tests: check both forks in test-rpc-paged-fa, send overflow prompts together A failed server fork reached kill(-1, SIGKILL) and waitpid(-1). The two overflow assertions now submit both prompts in one request instead of relying on seeing the leader busy before the follower is sent. --- tests/test-rpc-paged-fa.cpp | 8 ++++++++ tools/server/tests/unit/test_preempt.py | 12 ++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp index 058965ccdfce..53bc5357f78a 100644 --- a/tests/test-rpc-paged-fa.cpp +++ b/tests/test-rpc-paged-fa.cpp @@ -73,6 +73,10 @@ static bool port_open(int port) { static int run_client(const std::string & endpoint, bool paged) { const pid_t pid = fork(); + if (pid < 0) { + perror("fork the RPC client"); + return -1; + } if (pid == 0) { send_graph(endpoint, paged); } @@ -86,6 +90,10 @@ int main() { const std::string endpoint = "127.0.0.1:" + std::to_string(port); const pid_t server = fork(); + if (server < 0) { + perror("fork the RPC server"); + return 1; // nothing to kill: kill(-1) would signal every process this user owns + } if (server == 0) { ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); ggml_backend_rpc_start_server(endpoint.c_str(), nullptr, 1, 1, &dev); diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 855372768554..750c45775c68 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -131,6 +131,14 @@ def _complete_overlapping(n_predict, n_prompt, timeout: float = DEFAULT_REQUEST_ return [first.result(), second] +def _complete_together(n_predict: int, n_prompt, timeout: float = DEFAULT_REQUEST_TIMEOUT): + """Both prompts in one request, so they are queued at once and overlap whatever the client's or the host's speed.""" + return server.make_request("POST", "/completion", data={ + "n_predict": n_predict, "prompt": [_prompt_of(n_prompt[0], _PROMPT_A), _prompt_of(n_prompt[1], _PROMPT_B)], + "ignore_eos": True, "temperature": 0.0, "seed": 42, "cache_prompt": False, + }, timeout=timeout) + + def _wait_preempted(timeout: float = 30.0) -> bool: """True once some slot is parked: its cells are in host RAM and it wants them back.""" deadline = time.time() + timeout @@ -257,7 +265,7 @@ def test_a_request_that_cannot_be_helped_gets_the_context_error_and_the_server_l _start(n_ctx=256) if knob == "ram-0": - assert any(res.status_code != 200 for res in _complete_overlapping((110, 100), (120, 60))) + assert _complete_together(110, (120, 60)).status_code != 200 else: res = server.make_request("POST", "/completion", data={ "n_predict": 160, "n_cmpl": 2, "prompt": _PROMPT_A, @@ -284,7 +292,7 @@ def test_a_server_that_never_asked_for_parking_behaves_as_upstream(): assert "preemption:" not in text, "a server that did not ask for parking announced it" assert _ASYNC_BANNER not in text, "the async park path was set up without being asked for" - assert any(res.status_code != 200 for res in _complete_overlapping((110, 100), (120, 60))) + assert _complete_together(110, (120, 60)).status_code != 200 text = _log() assert "Context size has been exceeded" in text From 2a2d23209ce81266ed095c17ff71591fd7172a62 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 07:09:45 -0700 Subject: [PATCH 080/109] ci: leave bench.yml.disabled as upstream has it The action SHA pins came from the fork's own pinning pass, not from this pin; the fork has since removed the file, and the prebuilt uses upstream's copy. --- .github/workflows/bench.yml.disabled | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/bench.yml.disabled b/.github/workflows/bench.yml.disabled index 5829359ad10e..f2d7e16e981a 100644 --- a/.github/workflows/bench.yml.disabled +++ b/.github/workflows/bench.yml.disabled @@ -162,7 +162,7 @@ jobs: tools/server/bench/*.log - name: Commit status - uses: Sibz/github-status-action@faaa4d96fecf273bd762985e0e7f9f933c774918 # v1 + uses: Sibz/github-status-action@v1 with: authToken: ${{secrets.GITHUB_TOKEN}} sha: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} @@ -172,7 +172,7 @@ jobs: state: 'success' - name: Upload benchmark images - uses: devicons/public-upload-to-imgur@352cf5f2805c692539a96cfe49a09669e6fca88e # v2.2.2 + uses: devicons/public-upload-to-imgur@v2.2.2 continue-on-error: true # Important as it looks unstable: 503 id: imgur_step with: @@ -221,7 +221,7 @@ jobs: echo "IMAGE_3=${{ fromJSON(steps.imgur_step.outputs.imgur_urls)[3] }}" >> $GITHUB_ENV - name: Comment PR - uses: mshick/add-pr-comment@b8f338c590a895d50bcbfa6c5859251edc8952fc # v2 + uses: mshick/add-pr-comment@v2 id: comment_pr if: ${{ github.event.pull_request != '' && matrix.pr_comment_enabled == 'true' }} with: From 00d60d475b4b12385ea75eda75fc81094c6da821 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 07:09:45 -0700 Subject: [PATCH 081/109] ggml : one mask plane on the paged FLASH_ATTN_EXT path, and no page table on zDNN The paged vector kernel reads the mask without a head offset, so a mask with a plane per head was claimed and then applied to every head from plane 0; the dense path already refuses mask->ne[2] != 1. zDNN gained flash attention upstream after the other backends were taught to refuse a page table. --- ggml/src/ggml-cuda/fattn.cu | 4 ++-- ggml/src/ggml-zdnn/fattn.cpp | 3 ++- tests/test-paged-fa-supports.cpp | 5 ++++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index a3a3ceb105d0..b775ed7834ab 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -760,7 +760,7 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d } // [TAG_EXACT_CONCURRENCY] The shapes the paged kernel can run: one-column F16 vector kernel, whole 256-cell pages, a table row of -// [count, page IDs...] per query and a mask row per query covering every cell. supports_op answers with this and the launch asserts it. +// [count, page IDs...] per query and a mask row per query covering every cell, shared by every head. supports_op answers with this and the launch asserts it. static bool ggml_cuda_fattn_paged_shape_ok(const ggml_tensor * dst) { const ggml_tensor * Q = dst->src[0]; const ggml_tensor * K = dst->src[1]; @@ -776,7 +776,7 @@ static bool ggml_cuda_fattn_paged_shape_ok(const ggml_tensor * dst) { K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16 && Q->ne[3] == 1 && Q->ne[2] % K->ne[2] == 0 && K->ne[1] % FATTN_KQ_STRIDE == 0 && - mask->ne[0] >= K->ne[1] && mask->ne[1] >= Q->ne[1] && + mask->ne[0] >= K->ne[1] && mask->ne[1] >= Q->ne[1] && mask->ne[2] == 1 && // one mask plane: the vector kernel has no per-head mask offset pages->type == GGML_TYPE_I32 && ggml_is_contiguous(pages) && pages->ne[0] == 1 + K->ne[1]/FATTN_KQ_STRIDE && pages->ne[1] == Q->ne[1] && softcap == 0.0f; diff --git a/ggml/src/ggml-zdnn/fattn.cpp b/ggml/src/ggml-zdnn/fattn.cpp index 7c7801cbb1dc..3783826f8c6a 100644 --- a/ggml/src/ggml-zdnn/fattn.cpp +++ b/ggml/src/ggml-zdnn/fattn.cpp @@ -21,7 +21,8 @@ bool ggml_zdnn_supports_flash_attn_ext(const ggml_backend_zdnn_device_context * memcpy(&logit_softcap, (const float *) op->op_params + 2, sizeof(float)); // sinks, alibi, softcap and sparse k/v sets are not implemented - if (op->src[4] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { + // [TAG_EXACT_CONCURRENCY] src[5] is the page table, which only the CUDA backend reads + if (op->src[4] != nullptr || op->src[5] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { return false; } diff --git a/tests/test-paged-fa-supports.cpp b/tests/test-paged-fa-supports.cpp index 65a55481a9d2..dc6b63aceafc 100644 --- a/tests/test-paged-fa-supports.cpp +++ b/tests/test-paged-fa-supports.cpp @@ -16,6 +16,7 @@ struct paged_shape { int64_t mask_rows; // mask rows, one per query at least int64_t mask_cols; // mask columns, one per K cell at least bool valid; + int64_t mask_planes = 1; // the paged kernel reads one mask plane for every head }; static bool supports(ggml_backend_dev_t dev, const paged_shape & s) { @@ -29,7 +30,7 @@ static bool supports(ggml_backend_dev_t dev, const paged_shape & s) { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 256, s.n_tokens, 8, 1); ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 256, s.n_kv, 2, 1); ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, 256, s.n_kv, 2, 1); - ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, s.mask_cols, s.mask_rows, 1, 1); + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, s.mask_cols, s.mask_rows, s.mask_planes, 1); ggml_tensor * op = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/sqrtf(256.0f), 0.0f, 0.0f); ggml_prec_set_acc(op, GGML_PREC_F32); @@ -54,6 +55,8 @@ int main() { { "cells not a whole number of pages", 1000, 4, 4, 4, 1000, false }, { "mask with fewer rows than queries", 1024, 4, 5, 3, 1024, false }, { "mask narrower than the cells", 1024, 4, 5, 4, 768, false }, + { "a mask plane per head", 1024, 4, 5, 4, 1024, false, 8 }, + { "a mask plane per K/V head", 1024, 4, 5, 4, 1024, false, 2 }, }; int rc = 0; From df1d0ab7c405ae131bb946b1528f7a01039fb75b Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 07:09:45 -0700 Subject: [PATCH 082/109] common : sum the exact batch geometry in 64 bits A decode width near INT32_MAX wrapped the ubatch + width sum into a negative minimum, so the geometry was accepted. --- common/common.cpp | 7 ++++--- tests/test-exact-geometry.cpp | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/common/common.cpp b/common/common.cpp index 8a4961f4dddf..effe3b133b9d 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1462,13 +1462,14 @@ bool common_exact_batch_geometry(int n_batch, int n_ubatch, int n_decode_width, // 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); - const int n_min = n_ub + std::max(0, n_decode_width); + // 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 = n_min; + *n_batch_min = (int) std::min(n_min, INT32_MAX); } - return n_batch >= n_min; + return n_min <= INT32_MAX && n_batch >= n_min; } // [TAG_EXACT_CONCURRENCY] the refusals that need the loaded model, run before a context exists diff --git a/tests/test-exact-geometry.cpp b/tests/test-exact-geometry.cpp index 4c1d1ff7001a..40941069ea97 100644 --- a/tests/test-exact-geometry.cpp +++ b/tests/test-exact-geometry.cpp @@ -1,6 +1,7 @@ #include "common.h" +#include #include #undef NDEBUG @@ -36,6 +37,11 @@ int main() { assert(common_exact_batch_geometry(512, 512, 0, &n_min)); assert(n_min == 512); + // a decode width near INT32_MAX cannot wrap the sum into an accepted geometry + assert(!common_exact_batch_geometry(512, 512, INT32_MAX, &n_min)); + assert(n_min == INT32_MAX); + assert(!common_exact_batch_geometry(INT32_MAX, 512, INT32_MAX - 1)); + const uint32_t width = llama_exact_decode_width(); assert(!llama_set_exact_decode_width((uint32_t) INT32_MAX + 1)); assert(llama_exact_decode_width() == width); From 4e17297bad9ece7ac04c04937ff348aab345d2d0 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 07:09:45 -0700 Subject: [PATCH 083/109] server: planner accounting fixes for full-context, cache-reuse and decision-group prompts - a prompt held in full needs no extra cell to resume: a non-causal decision of exactly n_ctx tokens is admitted, so it must also fit again after a park - a started slot with n_cache_reuse keeps its whole cached prompt, since cache reuse shifts chunks from beyond the common prefix back in - a decision group member shares only its parent's n_tokens_shared, not its whole input, so its private suffix is counted - the final-capacity sum is taken in 64 bits (n_predict may be INT32_MAX) - the parked-head wait bound in the short-request stream test scales with how long a short request takes on the host --- tools/server/server-context.cpp | 24 +++++++- tools/server/tests/unit/test_preempt.py | 27 ++++++++- .../server/tests/unit/test_preempt_models.py | 56 +++++++++++++++++++ 3 files changed, 103 insertions(+), 4 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 2a2b2ec4663c..c3057035a326 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4363,6 +4363,11 @@ struct server_context_impl { return 0; } + // [TAG_PREEMPT] Cache reuse shifts chunks from beyond the common prefix back in, so the whole cached prompt is kept for it to search. + if (slot.task->params.n_cache_reuse > 0 && llama_memory_can_shift(llama_get_memory(ctx_tgt)) && !slot.prompt.tokens.has_mtmd) { + return slot.prompt.tokens.size(); + } + size_t n_keep = slot.prompt.tokens.get_common_prefix(slot.task->tokens); if (slot.alora_invocation_start > 0) { @@ -4418,13 +4423,25 @@ struct server_context_impl { const int32_t n_mtmd = preempt_n_mtmd_pending(slot, res); const int32_t n_left = slot.preempt_n_input() - res; - res += n_mtmd > 0 ? n_mtmd : std::max(1, std::min((int32_t) llama_n_batch(ctx_tgt), n_left)); + // a prompt held in full needs no further cell: a non-causal one may be exactly n_ctx long, as admission allows + res += n_mtmd > 0 ? n_mtmd : std::max(0, std::min((int32_t) llama_n_batch(ctx_tgt), n_left)); } // [TAG_EXACT_CONCURRENCY] A restore takes fresh pages and its tail page counts in full; undercounting admits a resume find_slot cannot satisfy. return preempt_n_cells(res); } + // [TAG_PREEMPT] Prompt tokens a family member shares with the one charged first: n_cmpl > 1 clones share all of it, a decision group only its parent's first n_tokens_shared. + int32_t preempt_family_n_shared(int family, const server_task & task) const { + for (const auto & other : slots) { + if (other.task && other.task->id == family && other.task->n_tokens_shared > 0) { + return other.task->n_tokens_shared; + } + } + + return task.n_tokens(); + } + int32_t preempt_kv_used() const { int32_t res = 0; @@ -4447,7 +4464,7 @@ struct server_context_impl { const int family = slot.task->is_parent() ? slot.task->id : slot.task->id_parent; if (std::find(charged.begin(), charged.end(), family) != charged.end()) { - res += preempt_n_cells(std::max(0, slot.prompt.n_tokens() - slot.task->n_tokens())); + res += preempt_n_cells(std::max(0, slot.prompt.n_tokens() - preempt_family_n_shared(family, *slot.task))); continue; } @@ -4468,7 +4485,8 @@ struct server_context_impl { const int32_t n_cur = std::max(slot.prompt.n_tokens(), slot.state == SLOT_STATE_GENERATING ? 0 : slot.preempt_n_input()); - return preempt_n_cells(std::min(slot.n_ctx, n_cur + slot.n_remaining() + 1)); + // n_predict may be INT32_MAX: sum in 64 bits before clamping + return preempt_n_cells((int32_t) std::min(slot.n_ctx, int64_t(n_cur) + slot.n_remaining() + 1)); } // Cells the residents hold once each reaches its output limit; -1 if one has no limit, or shares cells with a sibling. diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 750c45775c68..2f3313b4ccde 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1174,6 +1174,26 @@ def _serve_with_training_context(n_ctx_train: int): server.model_hf_repo = server.model_hf_file = None +def test_a_started_prompt_keeps_the_chunks_cache_reuse_shifts_in(): + """Trimming a started slot to its common prefix ahead of the batch builder must not discard what --cache-reuse would shift back in.""" + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "64" + _start(n_ctx=512, n_batch=64, n_ubatch=32, cache_ram=0) + + def run(prompt, id_slot, n_cache_reuse=0): + res = server.make_request("POST", "/completion", data={ + "n_predict": 1, "prompt": prompt, "id_slot": id_slot, "cache_prompt": True, + "n_cache_reuse": n_cache_reuse, "temperature": 0.0, "seed": 42, + }) + assert res.status_code == 200, res.body + return res.body["timings"] + + run([1] * 50 + [2] * 50 + [3] * 200, 0) + run([4] * 180, 1) + timings = run([1] * 50 + [3] * 200, 0, n_cache_reuse=50) + + assert timings["cache_n"] > 200, f"the reusable chunk was trimmed away: {timings}" + + def test_a_parked_head_is_not_overtaken_by_a_stream_of_short_requests(): os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "48" @@ -1230,7 +1250,12 @@ def stream(id_slot): assert "prompt held:" in text, "no prompt was held back for the head" waits = [float(w) for w in re.findall(r"id +3 \| task \d+ \| resumed after ([\d.]+) s", text)] assert waits, "the head was never parked and resumed" - assert max(waits) < 10.0, f"the head waited {waits} s behind requests that came after it" + # overtaken by the stream, the head would wait until the stream stopped (t_stream_max); waiting its turn, a few short requests' worth + t_short = max( + (res.body["timings"]["prompt_ms"] + res.body["timings"]["predicted_ms"]) / 1e3 for _, res in shorts + ) + t_bound = max(10.0, 3 * t_short) + assert max(waits) < t_bound, f"the head waited {waits} s behind requests that came after it (bound {t_bound:.1f} s, a short request took up to {t_short:.1f} s)" @pytest.mark.slow diff --git a/tools/server/tests/unit/test_preempt_models.py b/tools/server/tests/unit/test_preempt_models.py index fdb9cad46332..6e4e2f3ea8d1 100644 --- a/tools/server/tests/unit/test_preempt_models.py +++ b/tools/server/tests/unit/test_preempt_models.py @@ -1,4 +1,6 @@ import os +import re +import tempfile import pytest from utils import * @@ -44,6 +46,60 @@ def test_a_non_causal_decision_longer_than_the_ubatch_is_refused_and_the_server_ assert server.make_request("GET", "/health").status_code == 200 +def _decision(state: str): + return server.make_request("POST", "/v1/systemone", data={ + "state": state, + "questions": {"q": { + "type": "choice", + "instructions": "Is this a greeting?", + "criteria": {"yes": "a greeting", "no": "something else"}, + }}, + }) + + +def _decision_n_tokens(words: int) -> int: + """Input tokens of a decision whose state is `words` words, read from the refusal of one longer than the ubatch (= the context here).""" + res = _decision("Hello " * words) + assert res.status_code != 200, "this state should not fit the context" + m = re.search(r"input \((\d+) tokens\) is (?:too large to process|larger than the max context size)", res.body["error"]["message"]) + assert m, res.body + return int(m.group(1)) + + +def test_a_decision_as_long_as_the_context_resumes_after_a_park(): + """Admission takes a non-causal prompt of exactly n_ctx tokens, so a parked one must fit the pool again on resume.""" + global server + server = ServerPreset.tinyopenjev() + server.n_threads = 2 + server.override_kvs = ["qwen35.attention.causal=bool:false"] + n_ctx = 256 + server.n_ctx = n_ctx + server.n_slots = 2 + server.kv_unified = True + server.n_batch = n_ctx + server.n_ubatch = n_ctx + server.cache_ram = 0 + fd, server.log_path = tempfile.mkstemp(suffix=".log") + os.close(fd) + os.environ["LLAMA_ARG_PREEMPT_RAM"] = "32" + server.start(timeout_seconds=START_TIMEOUT) + + # the state that makes the input exactly n_ctx tokens: one word is one token here + a, b = 2 * n_ctx, 2 * n_ctx + 20 + n_a, n_b = _decision_n_tokens(a), _decision_n_tokens(b) + assert n_b - n_a == b - a, f"one word is not one token: {n_a} -> {n_b}" + words = a - (n_a - n_ctx) + assert _decision_n_tokens(words + 1) == n_ctx + 1 + + results = parallel_function_calls([(_decision, ("Hello " * words,)) for _ in range(12)]) + for res in results: + assert res.status_code == 200, res.body + + text = open(server.log_path, errors="replace").read() + assert "preempted" in text, "no decision was parked, so the resume was not exercised" + assert "cannot fit the pool" not in text + + def _final_bodies(): """The final record of a completion on every endpoint that reports how the request was served.""" msgs = [{"role": "user", "content": "Hello"}] From b0e8d2d1e654d8d74d5150aafe5f1a0d248f7130 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 09:03:13 -0700 Subject: [PATCH 084/109] llama : exact concurrency needs the backend that carries its kernels, not only its name A CUDA, ROCm or MUSA module from before these kernels has the same registry name and API version, answers the paged attention probe through its dense path and has no batch-invariant dispatch. The check now also requires the ggml_backend_cuda_set_exact_decode_width extension that ships with them. --- src/llama-impl.cpp | 7 ++++++- src/llama-impl.h | 3 +++ src/llama-kv-cache.cpp | 7 +------ tests/test-exact-buft.cpp | 21 ++++++++++++++++++++- 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/src/llama-impl.cpp b/src/llama-impl.cpp index 5bd9bb1406fd..2dad69360170 100644 --- a/src/llama-impl.cpp +++ b/src/llama-impl.cpp @@ -220,6 +220,11 @@ bool llama_exact_backend_name(const char * reg_name) { return reg_name && (strcmp(reg_name, "CUDA") == 0 || strcmp(reg_name, "ROCm") == 0 || strcmp(reg_name, "MUSA") == 0); } +bool llama_exact_backend_reg(ggml_backend_reg_t reg) { + return reg && llama_exact_backend_name(ggml_backend_reg_name(reg)) && + ggml_backend_reg_get_proc_address(reg, "ggml_backend_cuda_set_exact_decode_width") != nullptr; +} + // [TAG_EXACT_CONCURRENCY] Host buffers matter: an op runs where its weight lives, and a host weight's op moves to the GPU only for wide batches (ggml_backend_cuda_device_offload_op). // The CPU matmul picks between its SGEMM and its vector dot by the batch width too. bool llama_exact_buft_invariant(ggml_backend_buffer_type_t buft) { @@ -230,7 +235,7 @@ bool llama_exact_buft_invariant(ggml_backend_buffer_type_t buft) { ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft); ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr; - return reg && llama_exact_backend_name(ggml_backend_reg_name(reg)); + return llama_exact_backend_reg(reg); } bool llama_exact_concurrency() { diff --git a/src/llama-impl.h b/src/llama-impl.h index d4a704348870..b29e99e99b29 100644 --- a/src/llama-impl.h +++ b/src/llama-impl.h @@ -117,6 +117,9 @@ bool llama_exact_concurrency(); // [TAG_EXACT_CONCURRENCY] whether a backend registry carries the mode's batch-invariant kernels bool llama_exact_backend_name(const char * reg_name); +// [TAG_EXACT_CONCURRENCY] whether a backend registry carries the mode's kernels: the name, and the extension that ships with them (an older module of the same name has neither) +bool llama_exact_backend_reg(ggml_backend_reg_t reg); + // [TAG_EXACT_CONCURRENCY] whether a tensor placed in this buffer type is computed by such a backend bool llama_exact_buft_invariant(ggml_backend_buffer_type_t buft); diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 45a1c13bd0c4..3f8a2a55115c 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -69,12 +69,7 @@ static bool llama_dev_has_paged_attn(ggml_backend_dev_t dev) { return false; } - ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev); - if (!reg) { - return false; - } - - return llama_exact_backend_name(ggml_backend_reg_name(reg)); + return llama_exact_backend_reg(ggml_backend_dev_backend_reg(dev)); } // [TAG_EXACT_CONCURRENCY] Whether the device can run paged attention for this layer shape; the registry name only says which backends carry the kernels. diff --git a/tests/test-exact-buft.cpp b/tests/test-exact-buft.cpp index 02d714ef0eb5..f1495e370399 100644 --- a/tests/test-exact-buft.cpp +++ b/tests/test-exact-buft.cpp @@ -1,10 +1,12 @@ // [TAG_EXACT_CONCURRENCY] A host buffer is refused: its ops move to the GPU only once the batch is wide enough, so results depend on the step width. #include "ggml-backend.h" +#include "../ggml/src/ggml-backend-impl.h" #include "../src/llama-impl.h" #include +#include #undef NDEBUG #include @@ -27,7 +29,7 @@ int main() { ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev); - const bool invariant = reg && llama_exact_backend_name(ggml_backend_reg_name(reg)); + const bool invariant = llama_exact_backend_reg(reg); assert(llama_exact_buft_invariant(ggml_backend_dev_buffer_type(dev)) == invariant); @@ -45,6 +47,23 @@ int main() { assert(!llama_exact_backend_name("BLAS")); assert(!llama_exact_backend_name(nullptr)); + // a CUDA-named registry from before these kernels carries the name but not the extension: it is not exact + static void * the_extension = (void *) &the_extension; + struct fake { + static const char * name(ggml_backend_reg_t) { return "CUDA"; } + static size_t count(ggml_backend_reg_t) { return 0; } + static ggml_backend_dev_t dev(ggml_backend_reg_t, size_t) { return nullptr; } + static void * none(ggml_backend_reg_t, const char *) { return nullptr; } + static void * with(ggml_backend_reg_t, const char * n) { + return strcmp(n, "ggml_backend_cuda_set_exact_decode_width") == 0 ? the_extension : nullptr; + } + }; + ggml_backend_reg old_cuda = { GGML_BACKEND_API_VERSION, { fake::name, fake::count, fake::dev, fake::none }, nullptr }; + ggml_backend_reg new_cuda = { GGML_BACKEND_API_VERSION, { fake::name, fake::count, fake::dev, fake::with }, nullptr }; + assert(!llama_exact_backend_reg(&old_cuda)); + assert(llama_exact_backend_reg(&new_cuda)); + assert(!llama_exact_backend_reg(nullptr)); + printf("%s: all tests passed%s\n", __func__, checked_gpu ? "" : " (no batch-invariant device here, the positive case was not exercised)"); From 723efaa07d0c488b987ad7b8307f72e31a38a8ef Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 09:03:13 -0700 Subject: [PATCH 085/109] server: preemption fixes from review - decision-group accounting no longer depends on the parent staying resident: every member carries the shared length, and an idle slot's cached prompt counts as the member it last served - the sleeping /props answer carries the live async value, as the awake one - a state size of 0 (the size query's error return) is not parked as saved - a RAM restore does not call common_speculative_begin(), which reset the draft sampler's random stream though the per-sequence state never left - the replay test checks token counts, not prompt_ms against predicted_ms --- tools/server/server-context.cpp | 34 ++++++++++------- tools/server/server-decision.cpp | 2 + tools/server/server-task.h | 3 ++ tools/server/tests/unit/test_preempt.py | 50 ++++++++++++++++++++++++- 4 files changed, 73 insertions(+), 16 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index c3057035a326..4e2b78ada390 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -667,9 +667,7 @@ struct server_slot { preempt_mark_resumed(); - if (state == SLOT_STATE_GENERATING && can_speculate()) { - common_speculative_begin(spec, id, prompt.tokens.get_text_tokens()); - } + // the per-sequence speculative state stayed live while parked; begin() would reset the draft sampler's random stream return true; } @@ -781,6 +779,13 @@ struct server_slot { const size_t size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); const size_t size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + // a state always has its header, so 0 is the size query's error return: nothing can be saved, so the cells stay + if (size_tgt == 0 || (ctx_dft && size_dft == 0)) { + SLT_ERR(*this, "%s", "could not size the sequence state, so it is not parked to host memory\n"); + preempt_state_free(); + return false; + } + if (preempt_is_async()) { if (!preempt_buf_reserve(preempt_cpy_tgt.get(), size_tgt, preempt_grow) || (size_dft > 0 && (!preempt_cpy_dft || @@ -4432,14 +4437,8 @@ struct server_context_impl { } // [TAG_PREEMPT] Prompt tokens a family member shares with the one charged first: n_cmpl > 1 clones share all of it, a decision group only its parent's first n_tokens_shared. - int32_t preempt_family_n_shared(int family, const server_task & task) const { - for (const auto & other : slots) { - if (other.task && other.task->id == family && other.task->n_tokens_shared > 0) { - return other.task->n_tokens_shared; - } - } - - return task.n_tokens(); + static int32_t preempt_family_n_shared(const server_task & task) { + return task.family_n_shared > 0 ? task.family_n_shared : task.n_tokens(); } int32_t preempt_kv_used() const { @@ -4460,11 +4459,14 @@ struct server_context_impl { continue; } - if (slot.task && (slot.task->is_parent() || slot.task->is_child())) { - const int family = slot.task->is_parent() ? slot.task->id : slot.task->id_parent; + // [TAG_PREEMPT] A finished member's cached prompt still shares the family's cells, so an idle slot counts as the member it last served. + const server_task * member = slot.task ? slot.task.get() : (!slot.is_processing() ? slot.task_prev.get() : nullptr); + + if (member && (member->is_parent() || member->is_child())) { + const int family = member->is_parent() ? member->id : member->id_parent; if (std::find(charged.begin(), charged.end(), family) != charged.end()) { - res += preempt_n_cells(std::max(0, slot.prompt.n_tokens() - preempt_family_n_shared(family, *slot.task))); + res += preempt_n_cells(std::max(0, slot.prompt.n_tokens() - preempt_family_n_shared(*member))); continue; } @@ -9568,6 +9570,10 @@ void server_routes::update_cached_responses(bool is_sleeping) { if (is_sleeping) { cached_models = get_res_models(*meta); cached_props = get_res_props(*meta, params, true); + // [TAG_PREEMPT_ASYNC] as the awake handler: a slot may have fallen back to synchronous parks since load + if (cached_props["preempt"].contains("async")) { + cached_props["preempt"]["async"] = ctx_server.preempt_async_live.load(); + } cached_metrics = ctx_server.get_metrics(); should_reset_buckets = false; diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp index fb64096c67fe..1a1728ff8137 100644 --- a/tools/server/server-decision.cpp +++ b/tools/server/server-decision.cpp @@ -1613,8 +1613,10 @@ std::vector server_decision_group_tasks(std::vector && } parent.n_tokens_shared = n_shared; + parent.family_n_shared = n_shared; for (size_t j = i + 1; j < end; j++) { tasks[j].id_parent = parent.id; + tasks[j].family_n_shared = n_shared; parent.child_tasks.push_back(std::move(tasks[j])); } groups.push_back(std::move(parent)); diff --git a/tools/server/server-task.h b/tools/server/server-task.h index 4fde60a6c04a..d36029ddeb50 100644 --- a/tools/server/server-task.h +++ b/tools/server/server-task.h @@ -167,6 +167,9 @@ struct server_task { // if set on a parent, the children have their own prompt and only share its first n_tokens_shared tokens int32_t n_tokens_shared = 0; + // [TAG_PREEMPT] the same figure on every member of the group, so the planner can count a member's own cells after the parent is gone + int32_t family_n_shared = 0; + // used by SERVER_TASK_TYPE_INFERENCE task_params params; server_tokens tokens; diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 2f3313b4ccde..e91991a9a022 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -50,7 +50,7 @@ def create_server(): os.remove(_scratch.pop()) for name in ("LLAMA_SERVER_PREEMPT_EVERY", "LLAMA_SERVER_PREEMPT_GRANULARITY", "LLAMA_SERVER_PREEMPT_PLANNER", "LLAMA_ARG_PREEMPT_RAM", "LLAMA_ARG_PREEMPT_ASYNC", - "LLAMA_SERVER_PREEMPT_FAIL_SAVE", "LLAMA_SERVER_PREEMPT_PAGEABLE", "LLAMA_ARG_SPEC_DRAFT_P_MIN", "LLAMA_ARG_LOG_VERBOSITY", + "LLAMA_SERVER_PREEMPT_FAIL_SAVE", "LLAMA_SERVER_PREEMPT_PAGEABLE", "LLAMA_ARG_SPEC_DRAFT_P_MIN", "LLAMA_ARG_SPEC_DRAFT_SAMPLING", "LLAMA_ARG_LOG_VERBOSITY", "LLAMA_BATCH_DEBUG", "LLAMA_ARG_CTX_CHECKPOINTS", "LLAMA_MEDIA_MARKER", "LLAMA_EXACT_CONCURRENCY", "LLAMA_ARG_PREEMPT_POLICY"): os.environ.pop(name, None) @@ -921,6 +921,33 @@ def test_a_recompute_park_bounds_its_draft_by_the_tokens_it_comes_back_with(): assert "Context size has been exceeded" not in text +def test_a_ram_park_does_not_restart_a_probabilistic_draft(): + """A park that keeps the state in host RAM resumes the slot as it was, draft sampler included: the sampled output is that of a run never parked.""" + os.environ["LLAMA_ARG_SPEC_DRAFT_SAMPLING"] = "probabilistic" + os.environ["LLAMA_ARG_SPEC_DRAFT_P_MIN"] = "0.0" + + def run(park_every): + if park_every: + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = str(park_every) + else: + os.environ.pop("LLAMA_SERVER_PREEMPT_EVERY", None) + server.spec_type = "draft-simple" + server.model_draft_hf_repo = server.model_hf_repo + _start(n_ctx=512, spec_draft_n_max=4, spec_draft_n_min=1) + res = server.make_request("POST", "/completion", data={ + "prompt": "Once upon a time", "n_predict": 48, "ignore_eos": True, + "temperature": 0.8, "seed": 123, "cache_prompt": False, "return_tokens": True, + }) + server.stop() + assert res.status_code == 200, res.body + return res.body + + plain = run(0) + parked = run(8) + assert parked["preempt"]["parks"] > 0 and parked["preempt"]["recomputes"] == 0, parked["preempt"] + assert parked["tokens"] == plain["tokens"] + + def test_props_says_whether_exact_concurrency_is_running(): _start(n_ctx=256) res = server.make_request("GET", "/props") @@ -1000,7 +1027,6 @@ def test_a_recompute_restore_does_not_count_its_replay_as_prompt(): assert timings["cache_n"] == 0, timings assert timings["prompt_n"] == n_prompt, timings assert timings["predicted_n"] == n_predict, timings - assert timings["predicted_ms"] > timings["prompt_ms"], timings def test_slots_reports_the_recomputes_of_the_current_task(): @@ -1394,6 +1420,26 @@ def test_a_slot_whose_park_buffer_comes_back_pageable_is_no_longer_reported_asyn assert server.make_request("GET", "/props").body["preempt"]["async"] is False +def test_a_sleeping_server_reports_the_async_fallback_too(): + """/props is answered from a cache while the server sleeps; it must carry the same live async value as the awake answer.""" + os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" + os.environ["LLAMA_SERVER_PREEMPT_PAGEABLE"] = "1" + _start_async(n_ctx=512, sleep_idle_seconds=2) + + res = _complete(32) + assert res.status_code == 200, res.body + assert res.body["preempt"]["parks"] > 0, res.body["preempt"] + assert "is pageable, so this slot parks synchronously from now on" in _log() + + deadline = time.time() + 30 + props = server.make_request("GET", "/props").body + while not props["is_sleeping"] and time.time() < deadline: + time.sleep(0.1) + props = server.make_request("GET", "/props").body + assert props["is_sleeping"], "the server did not go to sleep" + assert props["preempt"]["async"] is False, props["preempt"] + + def test_a_multi_prompt_oai_completion_counts_the_parks_of_every_prompt(): os.environ["LLAMA_SERVER_PREEMPT_EVERY"] = "8" _start() From 514a2878d9c632f674d7e55b44ef15e01ed481ed Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 09:03:13 -0700 Subject: [PATCH 086/109] tests: a client that could not start is not an RPC refusal; use a free port --- tests/test-rpc-paged-fa.cpp | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp index 53bc5357f78a..690fd2d5fdba 100644 --- a/tests/test-rpc-paged-fa.cpp +++ b/tests/test-rpc-paged-fa.cpp @@ -71,11 +71,14 @@ static bool port_open(int port) { _exit(0); } +// a client that could not be started: distinct from every exit status and signal, so it is never read as a refusal +static const int CLIENT_NOT_RUN = -1000; + static int run_client(const std::string & endpoint, bool paged) { const pid_t pid = fork(); if (pid < 0) { perror("fork the RPC client"); - return -1; + return CLIENT_NOT_RUN; } if (pid == 0) { send_graph(endpoint, paged); @@ -85,8 +88,31 @@ static int run_client(const std::string & endpoint, bool paged) { return WIFEXITED(status) ? WEXITSTATUS(status) : -WTERMSIG(status); } +// a port the kernel just handed out, so a parallel run or another listener does not answer for the server +static int free_port() { + const int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + return -1; + } + sockaddr_in addr = {}; + addr.sin_family = AF_INET; + addr.sin_port = 0; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + socklen_t len = sizeof(addr); + int port = -1; + if (bind(fd, (sockaddr *) &addr, sizeof(addr)) == 0 && getsockname(fd, (sockaddr *) &addr, &len) == 0) { + port = ntohs(addr.sin_port); + } + close(fd); + return port; +} + int main() { - const int port = 41000 + getpid() % 9000; + const int port = free_port(); + if (port <= 0) { + perror("find a free port"); + return 1; + } const std::string endpoint = "127.0.0.1:" + std::to_string(port); const pid_t server = fork(); @@ -120,7 +146,10 @@ int main() { printf("unpaged: %d, paged: %d, unpaged after: %d\n", plain, paged, after); - if (plain != 0 || after != 0) { + if (plain == CLIENT_NOT_RUN || paged == CLIENT_NOT_RUN || after == CLIENT_NOT_RUN) { + fprintf(stderr, "a client could not be started, so this test proves nothing\n"); + rc = 1; + } else if (plain != 0 || after != 0) { fprintf(stderr, "an unpaged graph failed over RPC, so this test proves nothing\n"); rc = 1; } else if (paged == 0) { From ce0b9e4c0fd1bbbc2a8d745263f7afd78555827e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 12:05:14 -0700 Subject: [PATCH 087/109] llama : llama_memory_n_cells_used() reads occupancy from the KV cells Cells held by at least one sequence, a shared cell counted once and a partly used block in full, and optionally those held only by given sequences. The server's preemption planner reads its occupancy and idle-reclaim figures from it instead of rebuilding them from the task tree. -1 where a memory cannot tell (recurrent state, DSV4); the planner keeps its estimate there. --- include/llama.h | 10 +++ src/llama-context.cpp | 8 +++ src/llama-kv-cache-dsa-iswa.h | 2 + src/llama-kv-cache-dsa.h | 2 + src/llama-kv-cache-iswa.h | 2 + src/llama-kv-cache-msa.h | 2 + src/llama-kv-cache.cpp | 50 ++++++++++++++ src/llama-kv-cache.h | 3 + src/llama-memory-hybrid-iswa.h | 2 + src/llama-memory-hybrid.cpp | 5 ++ src/llama-memory-hybrid.h | 2 + src/llama-memory.h | 7 ++ tests/test-memory-cells-used.cpp | 111 +++++++++++++++++++++++++++++++ 13 files changed, 206 insertions(+) create mode 100644 tests/test-memory-cells-used.cpp diff --git a/include/llama.h b/include/llama.h index 1893731ce04c..22463441a147 100644 --- a/include/llama.h +++ b/include/llama.h @@ -828,6 +828,16 @@ extern "C" { // false for a recurrent state, a cache with a stream per sequence, or one that keeps its own streams per sequence whatever the unified flag says LLAMA_API bool llama_memory_shares_cells(llama_memory_t mem); + // [TAG_PREEMPT] cells held by at least one sequence, read from the cells themselves: a cell several sequences share counts once, + // and a block (llama_memory_alloc_granularity()) with one live cell counts in full + // n_reclaimable, if not NULL, receives how many of them are held only by sequences in seq_free (freed if those sequences were removed) + // returns -1 when the memory cannot tell (a recurrent state, or a cache that keeps per-sequence streams of its own) + LLAMA_API int32_t llama_memory_n_cells_used( + llama_memory_t mem, + const llama_seq_id * seq_free, + size_t n_seq_free, + int32_t * n_reclaimable); + // [TAG_PREEMPT] run the in-place update a seq_add() recorded, which llama_decode() would otherwise run at the start of the next batch // takes the context because the update is a graph; returns true when one was run LLAMA_API bool llama_memory_update(struct llama_context * ctx); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 6e953f8800a3..cdcd13a30ac4 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -5279,6 +5279,14 @@ bool llama_memory_shares_cells(llama_memory_t mem) { return mem->shares_cells(); } +int32_t llama_memory_n_cells_used(llama_memory_t mem, const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) { + if (!mem) { + return -1; + } + + return mem->n_cells_used(seq_free, n_seq_free, n_reclaimable); +} + bool llama_memory_update(llama_context * ctx) { if (!ctx) { return false; diff --git a/src/llama-kv-cache-dsa-iswa.h b/src/llama-kv-cache-dsa-iswa.h index c0a3215bc6f9..464c51450e29 100644 --- a/src/llama-kv-cache-dsa-iswa.h +++ b/src/llama-kv-cache-dsa-iswa.h @@ -47,6 +47,8 @@ class llama_kv_cache_dsa_iswa : public llama_memory_i { bool shares_cells() const override { return kv_dsa->shares_cells(); } + int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override { return kv_dsa->n_cells_used(seq_free, n_seq_free, n_reclaimable); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache-dsa.h b/src/llama-kv-cache-dsa.h index ae46efc78943..854c70786ab3 100644 --- a/src/llama-kv-cache-dsa.h +++ b/src/llama-kv-cache-dsa.h @@ -49,6 +49,8 @@ class llama_kv_cache_dsa : public llama_memory_i { bool shares_cells() const override { return kv_mla->shares_cells(); } + int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override { return kv_mla->n_cells_used(seq_free, n_seq_free, n_reclaimable); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache-iswa.h b/src/llama-kv-cache-iswa.h index 980f6526511d..91527c526957 100644 --- a/src/llama-kv-cache-iswa.h +++ b/src/llama-kv-cache-iswa.h @@ -67,6 +67,8 @@ class llama_kv_cache_iswa : public llama_memory_i { bool shares_cells() const override { return kv_base->shares_cells(); } + int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override { return kv_base->n_cells_used(seq_free, n_seq_free, n_reclaimable); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache-msa.h b/src/llama-kv-cache-msa.h index 9478a8fc0293..c7815f18513e 100644 --- a/src/llama-kv-cache-msa.h +++ b/src/llama-kv-cache-msa.h @@ -46,6 +46,8 @@ class llama_kv_cache_msa : public llama_memory_i { bool shares_cells() const override { return kv_base->shares_cells(); } + int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override { return kv_base->n_cells_used(seq_free, n_seq_free, n_reclaimable); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 3f8a2a55115c..331b1d91b953 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1536,6 +1536,56 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & } } +int32_t llama_kv_cache::n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const { + const uint32_t g = alloc_granularity(); + + int64_t n_used = 0; + int64_t n_reclaim = 0; + + for (const auto & cells : v_cells) { + // a block counts once one of its cells is live, and is reclaimable when every live cell in it is + int64_t block = -1; + bool block_free = true; + + auto flush = [&]() { + if (block >= 0) { + n_used += g; + n_reclaim += block_free ? g : 0; + } + }; + + const uint32_t n = cells.used_max_p1(); + + for (uint32_t i = 0; i < n; ++i) { + if (cells.is_empty(i)) { + continue; + } + + if ((int64_t) (i / g) != block) { + flush(); + block = i / g; + block_free = true; + } + + if (n_reclaimable && block_free) { + int n_in_free = 0; + for (size_t j = 0; j < n_seq_free; ++j) { + n_in_free += seq_free[j] >= 0 && seq_free[j] < LLAMA_MAX_SEQ && cells.seq_has(i, seq_free[j]); + } + block_free = n_in_free == cells.seq_count(i); + } + } + + flush(); + } + + if (n_reclaimable) { + *n_reclaimable = (int32_t) n_reclaim; + } + + return (int32_t) n_used; +} + uint32_t llama_kv_cache::alloc_granularity() const { // [TAG_EXACT_CONCURRENCY] Each page belongs to one (sequence, page) pair, so n tokens hold round_up(n, exact_page_size) cells. return exact_pages ? exact_page_size : 1; diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index f56e72f459a4..e1eb21b084ff 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -135,6 +135,9 @@ class llama_kv_cache : public llama_memory_i { bool shares_cells() const override { return get_n_stream() == 1; } // one stream: every sequence draws on the same cells + // [TAG_PREEMPT] counted from the cells of every stream, in blocks of alloc_granularity() + int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override; + // [TAG_EXACT_CONCURRENCY] the page size under exact mode, 1 otherwise uint32_t alloc_granularity() const override; diff --git a/src/llama-memory-hybrid-iswa.h b/src/llama-memory-hybrid-iswa.h index 69161eb10ad1..8749a1e46840 100644 --- a/src/llama-memory-hybrid-iswa.h +++ b/src/llama-memory-hybrid-iswa.h @@ -60,6 +60,8 @@ class llama_memory_hybrid_iswa : public llama_memory_i { bool shares_cells() const override { return mem_attn->shares_cells(); } // the recurrent half holds one state per sequence + int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override { return mem_attn->n_cells_used(seq_free, n_seq_free, n_reclaimable); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 2241962cc6cf..0053e078a584 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -154,6 +154,11 @@ bool llama_memory_hybrid::shares_cells() const { return mem_attn->shares_cells(); } +int32_t llama_memory_hybrid::n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const { + // the cells a caller plans capacity for are the attention half's + return mem_attn->n_cells_used(seq_free, n_seq_free, n_reclaimable); +} + void llama_memory_hybrid::clear(bool data) { mem_attn->clear(data); mem_recr->clear(data); diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index b514abb50a0e..2433efbdc99c 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -62,6 +62,8 @@ class llama_memory_hybrid : public llama_memory_i { bool shares_cells() const override; + int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override; + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/src/llama-memory.h b/src/llama-memory.h index 1b090054e3fd..c4cc6c25ede9 100644 --- a/src/llama-memory.h +++ b/src/llama-memory.h @@ -107,6 +107,13 @@ struct llama_memory_i { // [TAG_PREEMPT] True when the sequences draw on one pool of cells, so one sequence's growth takes room from the others. Not pure virtual, so old modules inherit true. virtual bool shares_cells() const { return true; } + // [TAG_PREEMPT] Cells held by at least one sequence, read from the cells: a shared cell once, a partly used block in full. With n_reclaimable, also + // the cells every one of whose sequences is in seq_free. -1 when this memory cannot tell. Not pure virtual, so old modules inherit -1. + virtual int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const { + (void) seq_free; (void) n_seq_free; (void) n_reclaimable; + return -1; + } + // // ops // diff --git a/tests/test-memory-cells-used.cpp b/tests/test-memory-cells-used.cpp new file mode 100644 index 000000000000..ad64126fa932 --- /dev/null +++ b/tests/test-memory-cells-used.cpp @@ -0,0 +1,111 @@ +// [TAG_PREEMPT] llama_memory_n_cells_used() reads the KV cells: a prefix copied to other sequences is counted once, and only cells +// whose every sequence is given are reported reclaimable. The server's preemption planner reads its occupancy from it. + +#include "llama.h" + +#include +#include +#include + +static bool decode(llama_context * ctx, llama_seq_id seq, llama_pos p0, int n) { + llama_batch batch = llama_batch_init(n, 0, 1); + for (int i = 0; i < n; ++i) { + batch.token[i] = 1 + (p0 + i) % 50; + batch.pos[i] = p0 + i; + batch.n_seq_id[i] = 1; + batch.seq_id[i][0] = seq; + batch.logits[i] = i == n - 1; + } + batch.n_tokens = n; + const bool ok = llama_decode(ctx, batch) == 0; + llama_batch_free(batch); + return ok; +} + +static int check(const char * what, int32_t got, int32_t want) { + printf("%-52s %4d (want %d)\n", what, got, want); + return got == want ? 0 : 1; +} + +int main(int argc, char ** argv) { + const char * path = nullptr; + for (int i = 1; i + 1 < argc; ++i) { + if (strcmp(argv[i], "-m") == 0) { + path = argv[i + 1]; + } + } + if (!path) { + fprintf(stderr, "usage: %s -m model.gguf\n", argv[0]); + return 1; + } + + llama_backend_init(); + + llama_model_params mparams = llama_model_default_params(); + mparams.n_gpu_layers = 0; + llama_model * model = llama_model_load_from_file(path, mparams); + if (!model) { + fprintf(stderr, "failed to load %s\n", path); + return 1; + } + + llama_context_params cparams = llama_context_default_params(); + cparams.n_ctx = 512; + cparams.n_batch = 256; + cparams.n_ubatch = 256; + cparams.n_seq_max = 3; + cparams.kv_unified = true; + llama_context * ctx = llama_init_from_model(model, cparams); + if (!ctx) { + fprintf(stderr, "failed to create a context\n"); + return 1; + } + + llama_memory_t mem = llama_get_memory(ctx); + + // seq 0: 120 cells; its first 100 copied to seqs 1 and 2, which then add 30 and 40 of their own + if (!decode(ctx, 0, 0, 120)) { + return 1; + } + llama_memory_seq_cp(mem, 0, 1, 0, 100); + llama_memory_seq_cp(mem, 0, 2, 0, 100); + if (!decode(ctx, 1, 100, 30) || !decode(ctx, 2, 100, 40)) { + return 1; + } + + int bad = 0; + int32_t reclaim = -1; + + const llama_seq_id s0[] = { 0 }; + const llama_seq_id s01[] = { 0, 1 }; + const llama_seq_id all[] = { 0, 1, 2 }; + + bad += check("used: 100 shared + 20 + 30 + 40", llama_memory_n_cells_used(mem, nullptr, 0, &reclaim), 190); + bad += check("reclaimable with no sequence given", reclaim, 0); + + llama_memory_n_cells_used(mem, s0, 1, &reclaim); + bad += check("reclaimable if seq 0 went: its own 20", reclaim, 20); + + llama_memory_n_cells_used(mem, s01, 2, &reclaim); + bad += check("reclaimable if seqs 0 and 1 went: 20 + 30", reclaim, 50); + + llama_memory_n_cells_used(mem, all, 3, &reclaim); + bad += check("reclaimable if every sequence went", reclaim, 190); + + // removing seq 0 frees only its own cells: the copied prefix is still held by 1 and 2 + llama_memory_seq_rm(mem, 0, -1, -1); + bad += check("used after seq 0 is removed: 100 + 30 + 40", llama_memory_n_cells_used(mem, nullptr, 0, nullptr), 170); + + const llama_seq_id s1[] = { 1 }; + llama_memory_n_cells_used(mem, s1, 1, &reclaim); + bad += check("reclaimable if seq 1 went: its own 30", reclaim, 30); + + bad += check("no memory: unknown", llama_memory_n_cells_used(nullptr, nullptr, 0, nullptr), -1); + + llama_free(ctx); + llama_model_free(model); + llama_backend_free(); + + printf("%s\n", bad == 0 ? "ok: shared cells are counted once and reclaimed only with every owner" : "FAIL"); + return bad == 0 ? 0 : 1; +} From 465da89909ad2ffdb07521ab31f54ee3568d001a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 12:05:14 -0700 Subject: [PATCH 088/109] server: preemption fixes from review - occupancy and idle reclaim come from llama_memory_n_cells_used(), so a cleared, finished or idle family member can neither hide nor double the cells its siblings still share; the task-tree estimate is only the fallback - a child slot's stale cache is cleared at launch, after the prompt cache has kept it: the parent's prompt replaces it, and until then it could be neither used nor parked - the planner keeps only the prefix the batch builder reuses: none for a stateless task, and none under exact concurrency, where cached cells come from other ubatches than a cold prompt's - accepted tokens waiting for a replay after a checkpoint restore survive a park or a rewind - a cache-reuse shift is applied to the draft too before anything can park it --- tools/server/server-context.cpp | 53 ++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 4e2b78ada390..3769af867c30 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -647,10 +647,12 @@ struct server_slot { // Take the slot out of the next step; the draft is a prediction, so it is dropped with the cells. void preempt_detach() { - spec_draft.clear(); + // [TAG_PREEMPT] Accepted tokens waiting for a replay after a checkpoint restore are output already decided: keep them, the cells are at the checkpoint. + if (!spec_is_replay) { + spec_draft.clear(); + spec_ckpt.clear(); + } spec_i_batch.clear(); - spec_ckpt.clear(); - spec_is_replay = false; i_batch = -1; } @@ -3413,6 +3415,9 @@ struct server_context_impl { prompt_cache->update(); } + // [TAG_PREEMPT] copy_prompt_to() replaces it once the parent's prompt is in; until then those cells could neither be used nor parked + slot->prompt_clear(); + int id_child = parent_task.child_tasks[idx].id; if (!launch_slot_with_task(*slot, std::move(parent_task.child_tasks[idx]))) { SRV_ERR("failed to launch slot with child task, id_task = %d\n", id_child); @@ -4363,8 +4368,14 @@ struct server_context_impl { } } + // The batch builder reuses a cached prefix only for a stateful task, and never under exact concurrency, where the cached cells + // were computed in other ubatches than a cold prompt's and would make the output depend on what ran before. + static bool slot_reuses_prefix(const server_task & task) { + return task.params.cache_prompt && !task.is_stateless() && !common_exact_concurrency(); + } + size_t preempt_n_keep(const server_slot & slot) const { - if (!slot.task->params.cache_prompt) { + if (!slot_reuses_prefix(*slot.task)) { return 0; } @@ -4441,7 +4452,31 @@ struct server_context_impl { return task.family_n_shared > 0 ? task.family_n_shared : task.n_tokens(); } + // [TAG_PREEMPT] Occupancy read from the KV cells themselves: a cell several sequences share counts once, whoever's task tree it came from. + // With n_idle, also the cells only idle slots hold, which purging them would free. -1 when the memory cannot tell; the estimates below are the fallback. + int32_t preempt_kv_cells(int32_t * n_idle) const { + llama_memory_t mem = ctx_tgt ? llama_get_memory(ctx_tgt) : nullptr; + if (!mem) { + return -1; + } + + std::vector idle; + if (n_idle) { + for (const auto & slot : slots) { + if (!slot.is_processing()) { + idle.push_back(slot.id); + } + } + } + + return llama_memory_n_cells_used(mem, idle.data(), idle.size(), n_idle); + } + int32_t preempt_kv_used() const { + if (const int32_t n = preempt_kv_cells(nullptr); n >= 0) { + return n; + } + int32_t res = 0; // n_cmpl > 1 siblings share the prompt's cells via seq_cp, so charge them once. @@ -4513,6 +4548,10 @@ struct server_context_impl { } int32_t preempt_n_idle_cells() const { + if (int32_t n_idle = 0; preempt_kv_cells(&n_idle) >= 0) { + return n_idle; + } + int32_t res = 0; for (const auto & slot : slots) { @@ -5795,8 +5834,8 @@ struct server_context_impl { int32_t off_next = 0; int32_t n_batch = llama_n_batch(ctx_tgt); - // [TAG_PREEMPT_ASYNC] A --cache-reuse shift is found inside pre_decode(), after the wait above. - preempt_wait_for_shift(); + // [TAG_PREEMPT_ASYNC] A --cache-reuse shift is found inside pre_decode(), after the wait above; apply it to the draft too, or a KV-full park saves a draft state with the shift still pending. + preempt_apply_shift(); for (int32_t off = 0; off < batch.size(); off = off_next) { const int32_t n_tokens = std::min(n_batch, batch.size() - off); @@ -6235,7 +6274,7 @@ struct server_context_impl { // the decision size is checked in slot_prompt_rejected; its first position bounds the reuse below const int32_t n_decision_first = slot.task->type == SERVER_TASK_TYPE_DECISION ? slot.task->decision.pos_first() : -1; - if (slot.task->params.cache_prompt && !slot.task->is_stateless()) { + if (slot_reuses_prefix(*slot.task)) { // reuse any previously computed tokens that are common with the new prompt n_past = slot.prompt.tokens.get_common_prefix(input_tokens); From 46b88cbcd84343f0491a75887ee1367b0cedb358 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 12:05:14 -0700 Subject: [PATCH 089/109] common : exact concurrency refuses a draft ubatch other than the target's The draft context splits each batch at its own ubatch size, so with another size its splits move with what else is in the batch. --- common/common.cpp | 11 +++++++++++ tests/test-exact-geometry.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/common/common.cpp b/common/common.cpp index effe3b133b9d..fc0239d25048 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1502,6 +1502,17 @@ bool common_exact_concurrency_init(const common_params & params) { } } + // [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) { diff --git a/tests/test-exact-geometry.cpp b/tests/test-exact-geometry.cpp index 40941069ea97..1111651ee244 100644 --- a/tests/test-exact-geometry.cpp +++ b/tests/test-exact-geometry.cpp @@ -2,6 +2,7 @@ #include "common.h" #include +#include #include #undef NDEBUG @@ -46,6 +47,33 @@ int main() { assert(!llama_set_exact_decode_width((uint32_t) INT32_MAX + 1)); assert(llama_exact_decode_width() == width); + // a draft context splits each batch at its own ubatch size, so a draft ubatch other than the target's moves with what else is in the batch + { +#ifdef _WIN32 + _putenv_s("LLAMA_EXACT_CONCURRENCY", "1"); +#else + setenv("LLAMA_EXACT_CONCURRENCY", "1", 1); +#endif + assert(common_exact_concurrency()); + + common_params p; + p.n_ctx = 2048; + p.n_batch = 512; + p.n_ubatch = 128; + p.n_parallel = 2; + p.speculative.types = { COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE }; + p.speculative.draft.mparams.path = "draft.gguf"; + + p.speculative.draft.n_ubatch = 100; + assert(!common_exact_concurrency_init(p)); + + p.speculative.draft.n_ubatch = 128; + assert(common_exact_concurrency_init(p)); + + p.speculative.draft.n_ubatch = 0; // the target's + assert(common_exact_concurrency_init(p)); + } + printf("%s: all tests passed\n", __func__); return 0; From 96de063d9a8ee999b9b0d1b1af6be806fd999ecc Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 12:05:14 -0700 Subject: [PATCH 090/109] tests: tighten the exact-mode and RPC tests - test-rpc-paged-fa: a client that fails in its own setup is not a refusal - test-paged-fa-supports also checks ROCm and MUSA devices - test-exact-pages fails on a model that does not load; a refused context is still a skip - test-exact-pages / test-exact-weights run against LLAMA_TEST_EXACT_MODEL (256-wide K/V heads), not the generic fixture they always skipped on - test-memory-cells-used registered against the generic fixture - server tests: the late-prompt test overlaps by observing the leader, new tests for an exact-mode prompt reusing no cached prefix --- tests/CMakeLists.txt | 18 +++++++++----- tests/test-exact-pages.cpp | 7 +++++- tests/test-paged-fa-supports.cpp | 4 ++-- tests/test-rpc-paged-fa.cpp | 20 +++++++++++++--- tools/server/tests/unit/test_preempt.py | 31 +++++++++++++++++++++---- 5 files changed, 64 insertions(+), 16 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e28fdc6c12dd..0c2ddd68b3fc 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -338,13 +338,19 @@ llama_build_and_test(test-backend-sampler.cpp LABEL "model") llama_build_and_test(test-state-seq-copy.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-state-seq-copy PROPERTIES FIXTURES_REQUIRED test-download-model) -# [TAG_EXACT_CONCURRENCY] page bookkeeping of the paged KV pool; skips itself where the mode cannot run -llama_build_and_test(test-exact-pages.cpp LABEL "model" ARGS -m "${MODEL_DEST}") -set_tests_properties(test-exact-pages PROPERTIES FIXTURES_REQUIRED test-download-model) +# [TAG_EXACT_CONCURRENCY] page bookkeeping of the paged KV pool, and a non-layer weight on the host refused; both skip themselves where the mode +# cannot run. Exact mode needs 256-wide K/V heads, which the generic test model does not have, so they run only against LLAMA_TEST_EXACT_MODEL. +set(LLAMA_TEST_EXACT_MODEL "" CACHE FILEPATH "a model with 256-wide K/V heads for the exact-concurrency model tests") +llama_build(test-exact-pages.cpp) +llama_build(test-exact-weights.cpp) +if (LLAMA_TEST_EXACT_MODEL) + llama_test(test-exact-pages LABEL "model" ARGS -m "${LLAMA_TEST_EXACT_MODEL}") + llama_test(test-exact-weights LABEL "model" ARGS -m "${LLAMA_TEST_EXACT_MODEL}") +endif() -# [TAG_EXACT_CONCURRENCY] a non-layer weight on the host is refused; skips itself where the mode cannot run -llama_build_and_test(test-exact-weights.cpp LABEL "model" ARGS -m "${MODEL_DEST}") -set_tests_properties(test-exact-weights PROPERTIES FIXTURES_REQUIRED test-download-model) +# [TAG_PREEMPT] the occupancy the server's planner reads: shared cells counted once, and the cells only given sequences hold +llama_build_and_test(test-memory-cells-used.cpp LABEL "model" ARGS -m "${MODEL_DEST}") +set_tests_properties(test-memory-cells-used PROPERTIES FIXTURES_REQUIRED test-download-model) if (APPLE) llama_build(test-rset-release.cpp) diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index 40045ad76e8e..b4ccf65396d2 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -66,7 +66,12 @@ int main(int argc, char ** argv) { llama_context * ctx = llama_init->context(); - if (llama_init->model() == nullptr || ctx == nullptr) { + if (llama_init->model() == nullptr) { + fprintf(stderr, "%s : the model did not load\n", __func__); + return 1; + } + + if (ctx == nullptr) { printf("%s : skipped, this build and model cannot run exact concurrency\n", __func__); return 0; } diff --git a/tests/test-paged-fa-supports.cpp b/tests/test-paged-fa-supports.cpp index dc6b63aceafc..5d2eabd3f12b 100644 --- a/tests/test-paged-fa-supports.cpp +++ b/tests/test-paged-fa-supports.cpp @@ -66,8 +66,8 @@ int main() { ggml_backend_dev_t dev = ggml_backend_dev_get(i); const char * reg_name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)); - // only the CUDA backend reads the page table; the others are kept off this path by llama_exact_backend_name() - if (strcmp(reg_name, "CUDA") != 0) { + // only the CUDA backend (also built as ROCm and MUSA) reads the page table; the others are kept off this path by llama_exact_backend_reg() + if (strcmp(reg_name, "CUDA") != 0 && strcmp(reg_name, "ROCm") != 0 && strcmp(reg_name, "MUSA") != 0) { continue; } diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp index 690fd2d5fdba..8dcec770ed38 100644 --- a/tests/test-rpc-paged-fa.cpp +++ b/tests/test-rpc-paged-fa.cpp @@ -31,12 +31,20 @@ static bool port_open(int port) { return ok; } +// client exit codes: setup failures are not the server's answer, so they never count as a refusal +enum { + CLIENT_OK = 0, + CLIENT_NO_BACKEND = 10, + CLIENT_NO_BUFFER = 11, + CLIENT_REFUSED = 20, // the server answered the compute with a failure +}; + [[noreturn]] static void send_graph(const std::string & endpoint, bool paged) { alarm(120); ggml_backend_t backend = ggml_backend_rpc_init(endpoint.c_str(), 0); if (!backend) { - _exit(10); + _exit(CLIENT_NO_BACKEND); } ggml_init_params params = { 16*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true }; @@ -59,11 +67,14 @@ static bool port_open(int port) { ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend); if (!buf) { - _exit(11); + _exit(CLIENT_NO_BUFFER); } ggml_backend_buffer_clear(buf, 0); - ggml_backend_graph_compute(backend, gf); + // everything above is setup; from here a failure or a dropped connection is the server's answer + if (ggml_backend_graph_compute(backend, gf) != GGML_STATUS_SUCCESS) { + _exit(CLIENT_REFUSED); + } std::vector res(ggml_nelements(out)); ggml_backend_tensor_get(out, res.data(), 0, ggml_nbytes(out)); @@ -155,6 +166,9 @@ int main() { } else if (paged == 0) { fprintf(stderr, "the RPC server computed a FLASH_ATTN_EXT that carries a page table\n"); rc = 1; + } else if (paged == CLIENT_NO_BACKEND || paged == CLIENT_NO_BUFFER) { + fprintf(stderr, "the paged client failed in its own setup (%d) before the server saw the graph, so this test proves nothing\n", paged); + rc = 1; } else { printf("ok, the RPC server refused the paged graph and kept serving\n"); } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index e91991a9a022..9b61b216f6dc 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -319,10 +319,7 @@ def test_a_late_prompt_and_a_generating_slot_both_finish(planner): n_predict_a = 230 n_predict_b = 90 assert 8 + n_predict_a + n_b + n_predict_b > 256 - results = parallel_function_calls([ - (_complete, (n_predict_a, "Hi how are you")), - (_complete, (n_predict_b, _prompt_of(n_b, _PROMPT_C), -1, 0.02)), - ]) + results = _complete_overlapping((n_predict_a, n_predict_b), (8, n_b)) text = _log() assert "Context size has been exceeded" not in text @@ -768,6 +765,32 @@ def _ubatch_widths(text: str) -> list: return res +def test_exact_concurrency_reuses_no_cached_prefix(): + """A cached prefix was computed in other ubatches than a cold prompt's; under exact concurrency it is recomputed, so the output does not depend on what ran before.""" + path = os.environ.get("LLAMA_SERVER_TEST_EXACT_MODEL") + if not path: + pytest.skip("set LLAMA_SERVER_TEST_EXACT_MODEL to a gguf exact concurrency accepts") # ty: ignore[too-many-positional-arguments] + server.model_file = path + server.model_hf_repo = server.model_hf_file = None + os.environ["LLAMA_EXACT_CONCURRENCY"] = "1" + _start(n_ctx=2048, n_slots=4, n_batch=128, n_ubatch=64, fa="on", n_gpu_layer=99, cache_ram=0) + + def run(prompt): + res = server.make_request("POST", "/completion", data={ + "prompt": prompt, "n_predict": 1, "id_slot": 0, "cache_prompt": True, + "temperature": 0.0, "seed": 42, "n_probs": 8, + }) + assert res.status_code == 200, res.body + return res.body + + prompt = list(range(1000, 1064)) + cold = run(prompt) + run(prompt[:16]) + warm = run(prompt) + assert warm["timings"]["cache_n"] == 0, warm["timings"] + assert warm["completion_probabilities"] == cold["completion_probabilities"] + + def test_exact_concurrency_prefills_a_prompt_in_the_ubatches_it_would_get_alone(): path = os.environ.get("LLAMA_SERVER_TEST_EXACT_MODEL") if not path: From 2ddd0b9672ff728886098633c83bfd8a02d6108d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 12:16:42 -0700 Subject: [PATCH 091/109] server: the granularity test knob keeps the planner's estimate LLAMA_SERVER_PREEMPT_GRANULARITY plans in blocks the KV memory does not have, so the occupancy is not read from the cells while it differs from them. --- tools/server/server-context.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 3769af867c30..352d03bb3111 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4460,6 +4460,11 @@ struct server_context_impl { return -1; } + // LLAMA_SERVER_PREEMPT_GRANULARITY (test knob) plans in blocks the memory does not have, so its cells cannot be read in them + if ((uint32_t) preempt_alloc_granularity != llama_memory_alloc_granularity(mem)) { + return -1; + } + std::vector idle; if (n_idle) { for (const auto & slot : slots) { From 8dd07ecdcbaf6c31a2fbd10a9ead72057fa1c0ca Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 12:35:01 -0700 Subject: [PATCH 092/109] server tests: wait on observed progress, not on wall-clock deadlines Every wait for a precondition (a resident growing into the pool, a leader decoding N tokens, a stream starting, slots coming back) now runs as long as the server keeps prefilling or decoding, and fails only when the request it depends on ends first or nothing moves for 120 s. Two upper bounds that were fixed seconds (the stream length the head may wait behind, and the wait behind a resident that ends by itself) now scale with the speed measured in the same run. A slow runner only makes the tests slower; the assertions on the behaviour under test are unchanged. --- tools/server/tests/unit/test_preempt.py | 158 +++++++++--------- .../server/tests/unit/test_preempt_notify.py | 46 +++-- 2 files changed, 111 insertions(+), 93 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 9b61b216f6dc..9c7319b2feb5 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -109,6 +109,33 @@ def _complete_all(n_predict: int, prompts=(_PROMPT_A, _PROMPT_B), timeout: float return parallel_function_calls([(_complete, (n_predict, prompt, -1, 0.0, None, timeout)) for prompt in prompts]) +def _server_progress(): + """What every slot has prefilled and decoded so far: it changes while the server is working, however slow the host.""" + return tuple((s["id"], s.get("id_task"), s.get("n_prompt_tokens_processed", 0), s.get("n_prompt_tokens", 0), + s.get("next_token", [{}])[0].get("n_decoded", 0), s.get("n_preempt", 0)) + for s in server.make_request("GET", "/slots").body) + + +def _await(cond, what: str, alive=None, stall: float = 120.0, poll: float = 0.02) -> None: + """Wait for cond() as long as the server keeps making progress, so a slow runner is only slower: fail if the request + it depends on ends first (alive() false) or nothing has moved for `stall` seconds, never on a wall-clock deadline.""" + last, t_last, t_check = None, time.time(), 0.0 + while not cond(): + if alive is not None and not alive(): + if cond(): + return + pytest.fail(f"{what}: the request it waits on ended first") # ty: ignore[invalid-argument-type] + now = time.time() + if now - t_check >= 0.5: + t_check = now + cur = _server_progress() + if cur != last: + last, t_last = cur, now + elif now - t_last > stall: + pytest.fail(f"{what}: the server made no progress for {stall:.0f} s") # ty: ignore[invalid-argument-type] + time.sleep(poll) + + def _wait_processing(slot_ids, timeout: float = 30.0): """Return once every one of these slots is processing; a request that ended first is a failure, not a hang.""" deadline = time.time() + timeout @@ -140,14 +167,19 @@ def _complete_together(n_predict: int, n_prompt, timeout: float = DEFAULT_REQUES def _wait_preempted(timeout: float = 30.0) -> bool: - """True once some slot is parked: its cells are in host RAM and it wants them back.""" - deadline = time.time() + timeout - while time.time() < deadline: + """True once some slot is parked: its cells are in host RAM and it wants them back. False once the server has gone + `timeout` seconds without progress and without parking: a slow host only takes longer.""" + last, t_last = None, time.time() + while True: slots = server.make_request("GET", "/slots").body if any(s["is_preempted"] for s in slots): return True + cur = _server_progress() + if cur != last: + last, t_last = cur, time.time() + elif time.time() - t_last > timeout: + return False time.sleep(0.005) - return False def _prompt_of(n_tokens: int, text: str) -> list: @@ -376,10 +408,8 @@ def lead(): leader = threading.Thread(target=lead, daemon=True) leader.start() try: - deadline = time.time() + 60 - while time.time() < deadline and _n_decoded(_slot_view(0)) <= 40: - time.sleep(0.005) - res = _raw_completion(1, head, 1, timeout=60) + _await(lambda: _n_decoded(_slot_view(0)) > 40, "the leader decoding 40 tokens", alive=leader.is_alive, poll=0.005) + res = _raw_completion(1, head, 1, timeout=600) finally: stop.set() leader.join(30) @@ -435,12 +465,8 @@ def run_unending(): t.start() try: - for _ in range(3000): - if "slot context shift" in _log(): - break - time.sleep(0.05) - else: - pytest.fail("the resident never reached the end of the pool") # ty: ignore[invalid-argument-type] + _await(lambda: "slot context shift" in open(server.log_path, errors="replace").read(), + "the resident reaching the end of the pool", alive=t.is_alive, poll=0.05) waiting = server.make_request("POST", "/completion", data={ "n_predict": 8, "prompt": _prompt_of(1800, _PROMPT_C), @@ -472,14 +498,10 @@ def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): except Exception: pass - for _ in range(600): - res = server.make_request("GET", "/slots") - assert res.status_code == 200 - if all(not slot["is_processing"] for slot in res.body): - break - time.sleep(0.2) - else: - pytest.fail("a slot never came back after a cancel during a copy") # ty: ignore[invalid-argument-type] + _await(lambda: all(not s["is_processing"] for s in server.make_request("GET", "/slots").body), + "every slot coming back after a cancel during a copy", poll=0.2) + res = server.make_request("GET", "/slots") + assert res.status_code == 200 for slot in res.body: assert slot["is_preempted"] is False assert slot["is_transferring"] is False @@ -828,13 +850,8 @@ def decoder(i): t.start() try: - for _ in range(600): - slots = server.make_request("GET", "/slots").body - if sum(1 for s in slots if s["is_processing"] and s["n_prompt_tokens"] > 0) >= 3: - break - time.sleep(0.1) - else: - pytest.fail("the decoders never started") # ty: ignore[invalid-argument-type] + _await(lambda: sum(1 for s in server.make_request("GET", "/slots").body if s["is_processing"] and s["n_prompt_tokens"] > 0) >= 3, + "the decoders starting", poll=0.1) time.sleep(1.0) beside = prefill(50000) @@ -855,8 +872,8 @@ def test_slots_reports_a_transferring_slot_apart_from_a_parked_one(): t.start() seen_parked = seen_transferring = False try: - deadline = time.time() + 120 - while time.time() < deadline and not (seen_parked and seen_transferring): + # polled for as long as the requests run, however long that is on this host + while t.is_alive() and not (seen_parked and seen_transferring): res = server.make_request("GET", "/slots") assert res.status_code == 200 for slot in res.body: @@ -866,7 +883,7 @@ def test_slots_reports_a_transferring_slot_apart_from_a_parked_one(): assert slot["n_prompt_tokens"] > 0, "a slot with a copy in flight still holds its cells" seen_parked = seen_parked or slot["is_preempted"] finally: - t.join(180) + t.join(1800) assert len(done) == 2, done for res in done: @@ -1064,8 +1081,7 @@ def test_slots_reports_the_recomputes_of_the_current_task(): seen = 0 try: - deadline = time.time() + 180 - while time.time() < deadline and seen == 0 and t.is_alive(): + while seen == 0 and t.is_alive(): res = server.make_request("GET", "/slots") assert res.status_code == 200 for slot in res.body: @@ -1073,7 +1089,7 @@ def test_slots_reports_the_recomputes_of_the_current_task(): seen = max(seen, slot["n_recompute"]) time.sleep(0.02) finally: - t.join(180) + t.join(1800) assert seen > 0, "no slot ever reported a recompute park" assert done and done[0].status_code == 200, done @@ -1161,14 +1177,8 @@ def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): t = threading.Thread(target=lambda: resident.append(_complete(1900, _PROMPT_A)), daemon=True) t.start() - deadline = time.time() + 90 - while t.is_alive() and time.time() < deadline: - slots = server.make_request("GET", "/slots").body - if any(slot.get("n_prompt_tokens", 0) >= 1600 for slot in slots): - break - time.sleep(0.005) - else: - pytest.fail("the resident never grew into the pool") # ty: ignore[invalid-argument-type] + _await(lambda: any(s.get("n_prompt_tokens", 0) >= 1600 for s in server.make_request("GET", "/slots").body), + "the resident growing into the pool", alive=t.is_alive, poll=0.005) n_prompt = 500 n_predict = 8 @@ -1271,12 +1281,13 @@ def stream(id_slot): w.start() try: - deadline = time.time() + 60 - while time.time() < deadline and len(shorts) < 6: - time.sleep(0.01) + _await(lambda: len(shorts) >= 6, "the short-request stream starting", poll=0.01) + # overtaken, the head waits until the stream stops: give it a span many short requests long, as slow as the host is + t_first_short = max((r.body["timings"]["prompt_ms"] + r.body["timings"]["predicted_ms"]) / 1e3 for _, r in list(shorts)) + t_stream_max = max(t_stream_max, 30 * t_first_short) t_head = time.time() with ThreadPoolExecutor(1) as pool: - fut = pool.submit(_raw_completion, n_head, head_prompt, 3, t_stream_max + 180) + fut = pool.submit(_raw_completion, n_head, head_prompt, 3, t_stream_max + 600) while not fut.done() and time.time() - t_head < t_stream_max: time.sleep(0.05) stopped_early = not fut.done() @@ -1321,10 +1332,10 @@ def run(name, n_predict, prompt, id_slot): done[name] = (time.time(), res) a = threading.Thread(target=run, args=("a", 16000, _prompt_of(64, _PROMPT_A), 0)) + t_a = time.time() a.start() - deadline = time.time() + 300 - while time.time() < deadline and _n_decoded(_slot_view(0)) < 2000: - time.sleep(0.01) + _await(lambda: _n_decoded(_slot_view(0)) >= 2000, "the resident decoding 2000 tokens", alive=a.is_alive, poll=0.01) + t_per_token = (time.time() - t_a) / 2000 b = threading.Thread(target=run, args=("b", 8000, _prompt_of(1500, _PROMPT_B), 1)) b.start() a.join(1800) @@ -1340,7 +1351,9 @@ def run(name, n_predict, prompt, id_slot): assert "slot context shift" not in text waits = [float(w) for w in re.findall(r"id +1 \| task \d+ \| resumed after ([\d.]+) s", text)] assert waits, "the second request was never parked" - assert max(waits) < 90.0, f"the parked request waited {waits} s behind a resident that ends by itself" + # waiting for the resident to end would take its remaining 14000 tokens; a rotation takes a small part of that, on any host + t_bound = max(90.0, 0.5 * 14000 * t_per_token) + assert max(waits) < t_bound, f"the parked request waited {waits} s behind a resident that ends by itself (bound {t_bound:.0f} s)" def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small_ones(): @@ -1353,12 +1366,8 @@ def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small with ThreadPoolExecutor(4) as pool: residents = [pool.submit(_raw_completion, 300, p, i) for i, p in enumerate(small + [medium])] - deadline = time.time() + 60 - while time.time() < deadline: - slots = server.make_request("GET", "/slots").body - if all(_n_decoded(s) > 0 for s in slots if s["id"] < 3): - break - time.sleep(0.002) + _await(lambda: all(_n_decoded(s) > 0 for s in server.make_request("GET", "/slots").body if s["id"] < 3), + "the three residents decoding", alive=lambda: not all(r.done() for r in residents), poll=0.002) last = pool.submit(_raw_completion, 8, leader, 3) results = [r.result() for r in residents] + [last.result()] @@ -1588,9 +1597,8 @@ def test_two_n_2_requests_that_do_not_fit_together_end_only_one(): _start(n_ctx=1024, n_slots=4, n_batch=128, n_ubatch=128) with ThreadPoolExecutor(2) as pool: first = pool.submit(_oai_n, [100 + k % 50 for k in range(200)], 2, 250) - deadline = time.time() + 30 - while time.time() < deadline and sum(s["is_processing"] for s in server.make_request("GET", "/slots").body) < 2: - time.sleep(0.005) + _await(lambda: sum(s["is_processing"] for s in server.make_request("GET", "/slots").body) >= 2, + "the first family on its two slots", alive=lambda: not first.done(), poll=0.005) second = pool.submit(_oai_n, [200 + k % 50 for k in range(200)], 2, 250) results = [first.result(), second.result()] assert sorted(r.status_code for r in results) == [200, 500], [r.body for r in results] @@ -1604,11 +1612,9 @@ def test_an_n_2_prompt_that_parked_an_older_request_is_not_held_behind_it(policy os.environ["LLAMA_ARG_PREEMPT_POLICY"] = policy _start(n_ctx=1024, n_slots=3, n_batch=128, cache_ram=0) with ThreadPoolExecutor(1) as pool: - single = pool.submit(_raw_completion, 300, [100 + k % 50 for k in range(600)], 0, 90) - deadline = time.time() + 60 - while time.time() < deadline and _n_decoded(_slot_view(0)) <= 4: - time.sleep(0.002) - family = _oai_n([200 + k % 50 for k in range(800)], 2, 1, timeout=90) + single = pool.submit(_raw_completion, 300, [100 + k % 50 for k in range(600)], 0, 900) + _await(lambda: _n_decoded(_slot_view(0)) > 4, "the single request decoding", alive=lambda: not single.done(), poll=0.002) + family = _oai_n([200 + k % 50 for k in range(800)], 2, 1, timeout=900) single = single.result() assert single.status_code == 200, single.body assert single.body["timings"]["predicted_n"] == 300 @@ -1624,9 +1630,7 @@ def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generati assert _cached(1, earlier, 1).status_code == 200 with ThreadPoolExecutor(1) as pool: older = pool.submit(_cached, 600, [100 + k % 50 for k in range(40)], 0) - deadline = time.time() + 60 - while time.time() < deadline and _n_decoded(_slot_view(0)) < 280: - time.sleep(0.002) + _await(lambda: _n_decoded(_slot_view(0)) >= 280, "the older request decoding 280 tokens", alive=lambda: not older.done(), poll=0.002) newer = _cached(4, earlier + [300 + k % 50 for k in range(300)], 1) older = older.result() for res, n_predict in ((older, 600), (newer, 4)): @@ -1645,9 +1649,7 @@ def test_the_policy_decides_whether_the_newest_or_the_cheapest_slot_is_parked(po assert _cached(1, [300 + k % 50 for k in range(150)], 2).status_code == 200 with ThreadPoolExecutor(1) as pool: older = pool.submit(_cached, 600, [100 + k % 50 for k in range(40)], 0) - deadline = time.time() + 60 - while time.time() < deadline and _n_decoded(_slot_view(0)) < 20: - time.sleep(0.005) + _await(lambda: _n_decoded(_slot_view(0)) >= 20, "the older request decoding 20 tokens", alive=lambda: not older.done(), poll=0.005) newer = _cached(500, [200 + k % 50 for k in range(300)], 1) older = older.result() for res, n_predict in ((older, 600), (newer, 500)): @@ -1697,10 +1699,7 @@ def test_fcfs_runs_the_oldest_to_the_end_of_the_window_beside_a_held_prompt(): oldest = pool.submit(lambda: server.make_request("POST", "/completion", timeout=600, data={ "n_predict": 100000, "prompt": [100 + k % 50 for k in range(20)], "id_slot": 0, "cache_prompt": True, "ignore_eos": True, "temperature": 0.0, "seed": 42})) - deadline = time.time() + 180 - while time.time() < deadline and _n_decoded(_slot_view(0)) < 100: - time.sleep(0.02) - assert _n_decoded(_slot_view(0)) >= 100, "the oldest did not start generating in time" + _await(lambda: _n_decoded(_slot_view(0)) >= 100, "the oldest generating 100 tokens", alive=lambda: not oldest.done()) # 120 cells and growing beside 4016: it cannot fit, so it is parked and is owed the cells first parked = pool.submit(_cached, 16, [200 + k % 50 for k in range(4000)], 1) assert _wait_preempted(120), "the second request was never parked, so the case was not reached" @@ -1727,10 +1726,7 @@ def test_a_started_slot_trimmed_below_its_sliding_window_prefills_again(): assert _cached(1, stale, 1).status_code == 200 with ThreadPoolExecutor(1) as pool: busy = pool.submit(_cached, 400, [300 + k % 50 for k in range(40)], 0) - deadline = time.time() + 180 - while time.time() < deadline and _n_decoded(_slot_view(0)) < 230: - time.sleep(0.02) - assert _n_decoded(_slot_view(0)) >= 230, "the busy slot did not fill the pool in time" + _await(lambda: _n_decoded(_slot_view(0)) >= 230, "the busy slot filling the pool", alive=lambda: not busy.done()) # 40 tokens in common, far below the 32 newest cells the window kept of the stale 200 res = _cached(16, stale[:40] + [400 + k % 50 for k in range(60)], 1) busy = busy.result() @@ -1774,9 +1770,7 @@ def test_a_prompt_dropped_in_its_prefill_waits_until_it_fits_whole(policy): assert server.make_request("GET", "/props").body["preempt"]["policy"] == policy with ThreadPoolExecutor(1) as pool: older = pool.submit(_cached, 1500, [100 + k % 50 for k in range(1500)], 0) - deadline = time.time() + 120 - while time.time() < deadline and _n_decoded(_slot_view(0)) < 100: - time.sleep(0.005) + _await(lambda: _n_decoded(_slot_view(0)) >= 100, "the older request decoding 100 tokens", alive=lambda: not older.done(), poll=0.005) newer = _cached(4, [200 + k % 50 for k in range(2500)], 1) older = older.result() for res, n_predict in ((older, 1500), (newer, 4)): diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py index 008a3d7dc0a0..4f3118de9c1d 100644 --- a/tools/server/tests/unit/test_preempt_notify.py +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -22,6 +22,7 @@ def create_server(): server = ServerPreset.tinyllama2() server.n_slots = 2 server.kv_unified = True + server.server_slots = True # _await() reads progress from /slots os.environ["LLAMA_ARG_PREEMPT_RAM"] = "8192" server.temperature = 0.0 server.seed = 42 @@ -61,6 +62,36 @@ def _log() -> str: return open(server.log_path, errors="replace").read() +def _slots() -> list: + return requests.get(f"http://{server.server_host}:{server.server_port}/slots").json() + + +def _server_progress(): + """What every slot has prefilled and decoded so far: it changes while the server is working, however slow the host.""" + return tuple((s["id"], s.get("id_task"), s.get("n_prompt_tokens_processed", 0), s.get("n_prompt_tokens", 0), + s.get("next_token", [{}])[0].get("n_decoded", 0), s.get("n_preempt", 0)) for s in _slots()) + + +def _await(cond, what: str, alive=None, stall: float = 120.0, poll: float = 0.02) -> None: + """Wait for cond() as long as the server keeps making progress (as in test_preempt.py): fail if the request it depends + on ends first or nothing has moved for `stall` seconds, never on a wall-clock deadline.""" + last, t_last, t_check = None, time.time(), 0.0 + while not cond(): + if alive is not None and not alive(): + if cond(): + return + pytest.fail(f"{what}: the request it waits on ended first") # ty: ignore[invalid-argument-type] + now = time.time() + if now - t_check >= 0.5: + t_check = now + cur = _server_progress() + if cur != last: + last, t_last = cur, now + elif now - t_last > stall: + pytest.fail(f"{what}: the server made no progress for {stall:.0f} s") # ty: ignore[invalid-argument-type] + time.sleep(poll) + + def _post(path: str, data: dict): return requests.post(f"http://{server.server_host}:{server.server_port}{path}", json=data, stream=True) @@ -99,7 +130,7 @@ def _resident(): t = threading.Thread(target=_resident) t.start() try: - assert started.wait(60) + _await(started.is_set, "the resident streaming its first token", alive=t.is_alive) res = _post("/completion", payload) if res.status_code != 200: return res.status_code, res.text, [] @@ -112,7 +143,7 @@ def _resident(): assert alive, "the resident had finished before this request was told anything" return 200, "", lines finally: - t.join(120) + t.join(1800) def _content(datas: list[str]) -> str: @@ -181,14 +212,7 @@ def _resident(): t = threading.Thread(target=_resident, daemon=True) t.start() - deadline = time.time() + 90 - while t.is_alive() and time.time() < deadline: - slots = requests.get(f"http://{server.server_host}:{server.server_port}/slots").json() - if any(slot.get("n_prompt_tokens", 0) >= 1400 for slot in slots): - break - time.sleep(0.02) - else: - pytest.fail("the resident never grew into the pool") # ty: ignore[invalid-argument-type] + _await(lambda: any(s.get("n_prompt_tokens", 0) >= 1400 for s in _slots()), "the resident growing into the pool", alive=t.is_alive) res = _post(path, _prefill_payload(path, " ".join([_PROMPT_B] * 31), 8)) assert res.status_code == 200 @@ -199,7 +223,7 @@ def _resident(): line = raw.decode("utf-8") if line: seen.append((time.time() - t0, line)) - t.join(120) + t.join(1800) text = _log() assert "preempted:" in text, "nothing was parked while the prompt was being processed" From fdc26c6cb0d72cab416f59ad2a3385eb22bfd5bc Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 13:33:13 -0700 Subject: [PATCH 093/109] server tests: the zero-budget park test overlaps its generations on any client Two 2000-token generations in 3840 cells overflowed only if the second started within ~180 tokens of the first; a slower client gave no park at all. 4000 each in 6144 cells (a model copy with a longer training context) overflow unless the second is ~1900 tokens late, and the shorter one then holds more than the 1 MiB budget, so the park still drops its cells. The planner-off variant sends both prompts in one request. --- tools/server/tests/unit/test_preempt.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 9c7319b2feb5..957b1a61d84e 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -581,10 +581,15 @@ def test_a_budget_that_holds_no_sequence_parks_by_dropping_the_cells(planner): os.environ["LLAMA_ARG_PREEMPT_RAM"] = "1" if planner == "off": os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" + # Two generations that overflow the pool together, each longer than the ~1500 tokens the 1 MiB budget holds when they do. + # With 4000 each in 6144 cells they overflow unless the second starts ~1900 tokens after the first (2000 in 3840 allowed + # only ~180, which a slow client exceeded), and the shorter one then holds over 2100 tokens, so the park drops its cells. + # A longer training context lets one slot take 4000 tokens. # One batch for the re-prefill: this prompt in 32-token batches hangs the CUDA build with graphs on, also on master. - _start(n_ctx=3840, n_batch=2048) + _serve_with_training_context(8192) + _start(n_ctx=6144, n_batch=4096) - n_predict = 2000 + n_predict = 4000 if planner == "on": results = parallel_function_calls([(_stream_completion, (n_predict, p)) for p in (_PROMPT_A, _PROMPT_B)]) for comments, final in results: @@ -593,7 +598,10 @@ def test_a_budget_that_holds_no_sequence_parks_by_dropping_the_cells(planner): comments = [c for cs, _ in results for c in cs] assert ": preempted" in comments and ": resumed" in comments, comments else: - _assert_completed(_complete_all(n_predict), n_predict) + # one request with both prompts: queued at once, whatever the client's speed + res = _complete_together(n_predict, (8, 8)) + assert res.status_code == 200, res.body + assert [r["tokens_predicted"] for r in res.body] == [n_predict, n_predict], res.body text = _log() assert "Context size has been exceeded" not in text From 463e1afd59523ae1b2ffc7469f77d22b8e36767a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 14:13:41 -0700 Subject: [PATCH 094/109] server, llama, tests: review fixes (round 9) - server: guard the second preempt_apply_shift() (the --cache-reuse shift before the decode loop) like the first; a throwing shift now fails the requests instead of terminating the server. - server: charge a park's RAM per buffer, so spare target capacity no longer hides the draft state's allocation. - server: a generating slot bounds its draft reservation by its own prompt, which a context shift made shorter than the task's; a slot still prefilling or re-prefilling keeps the whole input as the bound. - llama: llama_memory_n_cells_used() counts an owner given twice once, and an occupancy-only query reads the cells' used count (one cell per block) or skips the rest of a decided block. - tests: test-rpc-paged-fa counts only a failure armed after setup as a refusal; test-exact-pages and test-exact-weights fail when no exact context can be made; test-exact-pages checks the two counts agree. --- src/llama-kv-cache.cpp | 27 +++++++++++++++++++++------ tests/CMakeLists.txt | 4 ++-- tests/test-exact-pages.cpp | 18 ++++++++++++++++-- tests/test-exact-weights.cpp | 5 +++-- tests/test-memory-cells-used.cpp | 9 +++++++++ tests/test-rpc-paged-fa.cpp | 15 ++++++++++++--- tools/server/server-context.cpp | 30 ++++++++++++++++++++++++++---- 7 files changed, 89 insertions(+), 19 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 331b1d91b953..48f5cfee1cf5 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1539,10 +1539,24 @@ void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & int32_t llama_kv_cache::n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const { const uint32_t g = alloc_granularity(); + // a set, so an id given twice is one owner + llama_kv_cells::seq_set_t free_set; + for (size_t j = 0; n_reclaimable && j < n_seq_free; ++j) { + if (seq_free[j] >= 0 && seq_free[j] < LLAMA_MAX_SEQ) { + free_set.set(seq_free[j]); + } + } + int64_t n_used = 0; int64_t n_reclaim = 0; for (const auto & cells : v_cells) { + // occupancy alone, one cell per block: the cells keep the count + if (!n_reclaimable && g == 1) { + n_used += cells.get_used(); + continue; + } + // a block counts once one of its cells is live, and is reclaimable when every live cell in it is int64_t block = -1; bool block_free = true; @@ -1556,7 +1570,7 @@ int32_t llama_kv_cache::n_cells_used(const llama_seq_id * seq_free, size_t n_seq const uint32_t n = cells.used_max_p1(); - for (uint32_t i = 0; i < n; ++i) { + for (uint32_t i = cells.used_min(); i < n; ++i) { if (cells.is_empty(i)) { continue; } @@ -1568,11 +1582,12 @@ int32_t llama_kv_cache::n_cells_used(const llama_seq_id * seq_free, size_t n_seq } if (n_reclaimable && block_free) { - int n_in_free = 0; - for (size_t j = 0; j < n_seq_free; ++j) { - n_in_free += seq_free[j] >= 0 && seq_free[j] < LLAMA_MAX_SEQ && cells.seq_has(i, seq_free[j]); - } - block_free = n_in_free == cells.seq_count(i); + block_free = (cells.seq_get_all(i) & ~free_set).none(); + } + + // the block is decided: skip the rest of it + if (!n_reclaimable || !block_free) { + i = (uint32_t) (block + 1) * g - 1; } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0c2ddd68b3fc..7efe14a027af 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -338,8 +338,8 @@ llama_build_and_test(test-backend-sampler.cpp LABEL "model") llama_build_and_test(test-state-seq-copy.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-state-seq-copy PROPERTIES FIXTURES_REQUIRED test-download-model) -# [TAG_EXACT_CONCURRENCY] page bookkeeping of the paged KV pool, and a non-layer weight on the host refused; both skip themselves where the mode -# cannot run. Exact mode needs 256-wide K/V heads, which the generic test model does not have, so they run only against LLAMA_TEST_EXACT_MODEL. +# [TAG_EXACT_CONCURRENCY] page bookkeeping of the paged KV pool, and a non-layer weight on the host refused. Exact mode needs CUDA and 256-wide +# K/V heads, which the generic test model does not have, so they run only against LLAMA_TEST_EXACT_MODEL, and fail if no exact context can be made. set(LLAMA_TEST_EXACT_MODEL "" CACHE FILEPATH "a model with 256-wide K/V heads for the exact-concurrency model tests") llama_build(test-exact-pages.cpp) llama_build(test-exact-weights.cpp) diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index b4ccf65396d2..2fd451190c8e 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -71,9 +71,10 @@ int main(int argc, char ** argv) { return 1; } + // the test runs only when a model was named for it, so a context that cannot be made is a failure, never a pass if (ctx == nullptr) { - printf("%s : skipped, this build and model cannot run exact concurrency\n", __func__); - return 0; + fprintf(stderr, "%s : FAIL, no exact-concurrency context for this build and model (needs CUDA and 256-wide K/V heads)\n", __func__); + return 1; } llama_memory_t mem = llama_get_memory(ctx); @@ -121,6 +122,19 @@ int main(int argc, char ** argv) { return 1; } + { + // 656 tokens hold 3 pages; the occupancy-only count (block skip) must agree with the count that also sizes reclaim + const llama_seq_id s0[] = { 0, 0 }; + int32_t reclaim = -1; + const int32_t n_fast = llama_memory_n_cells_used(mem, nullptr, 0, nullptr); + const int32_t n_full = llama_memory_n_cells_used(mem, s0, 2, &reclaim); + if (n_fast != 3*(int32_t) PAGE || n_full != n_fast || reclaim != n_fast) { + fprintf(stderr, "%s : cells used %d (occupancy only) / %d (with reclaim %d), expected %u for 656 tokens\n", + __func__, n_fast, n_full, reclaim, 3*PAGE); + return 1; + } + } + const bool holes = llama_memory_seq_rm(mem, 0, 1, 511); if (holes && llama_memory_seq_pos_max(mem, 0) != 655) { diff --git a/tests/test-exact-weights.cpp b/tests/test-exact-weights.cpp index ee7aa9ec972c..d1d50d7307bc 100644 --- a/tests/test-exact-weights.cpp +++ b/tests/test-exact-weights.cpp @@ -62,10 +62,11 @@ int main(int argc, char ** argv) { ggml_backend_load_all(); llama_backend_init(); + // without the plain context the refusal below would pass for any reason, so this fails rather than skips if (!context_ok(path, nullptr)) { - printf("%s : skipped, this build and model cannot run exact concurrency\n", __func__); + fprintf(stderr, "%s : FAIL, no exact-concurrency context for this build and model (needs CUDA and 256-wide K/V heads)\n", __func__); llama_backend_free(); - return 0; + return 1; } const llama_model_tensor_buft_override host_norm[] = { diff --git a/tests/test-memory-cells-used.cpp b/tests/test-memory-cells-used.cpp index ad64126fa932..d196ebbe645f 100644 --- a/tests/test-memory-cells-used.cpp +++ b/tests/test-memory-cells-used.cpp @@ -92,6 +92,15 @@ int main(int argc, char ** argv) { llama_memory_n_cells_used(mem, all, 3, &reclaim); bad += check("reclaimable if every sequence went", reclaim, 190); + // an id given twice is still one owner: the prefix shared with seq 2 stays, seq 0's own cells go + const llama_seq_id s00[] = { 0, 0 }; + const llama_seq_id s001[] = { 0, 0, 1 }; + llama_memory_n_cells_used(mem, s00, 2, &reclaim); + bad += check("reclaimable if seq 0 (given twice) went: its own 20", reclaim, 20); + + llama_memory_n_cells_used(mem, s001, 3, &reclaim); + bad += check("reclaimable if seqs 0 (twice) and 1 went: 20 + 30", reclaim, 50); + // removing seq 0 frees only its own cells: the copied prefix is still held by 1 and 2 llama_memory_seq_rm(mem, 0, -1, -1); bad += check("used after seq 0 is removed: 100 + 30 + 40", llama_memory_n_cells_used(mem, nullptr, 0, nullptr), 170); diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp index 8dcec770ed38..185bb6ce7396 100644 --- a/tests/test-rpc-paged-fa.cpp +++ b/tests/test-rpc-paged-fa.cpp @@ -39,6 +39,10 @@ enum { CLIENT_REFUSED = 20, // the server answered the compute with a failure }; +static void on_server_dropped(int) { + _exit(CLIENT_REFUSED); +} + [[noreturn]] static void send_graph(const std::string & endpoint, bool paged) { alarm(120); @@ -71,7 +75,11 @@ enum { } ggml_backend_buffer_clear(buf, 0); - // everything above is setup; from here a failure or a dropped connection is the server's answer + // everything above is setup; from here a failure or a dropped connection is the server's answer. + // The client aborts (or takes SIGPIPE) when the server closes on it, so only these two, armed here, mean a refusal. + signal(SIGABRT, on_server_dropped); + signal(SIGPIPE, on_server_dropped); + if (ggml_backend_graph_compute(backend, gf) != GGML_STATUS_SUCCESS) { _exit(CLIENT_REFUSED); } @@ -166,8 +174,9 @@ int main() { } else if (paged == 0) { fprintf(stderr, "the RPC server computed a FLASH_ATTN_EXT that carries a page table\n"); rc = 1; - } else if (paged == CLIENT_NO_BACKEND || paged == CLIENT_NO_BUFFER) { - fprintf(stderr, "the paged client failed in its own setup (%d) before the server saw the graph, so this test proves nothing\n", paged); + } else if (paged != CLIENT_REFUSED) { + // a setup failure, a signal before the compute, or the client's own timeout: not the server's answer + fprintf(stderr, "the paged client ended with %d, not a refusal from the server, so this test proves nothing\n", paged); rc = 1; } else { printf("ok, the RPC server refused the paged graph and kept serving\n"); diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 352d03bb3111..9a2ae2078a5d 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -645,6 +645,18 @@ struct server_slot { (ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0); } + // [TAG_PREEMPT] RAM a park adds beyond what it holds, per buffer: spare target capacity cannot take the draft's state. + size_t preempt_state_extra() const { + const size_t need_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); + const size_t need_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; + + const size_t held_tgt = preempt_is_async() ? llama_state_seq_copy_buf_capacity(preempt_cpy_tgt.get()) : preempt_state_tgt.size(); + const size_t held_dft = preempt_is_async() ? (preempt_cpy_dft ? llama_state_seq_copy_buf_capacity(preempt_cpy_dft.get()) : 0) + : preempt_state_dft.size(); + + return (need_tgt > held_tgt ? need_tgt - held_tgt : 0) + (need_dft > held_dft ? need_dft - held_dft : 0); + } + // Take the slot out of the next step; the draft is a prediction, so it is dropped with the cells. void preempt_detach() { // [TAG_PREEMPT] Accepted tokens waiting for a replay after a checkpoint restore are output already decided: keep them, the cells are at the checkpoint. @@ -4256,7 +4268,10 @@ struct server_context_impl { } // A recompute park emptied the prompt, so bound the draft by preempt_tokens; reading the empty prompt once failed a fitting sequence as impossible. - const int32_t n_tokens = std::max(slot.prompt.n_tokens(), slot.preempt_n_input()); + // A generating slot reads its own prompt: a context shift made it shorter than the task's, and the task's would undercharge the draft. + const bool generating = slot.state == SLOT_STATE_GENERATING || (slot.preempt_is_out() && slot.state_before_preempt == SLOT_STATE_GENERATING); + const bool n_from_input = slot.preempt_recompute || slot.preempt_reprefill || !generating; + const int32_t n_tokens = n_from_input ? std::max(slot.prompt.n_tokens(), slot.preempt_n_input()) : slot.prompt.n_tokens(); res = std::min(res, slot.n_ctx - n_tokens - 2); @@ -4336,8 +4351,7 @@ struct server_context_impl { return false; } - const size_t need = slot.preempt_state_required(); - const size_t extra = need > held ? need - held : 0; + const size_t extra = slot.preempt_state_extra(); preempt_reclaim_idle_ram(budget, extra, slot); @@ -5840,7 +5854,15 @@ struct server_context_impl { int32_t n_batch = llama_n_batch(ctx_tgt); // [TAG_PREEMPT_ASYNC] A --cache-reuse shift is found inside pre_decode(), after the wait above; apply it to the draft too, or a KV-full park saves a draft state with the shift still pending. - preempt_apply_shift(); + try { + preempt_apply_shift(); + } catch (const std::exception & e) { + SRV_ERR("preempt_apply_shift() failed: %s\n", e.what()); + abort_all_slots("preempt_apply_shift() failed: " + std::string(e.what())); + + // the batch holds positions the shift did not move, skip now to avoid UB + return; + } for (int32_t off = 0; off < batch.size(); off = off_next) { const int32_t n_tokens = std::min(n_batch, batch.size() - off); From 8256bfb4bc101dedf06d01ccd7d0d79625c4c79d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 15:20:42 -0700 Subject: [PATCH 095/109] server, llama, tests: review fixes (round 10) - server: victim and rotation estimates, and the n_cmpl > 1 family ended when nothing can be parked, count the cells that would actually be freed (llama_memory_n_cells_used with the sequences given), so a prefix shared with another sequence no longer inflates them; rotation reads its candidates together. - server: the resume projection charges a prompt held behind the head only for the cells it sits on. - server: the growth estimate keeps the capacity of a grow-only park buffer when the next state is smaller, and counts a held draft buffer. - server: exact concurrency disables the RAM prompt cache, since every prompt is prefilled in full there. - llama: the indexed hybrid memory refuses shared tokens and isolates prompts under exact concurrency, as the hybrid memory does. - tests: test-paged-fa-supports fails instead of skipping when a build with the flash attention kernels refuses a valid paged shape; the async test gate reads the log up to its last startup line; the M-RoPE refusal test gets a batch that passes the batch geometry check. --- src/llama-memory-hybrid-idx.cpp | 12 +++- tests/CMakeLists.txt | 4 ++ tests/test-paged-fa-supports.cpp | 10 +++- tools/server/server-context.cpp | 73 ++++++++++++++++++++++--- tools/server/tests/unit/test_preempt.py | 24 ++++++-- 5 files changed, 108 insertions(+), 15 deletions(-) diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp index 2c5a57680dc8..658d12db6dbd 100644 --- a/src/llama-memory-hybrid-idx.cpp +++ b/src/llama-memory-hybrid-idx.cpp @@ -76,6 +76,13 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx( llama_memory_context_ptr llama_memory_hybrid_idx::init_batch(llama_batch_allocr & balloc, uint32_t n_ubatch, bool embd_all) { // note: repeats llama_memory_hybrid::init_batch, as the indexer needs the attention slot infos that the base context hides do { + // [TAG_EXACT_CONCURRENCY] as llama_memory_hybrid::init_batch: refused before the attention half asserts on it + if (llama_exact_concurrency() && balloc.has_shared_tokens()) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support tokens shared by several sequence ids; " + "give every token exactly one sequence id\n", __func__); + break; + } + balloc.split_reset(); // follow the recurrent pattern for creating the ubatch splits @@ -96,7 +103,10 @@ llama_memory_context_ptr llama_memory_hybrid_idx::init_batch(llama_batch_allocr // so that the rollback snapshots remain valid const uint32_t n_rs_seq = get_mem_recr()->n_rs_seq; - ubatch = balloc.split_equal(n_ubatch, !unified, n_rs_seq > 0 ? n_rs_seq + 1 : 0); + // [TAG_EXACT_CONCURRENCY] as llama_memory_hybrid::init_batch: the recurrent half is not invariant to the ubatch shape, so a prompt gets a ubatch of its own + const uint32_t isolate = llama_exact_concurrency() ? llama_exact_decode_tokens() : 0; + + ubatch = balloc.split_equal(n_ubatch, !unified, n_rs_seq > 0 ? n_rs_seq + 1 : 0, isolate); } if (ubatch.n_tokens == 0) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 7efe14a027af..d5d85986674b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -327,6 +327,10 @@ llama_build_and_test(test-event-query.cpp LINK ggml) # [TAG_EXACT_CONCURRENCY] a paged FLASH_ATTN_EXT is claimed only in the shapes the paged kernel launches llama_build_and_test(test-paged-fa-supports.cpp LINK ggml) +if (GGML_CUDA_FA AND (GGML_CUDA OR GGML_HIP)) + # the paged kernel is compiled in, so the test expects it rather than skipping when a valid shape is refused + target_compile_definitions(test-paged-fa-supports PRIVATE LLAMA_TEST_PAGED_FA_ENABLED) +endif() llama_build_and_test(test-tiled-mulmat.cpp LINK ggml) llama_build_and_test(test-model-load-cancel.cpp LABEL "model") diff --git a/tests/test-paged-fa-supports.cpp b/tests/test-paged-fa-supports.cpp index 5d2eabd3f12b..43a40fbaabb2 100644 --- a/tests/test-paged-fa-supports.cpp +++ b/tests/test-paged-fa-supports.cpp @@ -72,6 +72,14 @@ int main() { } if (!supports(dev, shapes[0])) { +#if defined(LLAMA_TEST_PAGED_FA_ENABLED) + // the build compiled the flash attention kernels for CUDA / ROCm, so refusing a valid paged shape is the failure, not a reason to skip + if (strcmp(reg_name, "MUSA") != 0) { + fprintf(stderr, "%s: FAIL, refuses the valid paged shape '%s' in a build with flash attention\n", ggml_backend_dev_name(dev), shapes[0].name); + rc = 1; + continue; + } +#endif printf("%s: no paged flash attention in this build, skipped\n", ggml_backend_dev_name(dev)); continue; } @@ -87,7 +95,7 @@ int main() { } } - if (n_checked == 0) { + if (n_checked == 0 && rc == 0) { printf("no CUDA device with paged flash attention, nothing to check\n"); } else { printf("%s\n", rc == 0 ? "ok: supports_op accepts exactly the paged shapes the kernel launches" : diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 9a2ae2078a5d..78d9b2858037 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -572,8 +572,9 @@ struct server_slot { // [TAG_PREEMPT_ASYNC] Grow pinned buffers by 1.5x so a slightly longer re-park does not re-pin. static size_t preempt_grown_capacity(size_t held, size_t need) { + // the buffers never shrink: a smaller state leaves the capacity where it was if (need <= held || held == 0) { - return need; + return std::max(held, need); } const size_t step = 64u << 10; @@ -607,7 +608,8 @@ struct server_slot { size_t res = preempt_grown_capacity(llama_state_seq_copy_buf_capacity(preempt_cpy_tgt.get()), size_tgt); - if (size_dft > 0 && preempt_cpy_dft) { + // a draft buffer is held whether or not this park fills it + if (preempt_cpy_dft) { res += preempt_grown_capacity(llama_state_seq_copy_buf_capacity(preempt_cpy_dft.get()), size_dft); } @@ -2331,6 +2333,13 @@ struct server_context_impl { params_base.cache_idle_slots = false; } + // [TAG_EXACT_CONCURRENCY] Exact mode prefills every prompt in full (slot_reuses_prefix()), so a state restored from RAM would be thrown away + if (common_exact_concurrency() && (params_base.cache_ram_mib != 0 || params_base.cache_idle_slots)) { + SRV_INF("%s", "exact concurrency: prompt cache disabled, prompts are always prefilled in full\n"); + params_base.cache_ram_mib = 0; + params_base.cache_idle_slots = false; + } + if (params_base.cache_ram_mib != 0) { if (params_base.cache_ram_mib < 0) { SRV_TRC("prompt cache is enabled, size limit: %s\n", "no limit"); @@ -4468,14 +4477,28 @@ struct server_context_impl { // [TAG_PREEMPT] Occupancy read from the KV cells themselves: a cell several sequences share counts once, whoever's task tree it came from. // With n_idle, also the cells only idle slots hold, which purging them would free. -1 when the memory cannot tell; the estimates below are the fallback. - int32_t preempt_kv_cells(int32_t * n_idle) const { + // The memory whose cells the planner can read, or null: LLAMA_SERVER_PREEMPT_GRANULARITY (test knob) plans in blocks the memory does not have. + llama_memory_t preempt_kv_mem() const { llama_memory_t mem = ctx_tgt ? llama_get_memory(ctx_tgt) : nullptr; - if (!mem) { + + return mem && (uint32_t) preempt_alloc_granularity == llama_memory_alloc_granularity(mem) ? mem : nullptr; + } + + // [TAG_PREEMPT] Cells freed if these sequences all went: a prefix one of them shares with a sequence that stays is not counted. -1 if unknown. + int32_t preempt_kv_reclaim(const std::vector & seqs) const { + llama_memory_t mem = preempt_kv_mem(); + int32_t res = -1; + + if (!mem || llama_memory_n_cells_used(mem, seqs.data(), seqs.size(), &res) < 0) { return -1; } - // LLAMA_SERVER_PREEMPT_GRANULARITY (test knob) plans in blocks the memory does not have, so its cells cannot be read in them - if ((uint32_t) preempt_alloc_granularity != llama_memory_alloc_granularity(mem)) { + return res; + } + + int32_t preempt_kv_cells(int32_t * n_idle) const { + llama_memory_t mem = preempt_kv_mem(); + if (!mem) { return -1; } @@ -4554,6 +4577,12 @@ struct server_context_impl { continue; } + // [TAG_PREEMPT] A held prompt does not grow before the head has had its turn: charge only the cells it sits on, as preempt_kv_reserve() does. + if (preempt_held(slot)) { + res += preempt_n_cells(slot.prompt.n_tokens()); + continue; + } + const int32_t n = preempt_n_final(slot); if (n < 0 || preempt_is_family(slot) || slot.state == SLOT_STATE_WAIT_OTHER) { @@ -4831,10 +4860,19 @@ struct server_context_impl { return false; } + // Cells a park of this slot releases; a prefix it shares with another sequence stays. + int32_t preempt_n_freed_cells(const server_slot & slot) const { + if (const int32_t n = preempt_kv_reclaim({ slot.id }); n >= 0) { + return n; + } + + return preempt_n_cells(slot.prompt.n_tokens()); + } + int32_t preempt_n_freed(const server_slot & slot) const { const int32_t n_cur = slot.prompt.n_tokens(); - int32_t res = preempt_n_cells(n_cur); + int32_t res = preempt_n_freed_cells(slot); if (slot.state == SLOT_STATE_GENERATING) { res += preempt_n_cells_step(n_cur, 1 + preempt_n_spec(slot)); @@ -5392,6 +5430,11 @@ struct server_context_impl { auto rotate_pick = [&](bool with_recompute) { n_freed_all = 0; + // [TAG_PREEMPT] A prefix two candidates share is freed only if both go, so all of them are read together. + std::vector seqs_all; + int32_t n_steps_all = 0; + int32_t n_pick = 0; + for (auto & slot : slots) { // [TAG_PREEMPT] Residents that have had their service since resuming, and held prompts sitting on cells. const bool held = preempt_held(slot) && slot.prompt.n_tokens() > 0; @@ -5420,9 +5463,10 @@ struct server_context_impl { } const int32_t n_freed = preempt_n_freed(slot); - const int32_t n_pick = pick ? preempt_n_freed(*pick) : 0; n_freed_all += n_freed; + n_steps_all += n_freed - preempt_n_freed_cells(slot); + seqs_all.push_back(slot.id); const bool enough = room_after(n_freed); @@ -5431,8 +5475,13 @@ struct server_context_impl { (enough == pick_enough && (enough ? n_freed < n_pick : n_freed > n_pick))) { pick = &slot; pick_enough = enough; + n_pick = n_freed; } } + + if (const int32_t n = seqs_all.empty() ? -1 : preempt_kv_reclaim(seqs_all); n >= 0) { + n_freed_all = n + n_steps_all; + } }; // [TAG_PREEMPT] Short alone, a pick is only a first step: if every candidate together cannot make room, it would wait parked beside the head for nothing. @@ -7058,12 +7107,20 @@ struct server_context_impl { int32_t n = 0; + std::vector seqs; + for (const auto & other : slots) { if (running(other) && preempt_is_family(other) && family_of(other) == family_of(slot)) { n += other.prompt.n_tokens(); + seqs.push_back(other.id); } } + // [TAG_PREEMPT] The members share their prompt's cells, so the sum of their prompts counts it once per member; read what ending them frees. + if (const int32_t n_freed = preempt_kv_reclaim(seqs); n_freed >= 0) { + n = n_freed; + } + if (family < 0 || n > n_cells) { family = family_of(slot); n_cells = n; diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 957b1a61d84e..8df9f7d174c4 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -69,7 +69,7 @@ def _start_async(**kwargs): """As _start, on the asynchronous park path; a backend that cannot copy off-thread skips the test.""" os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "1" _start(n_gpu_layer=99, **kwargs) - _require_async(_log()) + _require_async() def _log() -> str: @@ -85,8 +85,21 @@ def _log() -> str: return open(server.log_path, errors="replace").read() -def _require_async(text: str): - if _ASYNC_BANNER not in text: +def _startup_log() -> str: + """The server log up to its last startup line: the log is written by its own thread, so it can lag the server being up, + and a capability banner missing from a lagging log is not a missing capability.""" + deadline = time.time() + 60.0 + while True: + text = open(server.log_path, errors="replace").read() + if "listening on " in text: + return text + if time.time() > deadline: + pytest.fail("the server log never reached its last startup line") # ty: ignore[invalid-argument-type] + time.sleep(0.05) + + +def _require_async(): + if _ASYNC_BANNER not in _startup_log(): pytest.skip("this backend cannot copy asynchronously, the async park path is not exercised") # ty: ignore[too-many-positional-arguments] @@ -225,7 +238,7 @@ def test_forced_parks_do_not_change_the_output(mode): os.environ["LLAMA_ARG_PREEMPT_ASYNC"] = "1" if mode == "async" else "0" _start(n_ctx=512) if mode == "async": - _require_async(_log()) + _require_async() reference = _complete(64) assert reference.status_code == 200 server.stop() @@ -744,7 +757,8 @@ def test_exact_concurrency_refuses_an_mrope_model_with_a_projector(): proc = subprocess.run([ os.environ.get("LLAMA_SERVER_BIN_PATH", "../../../build/bin/llama-server"), "--model", path, "--mmproj", mmproj, "--host", "127.0.0.1", "--port", str(server.server_port), - "-c", "512", "--parallel", "2", "--kv-unified", "-fa", "on", "-ngl", "99", "--no-warmup", "--no-webui", + # a batch that holds a whole ubatch, so the batch geometry check passes and the M-RoPE one is what refuses + "-c", "512", "-b", "512", "-ub", "128", "--parallel", "2", "--kv-unified", "-fa", "on", "-ngl", "99", "--no-warmup", "--no-webui", ], env={**os.environ, "LLAMA_EXACT_CONCURRENCY": "1"}, capture_output=True, text=True, timeout=900) out = proc.stdout + proc.stderr assert proc.returncode != 0, out From ac1dbf8723ae7aaf2d944722582fcff875ba5d60 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 16:31:33 -0700 Subject: [PATCH 096/109] server, llama: review fixes (round 11) - llama: llama_memory_update() returns -1 when an update is still due after the call (a K-shift that failed to allocate or compute only logs); the server then fails the requests instead of parking a sequence whose shifted positions do not match its K. - server: a generating slot parked in RAM after a context shift projects its final size from its own prompt; the planner's kept prefix takes the batch builder's shared-prefix and decision bounds; the resident projection is summed in 64 bits. - llama: under exact concurrency, seq_id -1 (the whole cache) is refused on the per-sequence save paths too, before a file is opened, and a context without sequence memory (an encoder, whose batches are not isolated) is refused. - llama, ggml-cuda: document that the exact decode width is process-wide, so a context created later with a wider n_seq_max changes the numerics of contexts already decoding; GGML_CUDA_BATCH_INVARIANT_MAX_COLS pins it. --- ggml/src/ggml-cuda/ggml-cuda.cu | 4 +++- include/llama.h | 8 ++++++-- src/llama-context.cpp | 33 ++++++++++++++++++++++++++++++--- tests/test-exact-pages.cpp | 18 ++++++++++++++++++ tools/server/server-context.cpp | 30 ++++++++++++++++++++---------- 5 files changed, 77 insertions(+), 16 deletions(-) diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index e379c0695ce6..23bc50d31d81 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -2001,7 +2001,9 @@ int ggml_cuda_batch_invariant() { return mode; } -// [TAG_EXACT_CONCURRENCY] the widest decode ubatch the caller says it can build, 0 if it never said +// [TAG_EXACT_CONCURRENCY] the widest decode ubatch the caller says it can build, 0 if it never said. By design it is process-wide and only +// grows: a context created later with a wider n_seq_max moves the column bound for every context, so their numerics change with it (see +// llama_set_exact_decode_width in llama.h); GGML_CUDA_BATCH_INVARIANT_MAX_COLS pins the bound. static std::atomic g_exact_decode_width{0}; void ggml_backend_cuda_set_exact_decode_width(int n_cols) { diff --git a/include/llama.h b/include/llama.h index 22463441a147..bd0b84460d67 100644 --- a/include/llama.h +++ b/include/llama.h @@ -839,14 +839,18 @@ extern "C" { int32_t * n_reclaimable); // [TAG_PREEMPT] run the in-place update a seq_add() recorded, which llama_decode() would otherwise run at the start of the next batch - // takes the context because the update is a graph; returns true when one was run - LLAMA_API bool llama_memory_update(struct llama_context * ctx); + // takes the context because the update is a graph; returns 1 when one was run, 0 when none was due, and -1 when one is still due + // after the call (the update failed): the shifted positions do not match their K yet, so the cells must not be saved or dropped + LLAMA_API int32_t llama_memory_update(struct llama_context * ctx); // [TAG_EXACT_CONCURRENCY] the most tokens one sequence contributes to a decode step: 1, or 1 plus the draft length. Never lowered; false when a column bound cannot cover it. LLAMA_API bool llama_set_exact_decode_tokens(uint32_t n_tokens); LLAMA_API uint32_t llama_exact_decode_tokens(void); // [TAG_EXACT_CONCURRENCY] the widest decode ubatch this process can build, in columns; never lowered, and false when GGML_CUDA_BATCH_INVARIANT_MAX_COLS is below it + // The width is process-wide and picks the kernels of every context: results are invariant to concurrency at a fixed width, so create every + // context (each raises it to fit its n_seq_max) before decoding; a context created later with a wider n_seq_max changes the numerics of + // contexts already decoding. Setting GGML_CUDA_BATCH_INVARIANT_MAX_COLS pins the policy instead. LLAMA_API bool llama_set_exact_decode_width(uint32_t n_cols); LLAMA_API uint32_t llama_exact_decode_width(void); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index cdcd13a30ac4..7b2e0dd8c635 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -546,6 +546,12 @@ llama_context::llama_context( LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set and this context has a KV cache, so it cannot be created with non-causal attention\n", __func__); throw std::runtime_error("exact concurrency: non-causal attention is not supported with a KV cache"); } + + // [TAG_EXACT_CONCURRENCY] without a memory, decode() runs encode(), which packs the sequences of a batch into one ubatch with no isolation + if (llama_exact_concurrency() && !memory) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but this model has no sequence memory (an encoder); its batches are not isolated per sequence\n", __func__); + throw std::runtime_error("exact concurrency: a context without sequence memory is not supported"); + } } // init backends @@ -4356,6 +4362,11 @@ size_t llama_context::state_seq_load_file(llama_seq_id seq_id, const char * file } size_t llama_context::state_seq_save_file(llama_seq_id seq_id, const char * filepath, const llama_token * tokens, size_t n_token_count) { + // refused before the destination is opened, so an existing file is not truncated + if (seq_id == -1) { + state_write_check(); + } + llama_file file(filepath, "wb"); file.write_u32(LLAMA_STATE_SEQ_MAGIC); @@ -4436,6 +4447,11 @@ size_t llama_context::state_read_data(llama_io_read_i & io) { } size_t llama_context::state_seq_write_data(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) { + // [TAG_EXACT_CONCURRENCY] seq_id -1 is the whole cache, which cannot be restored in this mode either + if (seq_id == -1) { + state_write_check(); + } + if (memory) { memory->state_write(io, seq_id, flags); } @@ -5287,12 +5303,23 @@ int32_t llama_memory_n_cells_used(llama_memory_t mem, const llama_seq_id * seq_f return mem->n_cells_used(seq_free, n_seq_free, n_reclaimable); } -bool llama_memory_update(llama_context * ctx) { +int32_t llama_memory_update(llama_context * ctx) { if (!ctx) { - return false; + return 0; + } + + const bool ran = ctx->memory_update(false); + + // memory_update() logs a failed K-shift and returns, leaving the shift recorded; ask the memory whether one is still due + if (llama_memory_t mem = ctx->get_memory()) { + const auto mctx = mem->init_update(ctx, false); + + if (!mctx || mctx->get_status() != LLAMA_MEMORY_STATUS_NO_UPDATE) { + return -1; + } } - return ctx->memory_update(false); + return ran ? 1 : 0; } // llama state API diff --git a/tests/test-exact-pages.cpp b/tests/test-exact-pages.cpp index 2fd451190c8e..e6c70f10ee45 100644 --- a/tests/test-exact-pages.cpp +++ b/tests/test-exact-pages.cpp @@ -230,6 +230,24 @@ int main(int argc, char ** argv) { fprintf(stderr, "%s : a whole-context state was restored\n", __func__); return 1; } + + // seq_id -1 is the whole cache on the per-sequence API too: no state, and no file, since it could not be restored + if (llama_state_seq_get_size(ctx, -1) != 0 || llama_state_seq_get_data(ctx, whole.data(), whole.size(), -1) != 0) { + fprintf(stderr, "%s : a whole-cache state was saved through the per-sequence API\n", __func__); + return 1; + } + + const char * seq_file = "test-exact-pages.seq"; + std::remove(seq_file); + + if (llama_state_seq_save_file(ctx, seq_file, -1, &tok, 1) != 0 || (f = fopen(seq_file, "rb")) != nullptr) { + if (f) { + fclose(f); + } + std::remove(seq_file); + fprintf(stderr, "%s : a whole-cache sequence file was written\n", __func__); + return 1; + } } printf("%s : ok, page ownership survived a no-op removal, holes and a full removal, and a negative restored position and a whole-context save and restore were refused\n", __func__); diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 78d9b2858037..48ac5e897adf 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4409,6 +4409,15 @@ struct server_context_impl { size_t n_keep = slot.prompt.tokens.get_common_prefix(slot.task->tokens); + // the bounds the batch builder applies to n_past: a decision group's children start from the shared prefix, and a decision's first position is evaluated + if (slot.task->n_tokens_shared > 0) { + n_keep = std::min(n_keep, (size_t) slot.task->n_tokens_shared); + } + + if (const int32_t n_decision_first = slot.task->type == SERVER_TASK_TYPE_DECISION ? slot.task->decision.pos_first() : -1; n_decision_first >= 0) { + n_keep = std::min(n_keep, (size_t) n_decision_first); + } + if (slot.alora_invocation_start > 0) { n_keep = std::min(n_keep, (size_t) (slot.alora_invocation_start - 1)); } @@ -4562,15 +4571,17 @@ struct server_context_impl { return -1; } - const int32_t n_cur = std::max(slot.prompt.n_tokens(), slot.state == SLOT_STATE_GENERATING ? 0 : slot.preempt_n_input()); + // a generating slot, also one parked in RAM, reads its own prompt: a context shift made it shorter than the task's + const bool generating = slot.state == SLOT_STATE_GENERATING || (slot.preempt_is_out() && slot.state_before_preempt == SLOT_STATE_GENERATING); + const int32_t n_cur = std::max(slot.prompt.n_tokens(), !generating || slot.preempt_recompute || slot.preempt_reprefill ? slot.preempt_n_input() : 0); // n_predict may be INT32_MAX: sum in 64 bits before clamping return preempt_n_cells((int32_t) std::min(slot.n_ctx, int64_t(n_cur) + slot.n_remaining() + 1)); } - // Cells the residents hold once each reaches its output limit; -1 if one has no limit, or shares cells with a sibling. - int32_t preempt_kv_projected() const { - int32_t res = 0; + // Cells the residents hold once each reaches its output limit; -1 if one has no limit, or shares cells with a sibling. 64 bits: many slots of a large context overflow 32. + int64_t preempt_kv_projected() const { + int64_t res = 0; for (const auto & slot : slots) { if (!slot.is_processing() || slot.state == SLOT_STATE_PREEMPTED) { @@ -5268,10 +5279,9 @@ struct server_context_impl { preempt_wait_for_shift(); - llama_memory_update(ctx_tgt); - - if (ctx_dft) { - llama_memory_update(ctx_dft); + // a shift that did not complete stays recorded: a park now would save moved positions with unshifted K and drop the pending deltas + if (llama_memory_update(ctx_tgt) < 0 || (ctx_dft && llama_memory_update(ctx_dft) < 0)) { + throw std::runtime_error("the KV cache shift did not complete"); } } @@ -5381,11 +5391,11 @@ struct server_context_impl { const int32_t margin = occupied == 0 ? 0 : preempt_n_margin(1); // [TAG_PREEMPT] With every resident bounded, also wait until all of them can reach their output limit beside it, or the growth parks someone again. - const int32_t projected = occupied == 0 ? 0 : preempt_kv_projected(); + const int64_t projected = occupied == 0 ? 0 : preempt_kv_projected(); for (auto * slot : parked) { if (occupied + preempt_n_need(*slot) + margin <= n_cells && - (projected < 0 || preempt_n_final(*slot) < 0 || projected + preempt_n_final(*slot) + margin <= n_cells)) { + (projected < 0 || preempt_n_final(*slot) < 0 || projected + preempt_n_final(*slot) + margin <= (int64_t) n_cells)) { best = slot; break; } From 95ddf1f93421ca7778b8dc39c2aa4d7b9eedcddf Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 17:50:02 -0700 Subject: [PATCH 097/109] server: preemption review fixes (round 12) - A failed pre-decode shift (or any abort_all_slots() error) clears the slots' cached prompts, as a failed decode does: the batch builder had already counted tokens that never reached the cells, so an identical retry failed with an invalid batch. - A prompt held in full takes no extra cell in the live reservation and the victim estimate, as on restore: repeating a fully cached prompt no longer purges another slot's cache. - The victim fallbacks of both policies cover every resident that cannot be parked (n_cmpl > 1, TTS, realtime transcription), so an older text request beside a realtime transcription can still be parked. - Realtime transcriptions take their next audio rows before planning, and the reservation charges the rows a step holds (the first step is the whole prefix). - The --preempt-ram budget is computed in 64 bits and saturated, so a 32-bit build does not wrap 4096 MiB to 0. --- tools/server/server-context.cpp | 43 ++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 48ac5e897adf..00912c119b0d 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4162,6 +4162,9 @@ struct server_context_impl { if (slot.is_processing() && !slot.preempt_is_out()) { send_error(slot, reason, ERROR_TYPE_SERVER); slot.release(); + + // the batch builder already counted tokens that never reached the cells, so a retry must not reuse them (as on a failed decode) + slot.prompt_clear(); } } } @@ -4340,7 +4343,14 @@ struct server_context_impl { } size_t preempt_ram_budget() const { - return params_base.preempt_ram_mib < 0 ? SIZE_MAX : (size_t) params_base.preempt_ram_mib * 1024 * 1024; + if (params_base.preempt_ram_mib < 0) { + return SIZE_MAX; + } + + // in 64 bits, saturated: a 32-bit size_t wraps 4096 MiB to 0 + const uint64_t bytes = (uint64_t) params_base.preempt_ram_mib * 1024 * 1024; + + return bytes > (uint64_t) SIZE_MAX ? SIZE_MAX : (size_t) bytes; } bool preempt_fits_budget(const server_slot & slot) { @@ -4661,7 +4671,10 @@ struct server_context_impl { case SLOT_STATE_GENERATING: case SLOT_STATE_DONE_PROMPT: { - res += preempt_n_cells_step(n_cur, 1 + preempt_n_spec(slot)); + // [TAG_PREEMPT] A realtime transcription step decodes the audio rows it holds: its first step is the whole prefix at once. + const int32_t n_audio = slot.audio_stream ? (int32_t) (slot.inp_embd.size() / batch.n_embd) : 0; + + res += preempt_n_cells_step(n_cur, n_audio > 0 ? n_audio : 1 + preempt_n_spec(slot)); } break; case SLOT_STATE_STARTED: case SLOT_STATE_PROCESSING_PROMPT: @@ -4688,7 +4701,8 @@ struct server_context_impl { break; } - res_pmt += preempt_n_cells_step(n_have, std::max(1, std::min(n_batch, n_left))); + // a prompt held in full needs no further cell: the builder re-evaluates its last token in the cell it frees, as preempt_n_need() counts + res_pmt += preempt_n_cells_step(n_have, std::max(0, std::min(n_batch, n_left))); n_pmt++; } break; default: @@ -4782,7 +4796,7 @@ struct server_context_impl { } // the largest-policy test knob exempts nobody; an n_cmpl > 1 leader cannot be parked anyway, so exempting it keeps nobody else safe - const server_slot * exempt = preempt_test_policy == "largest" || preempt_is_family(*leader) ? nullptr : leader; + const server_slot * exempt = preempt_test_policy == "largest" || !preempt_parkable(*leader) ? nullptr : leader; // only the default policy weighs the deficit; the others pin the order if (preempt_test_policy != "smallest") { @@ -4791,8 +4805,8 @@ struct server_context_impl { server_slot * victim = preempt_pick_victim_pass_any(exempt, recompute, n_deficit); - // [TAG_PREEMPT] Beside n_cmpl > 1 slots the leader may be the only slot that can be parked; parking it lets them finish. - if (!victim && exempt && preempt_any_family_running()) { + // [TAG_PREEMPT] Beside slots that cannot be parked (n_cmpl > 1, TTS, realtime transcription) the leader may be the only one that can; parking it lets them finish. + if (!victim && exempt && preempt_any_unparkable_running()) { victim = preempt_pick_victim_pass_any(nullptr, recompute, n_deficit); } @@ -4836,10 +4850,10 @@ struct server_context_impl { server_slot * victim = pick(oldest); - // [TAG_PREEMPT] Beside n_cmpl > 1 slots the oldest may be the only slot that can be parked; parking it lets them finish. A held one would not take the cells, so it does not count. + // [TAG_PREEMPT] Beside slots that cannot be parked (n_cmpl > 1, TTS, realtime transcription) the oldest may be the only one that can; parking it lets them finish. A held one would not take the cells, so it does not count. if (!victim && oldest) { for (const auto & slot : slots) { - if (slot.is_processing() && !slot.preempt_is_out() && preempt_is_family(slot) && !preempt_held(slot)) { + if (slot.is_processing() && !slot.preempt_is_out() && !preempt_parkable(slot) && !preempt_held(slot)) { victim = pick(nullptr); break; } @@ -4861,9 +4875,9 @@ struct server_context_impl { return slot.task && (slot.task->is_parent() || slot.task->is_child()); } - bool preempt_any_family_running() const { + bool preempt_any_unparkable_running() const { for (const auto & slot : slots) { - if (slot.is_processing() && !slot.preempt_is_out() && preempt_is_family(slot)) { + if (slot.is_processing() && !slot.preempt_is_out() && !preempt_parkable(slot)) { return true; } } @@ -4895,7 +4909,7 @@ struct server_context_impl { if (n_mtmd == 0 && slot.preempt_reprefill) { res += preempt_n_cells_step(n_have, std::max(0, n_left) + 1 + preempt_n_spec(slot)); // as preempt_kv_reserve() charges it } else { - res += preempt_n_cells_step(n_have, n_mtmd > 0 ? n_mtmd : std::max(1, std::min((int32_t) llama_n_batch(ctx_tgt), n_left))); + res += preempt_n_cells_step(n_have, n_mtmd > 0 ? n_mtmd : std::max(0, std::min((int32_t) llama_n_batch(ctx_tgt), n_left))); } } @@ -5865,6 +5879,13 @@ struct server_context_impl { // [TAG_PREEMPT] Fit the pool to the next step, after any context shift; inside the guard since a shift or park can throw. pre_decode_shift(); + // [TAG_PREEMPT] Take the next audio rows of realtime transcriptions now, so the plan reserves their width; pre_decode() decodes the rows a slot holds. + iterate(slots, [&](server_slot & slot) { + if (slot.state == SLOT_STATE_GENERATING && slot.audio_stream && slot.task->type != SERVER_TASK_TYPE_TTS) { + slot_audio_step(slot); + } + }); + // A slot must never be parked with a shift pending on its cells. preempt_apply_shift(); From 68ea6054a7641d95d40a059d63604f5a6060cb4a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 19:36:49 -0700 Subject: [PATCH 098/109] server, llama, ggml-cuda, tools: review fixes (round 13) - server: a context shift moves the aLoRA invocation start with its tokens, so a recompute park replays the adapted tokens with the adapter. - ggml-cuda: a captured CUDA graph is recaptured when the exact decode width (the batch-invariant column bound) has changed since its capture; the reused graph replayed the kernels chosen under the old bound. - llama: the MSA cache forwards the base cache's allocation granularity and, under exact concurrency, refuses shared tokens and isolates prompts, as llama_kv_cache does; exact concurrency also refuses encoder-decoder models, whose encode() packs sequences without isolation. - common, speculative: exact concurrency refuses -pps and a branching draft (-np > 1), whose prompt copies it refuses. - tests: the late-prompt test gives the follower a long leader to overlap. --- common/common.cpp | 6 ++++++ examples/speculative/speculative.cpp | 6 ++++++ ggml/src/ggml-cuda/common.cuh | 1 + ggml/src/ggml-cuda/ggml-cuda.cu | 10 +++++++++- src/llama-context.cpp | 10 ++++++---- src/llama-kv-cache-msa.cpp | 12 +++++++++++- src/llama-kv-cache-msa.h | 3 +++ tools/server/server-context.cpp | 7 +++++++ tools/server/tests/unit/test_preempt.py | 11 ++++++----- 9 files changed, 55 insertions(+), 11 deletions(-) diff --git a/common/common.cpp b/common/common.cpp index fc0239d25048..db652e1e3c55 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1494,6 +1494,12 @@ bool common_exact_concurrency_init(const common_params & params) { return true; } + // -pps copies the prompt's cells to the other sequences, and exact mode gives each page one owner: the copy is refused, so the tools would run without it. + if (params.is_pp_shared) { + COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY does not support -pps (a prompt shared by copying its cells): use independent prompts\n"); + 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) { diff --git a/examples/speculative/speculative.cpp b/examples/speculative/speculative.cpp index 8f347b0d4eee..2d66475815e8 100644 --- a/examples/speculative/speculative.cpp +++ b/examples/speculative/speculative.cpp @@ -55,6 +55,12 @@ int main(int argc, char ** argv) { return 1; } + // [TAG_EXACT_CONCURRENCY] the draft branches copy the target's cells to other sequences, which exact mode refuses (one owner per page) + if (common_exact_concurrency() && params.n_parallel > 1) { + LOG_ERR("%s: LLAMA_EXACT_CONCURRENCY does not support a branching draft (--parallel/-np > 1), use -np 1\n", __func__); + return 1; + } + if (params.speculative.draft.mparams.path.empty()) { LOG_ERR("%s: --model-draft is required\n", __func__); return 1; diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index b9b52c54bb10..0af7a8293251 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -1283,6 +1283,7 @@ struct ggml_cuda_graph { bool disable_due_to_gpu_arch = false; bool warmup_complete = false; uint64_t uid = 0; + int max_cols = -1; // [TAG_EXACT_CONCURRENCY] the batch-invariant column bound the kernels were captured under int64_t last_used_time = 0; struct node_properties { ggml_tensor node; diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 23bc50d31d81..3cbe5008959e 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -3065,7 +3065,15 @@ static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx const void * graph_key = ggml_cuda_graph_get_key(cgraph); ggml_cuda_graph * graph = cuda_ctx->cuda_graph(graph_key); - if (cgraph->uid != 0 && + // [TAG_EXACT_CONCURRENCY] a wider decode width moves the column bound process-wide; a graph captured under the old one replays the kernels it chose + const int max_cols = ggml_cuda_batch_invariant_max_cols(); + + if (graph->max_cols != max_cols) { + graph->max_cols = max_cols; + res = true; + } + + if (!res && cgraph->uid != 0 && cgraph->uid == graph->uid) { if (ggml_cuda_graph_debug_enabled()) { GGML_LOG_DEBUG("CUDA Graph id %zu reused\n", cgraph->uid); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 7b2e0dd8c635..272e8c163335 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -547,10 +547,12 @@ llama_context::llama_context( throw std::runtime_error("exact concurrency: non-causal attention is not supported with a KV cache"); } - // [TAG_EXACT_CONCURRENCY] without a memory, decode() runs encode(), which packs the sequences of a batch into one ubatch with no isolation - if (llama_exact_concurrency() && !memory) { - LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but this model has no sequence memory (an encoder); its batches are not isolated per sequence\n", __func__); - throw std::runtime_error("exact concurrency: a context without sequence memory is not supported"); + // [TAG_EXACT_CONCURRENCY] encode() packs the sequences of a batch into one ubatch with no isolation: a memoryless model runs it from decode(), + // an encoder-decoder (T5) runs it for every input + if (llama_exact_concurrency() && (!memory || llama_model_has_encoder(&model))) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY is set but this model encodes (%s); encoder batches are not isolated per sequence\n", __func__, + memory ? "an encoder-decoder" : "an encoder without sequence memory"); + throw std::runtime_error("exact concurrency: encoder models are not supported"); } } diff --git a/src/llama-kv-cache-msa.cpp b/src/llama-kv-cache-msa.cpp index 55ef286cafa7..c6788ff1bf37 100644 --- a/src/llama-kv-cache-msa.cpp +++ b/src/llama-kv-cache-msa.cpp @@ -106,11 +106,21 @@ llama_memory_context_ptr llama_kv_cache_msa::init_batch( GGML_UNUSED(embd_all); do { + // [TAG_EXACT_CONCURRENCY] as llama_kv_cache::init_batch: a token of several sequences cannot sit in single-owner pages + if (llama_exact_concurrency() && balloc.has_shared_tokens()) { + LLAMA_LOG_ERROR("%s: exact concurrency does not support tokens shared by several sequence ids; " + "give every token exactly one sequence id\n", __func__); + break; + } + balloc.split_reset(); std::vector ubatches; while (true) { - auto ubatch = n_stream == 1 ? balloc.split_simple(n_ubatch) : balloc.split_equal(n_ubatch, true, 0); + // [TAG_EXACT_CONCURRENCY] as llama_kv_cache::init_batch: split_simple packs all prompts into one ubatch, the set split gives each its own + const uint32_t isolate = llama_exact_concurrency() && balloc.has_seq_wider_than(llama_exact_decode_tokens()) ? llama_exact_decode_tokens() : 0; + + auto ubatch = n_stream == 1 && !isolate ? balloc.split_simple(n_ubatch) : balloc.split_equal(n_ubatch, n_stream > 1, 0, isolate); if (ubatch.n_tokens == 0) { break; diff --git a/src/llama-kv-cache-msa.h b/src/llama-kv-cache-msa.h index c7815f18513e..28bc969f173b 100644 --- a/src/llama-kv-cache-msa.h +++ b/src/llama-kv-cache-msa.h @@ -48,6 +48,9 @@ class llama_kv_cache_msa : public llama_memory_i { int32_t n_cells_used(const llama_seq_id * seq_free, size_t n_seq_free, int32_t * n_reclaimable) const override { return kv_base->n_cells_used(seq_free, n_seq_free, n_reclaimable); } + // [TAG_EXACT_CONCURRENCY] the pages of the base cache: the planner and the whole-context save refusal read it + uint32_t alloc_granularity() const override { return kv_base->alloc_granularity(); } + void clear(bool data) override; bool seq_rm (llama_seq_id seq_id, llama_pos p0, llama_pos p1) override; diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 00912c119b0d..d79835300638 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -6115,6 +6115,13 @@ struct server_context_impl { slot.mem.seq_rm (slot.id, n_keep , n_keep + n_discard); slot.mem.seq_add(slot.id, n_keep + n_discard, slot.prompt.tokens.pos_next(), -n_discard); + // [TAG_PREEMPT] the aLoRA invocation moves with its tokens, or a recompute park would replay the adapted tokens without the adapter + if (slot.alora_invocation_start > 0) { + const int n_pre = slot.alora_invocation_start - 1; + + slot.alora_invocation_start = 1 + n_pre - std::clamp(n_pre - n_keep, 0, n_discard); + } + // add generated tokens to cache // ref: https://github.com/ggml-org/llama.cpp/pull/16818#discussion_r2473269481 { diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 8df9f7d174c4..82b7553670a4 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -358,12 +358,13 @@ def test_a_server_that_never_asked_for_parking_behaves_as_upstream(): def test_a_late_prompt_and_a_generating_slot_both_finish(planner): if planner == "off": os.environ["LLAMA_SERVER_PREEMPT_PLANNER"] = "off" - _start(n_ctx=256) + # a long leader: the follower is sent once the leader is seen processing, and a short one could finish before the follower arrives + _start(n_ctx=2048) - n_b = 150 - n_predict_a = 230 - n_predict_b = 90 - assert 8 + n_predict_a + n_b + n_predict_b > 256 + n_b = 1500 + n_predict_a = 1900 + n_predict_b = 500 + assert 8 + n_predict_a + n_b + n_predict_b > 2048 results = _complete_overlapping((n_predict_a, n_predict_b), (8, n_b)) text = _log() From c5202163664f96c7bedeacb6306f6d76d65baff4 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 22:34:06 -0700 Subject: [PATCH 099/109] llama, common, tools: review fixes (round 14) - common: one helper, common_exact_concurrency_seq_copy_ok(), that every tool copying cells between sequences calls before loading a model; under exact concurrency it logs why and refuses. Called by lookahead (always), parallel and batched-bench (-pps) and speculative (-np > 1); the per-tool checks of round 13 move into it. The audited copiers are these four; the server's only copy is for n_cmpl > 1, which exact mode already rejects. - lookahead, parallel, speculative: a model or context that failed to load is reported instead of dereferenced (a refused exact context segfaulted lookahead on CPU). - tests: CTest runs each of the four copying tools under LLAMA_EXACT_CONCURRENCY=1 and expects the refusal. - llama: MSA attention does not read the page table, so exact concurrency refuses it at graph build, like the other layouts without one. - llama: context creation enforces the exact batch geometry itself (a batch holding a whole ubatch beside a decode step of every sequence), so library callers that skip the common init get the same refusal. --- common/common.cpp | 16 +++++++++++----- common/common.h | 4 ++++ examples/lookahead/lookahead.cpp | 10 ++++++++++ examples/parallel/parallel.cpp | 10 ++++++++++ examples/speculative/speculative.cpp | 15 ++++++++++++--- src/llama-context.cpp | 14 ++++++++++++++ src/llama-graph.cpp | 3 +++ tests/CMakeLists.txt | 19 +++++++++++++++++++ tools/batched-bench/batched-bench.cpp | 5 +++++ 9 files changed, 88 insertions(+), 8 deletions(-) diff --git a/common/common.cpp b/common/common.cpp index db652e1e3c55..dee035ec6e97 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1489,17 +1489,23 @@ bool common_exact_concurrency_model(const common_params & params, const llama_mo return true; } -bool common_exact_concurrency_init(const common_params & params) { +bool common_exact_concurrency_seq_copy_ok(const char * what) { if (!common_exact_concurrency()) { return true; } - // -pps copies the prompt's cells to the other sequences, and exact mode gives each page one owner: the copy is refused, so the tools would run without it. - if (params.is_pp_shared) { - COM_ERR("%s", "LLAMA_EXACT_CONCURRENCY does not support -pps (a prompt shared by copying its cells): use independent prompts\n"); - return false; + 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); + + return false; +} + +bool common_exact_concurrency_init(const common_params & params) { + if (!common_exact_concurrency()) { + return true; } + // 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) { diff --git a/common/common.h b/common/common.h index 26bdb9fd73f7..c5b8ca5a7403 100644 --- a/common/common.h +++ b/common/common.h @@ -1030,6 +1030,10 @@ bool common_exact_batch_geometry(int n_batch, int n_ubatch, int n_decode_width, // 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); + // 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); diff --git a/examples/lookahead/lookahead.cpp b/examples/lookahead/lookahead.cpp index 62772814fa5d..7ddc34b99900 100644 --- a/examples/lookahead/lookahead.cpp +++ b/examples/lookahead/lookahead.cpp @@ -49,6 +49,11 @@ int main(int argc, char ** argv) { return 1; } + // the Jacobi window and the verification n-grams are copies of sequence 0 + if (!common_exact_concurrency_seq_copy_ok("lookahead decoding")) { + return 1; + } + const int W = 15; // lookahead window const int N = 5; // n-gram size const int G = 15; // max verification n-grams @@ -69,6 +74,11 @@ int main(int argc, char ** argv) { auto * model = llama_init->model(); auto * ctx = llama_init->context(); + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + return 1; + } + auto * mem = llama_get_memory(ctx); const llama_vocab * vocab = llama_model_get_vocab(model); diff --git a/examples/parallel/parallel.cpp b/examples/parallel/parallel.cpp index de877ca365f4..8665dd7212df 100644 --- a/examples/parallel/parallel.cpp +++ b/examples/parallel/parallel.cpp @@ -170,6 +170,11 @@ int main(int argc, char ** argv) { return 1; } + // -pps evaluates the system prompt once and copies it to every client's sequence + if (params.is_pp_shared && !common_exact_concurrency_seq_copy_ok("a shared system prompt (-pps)")) { + return 1; + } + // number of simultaneous "clients" to simulate const int32_t n_clients = params.n_parallel; @@ -201,6 +206,11 @@ int main(int argc, char ** argv) { auto * model = llama_init->model(); auto * ctx = llama_init->context(); + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + return 1; + } + auto * mem = llama_get_memory(ctx); const llama_vocab * vocab = llama_model_get_vocab(model); diff --git a/examples/speculative/speculative.cpp b/examples/speculative/speculative.cpp index 2d66475815e8..6c6a85f5e57e 100644 --- a/examples/speculative/speculative.cpp +++ b/examples/speculative/speculative.cpp @@ -55,9 +55,8 @@ int main(int argc, char ** argv) { return 1; } - // [TAG_EXACT_CONCURRENCY] the draft branches copy the target's cells to other sequences, which exact mode refuses (one owner per page) - if (common_exact_concurrency() && params.n_parallel > 1) { - LOG_ERR("%s: LLAMA_EXACT_CONCURRENCY does not support a branching draft (--parallel/-np > 1), use -np 1\n", __func__); + // the draft branches (-np > 1) copy the target's and the draft's cells between sequences + if (params.n_parallel > 1 && !common_exact_concurrency_seq_copy_ok("a branching draft (--parallel/-np > 1), use -np 1")) { return 1; } @@ -96,6 +95,11 @@ int main(int argc, char ** argv) { model_tgt = llama_init_tgt->model(); ctx_tgt = llama_init_tgt->context(); + if (model_tgt == nullptr || ctx_tgt == nullptr) { + LOG_ERR("%s: failed to load the target model or create its context\n", __func__); + return 1; + } + // load the draft model params.devices = params.speculative.draft.devices; params.model = params.speculative.draft.mparams; @@ -114,6 +118,11 @@ int main(int argc, char ** argv) { model_dft = llama_init_dft->model(); ctx_dft = llama_init_dft->context(); + if (model_dft == nullptr || ctx_dft == nullptr) { + LOG_ERR("%s: failed to load the draft model or create its context\n", __func__); + return 1; + } + const llama_vocab * vocab_tgt = llama_model_get_vocab(model_tgt); const llama_vocab * vocab_dft = llama_model_get_vocab(model_dft); diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 272e8c163335..0114cd58b250 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -391,6 +391,20 @@ llama_context::llama_context( cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch); + // [TAG_EXACT_CONCURRENCY] the batch must hold a whole ubatch beside a decode step of every other sequence, or a prompt that shares a + // batch is split into shorter ubatches than it gets alone; checked here too, so callers that skip common_exact_concurrency_init() get it + if (llama_exact_concurrency() && cparams.n_seq_max > 1) { + const uint64_t n_cols = uint64_t(cparams.n_seq_max) * std::max(1u, llama_exact_decode_tokens()); + const uint64_t n_min = uint64_t(cparams.n_ubatch) + n_cols; + + if (uint64_t(cparams.n_batch) < n_min) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY needs a batch of at least %" PRIu64 " tokens for a %u-token ubatch beside a decode step of " + "%u sequences (%" PRIu64 " columns), but the batch is %u%s: raise n_batch (and n_ctx), or lower n_ubatch\n", __func__, + n_min, cparams.n_ubatch, cparams.n_seq_max, n_cols, cparams.n_batch, cparams.causal_attn && cparams.n_batch == cparams.n_ctx ? " (clamped to n_ctx)" : ""); + throw std::runtime_error("exact concurrency: the batch cannot hold a whole ubatch beside a decode step"); + } + } + cparams.n_outputs_max = params.n_outputs_max == 0 || llama_model_has_encoder(&model) ? cparams.n_batch : params.n_outputs_max; cparams.n_outputs_max_per_seq = params.n_outputs_max_per_seq == 0 ? cparams.n_outputs_max : std::min(params.n_outputs_max_per_seq, cparams.n_outputs_max); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index c4787a409c7a..d231d8e8ee59 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -3755,6 +3755,9 @@ llm_graph_input_attn_k_dsa_iswa * llm_graph_context::build_attn_inp_k_dsa_iswa() } llm_graph_input_attn_kv_msa * llm_graph_context::build_attn_inp_kv_msa(bool msa_enabled) const { + // [TAG_EXACT_CONCURRENCY] the MSA attention does not read the page table, so its pages would be attended as if contiguous + llm_graph_reject_exact_concurrency("MSA KV (attn_kv_msa)"); + const auto * mctx_cur = static_cast(mctx); auto inp = std::make_unique(hparams, cparams, mctx_cur); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d5d85986674b..ca0020568595 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -352,6 +352,25 @@ if (LLAMA_TEST_EXACT_MODEL) llama_test(test-exact-weights LABEL "model" ARGS -m "${LLAMA_TEST_EXACT_MODEL}") endif() +# [TAG_EXACT_CONCURRENCY] every tool that copies cells between sequences refuses exact concurrency up front (common_exact_concurrency_seq_copy_ok), +# before any model or context exists: the refusal message must appear, and nothing may crash first +function(llama_test_exact_seq_copy name target) + add_test(NAME ${name} COMMAND $ ${ARGN}) + set_tests_properties(${name} PROPERTIES + LABELS "main" + ENVIRONMENT "LLAMA_EXACT_CONCURRENCY=1" + PASS_REGULAR_EXPRESSION "LLAMA_EXACT_CONCURRENCY does not support") +endfunction() + +if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_EXAMPLES AND NOT EMSCRIPTEN) + llama_test_exact_seq_copy(test-exact-seq-copy-lookahead llama-lookahead -m "${MODEL_DEST}" -p "hi" -n 1) + llama_test_exact_seq_copy(test-exact-seq-copy-parallel llama-parallel -m "${MODEL_DEST}" -pps -np 2 -ns 2) + llama_test_exact_seq_copy(test-exact-seq-copy-speculative llama-speculative -m "${MODEL_DEST}" -md "${MODEL_DEST}" -np 2 -kvu -p "hi") +endif() +if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_TOOLS AND NOT EMSCRIPTEN) + llama_test_exact_seq_copy(test-exact-seq-copy-batched-bench llama-batched-bench -m "${MODEL_DEST}" -pps -npp 8 -ntg 1 -npl 2) +endif() + # [TAG_PREEMPT] the occupancy the server's planner reads: shared cells counted once, and the cells only given sequences hold llama_build_and_test(test-memory-cells-used.cpp LABEL "model" ARGS -m "${MODEL_DEST}") set_tests_properties(test-memory-cells-used PROPERTIES FIXTURES_REQUIRED test-download-model) diff --git a/tools/batched-bench/batched-bench.cpp b/tools/batched-bench/batched-bench.cpp index c260425d83c9..0df6e79b1194 100644 --- a/tools/batched-bench/batched-bench.cpp +++ b/tools/batched-bench/batched-bench.cpp @@ -29,6 +29,11 @@ int llama_batched_bench(int argc, char ** argv) { return 1; } + // -pps evaluates the prompt once and copies it to the other sequences + if (params.is_pp_shared && !common_exact_concurrency_seq_copy_ok("a shared prompt (-pps)")) { + return 1; + } + int is_pp_shared = params.is_pp_shared; int is_tg_separate = params.is_tg_separate; From f815b632bd2d90408d7807cbff02a24957d7b0fa Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 22 Oct 2026 23:46:00 -0700 Subject: [PATCH 100/109] common, tools: flush the log on the exact concurrency refusals The common logger writes on its own thread and is never torn down, so a line logged just before a tool returns from main() can be lost (on Windows CI only the timestamp prefix of the refusal came out). Flush it on every refusal exit: common_exact_concurrency_seq_copy_ok(), the failed common_exact_concurrency_init() in argument parsing, the refused model, context and served-context paths of common_init_result, and the failed-load reports of lookahead, parallel and speculative. --- common/arg.cpp | 1 + common/common.cpp | 7 +++++++ examples/lookahead/lookahead.cpp | 1 + examples/parallel/parallel.cpp | 1 + examples/speculative/speculative.cpp | 2 ++ 5 files changed, 12 insertions(+) diff --git a/common/arg.cpp b/common/arg.cpp index 6ecd49fd70c5..7fce7d0ddf16 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -1312,6 +1312,7 @@ bool common_params_parse(int argc, char ** argv, common_params & params, llama_e 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; } diff --git a/common/common.cpp b/common/common.cpp index dee035ec6e97..d5641200e9db 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1247,6 +1247,7 @@ common_init_result::common_init_result(common_params & params, bool model_only) // [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; } @@ -1300,6 +1301,7 @@ common_init_result::common_init_result(common_params & params, bool model_only) 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; } @@ -1388,6 +1390,7 @@ 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; } @@ -1395,6 +1398,7 @@ common_init_result::common_init_result(common_params & params, bool model_only) 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; } @@ -1497,6 +1501,9 @@ bool common_exact_concurrency_seq_copy_ok(const char * what) { 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; } diff --git a/examples/lookahead/lookahead.cpp b/examples/lookahead/lookahead.cpp index 7ddc34b99900..510059fbf5f8 100644 --- a/examples/lookahead/lookahead.cpp +++ b/examples/lookahead/lookahead.cpp @@ -76,6 +76,7 @@ int main(int argc, char ** argv) { if (model == nullptr || ctx == nullptr) { LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); return 1; } diff --git a/examples/parallel/parallel.cpp b/examples/parallel/parallel.cpp index 8665dd7212df..f5809b2cd8f0 100644 --- a/examples/parallel/parallel.cpp +++ b/examples/parallel/parallel.cpp @@ -208,6 +208,7 @@ int main(int argc, char ** argv) { if (model == nullptr || ctx == nullptr) { LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); return 1; } diff --git a/examples/speculative/speculative.cpp b/examples/speculative/speculative.cpp index 6c6a85f5e57e..ea52cfa69b4e 100644 --- a/examples/speculative/speculative.cpp +++ b/examples/speculative/speculative.cpp @@ -97,6 +97,7 @@ int main(int argc, char ** argv) { if (model_tgt == nullptr || ctx_tgt == nullptr) { LOG_ERR("%s: failed to load the target model or create its context\n", __func__); + common_log_flush(common_log_main()); return 1; } @@ -120,6 +121,7 @@ int main(int argc, char ** argv) { if (model_dft == nullptr || ctx_dft == nullptr) { LOG_ERR("%s: failed to load the draft model or create its context\n", __func__); + common_log_flush(common_log_main()); return 1; } From 9226f57da84d260798433b35943d02c547a4ae4e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 00:00:46 -0700 Subject: [PATCH 101/109] tests: preemption and RPC test robustness (round 15) - _wait_processing() waits while the server makes progress, like _await(), instead of a fixed 30 s deadline. - The started-slot test tokenizes its prompts first and counts parks from the responses, which a poll of /slots can miss; its "trimmed" log requirement is dropped, since the batch builder may correctly drop the stale cells first. - The partial-prefill park test uses 64-token chunks, a 1500-token follower tokenized before the resident starts, and sends it once the resident holds 1000 cells, so the follower is parked mid-prefill over a wide window. - The sliding-window test gives the follower ~500 steps before the stale cache would be purged, instead of ~40. - The test harness forwards --spec-ngram-mod-n-min / -n-max, which the n-gram reservation test sets. - test-rpc-paged-fa also requires the RPC server's own log of refusing the paged graph, so a client that fails locally (an error return or an abort before sending) is no longer read as the server's refusal. --- tests/test-rpc-paged-fa.cpp | 28 ++++++++++++- tools/server/tests/unit/test_preempt.py | 56 ++++++++++++++----------- tools/server/tests/utils.py | 6 +++ 3 files changed, 65 insertions(+), 25 deletions(-) diff --git a/tests/test-rpc-paged-fa.cpp b/tests/test-rpc-paged-fa.cpp index 185bb6ce7396..fd88b5b68587 100644 --- a/tests/test-rpc-paged-fa.cpp +++ b/tests/test-rpc-paged-fa.cpp @@ -14,6 +14,8 @@ #include #include +#include +#include #include #include @@ -134,12 +136,24 @@ int main() { } const std::string endpoint = "127.0.0.1:" + std::to_string(port); + // the server's stderr, so the test can see the server itself refuse the graph: a client that fails locally looks the same from the client side + const char * tmp = getenv("TMPDIR"); + std::string log_path = std::string(tmp && *tmp ? tmp : "/tmp") + "/test-rpc-paged-fa.XXXXXX"; + const int log_fd = mkstemp(&log_path[0]); + if (log_fd < 0) { + perror("create a file for the RPC server's log"); + return 1; + } + const pid_t server = fork(); if (server < 0) { perror("fork the RPC server"); + close(log_fd); + unlink(log_path.c_str()); return 1; // nothing to kill: kill(-1) would signal every process this user owns } if (server == 0) { + dup2(log_fd, STDERR_FILENO); ggml_backend_dev_t dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU); ggml_backend_rpc_start_server(endpoint.c_str(), nullptr, 1, 1, &dev); _exit(1); @@ -179,12 +193,24 @@ int main() { fprintf(stderr, "the paged client ended with %d, not a refusal from the server, so this test proves nothing\n", paged); rc = 1; } else { - printf("ok, the RPC server refused the paged graph and kept serving\n"); + std::ifstream log_in(log_path); + std::stringstream log_text; + log_text << log_in.rdbuf(); + + if (log_text.str().find("is a paged FLASH_ATTN_EXT, which RPC does not support") == std::string::npos) { + fprintf(stderr, "the paged client was refused, but the RPC server did not log refusing the graph: the failure was the client's own\n"); + rc = 1; + } else { + printf("ok, the RPC server refused the paged graph and kept serving\n"); + } } } kill(server, SIGKILL); waitpid(server, nullptr, 0); + close(log_fd); + unlink(log_path.c_str()); + return rc; } diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 82b7553670a4..0a5582fd0f4a 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -149,15 +149,13 @@ def _await(cond, what: str, alive=None, stall: float = 120.0, poll: float = 0.02 time.sleep(poll) -def _wait_processing(slot_ids, timeout: float = 30.0): - """Return once every one of these slots is processing; a request that ended first is a failure, not a hang.""" - deadline = time.time() + timeout - while time.time() < deadline: +def _wait_processing(slot_ids, stall: float = 120.0): + """Return once every one of these slots is processing, waiting as long as the server keeps making progress (see _await).""" + def processing(): slots = server.make_request("GET", "/slots").body - if all(any(s["id"] == i and s["is_processing"] for s in slots) for i in slot_ids): - return - time.sleep(0.005) - pytest.fail(f"slots {slot_ids} never showed as processing") # ty: ignore[invalid-argument-type] + return all(any(s["id"] == i and s["is_processing"] for s in slots) for i in slot_ids) + + _await(processing, f"slots {slot_ids} processing", stall=stall, poll=0.005) def _complete_overlapping(n_predict, n_prompt, timeout: float = DEFAULT_REQUEST_TIMEOUT): @@ -529,20 +527,24 @@ def test_cancel_while_a_copy_is_in_flight_frees_the_slot(): def test_a_started_slot_is_counted_by_the_cells_it_holds_not_by_the_prompt_it_keeps(): _start(n_ctx=1024, n_slots=3) + # tokenized before anything runs, so no request waits on /tokenize inside the overlap window ids = _prompt_of(500, _PROMPT_C) + long_prompts = [_prompt_of(200, _PROMPT_A), _prompt_of(200, _PROMPT_B)] with ThreadPoolExecutor(4) as pool: first = pool.submit(_complete, 460, ids, 0) _wait_processing([0]) follower = pool.submit(_complete, 8, ids[:8], 0) - long_ones = [pool.submit(_complete, 400, _prompt_of(200, _PROMPT_A), 1), - pool.submit(_complete, 400, _prompt_of(200, _PROMPT_B), 2)] - parked = _wait_preempted() + long_ones = [pool.submit(_complete, 400, long_prompts[0], 1), + pool.submit(_complete, 400, long_prompts[1], 2)] results = [first.result(), follower.result(), long_ones[0].result(), long_ones[1].result()] text = _log() - assert parked, "the pool never came under pressure, so no slot was waiting for the cells slot 0 keeps" - assert "trimmed to the" in text, "the started slot kept the cells of the request before it" + # a park is counted in its request's response, which a poll of /slots can miss between two reads + assert any(r.body.get("preempt", {}).get("parks", 0) > 0 for r in results if r.status_code == 200), \ + "the pool never came under pressure, so no slot was waiting for the cells slot 0 keeps" + # no "trimmed to the" requirement: when the batch builder reaches the started slot before the planner needs its cells, the + # stale cells are gone without a trim, which is correct; a slot counted by the prompt it kept fails the completions below assert "resume failed" not in text assert "Context size has been exceeded" not in text for res, n_predict in zip(results, (460, 8, 400, 400)): @@ -1194,18 +1196,22 @@ def test_two_image_chats_that_outgrow_the_parking_budget_both_finish(): def test_a_park_during_the_prefill_does_not_count_the_restarted_prompt_twice(): os.environ["LLAMA_SERVER_PREEMPT_FAIL_SAVE"] = "1" - _start(n_ctx=2048, n_batch=256) + # 64-token chunks: the follower's first chunk fits beside the resident long before its 1500 tokens do, so it is parked mid-prefill + # over a window of ~1000 resident steps rather than the few that separate one 256-token chunk fitting from two + _start(n_ctx=2048, n_batch=64) + + n_prompt = 1500 + n_predict = 8 + follower_prompt = _prompt_of(n_prompt, _PROMPT_B) # tokenized before the resident starts, not inside the window resident = [] t = threading.Thread(target=lambda: resident.append(_complete(1900, _PROMPT_A)), daemon=True) t.start() - _await(lambda: any(s.get("n_prompt_tokens", 0) >= 1600 for s in server.make_request("GET", "/slots").body), + _await(lambda: any(s.get("n_prompt_tokens", 0) >= 1000 for s in server.make_request("GET", "/slots").body), "the resident growing into the pool", alive=t.is_alive, poll=0.005) - n_prompt = 500 - n_predict = 8 - comments, final = _stream_completion(n_predict, _prompt_of(n_prompt, _PROMPT_B)) + comments, final = _stream_completion(n_predict, follower_prompt) t.join(120) assert resident and resident[0].status_code == 200, resident @@ -1744,14 +1750,16 @@ def test_a_started_slot_trimmed_below_its_sliding_window_prefills_again(): server.model_hf_file = None server.model_alias = "tinygemma3" server.override_kvs = ["gemma3.attention.sliding_window=int:32"] - _start(n_ctx=512, n_slots=2, n_batch=64, n_ubatch=64, cache_ram=0, n_threads=4) - stale = [100 + k % 50 for k in range(200)] + # the busy slot reaches the follower's admission ~500 steps before the pool would purge the stale cache, not ~40 + _start(n_ctx=1024, n_slots=2, n_batch=512, n_ubatch=64, cache_ram=0, n_threads=4) + stale = [100 + k % 50 for k in range(400)] + follower = stale[:40] + [400 + k % 50 for k in range(500)] assert _cached(1, stale, 1).status_code == 200 with ThreadPoolExecutor(1) as pool: - busy = pool.submit(_cached, 400, [300 + k % 50 for k in range(40)], 0) - _await(lambda: _n_decoded(_slot_view(0)) >= 230, "the busy slot filling the pool", alive=lambda: not busy.done()) - # 40 tokens in common, far below the 32 newest cells the window kept of the stale 200 - res = _cached(16, stale[:40] + [400 + k % 50 for k in range(60)], 1) + busy = pool.submit(_cached, 800, [300 + k % 50 for k in range(40)], 0) + _await(lambda: _n_decoded(_slot_view(0)) >= 100, "the busy slot filling the pool", alive=lambda: not busy.done()) + # 40 tokens in common, far below the 32 newest cells the window kept of the stale 400 + res = _cached(16, follower, 1) busy = busy.result() for r in (res, busy): assert r.status_code == 200, r.body diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index 8c12ad1b699a..9a23e9975be2 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -102,6 +102,8 @@ class ServerProcess: spec_draft_n_min: int | None = None spec_draft_n_max: int | None = None spec_draft_n_ubatch: int | None = None + spec_ngram_mod_n_min: int | None = None + spec_ngram_mod_n_max: int | None = None spec_synth_len: float | None = None spec_synth_rates: List[float] | None = None no_ui: bool | None = None @@ -258,6 +260,10 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.extend(["--api-key", self.api_key]) if self.spec_draft_n_max: server_args.extend(["--spec-draft-n-max", self.spec_draft_n_max]) + if self.spec_ngram_mod_n_min is not None: + server_args.extend(["--spec-ngram-mod-n-min", self.spec_ngram_mod_n_min]) + if self.spec_ngram_mod_n_max is not None: + server_args.extend(["--spec-ngram-mod-n-max", self.spec_ngram_mod_n_max]) if self.spec_draft_n_min: server_args.extend(["--spec-draft-n-min", self.spec_draft_n_min]) if self.spec_draft_n_ubatch: From 839caccdf3d92b56d6ba36be3b726f80f1062061 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 01:54:32 -0700 Subject: [PATCH 102/109] tools, server, common: review fixes (round 16) - Every common_init_from_params() caller in examples/ and tools/ that used the model or context unchecked now reports a missing one and returns (lookup, lookup-stats, lookup-create, speculative-simple, cvector-generator, mtmd-debug, and the model-only checks of embedding, retrieval, finetune, results); exact concurrency refuses the context of a model it cannot run and leaves the model loaded, which these dereferenced. CTest runs the four lookup / speculative-simple tools under LLAMA_EXACT_CONCURRENCY=1 and expects the report. - server: an empty prompt passes the up-front prompt checks, as the batch builder answers it with an empty response; an embedding-only server answered {"prompt": [[]]} with a 500 for logits it never needed. - common/speculative: DSpark and DFlash2 split one batch into equal blocks, so their drafting sequences share the tightest per-call bound (common_speculative_n_draft_shared); other drafters keep a bound per sequence. --- common/speculative.cpp | 19 ++++++++- common/speculative.h | 4 ++ examples/embedding/embedding.cpp | 6 ++- examples/lookup/lookup-create.cpp | 8 +++- examples/lookup/lookup-stats.cpp | 7 ++++ examples/lookup/lookup.cpp | 7 ++++ examples/retrieval/retrieval.cpp | 6 ++- .../speculative-simple/speculative-simple.cpp | 7 ++++ examples/training/finetune.cpp | 6 ++- tests/CMakeLists.txt | 18 +++++++++ tests/test-speculative-shared-bound.cpp | 39 +++++++++++++++++++ tools/cvector-generator/cvector-generator.cpp | 8 ++++ tools/mtmd/debug/mtmd-debug.cpp | 6 +++ tools/results/results.cpp | 6 ++- tools/server/server-context.cpp | 5 +++ tools/server/tests/unit/test_embedding.py | 15 +++++++ 16 files changed, 157 insertions(+), 10 deletions(-) create mode 100644 tests/test-speculative-shared-bound.cpp diff --git a/common/speculative.cpp b/common/speculative.cpp index 777a7c1d0df3..07bf9c4e70f5 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -171,6 +171,18 @@ bool common_speculative_are_compatible( using common_speculative_draft_params_vec = std::vector; +int32_t common_speculative_n_draft_shared(const common_speculative_draft_params_vec & dparams, int32_t n_max) { + int32_t res = n_max; + + for (const auto & dp : dparams) { + if (dp.drafting && dp.n_max > 0) { + res = std::min(res, dp.n_max); + } + } + + return res; +} + // state of an implementation of speculative decoding // // each implementation has a unique type and a state that is implementation-specific @@ -1281,6 +1293,11 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { batch.clear(); + // DSpark's markov head and DFlash2's convolution and selector split the token axis into equal blocks, so their sequences share + // one bound, the tightest per-call bound; each draft is truncated to its own bound afterwards. Other drafters keep their own bound. + const bool equal_blocks = is_dspark || is_dflash2; + const int32_t n_draft_shared = common_speculative_n_draft_shared(dparams, params.n_max); + // build one batch holding every drafting sequence's noise block into a single decode) // record where each block starts and its size std::vector i_block_beg(n_seq, -1); @@ -1297,7 +1314,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const int32_t n = (int32_t) dp.pos0; // the caller's remaining context bounds the block as well as the configured maximum: the whole block is decoded before any truncation - const int32_t n_draft = dp.n_max > 0 ? std::min(params.n_max, dp.n_max) : params.n_max; + const int32_t n_draft = equal_blocks ? n_draft_shared : dp.n_max > 0 ? std::min(params.n_max, dp.n_max) : params.n_max; const int32_t n_block_tokens = is_lilicorr ? block_size : n_draft + (is_dspark && sample_from_anchor ? 0 : 1); i_block_beg[seq_id] = batch.size(); n_block [seq_id] = n_block_tokens; diff --git a/common/speculative.h b/common/speculative.h index a59846829683..e2ac05c18cba 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -81,6 +81,10 @@ struct common_speculative_draft_params { uint32_t seed = LLAMA_DEFAULT_SEED; }; +// [TAG_PREEMPT] The draft bound every drafting sequence of one batch shares when the drafter needs equal blocks (DSpark, DFlash2): the configured +// n_max, lowered to the tightest per-call bound (dp.n_max > 0) among the sequences that are drafting. +int32_t common_speculative_n_draft_shared(const std::vector & dparams, int32_t n_max); + common_speculative_draft_params & common_speculative_get_draft_params(common_speculative * spec, llama_seq_id seq_id); // optionally call once at the beginning of a new generation diff --git a/examples/embedding/embedding.cpp b/examples/embedding/embedding.cpp index a59f04cae9ec..9753cf7a1ab9 100644 --- a/examples/embedding/embedding.cpp +++ b/examples/embedding/embedding.cpp @@ -139,8 +139,10 @@ int main(int argc, char ** argv) { auto * model = llama_init->model(); auto * ctx = llama_init->context(); - if (model == NULL) { - LOG_ERR("%s: unable to load model\n", __func__); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); return 1; } diff --git a/examples/lookup/lookup-create.cpp b/examples/lookup/lookup-create.cpp index c0f6c8fc2029..2e8513ab39d9 100644 --- a/examples/lookup/lookup-create.cpp +++ b/examples/lookup/lookup-create.cpp @@ -1,5 +1,6 @@ #include "arg.h" #include "common.h" +#include "log.h" #include "ngram-cache.h" #include "llama.h" @@ -28,7 +29,12 @@ int main(int argc, char ** argv){ auto * model = llama_init->model(); auto * ctx = llama_init->context(); - GGML_ASSERT(model != nullptr); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); + return 1; + } // tokenize the prompt std::vector inp; diff --git a/examples/lookup/lookup-stats.cpp b/examples/lookup/lookup-stats.cpp index 84642e05d1d0..40737f475f4f 100644 --- a/examples/lookup/lookup-stats.cpp +++ b/examples/lookup/lookup-stats.cpp @@ -35,6 +35,13 @@ int main(int argc, char ** argv){ llama_context * ctx = llama_init->context(); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (llama_init->model() == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); + return 1; + } + // tokenize the prompt std::vector inp; inp = common_tokenize(ctx, params.prompt, true, true); diff --git a/examples/lookup/lookup.cpp b/examples/lookup/lookup.cpp index 004062c57650..fa8f217652d3 100644 --- a/examples/lookup/lookup.cpp +++ b/examples/lookup/lookup.cpp @@ -43,6 +43,13 @@ int main(int argc, char ** argv){ auto * model = llama_init->model(); auto * ctx = llama_init->context(); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); + return 1; + } + const llama_vocab * vocab = llama_model_get_vocab(model); // tokenize the prompt diff --git a/examples/retrieval/retrieval.cpp b/examples/retrieval/retrieval.cpp index 8793e57519d7..5ffe2b04aba1 100644 --- a/examples/retrieval/retrieval.cpp +++ b/examples/retrieval/retrieval.cpp @@ -157,8 +157,10 @@ int main(int argc, char ** argv) { auto * model = llama_init->model(); auto * ctx = llama_init->context(); - if (model == NULL) { - LOG_ERR("%s: unable to load model\n", __func__); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); return 1; } diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp index e4a878b82842..418acbfb514c 100644 --- a/examples/speculative-simple/speculative-simple.cpp +++ b/examples/speculative-simple/speculative-simple.cpp @@ -49,6 +49,13 @@ int main(int argc, char ** argv) { model_tgt = llama_init_tgt->model(); ctx_tgt = llama_init_tgt->context(); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model_tgt == nullptr || ctx_tgt == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); + return 1; + } + const llama_vocab * vocab = llama_model_get_vocab(model_tgt); // load the draft model (if any) - this also creates the MTP draft context when MTP speculation is enabled diff --git a/examples/training/finetune.cpp b/examples/training/finetune.cpp index 44b2843918b1..e86a323b9064 100644 --- a/examples/training/finetune.cpp +++ b/examples/training/finetune.cpp @@ -47,8 +47,10 @@ int main(int argc, char ** argv) { auto * model = llama_init->model(); auto * ctx = llama_init->context(); - if (model == NULL) { - LOG_ERR("%s: unable to load model\n", __func__); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); return 1; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ca0020568595..a6c907e499fe 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -367,6 +367,23 @@ if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_EXAMPLES AND NOT EMSCRIPTEN) llama_test_exact_seq_copy(test-exact-seq-copy-parallel llama-parallel -m "${MODEL_DEST}" -pps -np 2 -ns 2) llama_test_exact_seq_copy(test-exact-seq-copy-speculative llama-speculative -m "${MODEL_DEST}" -md "${MODEL_DEST}" -np 2 -kvu -p "hi") endif() +# exact concurrency refuses the context of a model it cannot run (on CPU every model): a tool must report the null context, not dereference it +function(llama_test_exact_null_context name target) + add_test(NAME ${name} COMMAND $ ${ARGN}) + set_tests_properties(${name} PROPERTIES + LABELS "model" + FIXTURES_REQUIRED test-download-model + ENVIRONMENT "LLAMA_EXACT_CONCURRENCY=1" + PASS_REGULAR_EXPRESSION "failed to load the model or create the context") +endfunction() + +if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_EXAMPLES AND NOT EMSCRIPTEN) + llama_test_exact_null_context(test-exact-null-context-lookup llama-lookup -m "${MODEL_DEST}" -c 512 -b 256 -ub 64 -p "hello" -n 4) + llama_test_exact_null_context(test-exact-null-context-lookup-stats llama-lookup-stats -m "${MODEL_DEST}" -c 512 -b 256 -ub 64 -p "hello") + llama_test_exact_null_context(test-exact-null-context-lookup-create llama-lookup-create -m "${MODEL_DEST}" -c 512 -b 256 -ub 64 -p "hello") + llama_test_exact_null_context(test-exact-null-context-speculative-simple llama-speculative-simple -m "${MODEL_DEST}" -md "${MODEL_DEST}" -c 512 -b 256 -ub 64 -p "hello" -n 4) +endif() + if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_TOOLS AND NOT EMSCRIPTEN) llama_test_exact_seq_copy(test-exact-seq-copy-batched-bench llama-batched-bench -m "${MODEL_DEST}" -pps -npp 8 -ntg 1 -npl 2) endif() @@ -397,6 +414,7 @@ llama_build_and_test(test-mtmd-impl.cpp LINK mtmd) # [TAG_EXACT_CONCURRENCY] the batch shape the mode requires, checked without a model llama_build_and_test(test-exact-geometry.cpp) +llama_build_and_test(test-speculative-shared-bound.cpp) # server helpers that need no model; server-context exists only where tools/ adds the server if (LLAMA_BUILD_TOOLS AND LLAMA_BUILD_SERVER AND NOT EMSCRIPTEN) diff --git a/tests/test-speculative-shared-bound.cpp b/tests/test-speculative-shared-bound.cpp new file mode 100644 index 000000000000..dc29607c01dd --- /dev/null +++ b/tests/test-speculative-shared-bound.cpp @@ -0,0 +1,39 @@ +// [TAG_PREEMPT] DSpark and DFlash2 decode every drafting sequence's block in one batch and split it into equal blocks, so the sequences +// share one draft bound: the configured n_max lowered to the tightest per-call bound. Different bounds (here 1 and 2 with n_max 3) +// once built blocks of different lengths, which the DSpark markov head asserts against. + +#include "speculative.h" + +#include +#include + +static int check(const char * what, int got, int want) { + printf("%-58s %3d (want %d)\n", what, got, want); + return got != want; +} + +int main() { + std::vector dp(3); + + int bad = 0; + + bad += check("no sequence drafting", common_speculative_n_draft_shared(dp, 3), 3); + + dp[0].drafting = true; dp[0].n_max = 1; + dp[1].drafting = true; dp[1].n_max = 2; + bad += check("drafting with per-call bounds 1 and 2, n_max 3", common_speculative_n_draft_shared(dp, 3), 1); + + dp[0].n_max = -1; + bad += check("one unbounded, one bounded at 2", common_speculative_n_draft_shared(dp, 3), 2); + + dp[1].drafting = false; + dp[2].drafting = false; dp[2].n_max = 1; + bad += check("bounds of sequences not drafting are ignored", common_speculative_n_draft_shared(dp, 3), 3); + + dp[0].n_max = 5; + dp[1].drafting = true; dp[1].n_max = 4; + bad += check("per-call bounds above n_max leave n_max", common_speculative_n_draft_shared(dp, 3), 3); + + printf("%s\n", bad == 0 ? "ok" : "FAIL"); + return bad == 0 ? 0 : 1; +} diff --git a/tools/cvector-generator/cvector-generator.cpp b/tools/cvector-generator/cvector-generator.cpp index af05031f238e..d44b455ea462 100644 --- a/tools/cvector-generator/cvector-generator.cpp +++ b/tools/cvector-generator/cvector-generator.cpp @@ -4,6 +4,7 @@ #include "arg.h" #include "build-info.h" #include "common.h" +#include "log.h" #include "llama.h" #include "pca.hpp" #include "mean.hpp" @@ -432,6 +433,13 @@ int main(int argc, char ** argv) { auto * model = llama_init->model(); auto * ctx = llama_init->context(); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model == nullptr || ctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); + return 1; + } + // int n_ctx = llama_n_ctx(ctx); int n_layers = llama_model_n_layer(model); int n_embd = llama_model_n_embd(model); diff --git a/tools/mtmd/debug/mtmd-debug.cpp b/tools/mtmd/debug/mtmd-debug.cpp index 2719dae9b255..d99e569cbc9d 100644 --- a/tools/mtmd/debug/mtmd-debug.cpp +++ b/tools/mtmd/debug/mtmd-debug.cpp @@ -81,6 +81,12 @@ int main(int argc, char ** argv) { llama_init = common_init_from_params(params); { auto * model = llama_init->model(); + // only the model is used here, so a refused context does not matter, a missing model does + if (model == nullptr) { + LOG_ERR("%s: failed to load the model\n", __func__); + common_log_flush(common_log_main()); + return 1; + } const char * clip_path = params.mmproj.path.c_str(); mtmd_context_params mparams = mtmd_context_params_default(); mparams.use_gpu = params.mmproj_use_gpu; diff --git a/tools/results/results.cpp b/tools/results/results.cpp index 2d6479482e38..65d368cd0123 100644 --- a/tools/results/results.cpp +++ b/tools/results/results.cpp @@ -70,8 +70,10 @@ int main(int argc, char ** argv) { common_init_result_ptr llama_init = common_init_from_params(params); struct llama_model * model = llama_init->model(); struct llama_context * lctx = llama_init->context(); - if (model == nullptr) { - LOG_ERR("%s: unable to load model\n", __func__); + // a refused context (e.g. an exact concurrency check) leaves the model loaded and the context null + if (model == nullptr || lctx == nullptr) { + LOG_ERR("%s: failed to load the model or create the context\n", __func__); + common_log_flush(common_log_main()); return 1; } const uint32_t n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index d79835300638..2ded322e4ada 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -5733,6 +5733,11 @@ struct server_context_impl { // Checks a request must pass before its prompt is processed; true if rejected. An empty prompt is a final response, not an error. bool task_prompt_rejected(const server_task & task, std::string & msg, error_type & type) const { + // as the batch builder: an empty prompt is answered with an empty final response before any check below + if (task.tokens.empty()) { + return false; + } + // TODO: support memory-less logits computation if (task.need_logits() && !llama_get_memory(ctx_tgt)) { msg = "the current context does not support logits computation. skipping"; diff --git a/tools/server/tests/unit/test_embedding.py b/tools/server/tests/unit/test_embedding.py index 9efa273fc9fe..2295440108c4 100644 --- a/tools/server/tests/unit/test_embedding.py +++ b/tools/server/tests/unit/test_embedding.py @@ -345,3 +345,18 @@ def test_embedding_invalid_request(data): assert res.status_code == 400 assert "error" in res.body assert res.body["error"]["type"] == "invalid_request_error" + + +def test_an_empty_completion_prompt_on_an_embedding_server_is_an_empty_response(): + # an empty prompt is answered with an empty final response before any check that needs logits or memory + global server + server.start() + res = server.make_request("POST", "/completion", data={"prompt": [[]], "n_predict": 1}) + assert res.status_code == 200, res.body + assert res.body["tokens_predicted"] == 0, res.body + assert res.body["content"] == "", res.body + # the controls keep their answers: no prompt at all is a bad request, and a real prompt on this embedding-only context is still + # refused for needing logits (a 500, as before the exemption) + assert server.make_request("POST", "/completion", data={"prompt": [], "n_predict": 1}).status_code == 400 + res = server.make_request("POST", "/completion", data={"prompt": [[1] * 600], "n_predict": 1}) + assert res.status_code == 500 and "logits" in res.body["error"]["message"], res.body From ef9fc2b60b061f37debf20a18a683169947d9b52 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 03:27:19 -0700 Subject: [PATCH 103/109] server tests: bound the sliding-window trim test; print the server log of a failed preemption test The round-15 widening left the busy request a 700-token tail after the wait, which the Windows CI runner (1.6 s a step on tinygemma3) could not finish inside the 600 s read timeout; it is not a hang (on Linux the request ends in 5-10 s). The test now waits for 40 decoded tokens of a 200-token busy request (a 160-token tail, as before round 15), with a stale cache of 450 so its cells, the stale cache and the follower's first chunk still overflow the pool and the planner trims the follower's started slot; both requests are bounded at 450 s and a busy request that does not finish fails with its own message. A conftest hook records each phase's report on the item, and the preemption fixture prints the last 300 lines of the server log when its test failed, which CI keeps nowhere else. --- tools/server/tests/conftest.py | 8 ++++++ tools/server/tests/unit/test_preempt.py | 33 +++++++++++++++++-------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/tools/server/tests/conftest.py b/tools/server/tests/conftest.py index 69c4fd687f1b..01340e16a98f 100644 --- a/tools/server/tests/conftest.py +++ b/tools/server/tests/conftest.py @@ -12,6 +12,14 @@ def configure_worker_port(request): os.environ["PORT"] = str(8080 + worker_num * 10) +# the report of each phase on the item (item.rep_setup / rep_call / rep_teardown), so a fixture can tell that its test failed +@pytest.hookimpl(hookwrapper=True, tryfirst=True) +def pytest_runtest_makereport(item, call): + outcome = yield + rep = outcome.get_result() + setattr(item, "rep_" + rep.when, rep) + + # ref: https://stackoverflow.com/questions/22627659/run-code-before-and-after-each-test-in-py-test @pytest.fixture(autouse=True) def stop_server_after_each_test(): diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 0a5582fd0f4a..c10347654141 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -27,7 +27,7 @@ @pytest.fixture(autouse=True) -def create_server(): +def create_server(request): global server server = ServerPreset.tinyllama2() server.n_slots = 2 @@ -40,6 +40,13 @@ def create_server(): fd, server.log_path = tempfile.mkstemp(suffix=".log") os.close(fd) yield + # a failed test shows the end of the server log, which CI does not keep otherwise + rep = getattr(request.node, "rep_call", None) + if rep is not None and rep.failed and server.log_path and os.path.exists(server.log_path): + with open(server.log_path, errors="replace") as f: + tail = f.readlines()[-300:] + print(f"---- last {len(tail)} lines of the server log ({server.log_path}) ----") + print("".join(tail)) if _cuda_devices is None: os.environ.pop("CUDA_VISIBLE_DEVICES", None) else: @@ -1519,11 +1526,11 @@ def test_a_multi_prompt_oai_completion_counts_the_parks_of_every_prompt(): assert merged.body["preempt"]["recomputes"] == sum(c["recomputes"] for c in counts), (merged.body["preempt"], counts) -def _cached(n_predict: int, prompt: list, id_slot: int): +def _cached(n_predict: int, prompt: list, id_slot: int, timeout: float = DEFAULT_REQUEST_TIMEOUT): return server.make_request("POST", "/completion", data={ "n_predict": n_predict, "prompt": prompt, "id_slot": id_slot, "cache_prompt": True, "ignore_eos": True, "temperature": 0.0, "seed": 42, - }) + }, timeout=timeout) def test_a_started_slot_replacing_its_prompt_does_not_purge_an_idle_slot(): @@ -1750,17 +1757,23 @@ def test_a_started_slot_trimmed_below_its_sliding_window_prefills_again(): server.model_hf_file = None server.model_alias = "tinygemma3" server.override_kvs = ["gemma3.attention.sliding_window=int:32"] - # the busy slot reaches the follower's admission ~500 steps before the pool would purge the stale cache, not ~40 + # Once the busy slot holds 80 cells, its cells, the stale 450 and the follower's first 512-token chunk overflow the 1024-cell pool, so + # the planner trims the follower's started slot before the batch builder would; the busy slot (40 + 200 cells beside the stale 450) + # never grows enough to purge the stale cache first. Its tail past the wait is 160 tokens, as before round 15 (170), not the 700 a + # slow runner (1.6 s a step on the Windows CI runner) spent past the 600 s read timeout, and both requests are bounded below it. _start(n_ctx=1024, n_slots=2, n_batch=512, n_ubatch=64, cache_ram=0, n_threads=4) - stale = [100 + k % 50 for k in range(400)] + stale = [100 + k % 50 for k in range(450)] follower = stale[:40] + [400 + k % 50 for k in range(500)] assert _cached(1, stale, 1).status_code == 200 with ThreadPoolExecutor(1) as pool: - busy = pool.submit(_cached, 800, [300 + k % 50 for k in range(40)], 0) - _await(lambda: _n_decoded(_slot_view(0)) >= 100, "the busy slot filling the pool", alive=lambda: not busy.done()) - # 40 tokens in common, far below the 32 newest cells the window kept of the stale 400 - res = _cached(16, follower, 1) - busy = busy.result() + busy = pool.submit(_cached, 200, [300 + k % 50 for k in range(40)], 0, 450.0) + _await(lambda: _n_decoded(_slot_view(0)) >= 40, "the busy slot filling the pool", alive=lambda: not busy.done()) + # 40 tokens in common, far below the 32 newest cells the window kept of the stale 450 + res = _cached(16, follower, 1, 450.0) + try: + busy = busy.result(timeout=480.0) + except Exception as e: + pytest.fail(f"the busy 200-token request did not finish ({type(e).__name__}: {e}); see the server log below") # ty: ignore[invalid-argument-type] for r in (res, busy): assert r.status_code == 200, r.body text = _log() From b867ddc0c268c2b0c99b7bce950c6fa642ddffa1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 03:29:08 -0700 Subject: [PATCH 104/109] common/speculative: the shared equal-block bound needs no truncation, say so The shared bound is the tightest per-call bound among the drafting sequences, so it is at most every one's own bound and no draft exceeds its caller's limit; the comment said each draft was truncated afterwards. --- common/speculative.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common/speculative.cpp b/common/speculative.cpp index 07bf9c4e70f5..a100eb736f03 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -1294,7 +1294,8 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { batch.clear(); // DSpark's markov head and DFlash2's convolution and selector split the token axis into equal blocks, so their sequences share - // one bound, the tightest per-call bound; each draft is truncated to its own bound afterwards. Other drafters keep their own bound. + // one bound, the tightest per-call bound; it is at most every drafting sequence's own bound, so no draft exceeds its caller's + // limit. Other drafters keep their own bound. const bool equal_blocks = is_dspark || is_dflash2; const int32_t n_draft_shared = common_speculative_n_draft_shared(dparams, params.n_max); From a483bb9dba1fd7e4a64656b4b5600f1d893bf4d4 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 05:42:19 -0700 Subject: [PATCH 105/109] exact : refuse self-extend, context shift and passkey position edits, check the speculative-simple draft context, validate the decode figure before any context - common_exact_concurrency_position_edit_ok() refuses a tool that would move or rescale cached cells (seq_add / seq_div); self-extend (--grp-attn-n > 1) is refused in common_exact_concurrency_init(), passkey after parsing, llama-completion with --context-shift after parsing - speculative-simple returns 1 when the speculative types need a draft context and it could not be created - llama_set_exact_decode_tokens() checks the explicit column bound for one sequence before any context exists, so a figure past it is refused instead of stored for good - tests: test-exact-decode-tokens and ctests for passkey, completion --grp-attn-n 2 and --context-shift --- common/common.cpp | 19 +++++++++ common/common.h | 4 ++ examples/passkey/passkey.cpp | 5 +++ .../speculative-simple/speculative-simple.cpp | 10 +++++ src/llama-impl.cpp | 8 ++-- tests/CMakeLists.txt | 5 +++ tests/test-exact-decode-tokens.cpp | 39 +++++++++++++++++++ tools/completion/completion.cpp | 5 +++ 8 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 tests/test-exact-decode-tokens.cpp diff --git a/common/common.cpp b/common/common.cpp index d5641200e9db..3bc99eb507d5 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1507,11 +1507,30 @@ bool common_exact_concurrency_seq_copy_ok(const char * what) { 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) { diff --git a/common/common.h b/common/common.h index c5b8ca5a7403..22ea1f9343f4 100644 --- a/common/common.h +++ b/common/common.h @@ -1034,6 +1034,10 @@ bool common_exact_concurrency_init(const common_params & params); // 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); diff --git a/examples/passkey/passkey.cpp b/examples/passkey/passkey.cpp index 9ac8a01702d9..9fe3922a8403 100644 --- a/examples/passkey/passkey.cpp +++ b/examples/passkey/passkey.cpp @@ -31,6 +31,11 @@ int main(int argc, char ** argv) { return 1; } + // the junk is decoded in a rolling context: once it fills, a prefix is removed and the rest shifted down (and --grp-attn-n divides positions) + if (!common_exact_concurrency_position_edit_ok("passkey's rolling context")) { + return 1; + } + int n_junk = params.n_junk; int n_keep = params.n_keep; int n_grp = params.grp_attn_n; diff --git a/examples/speculative-simple/speculative-simple.cpp b/examples/speculative-simple/speculative-simple.cpp index 418acbfb514c..c78cf8c4592a 100644 --- a/examples/speculative-simple/speculative-simple.cpp +++ b/examples/speculative-simple/speculative-simple.cpp @@ -66,6 +66,16 @@ int main(int argc, char ** argv) { spec_init = common_speculative_init_from_params(params_dft, model_tgt, ctx_tgt); + // a draft model or an MTP head needs its draft context, which can be refused (e.g. by exact concurrency) while the target's is not + const bool needs_dft = params.speculative.has_dft() || + std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_MTP) != params.speculative.types.end(); + + if (needs_dft && ((params.speculative.has_dft() && spec_init->model() == nullptr) || spec_init->context() == nullptr)) { + LOG_ERR("%s: failed to load the draft model or create the draft context\n", __func__); + common_log_flush(common_log_main()); + return 1; + } + params.speculative.draft.ctx_tgt = ctx_tgt; params.speculative.draft.ctx_dft = spec_init->context(); } diff --git a/src/llama-impl.cpp b/src/llama-impl.cpp index 2dad69360170..38c8fbf182bb 100644 --- a/src/llama-impl.cpp +++ b/src/llama-impl.cpp @@ -310,12 +310,14 @@ bool llama_set_exact_decode_tokens(uint32_t n_tokens) { return true; } - // every context widens with the figure, so report the width first; one the explicit bound cannot cover leaves the old figure in place - const uint32_t n_seq = g_exact_max_n_seq.load(std::memory_order_relaxed); + // every context widens with the figure, so report the width first; one the explicit bound cannot cover leaves the old figure in place. + // Before any context exists, check it for one sequence: stored unchecked, a figure past the bound could never be lowered again and + // would refuse every later context, a one-sequence one included. + const uint32_t n_seq = std::max(1u, g_exact_max_n_seq.load(std::memory_order_relaxed)); uint32_t n_cols = 0; - if (n_seq > 0 && (!llama_exact_width_of(n_seq, n_tokens, n_cols) || !llama_set_exact_decode_width(n_cols))) { + if (!llama_exact_width_of(n_seq, n_tokens, n_cols) || !llama_set_exact_decode_width(n_cols)) { return false; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a6c907e499fe..5c36c55aa763 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -366,6 +366,8 @@ if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_EXAMPLES AND NOT EMSCRIPTEN) llama_test_exact_seq_copy(test-exact-seq-copy-lookahead llama-lookahead -m "${MODEL_DEST}" -p "hi" -n 1) llama_test_exact_seq_copy(test-exact-seq-copy-parallel llama-parallel -m "${MODEL_DEST}" -pps -np 2 -ns 2) llama_test_exact_seq_copy(test-exact-seq-copy-speculative llama-speculative -m "${MODEL_DEST}" -md "${MODEL_DEST}" -np 2 -kvu -p "hi") + # the same refusal for tools that move or rescale cached positions (context shift, self-extend) + llama_test_exact_seq_copy(test-exact-position-edit-passkey llama-passkey -m "${MODEL_DEST}") endif() # exact concurrency refuses the context of a model it cannot run (on CPU every model): a tool must report the null context, not dereference it function(llama_test_exact_null_context name target) @@ -385,6 +387,8 @@ if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_EXAMPLES AND NOT EMSCRIPTEN) endif() if (LLAMA_BUILD_COMMON AND LLAMA_BUILD_TOOLS AND NOT EMSCRIPTEN) + llama_test_exact_seq_copy(test-exact-position-edit-completion-self-extend llama-completion -m "${MODEL_DEST}" --grp-attn-n 2 -p "hi" -n 1 -no-cnv) + llama_test_exact_seq_copy(test-exact-position-edit-completion-context-shift llama-completion -m "${MODEL_DEST}" --context-shift -p "hi" -n 1 -no-cnv) llama_test_exact_seq_copy(test-exact-seq-copy-batched-bench llama-batched-bench -m "${MODEL_DEST}" -pps -npp 8 -ntg 1 -npl 2) endif() @@ -414,6 +418,7 @@ llama_build_and_test(test-mtmd-impl.cpp LINK mtmd) # [TAG_EXACT_CONCURRENCY] the batch shape the mode requires, checked without a model llama_build_and_test(test-exact-geometry.cpp) +llama_build_and_test(test-exact-decode-tokens.cpp) llama_build_and_test(test-speculative-shared-bound.cpp) # server helpers that need no model; server-context exists only where tools/ adds the server diff --git a/tests/test-exact-decode-tokens.cpp b/tests/test-exact-decode-tokens.cpp new file mode 100644 index 000000000000..9a72908b94cd --- /dev/null +++ b/tests/test-exact-decode-tokens.cpp @@ -0,0 +1,39 @@ +// [TAG_EXACT_CONCURRENCY] llama_set_exact_decode_tokens() checks the explicit column bound before any context exists: a figure past +// it is refused and leaves the stored one, which is never lowered, so nothing later is refused because of it. + +#include "llama.h" + +#include +#include + +static int check(const char * what, bool ok) { + printf("%-72s %s\n", what, ok ? "ok" : "FAIL"); + return ok ? 0 : 1; +} + +int main() { +#ifdef _WIN32 + _putenv_s("GGML_CUDA_BATCH_INVARIANT_MAX_COLS", "8"); +#else + setenv("GGML_CUDA_BATCH_INVARIANT_MAX_COLS", "8", 1); +#endif + + int bad = 0; + + const uint32_t tokens0 = llama_exact_decode_tokens(); + const uint32_t width0 = llama_exact_decode_width(); + + bad += check("9 tokens per sequence, bound 8, no context yet: refused", !llama_set_exact_decode_tokens(9)); + bad += check(" the stored figure is unchanged", llama_exact_decode_tokens() == tokens0); + bad += check(" the reported width is unchanged", llama_exact_decode_width() == width0); + bad += check("8 tokens per sequence: accepted", llama_set_exact_decode_tokens(8)); + bad += check(" stored as 8, width 8", llama_exact_decode_tokens() == 8 && llama_exact_decode_width() == 8); + bad += check("9 after 8: refused, 8 kept", !llama_set_exact_decode_tokens(9) && llama_exact_decode_tokens() == 8); + bad += check("1 after 8: accepted, never lowered", llama_set_exact_decode_tokens(1) && llama_exact_decode_tokens() == 8); + bad += check("0 is 1: accepted, 8 kept", llama_set_exact_decode_tokens(0) && llama_exact_decode_tokens() == 8); + bad += check("a width of 9 past the bound: refused", !llama_set_exact_decode_width(9) && llama_exact_decode_width() == 8); + bad += check("a width of 8: accepted", llama_set_exact_decode_width(8)); + + printf("%s\n", bad == 0 ? "ok" : "FAIL"); + return bad == 0 ? 0 : 1; +} diff --git a/tools/completion/completion.cpp b/tools/completion/completion.cpp index b5b5daf2a6dc..551a807bb6a9 100644 --- a/tools/completion/completion.cpp +++ b/tools/completion/completion.cpp @@ -95,6 +95,11 @@ int llama_completion(int argc, char ** argv) { return 1; } + // --context-shift removes cached cells and shifts the rest down once the context fills (self-extend is refused in the common init) + if (params.ctx_shift && !common_exact_concurrency_position_edit_ok("--context-shift")) { + return 1; + } + auto & sparams = params.sampling; // save choice to use color for later From 841ba3fe3b4cc5a8eb7ef3ccfd6b451e469a8da8 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 05:42:19 -0700 Subject: [PATCH 106/109] server : tests establish the overlap they depend on, bound the notification tests' network calls - _wait_processing() takes alive= and every caller passes its request, so a request that ended first fails at once - the two-generation, trimmed-slot and FCFS arrival-order tests submit their prompts in one request, so they overlap whatever the client's speed - the remaining overlap tests check from the server log that the requests were in flight together, and those asserting a park first check that something was parked, failing with a precondition message otherwise - the cached-prefix test gates its FCFS outcome on /props preempt.policy - test_preempt_notify bounds its /slots GET and streamed POSTs - README: a parked stream is kept alive with : preempt-keepalive --- tools/server/README.md | 2 +- tools/server/tests/unit/test_preempt.py | 129 ++++++++++++------ .../server/tests/unit/test_preempt_notify.py | 7 +- 3 files changed, 94 insertions(+), 44 deletions(-) diff --git a/tools/server/README.md b/tools/server/README.md index 0a1d5e5df8ac..e06de9d1af24 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -688,7 +688,7 @@ These words will not be included in the completion, so make sure to add them to While a request is streaming, the server sends SSE comment lines that a client reading raw lines can act on and every SSE event consumer ignores: -- `: preempted` - the slot was parked and the stream is silent until it comes back. A parked stream is kept alive with the same comment about every two seconds. +- `: preempted` - the slot was parked. Until it comes back the stream carries no data, only the `: preempt-keepalive` comments described below. - `: resumed` - the slot is running again. - `: recomputed` - sent right after `: resumed` when that resume re-prefilled the sequence rather than restoring its saved bytes, i.e. what follows is the continuation `preempt.recomputes` counts. - `: preempt-keepalive` - sent while the slot stays parked, at most every 2 seconds, or at the request's `sse_ping_interval` when that is shorter. diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index c10347654141..73d2ce2b56bb 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -156,13 +156,45 @@ def _await(cond, what: str, alive=None, stall: float = 120.0, poll: float = 0.02 time.sleep(poll) -def _wait_processing(slot_ids, stall: float = 120.0): - """Return once every one of these slots is processing, waiting as long as the server keeps making progress (see _await).""" +def _wait_processing(slot_ids, alive=None, stall: float = 120.0): + """Return once every one of these slots is processing, waiting as long as the server keeps making progress (see _await); + alive() false (the request that was to make them busy has ended) fails at once instead of polling for what cannot happen.""" def processing(): slots = server.make_request("GET", "/slots").body return all(any(s["id"] == i and s["is_processing"] for s in slots) for i in slot_ids) - _await(processing, f"slots {slot_ids} processing", stall=stall, poll=0.005) + _await(processing, f"slots {slot_ids} processing", alive=alive, stall=stall, poll=0.005) + + +_LAUNCH_RE = re.compile(r"id +(\d+) \| task \d+ \| processing task") +_RELEASE_RE = re.compile(r"id +(\d+) \| task \d+ \| stop processing") + + +def _require_overlap(slot: int, what: str) -> None: + """Fail, naming the setup and not the scheduler, unless another slot's request was launched while this slot's last one was + in flight. The server writes its log in order, so that launch must fall between this slot's last launch and its release: a + client delay that lets the earlier request end first leaves nothing to preempt, and a run like that exercised nothing.""" + start, end, others = None, None, [] + for i, line in enumerate(_log().splitlines()): + if m := _LAUNCH_RE.search(line): + if int(m.group(1)) == slot: + start, end = i, None + else: + others.append(i) + elif (m := _RELEASE_RE.search(line)) and int(m.group(1)) == slot and start is not None: + end = i + if start is None or not any(start < i and (end is None or i < end) for i in others): + pytest.fail(f"precondition not met, the case was not exercised: {what}; slot {slot} ended before any other " # ty: ignore[invalid-argument-type] + f"request was launched (the client was too slow to overlap them)") + + +def _require_pressure(bodies, what: str) -> None: + """Fail, naming the setup, when none of these completed requests was parked: two requests that both finished whole without a + park never needed more cells than the pool has (one that did would have been refused or truncated), so the newer one came + when the older was too near its end, and the policy under test was never asked.""" + if sum(body["preempt"]["parks"] for body in bodies) == 0: + pytest.fail(f"precondition not met, the case was not exercised: {what}; nothing was parked, so the pool was never " # ty: ignore[invalid-argument-type] + f"short (the client was too slow to overlap them)") def _complete_overlapping(n_predict, n_prompt, timeout: float = DEFAULT_REQUEST_TIMEOUT): @@ -171,8 +203,9 @@ def _complete_overlapping(n_predict, n_prompt, timeout: float = DEFAULT_REQUEST_ other = _prompt_of(n_prompt[1], _PROMPT_B) with ThreadPoolExecutor(1) as pool: first = pool.submit(_complete, n_predict[0], leader, 0, 0.0, None, timeout) - _wait_processing([0]) + _wait_processing([0], alive=lambda: not first.done()) second = _complete(n_predict[1], other, 1, 0.0, None, timeout) + _require_overlap(0, "the follower on slot 1 beside the leader on slot 0") return [first.result(), second] @@ -180,7 +213,7 @@ def _complete_together(n_predict: int, n_prompt, timeout: float = DEFAULT_REQUES """Both prompts in one request, so they are queued at once and overlap whatever the client's or the host's speed.""" return server.make_request("POST", "/completion", data={ "n_predict": n_predict, "prompt": [_prompt_of(n_prompt[0], _PROMPT_A), _prompt_of(n_prompt[1], _PROMPT_B)], - "ignore_eos": True, "temperature": 0.0, "seed": 42, "cache_prompt": False, + "ignore_eos": True, "return_tokens": True, "temperature": 0.0, "seed": 42, "cache_prompt": False, }, timeout=timeout) @@ -279,16 +312,17 @@ def test_two_generations_that_do_not_fit_together_both_finish(knob): n_ctx = 1024 (_start_async if knob == "async" else _start)(n_ctx=n_ctx) - n_predict = (460, 400) - results = _complete_overlapping(n_predict, (500, 200)) + # one request with both prompts: queued at once, so they overlap whatever the client's speed; 500 + 200 + 2 * 460 > 1024 + n_predict = 460 + response = _complete_together(n_predict, (500, 200)) + assert response.status_code == 200, response.body text = _log() _assert_recovered(text, "preempted as a last resort" if knob.startswith("last-resort") else "preempted:") - for res, n_wanted in zip(results, n_predict): - assert res.status_code == 200, res.body - assert res.body["timings"]["predicted_n"] == n_wanted - assert res.body["truncated"] is False - assert len(res.body["tokens"]) == n_wanted + for body in response.body: + assert body["timings"]["predicted_n"] == n_predict + assert body["truncated"] is False + assert len(body["tokens"]) == n_predict if knob == "pages": held = [int(n) for n in re.findall(rf"kv (\d+)/{n_ctx}", text)] @@ -447,9 +481,10 @@ def test_a_park_whose_host_allocation_fails_is_parked_by_recompute(): other = _prompt_of(200, _PROMPT_B) with ThreadPoolExecutor(1) as pool: first = pool.submit(_complete, 460, leader, 0) - _wait_processing([0]) + _wait_processing([0], alive=lambda: not first.done()) second = _complete(400, other, 1) results = [first.result(), second] + _require_overlap(0, "the request on slot 1 beside the one on slot 0") text = _log() assert "could not take the host memory" in text, "the injected allocation failure never fired" @@ -540,7 +575,7 @@ def test_a_started_slot_is_counted_by_the_cells_it_holds_not_by_the_prompt_it_ke with ThreadPoolExecutor(4) as pool: first = pool.submit(_complete, 460, ids, 0) - _wait_processing([0]) + _wait_processing([0], alive=lambda: not first.done()) follower = pool.submit(_complete, 8, ids[:8], 0) long_ones = [pool.submit(_complete, 400, long_prompts[0], 1), pool.submit(_complete, 400, long_prompts[1], 2)] @@ -1561,14 +1596,17 @@ def test_a_started_slot_that_fits_once_trimmed_parks_nobody(): idle = [300 + i % 30 for i in range(60)] assert _cached(1, old, 0).status_code == 200 assert _cached(1, idle, 2).status_code == 200 - with ThreadPoolExecutor(1) as pool: - gen = pool.submit(_cached, 220, [200 + i for i in range(90)], 1) - _wait_processing([1]) - started = _cached(4, old[:300] + [400 + i % 100 for i in range(336)], 0) - generating = gen.result() - for res in (started, generating): - assert res.status_code == 200, res.body - assert res.body["preempt"]["parks"] == 0, res.body["preempt"] + # both prompts in one request, so they overlap whatever the client's speed: the new one takes the never-used slot 1, the one + # sharing old[:300] takes slot 0, and before slot 0 is trimmed 600 + 336 + 90 + 60 cells exceed the pool + response = server.make_request("POST", "/completion", data={ + "prompt": [[200 + i for i in range(90)], old[:300] + [400 + i % 100 for i in range(336)]], + "n_predict": 4, "cache_prompt": True, "ignore_eos": True, "temperature": 0.0, "seed": 42, + }) + assert response.status_code == 200, response.body + assert [body["id_slot"] for body in response.body] == [1, 0], [body["id_slot"] for body in response.body] + for body in response.body: + assert body["tokens_predicted"] == 4, body + assert body["preempt"]["parks"] == 0, body["preempt"] rerun = _cached(1, idle, 2) assert rerun.body["timings"]["cache_n"] == 59, rerun.body["timings"] text = _log() @@ -1618,9 +1656,10 @@ def test_a_single_request_beside_an_n_2_request_is_parked_so_both_finish(): _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128) with ThreadPoolExecutor(1) as pool: single = pool.submit(_cached, 300, [100 + k % 50 for k in range(600)], 0) - _wait_processing([0]) + _wait_processing([0], alive=lambda: not single.done()) family = _oai_n([200 + k % 50 for k in range(200)], 2, 250) single = single.result() + _require_overlap(0, "the n = 2 request beside the single one on slot 0") assert single.status_code == 200, single.body assert single.body["timings"]["predicted_n"] == 300 assert family.status_code == 200, family.body @@ -1669,11 +1708,16 @@ def test_a_started_request_reusing_a_long_prefix_does_not_park_an_older_generati _await(lambda: _n_decoded(_slot_view(0)) >= 280, "the older request decoding 280 tokens", alive=lambda: not older.done(), poll=0.002) newer = _cached(4, earlier + [300 + k % 50 for k in range(300)], 1) older = older.result() + # launched beside an older request holding 320+ cells, the newer one's 904 exceed the pool + _require_overlap(0, "the newer request on slot 1 beside the older one decoding on slot 0") for res, n_predict in ((older, 600), (newer, 4)): assert res.status_code == 200, res.body assert res.body["timings"]["predicted_n"] == n_predict - assert older.body["preempt"]["parks"] == 0, "the older generating request was parked for a newer one" - assert newer.body["preempt"]["parks"] > 0 + _require_pressure((older.body, newer.body), "the newer request reusing a long prefix beside the older one") + # the suite also runs under LLAMA_ARG_PREEMPT_POLICY=cost, which may park the older request, the cheaper one, instead + if server.make_request("GET", "/props").body["preempt"]["policy"] == "fcfs": + assert older.body["preempt"]["parks"] == 0, "the older generating request was parked for a newer one" + assert newer.body["preempt"]["parks"] > 0 @pytest.mark.parametrize("policy", ["fcfs", "cost"]) @@ -1688,14 +1732,14 @@ def test_the_policy_decides_whether_the_newest_or_the_cheapest_slot_is_parked(po _await(lambda: _n_decoded(_slot_view(0)) >= 20, "the older request decoding 20 tokens", alive=lambda: not older.done(), poll=0.005) newer = _cached(500, [200 + k % 50 for k in range(300)], 1) older = older.result() + _require_overlap(0, "the newer request on slot 1 beside the older one decoding on slot 0") for res, n_predict in ((older, 600), (newer, 500)): assert res.status_code == 200, res.body assert res.body["timings"]["predicted_n"] == n_predict + _require_pressure((older.body, newer.body), "the newer request beside the older one") if policy == "fcfs": - assert older.body["preempt"]["parks"] == 0 + assert older.body["preempt"]["parks"] == 0, "the older request was parked for a newer one" assert newer.body["preempt"]["parks"] > 0 - else: - assert older.body["preempt"]["parks"] + newer.body["preempt"]["parks"] > 0 text = _log() assert 0 <= text.find("purging slot 2") < text.find("preempted:"), "a running slot was parked while an idle one held cells" @@ -1705,23 +1749,26 @@ def test_fcfs_resumes_parked_requests_in_arrival_order(): os.environ["LLAMA_ARG_PREEMPT_POLICY"] = "fcfs" _start(n_ctx=1024, n_slots=3, n_batch=128, n_ubatch=128) assert server.make_request("GET", "/props").body["preempt"]["policy"] == "fcfs" - with ThreadPoolExecutor(3) as pool: - futures = [] - for i, n_predict in enumerate((700, 450, 450)): - futures.append(pool.submit(_cached, n_predict, [100 * (i + 1) + k % 50 for k in range(40)], i)) - _wait_processing([i]) - results = [f.result() for f in futures] - for res, n_predict in zip(results, (700, 450, 450)): - assert res.status_code == 200, res.body - assert res.body["timings"]["predicted_n"] == n_predict - assert results[0].body["preempt"]["parks"] == 0, "the oldest request was parked" + # three prompts in one request: queued at once in this order, so they overlap whatever the client's speed; each fits alone + # (40 + 700 cells), together they need 2220 of 1024 + response = server.make_request("POST", "/completion", data={ + "prompt": [[100 * (i + 1) + k % 50 for k in range(40)] for i in range(3)], + "n_predict": 700, "cache_prompt": True, "ignore_eos": True, "temperature": 0.0, "seed": 42, + }) + assert response.status_code == 200, response.body + results = response.body + for body in results: + assert body["timings"]["predicted_n"] == 700, body + assert results[0]["preempt"]["parks"] == 0, "the oldest request was parked" + oldest, middle, newest = (body["id_slot"] for body in results) text = _log() resumed = [int(m) for m in re.findall(r"id +(\d+) \| task \d+ \| resumed after", text)] assert resumed, "nothing was parked" parked = [int(m) for m in re.findall(r"id +(\d+) \| task \d+ \| preempted:", text)] - assert parked[0] == 2, parked - if 1 in parked: - assert resumed.index(1) < resumed.index(2), resumed + assert oldest not in parked, parked + assert parked[0] == newest, (parked, newest) + if middle in parked: + assert resumed.index(middle) < resumed.index(newest), resumed def test_fcfs_runs_the_oldest_to_the_end_of_the_window_beside_a_held_prompt(): diff --git a/tools/server/tests/unit/test_preempt_notify.py b/tools/server/tests/unit/test_preempt_notify.py index 4f3118de9c1d..0c6b8805b40c 100644 --- a/tools/server/tests/unit/test_preempt_notify.py +++ b/tools/server/tests/unit/test_preempt_notify.py @@ -63,7 +63,7 @@ def _log() -> str: def _slots() -> list: - return requests.get(f"http://{server.server_host}:{server.server_port}/slots").json() + return requests.get(f"http://{server.server_host}:{server.server_port}/slots", timeout=DEFAULT_HTTP_TIMEOUT).json() def _server_progress(): @@ -93,7 +93,10 @@ def _await(cond, what: str, alive=None, stall: float = 120.0, poll: float = 0.02 def _post(path: str, data: dict): - return requests.post(f"http://{server.server_host}:{server.server_port}{path}", json=data, stream=True) + # bounded like make_request: a server that takes the connection and then stops sending fails the test instead of hanging it. + # The read timeout is per read, and a parked stream is kept alive every two seconds, so only a stall reaches it + return requests.post(f"http://{server.server_host}:{server.server_port}{path}", json=data, stream=True, + timeout=(DEFAULT_HTTP_TIMEOUT, DEFAULT_REQUEST_TIMEOUT)) def _stream_raw(path: str, data: dict) -> tuple[list[str], list[str]]: From be076be94a0637bf7143245851f6745b3164c3b1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 08:30:24 -0700 Subject: [PATCH 107/109] server : up-front prompt checks keep the order a slot meets them, the covering-victim test queues its prompts together under cost - task_prompt_rejected() checks as launch_slot_with_task() and then the batch builder do: the aLoRA set, the token ids, then the empty prompt, logits and sizes; a request the batch-builder checks refuse gets the sampler error first when its sampling parameters cannot be built, as before - test_embedding: an invalid token is a 400 and refused sampling parameters a 400 on an embedding-only server, as on base - test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small_ones sends all four prompts in one request under LLAMA_ARG_PREEMPT_POLICY=cost and checks the one parked slot is the covering one --- tools/server/server-context.cpp | 76 ++++++++++++++++++++--- tools/server/tests/unit/test_embedding.py | 8 +++ tools/server/tests/unit/test_preempt.py | 32 +++++----- 3 files changed, 91 insertions(+), 25 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 2ded322e4ada..7778259e1be1 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1646,7 +1646,7 @@ struct server_context_impl { error_type type = ERROR_TYPE_SERVER; for (const auto & task : tasks) { - if (!task_prompt_rejected(task, msg, type)) { + if (!task_prompt_rejected(task, msg, type, /* with_sampler */ true)) { continue; } @@ -5731,13 +5731,78 @@ struct server_context_impl { } } + // As launch_slot_with_task() resolves them: the task's own adapter scales, or the server's, refused when all the enabled ones + // are aLoRAs and there is not exactly one of them. + bool task_runs_several_aloras(const server_task & task) const { + const auto & loras = params_base.lora_adapters; + + bool all_alora = false; + size_t n_enabled = 0; + + for (size_t i = 0; i < loras.size(); ++i) { + float scale = loras[i].scale; + if (!task.params.lora.empty()) { + const auto it = task.params.lora.find((int) i); + scale = it != task.params.lora.end() ? it->second : 0.0f; + } + if (scale != 0) { + if (llama_adapter_get_alora_n_invocation_tokens(loras[i].ptr) == 0) { + return false; + } + all_alora = true; + } + if (scale > 0) { + n_enabled++; + } + } + + return all_alora && n_enabled != 1; + } + // Checks a request must pass before its prompt is processed; true if rejected. An empty prompt is a final response, not an error. - bool task_prompt_rejected(const server_task & task, std::string & msg, error_type & type) const { + // They run in the order a slot meets them, so a request failing several gets the error it got before they were moved up front: + // launch_slot_with_task() first (aLoRA set, token ids, samplers), then the batch builder (empty prompt, logits, sizes). + // with_sampler: a task not launched yet, whose sampling parameters are tried when a batch-builder check would refuse it. + bool task_prompt_rejected(const server_task & task, std::string & msg, error_type & type, bool with_sampler = false) const { + if (task_runs_several_aloras(task)) { + msg = "Cannot run multiple aLoRAs in a single request"; + type = ERROR_TYPE_INVALID_REQUEST; + return true; + } + + // Mirrors launch_slot_with_task(), run earlier so a sibling is not rejected inside an already opened 200 stream. + if (!task.tokens.validate(ctx_tgt)) { + msg = "Prompt contains invalid tokens"; + type = ERROR_TYPE_INVALID_REQUEST; + return true; + } + // as the batch builder: an empty prompt is answered with an empty final response before any check below if (task.tokens.empty()) { return false; } + if (!task_built_prompt_rejected(task, msg, type)) { + return false; + } + + // the launch refuses sampling parameters the samplers cannot take before the batch builder gets to the checks above; tried + // only on this path, where the request is refused either way, so an accepted one builds its samplers once, at the launch + if (with_sampler && task.need_sampling()) { + try { + common_params_sampling sampling = task.params.sampling; // common_sampler_init() takes them by non-const reference + common_sampler_ptr smpl(common_sampler_init(model_tgt, sampling)); + } catch (const std::exception & e) { + msg = std::string("Failed to initialize samplers: ") + e.what(); + type = ERROR_TYPE_INVALID_REQUEST; + } + } + + return true; + } + + // The batch builder's checks of a non-empty prompt, in its order; true if rejected. + bool task_built_prompt_rejected(const server_task & task, std::string & msg, error_type & type) const { // TODO: support memory-less logits computation if (task.need_logits() && !llama_get_memory(ctx_tgt)) { msg = "the current context does not support logits computation. skipping"; @@ -5745,13 +5810,6 @@ struct server_context_impl { return true; } - // Mirrors launch_slot_with_task(), run earlier so a sibling is not rejected inside an already opened 200 stream. - if (!task.tokens.validate(ctx_tgt)) { - msg = "Prompt contains invalid tokens"; - type = ERROR_TYPE_INVALID_REQUEST; - return true; - } - if (!task_can_split(task, ctx_tgt)) { const int32_t n_ubatch = llama_n_ubatch(ctx_tgt); diff --git a/tools/server/tests/unit/test_embedding.py b/tools/server/tests/unit/test_embedding.py index 2295440108c4..0b257b22baa6 100644 --- a/tools/server/tests/unit/test_embedding.py +++ b/tools/server/tests/unit/test_embedding.py @@ -360,3 +360,11 @@ def test_an_empty_completion_prompt_on_an_embedding_server_is_an_empty_response( assert server.make_request("POST", "/completion", data={"prompt": [], "n_predict": 1}).status_code == 400 res = server.make_request("POST", "/completion", data={"prompt": [[1] * 600], "n_predict": 1}) assert res.status_code == 500 and "logits" in res.body["error"]["message"], res.body + # the checks keep the order they have when the slot is launched and its prompt built: an invalid token is a bad request (400) + # before the context is asked for logits, and so are sampling parameters the samplers refuse + res = server.make_request("POST", "/completion", data={"prompt": [[99999999]], "n_predict": 1}) + assert res.status_code == 400 and res.body["error"]["type"] == "invalid_request_error", res.body + assert "invalid tokens" in res.body["error"]["message"], res.body + res = server.make_request("POST", "/completion", data={"prompt": [[1] * 600], "n_predict": 1, "repeat_penalty": 0}) + assert res.status_code == 400 and res.body["error"]["type"] == "invalid_request_error", res.body + assert "Failed to initialize samplers" in res.body["error"]["message"], res.body diff --git a/tools/server/tests/unit/test_preempt.py b/tools/server/tests/unit/test_preempt.py index 73d2ce2b56bb..b09b3b8dea09 100644 --- a/tools/server/tests/unit/test_preempt.py +++ b/tools/server/tests/unit/test_preempt.py @@ -1428,31 +1428,31 @@ def run(name, n_predict, prompt, id_slot): def test_one_victim_that_covers_the_shortfall_is_parked_instead_of_several_small_ones(): + # the smallest single victim that covers the shortfall is the cost policy's choice; the fixture restores the policy afterwards + os.environ["LLAMA_ARG_PREEMPT_POLICY"] = "cost" _serve_with_training_context(8192) _start(n_ctx=4864, n_slots=4, n_batch=2048) + assert server.make_request("GET", "/props").body["preempt"]["policy"] == "cost" - small = [_prompt_of(400, _PROMPT_A), _prompt_of(400, _PROMPT_B)] - medium = _prompt_of(1400, _PROMPT_C) - leader = _prompt_of(3267, _PROMPT_A) - - with ThreadPoolExecutor(4) as pool: - residents = [pool.submit(_raw_completion, 300, p, i) for i, p in enumerate(small + [medium])] - _await(lambda: all(_n_decoded(s) > 0 for s in server.make_request("GET", "/slots").body if s["id"] < 3), - "the three residents decoding", alive=lambda: not all(r.done() for r in residents), poll=0.002) - last = pool.submit(_raw_completion, 8, leader, 3) - results = [r.result() for r in residents] + [last.result()] - - for res, n_predict in zip(results, (300, 300, 300, 8)): - assert res.status_code == 200, res.body - assert res.body["timings"]["predicted_n"] == n_predict + # all four prompts in one request, so they are queued at once whatever the client's speed. At their output limits the two small + # ones and the leader hold 700 + 700 + 3400 cells, which fit the 4864 once the 1700 of the medium one are parked; parking both + # small ones instead would not be enough + prompts = [_prompt_of(400, _PROMPT_A), _prompt_of(400, _PROMPT_B), _prompt_of(1400, _PROMPT_C), _prompt_of(3100, _PROMPT_A)] + response = server.make_request("POST", "/completion", data={ + "prompt": prompts, "n_predict": 300, "ignore_eos": True, "temperature": 0.0, "seed": 42, "cache_prompt": False, + }) + assert response.status_code == 200, response.body + for body in response.body: + assert body["timings"]["predicted_n"] == 300, body text = _log() assert "Context size has been exceeded" not in text first_resume = text.find("resumed after") assert first_resume > 0, "nothing was parked" - parks = [int(n) for n in re.findall(r"preempted: (\d+) cells", text[:first_resume])] + parks = [(int(slot), int(n)) for slot, n in re.findall(r"id +(\d+) \| task \d+ \| preempted: (\d+) cells", text[:first_resume])] assert len(parks) == 1, f"parked {parks} where one resident covered the shortfall" - assert parks[0] >= 1400, parks + assert parks[0][0] == response.body[2]["id_slot"], (parks, [body["id_slot"] for body in response.body]) + assert parks[0][1] >= 1400, parks @pytest.mark.parametrize("ram", ["8192", "0", "unset"]) From 32abc8ddfcdc99a0276705f01da1794cc28eda2e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 09:38:50 -0700 Subject: [PATCH 108/109] server : keep the aLoRA-set check on the server loop, out of the up-front prompt check task_prompt_rejected() also runs on the HTTP thread (tasks_prompt_rejected() before the tasks are posted). The aLoRA-set check moved into it read params_base.lora_adapters and their scales there, while SERVER_TASK_TYPE_SET_LORA replaces that vector on the server loop: a data race, seen as a spurious 400 "Cannot run multiple aLoRAs in a single request". The check is back where it was, only in launch_slot_with_task(), which runs on the server loop like every other reader and writer of the adapters (GET_LORA, SET_LORA, construct_lora_list), so no lock is needed and none is added. What the up-front check still reads off the server loop, none of it written after loading: the vocabulary and model (validate(), common_sampler_init() in the sampler trial, llama_model_n_ctx_train()), the context's sizes and flags (llama_n_ctx_seq, llama_n_batch, llama_n_ubatch, llama_get_memory, llama_get_causal_attn, which the server never sets), the constant params_base.kv_unified_per_slot, and the task itself. A request that both enables several aLoRAs and fails a check run up front now gets that check's error instead of the aLoRA one; both are refusals, and none of them is a 200. --- tools/server/server-context.cpp | 39 ++++----------------------------- 1 file changed, 4 insertions(+), 35 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 7778259e1be1..33f4c3569fc4 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -5731,45 +5731,14 @@ struct server_context_impl { } } - // As launch_slot_with_task() resolves them: the task's own adapter scales, or the server's, refused when all the enabled ones - // are aLoRAs and there is not exactly one of them. - bool task_runs_several_aloras(const server_task & task) const { - const auto & loras = params_base.lora_adapters; - - bool all_alora = false; - size_t n_enabled = 0; - - for (size_t i = 0; i < loras.size(); ++i) { - float scale = loras[i].scale; - if (!task.params.lora.empty()) { - const auto it = task.params.lora.find((int) i); - scale = it != task.params.lora.end() ? it->second : 0.0f; - } - if (scale != 0) { - if (llama_adapter_get_alora_n_invocation_tokens(loras[i].ptr) == 0) { - return false; - } - all_alora = true; - } - if (scale > 0) { - n_enabled++; - } - } - - return all_alora && n_enabled != 1; - } - // Checks a request must pass before its prompt is processed; true if rejected. An empty prompt is a final response, not an error. // They run in the order a slot meets them, so a request failing several gets the error it got before they were moved up front: - // launch_slot_with_task() first (aLoRA set, token ids, samplers), then the batch builder (empty prompt, logits, sizes). + // launch_slot_with_task() first (token ids, samplers), then the batch builder (empty prompt, logits, sizes). // with_sampler: a task not launched yet, whose sampling parameters are tried when a batch-builder check would refuse it. + // [TAG_PREEMPT] This also runs on the HTTP thread (tasks_prompt_rejected()), so it reads only what the server loop never changes + // after loading: the vocabulary and model, the context's sizes and flags, and the task itself. The aLoRA-set check stays in + // launch_slot_with_task(): it reads params_base.lora_adapters, which POST /lora-adapters replaces on the server loop. bool task_prompt_rejected(const server_task & task, std::string & msg, error_type & type, bool with_sampler = false) const { - if (task_runs_several_aloras(task)) { - msg = "Cannot run multiple aLoRAs in a single request"; - type = ERROR_TYPE_INVALID_REQUEST; - return true; - } - // Mirrors launch_slot_with_task(), run earlier so a sibling is not rejected inside an already opened 200 stream. if (!task.tokens.validate(ctx_tgt)) { msg = "Prompt contains invalid tokens"; From d5b2f1ca88423a80eccd4b7f10d25761f4aa5297 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 23 Oct 2026 11:01:59 -0700 Subject: [PATCH 109/109] exact : the decode tokens figure cannot outgrow a live context's batch geometry llama_set_exact_decode_tokens() raised the process-wide figure after checking only the explicit column bound, while every exact context's constructor requires n_batch >= n_ubatch + n_seq_max * figure. A context valid at the old figure (132/128/2 at 1) kept decoding after the figure grew to 8, though an identical new one is refused, and a prompt beside a neighbour was then split into other ubatches than alone. - each exact context with more than one sequence holds its slack, (n_batch - n_ubatch) / n_seq_max, in a process-wide multiset for its life (llama_exact_geometry_hold, a member, so a constructor that throws later releases it); the check and the record are one step under the lock the figure uses, so no figure grows in between - the setter refuses, logging and leaving the old figure, a figure past the tightest live slack - decode() and encode() refuse a step, before touching the batch or memory, when the figure has outgrown the context anyway - test-exact-decode-tokens -m MODEL (new ctest test-exact-decode-tokens-live-context): a vocab-only 132/128/2 context refuses 8 and 3, accepts 2; freed, 8 is accepted; an identical context is then refused and a 144/128/2 one accepted, which refuses 9 --- src/llama-context.cpp | 40 +++++++++++++--- src/llama-context.h | 6 +++ src/llama-impl.cpp | 43 +++++++++++++++++ src/llama-impl.h | 17 +++++++ tests/CMakeLists.txt | 2 + tests/test-exact-decode-tokens.cpp | 74 +++++++++++++++++++++++++++++- 6 files changed, 174 insertions(+), 8 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 0114cd58b250..ad2812a85a7f 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -393,16 +393,15 @@ llama_context::llama_context( // [TAG_EXACT_CONCURRENCY] the batch must hold a whole ubatch beside a decode step of every other sequence, or a prompt that shares a // batch is split into shorter ubatches than it gets alone; checked here too, so callers that skip common_exact_concurrency_init() get it - if (llama_exact_concurrency() && cparams.n_seq_max > 1) { + // The geometry is held for the context's life, so the tokens figure cannot later grow past it (llama_exact_geometry_hold). + if (llama_exact_concurrency() && cparams.n_seq_max > 1 && !exact_geometry.acquire(cparams.n_batch, cparams.n_ubatch, cparams.n_seq_max)) { const uint64_t n_cols = uint64_t(cparams.n_seq_max) * std::max(1u, llama_exact_decode_tokens()); const uint64_t n_min = uint64_t(cparams.n_ubatch) + n_cols; - if (uint64_t(cparams.n_batch) < n_min) { - LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY needs a batch of at least %" PRIu64 " tokens for a %u-token ubatch beside a decode step of " - "%u sequences (%" PRIu64 " columns), but the batch is %u%s: raise n_batch (and n_ctx), or lower n_ubatch\n", __func__, - n_min, cparams.n_ubatch, cparams.n_seq_max, n_cols, cparams.n_batch, cparams.causal_attn && cparams.n_batch == cparams.n_ctx ? " (clamped to n_ctx)" : ""); - throw std::runtime_error("exact concurrency: the batch cannot hold a whole ubatch beside a decode step"); - } + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY needs a batch of at least %" PRIu64 " tokens for a %u-token ubatch beside a decode step of " + "%u sequences (%" PRIu64 " columns), but the batch is %u%s: raise n_batch (and n_ctx), or lower n_ubatch\n", __func__, + n_min, cparams.n_ubatch, cparams.n_seq_max, n_cols, cparams.n_batch, cparams.causal_attn && cparams.n_batch == cparams.n_ctx ? " (clamped to n_ctx)" : ""); + throw std::runtime_error("exact concurrency: the batch cannot hold a whole ubatch beside a decode step"); } cparams.n_outputs_max = params.n_outputs_max == 0 || llama_model_has_encoder(&model) ? cparams.n_batch : params.n_outputs_max; @@ -1682,7 +1681,30 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll return res; } +// [TAG_EXACT_CONCURRENCY] Backstop for llama_set_exact_decode_tokens(), which refuses to grow the figure past a live context's batch: +// a context never runs under a geometry its constructor would refuse, and is refused before any batch or memory state is touched. +bool llama_context::exact_geometry_holds(const char * fn) const { + if (!llama_exact_concurrency() || cparams.n_seq_max <= 1) { + return true; + } + + const uint64_t n_cols = uint64_t(cparams.n_seq_max) * std::max(1u, llama_exact_decode_tokens()); + + if (uint64_t(cparams.n_batch) < uint64_t(cparams.n_ubatch) + n_cols) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY needs a batch of at least %" PRIu64 " tokens for a %u-token ubatch beside a decode step of " + "%u sequences (%" PRIu64 " columns) since the decode tokens figure grew, but this context's batch is %u; the step is refused\n", + fn, uint64_t(cparams.n_ubatch) + n_cols, cparams.n_ubatch, cparams.n_seq_max, n_cols, cparams.n_batch); + return false; + } + + return true; +} + int llama_context::encode(const llama_batch_ext & batch_inp) { + if (!exact_geometry_holds(__func__)) { + return -1; + } + if (batch_inp.tokens.empty()) { LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); return -1; @@ -1922,6 +1944,10 @@ static bool needs_raw_logits(const llama_ubatch & ubatch, const std::map #include #include +#include #include #include #include @@ -300,6 +301,39 @@ bool llama_exact_report_n_seq(uint32_t n_seq) { return true; } +// the slack of every live exact context with more than one sequence (see llama_exact_geometry_hold), guarded by g_exact_mutex +static std::multiset g_exact_live_slack; + +bool llama_exact_geometry_hold::acquire(uint32_t n_batch, uint32_t n_ubatch, uint32_t n_seq_max) { + if (n_seq_max <= 1) { + return true; + } + + std::lock_guard lock(g_exact_mutex); + + const uint32_t s = n_batch >= n_ubatch ? (n_batch - n_ubatch) / n_seq_max : 0; + + if (s < std::max(1u, g_exact_decode_tokens.load(std::memory_order_relaxed))) { + return false; + } + + g_exact_live_slack.insert(s); + held = true; + slack = s; + + return true; +} + +llama_exact_geometry_hold::~llama_exact_geometry_hold() { + if (!held) { + return; + } + + std::lock_guard lock(g_exact_mutex); + + g_exact_live_slack.erase(g_exact_live_slack.find(slack)); +} + bool llama_set_exact_decode_tokens(uint32_t n_tokens) { n_tokens = n_tokens > 0 ? n_tokens : 1; @@ -310,6 +344,15 @@ bool llama_set_exact_decode_tokens(uint32_t n_tokens) { return true; } + // a live context whose batch cannot hold the larger step beside a whole ubatch would be split differently than it is alone, which + // its constructor refuses; refused here as well, leaving the old figure, until that context is gone + if (!g_exact_live_slack.empty() && n_tokens > *g_exact_live_slack.begin()) { + LLAMA_LOG_ERROR("%s: LLAMA_EXACT_CONCURRENCY cannot raise the decode tokens per sequence to %u: a live context's batch holds only %u " + "per sequence beside a whole ubatch; create it with a larger n_batch (or a smaller n_ubatch), or free it first\n", + __func__, n_tokens, *g_exact_live_slack.begin()); + return false; + } + // every context widens with the figure, so report the width first; one the explicit bound cannot cover leaves the old figure in place. // Before any context exists, check it for one sequence: stored unchecked, a figure past the bound could never be lowered again and // would refuse every later context, a one-sequence one included. diff --git a/src/llama-impl.h b/src/llama-impl.h index b29e99e99b29..b3676d6023ce 100644 --- a/src/llama-impl.h +++ b/src/llama-impl.h @@ -127,3 +127,20 @@ bool llama_exact_buft_invariant(ggml_backend_buffer_type_t buft); bool llama_exact_report_n_seq(uint32_t n_seq); bool llama_exact_check_n_seq(uint32_t n_seq); + +// [TAG_EXACT_CONCURRENCY] A live exact context's batch geometry, held while it lives: its batch must keep holding a whole ubatch +// beside a decode step of every sequence, n_batch >= n_ubatch + n_seq_max * llama_exact_decode_tokens(), so the process-wide +// tokens figure may only grow to what the tightest live context still holds (llama_set_exact_decode_tokens() refuses past it). +struct llama_exact_geometry_hold { + llama_exact_geometry_hold() = default; + llama_exact_geometry_hold(const llama_exact_geometry_hold &) = delete; + llama_exact_geometry_hold & operator=(const llama_exact_geometry_hold &) = delete; + ~llama_exact_geometry_hold(); + + // checks the geometry against the current figure and records it in one step, so no figure can grow in between; false, recording + // nothing, when it does not hold. A context with one sequence has no decode step beside its ubatch and is not recorded + bool acquire(uint32_t n_batch, uint32_t n_ubatch, uint32_t n_seq_max); + + bool held = false; + uint32_t slack = 0; // decode tokens per sequence the batch holds beside a whole ubatch +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5c36c55aa763..f42b4781d458 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -419,6 +419,8 @@ llama_build_and_test(test-mtmd-impl.cpp LINK mtmd) # [TAG_EXACT_CONCURRENCY] the batch shape the mode requires, checked without a model llama_build_and_test(test-exact-geometry.cpp) llama_build_and_test(test-exact-decode-tokens.cpp) +llama_test(test-exact-decode-tokens NAME test-exact-decode-tokens-live-context LABEL "model" ARGS -m "${MODEL_DEST}") +set_tests_properties(test-exact-decode-tokens-live-context PROPERTIES FIXTURES_REQUIRED test-download-model) llama_build_and_test(test-speculative-shared-bound.cpp) # server helpers that need no model; server-context exists only where tools/ adds the server diff --git a/tests/test-exact-decode-tokens.cpp b/tests/test-exact-decode-tokens.cpp index 9a72908b94cd..85dff9c8fd14 100644 --- a/tests/test-exact-decode-tokens.cpp +++ b/tests/test-exact-decode-tokens.cpp @@ -1,17 +1,89 @@ // [TAG_EXACT_CONCURRENCY] llama_set_exact_decode_tokens() checks the explicit column bound before any context exists: a figure past // it is refused and leaves the stored one, which is never lowered, so nothing later is refused because of it. +// With -m MODEL it checks instead that the figure cannot outgrow a live exact context's batch geometry, which that context's +// constructor enforces (n_batch >= n_ubatch + n_seq_max * figure): a vocab-only load, as the geometry needs no weights. #include "llama.h" #include #include +#include static int check(const char * what, bool ok) { printf("%-72s %s\n", what, ok ? "ok" : "FAIL"); return ok ? 0 : 1; } -int main() { +static void set_env(const char * name, const char * value) { +#ifdef _WIN32 + _putenv_s(name, value); +#else + setenv(name, value, 1); +#endif +} + +static llama_context * exact_context(llama_model * model, uint32_t n_batch, uint32_t n_ubatch, uint32_t n_seq_max) { + llama_context_params cparams = llama_context_default_params(); + cparams.n_ctx = 512; + cparams.n_batch = n_batch; + cparams.n_ubatch = n_ubatch; + cparams.n_seq_max = n_seq_max; + cparams.kv_unified = true; + return llama_init_from_model(model, cparams); +} + +static int live_contexts(const char * path) { + // a fresh process: the figure starts at 1 and only grows + set_env("LLAMA_EXACT_CONCURRENCY", "1"); + + llama_backend_init(); + + llama_model_params mparams = llama_model_default_params(); + mparams.vocab_only = true; + + llama_model * model = llama_model_load_from_file(path, mparams); + if (model == nullptr) { + printf("could not load %s\n", path); + return 1; + } + + int bad = 0; + + // valid at a figure of 1: 128 + 2 * 1 <= 132 + llama_context * tight = exact_context(model, 132, 128, 2); + bad += check("a 132/128/2 context at a figure of 1: created", tight != nullptr && llama_exact_decode_tokens() == 1); + bad += check("8 beside it (needs a batch of 144): refused, 1 kept", !llama_set_exact_decode_tokens(8) && llama_exact_decode_tokens() == 1); + bad += check("2 beside it (needs exactly 132): accepted", llama_set_exact_decode_tokens(2) && llama_exact_decode_tokens() == 2); + bad += check("3 beside it: refused, 2 kept", !llama_set_exact_decode_tokens(3) && llama_exact_decode_tokens() == 2); + + llama_context * single = exact_context(model, 132, 128, 1); + bad += check("a one-sequence context: created", single != nullptr); + + llama_free(tight); + bad += check("8 once the tight context is freed, a one-sequence one alive: accepted", llama_set_exact_decode_tokens(8) && llama_exact_decode_tokens() == 8); + llama_free(single); + + llama_context * again = exact_context(model, 132, 128, 2); + bad += check("an identical 132/128/2 context at a figure of 8: refused", again == nullptr); + llama_free(again); + + llama_context * wide = exact_context(model, 144, 128, 2); + bad += check("a 144/128/2 context at a figure of 8: created", wide != nullptr); + bad += check("9 beside it: refused, 8 kept", !llama_set_exact_decode_tokens(9) && llama_exact_decode_tokens() == 8); + llama_free(wide); + + llama_model_free(model); + llama_backend_free(); + + printf("%s\n", bad == 0 ? "ok" : "FAIL"); + return bad == 0 ? 0 : 1; +} + +int main(int argc, char ** argv) { + if (argc == 3 && strcmp(argv[1], "-m") == 0) { + return live_contexts(argv[2]); + } + #ifdef _WIN32 _putenv_s("GGML_CUDA_BATCH_INVARIANT_MAX_COLS", "8"); #else