Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ endif ()

llama_build(test-recurrent-state-rollback.cpp)
llama_build_and_test(test-sampler-penalties.cpp)
llama_build(test-server-lanes.cpp) # needs -m <model>: laned sampling picks the serial tokens; the step's us serial vs laned
target_compile_features(test-server-lanes PRIVATE cxx_std_20)
llama_build(test-sampler-coarse.cpp) # needs -m <model>: ballpark sampling picks exactly the full path's token
llama_build_and_test(test-server-view-end.cpp)

Expand Down
184 changes: 184 additions & 0 deletions tests/test-server-lanes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
// what this catches: sampling one step's sequences on the lanes (server-lanes.h, CONTINUUM-ENGINE 4.7.14)
// choosing a different token than sampling them one after another, a lane run that loses or repeats a
// job, a job exception that does not reach the caller; and it reports the step's sampling time serial vs
// laned on real logits (needs -m <model>; the receipt is the per-step microseconds it prints).
#include "../tools/server/server-lanes.h"

#include "arg.h"
#include "common.h"
#include "llama.h"
#include "sampling.h"

#include <algorithm>
#include <system_error>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <vector>

static void require(bool condition, const char * message) {
if (!condition) {
std::fprintf(stderr, "FAILED: %s\n", message);
std::exit(1);
}
}

static double now_us() {
return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now().time_since_epoch()).count();
}

// the lanes alone: every job once, any count, exceptions carried back
static void lanes_run_every_job_once() {
server_lanes lanes(5);
for (size_t n : { (size_t) 1, (size_t) 2, (size_t) 6, (size_t) 64, (size_t) 1000 }) {
for (int rep = 0; rep < 200; ++rep) {
std::vector<std::atomic<int>> hits(n);
lanes.run(n, [&](size_t i) { hits[i].fetch_add(1, std::memory_order_relaxed); });
for (auto & h : hits) {
require(h.load() == 1, "every job runs exactly once");
}
}
}
bool caught = false;
try {
lanes.run(6, [](size_t i) { if (i == 3) { throw std::runtime_error("job 3"); } });
} catch (const std::runtime_error & e) {
caught = std::string(e.what()) == "job 3";
}
require(caught, "a job's exception reaches the caller");
std::atomic<int> after{0};
lanes.run(6, [&](size_t) { after++; });
require(after.load() == 6, "the lanes run normally after a failed run");
}

// regressions for Codex's review of #125: a stop signalled before a lane's first wait was missed (the
// join hung); and a lane holding an earlier run's claim word could claim against the next run's jobs
static void lanes_never_hang_and_never_cross_runs() {
for (int i = 0; i < 2000; ++i) {
server_lanes lanes(5); // destroyed at once: a lane may not have reached its first wait yet
}
server_lanes lanes(5);
std::vector<std::atomic<int>> hits(8);
for (int run = 0; run < 50000; ++run) {
const size_t n = 2 + (size_t) (run % 6);
for (size_t i = 0; i < n; ++i) {
hits[i].store(0, std::memory_order_relaxed);
}
lanes.run(n, [&](size_t i) { hits[i].fetch_add(1, std::memory_order_relaxed); });
for (size_t i = 0; i < n; ++i) {
require(hits[i].load() == 1, "back to back, every job of every run runs exactly once");
}
}
}

// what this catches: a lane thread that fails to start after others did destroyed joinable threads
// (std::terminate); the started lanes must be stopped and joined and the error reach the caller
static void lanes_failed_start_joins_the_started() {
size_t started = 0;
bool threw = false;
try {
server_lanes lanes(4, [&](std::function<void()> f) {
if (started == 2) {
throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again));
}
++started;
return std::thread(std::move(f));
});
} catch (const std::system_error &) {
threw = true;
}
require(threw && started == 2, "a failed lane start reaches the caller after the started lanes are joined");
}

int main(int argc, char ** argv) {
lanes_failed_start_joins_the_started();
lanes_run_every_job_once();
lanes_never_hang_and_never_cross_runs();

common_params params;
if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) {
return 1;
}
const int n_seq = 6;
params.n_parallel = n_seq;
params.kv_unified = true;
common_init();
llama_backend_init();
auto init = common_init_from_params(params);
llama_model * model = init->model();
llama_context * ctx = init->context();
require(model && ctx, "model loads");
const llama_vocab * vocab = llama_model_get_vocab(model);

// one decode of six sequences, one output row each: the shape of a serving step
const char * topics[n_seq] = { "the ledger", "a merge queue", "a kv cache", "the grid", "a resident", "a checkpoint" };
llama_batch batch = llama_batch_init(512, 0, n_seq);
std::vector<int> out_idx(n_seq);
for (int s = 0; s < n_seq; ++s) {
const auto toks = common_tokenize(vocab, std::string("Write about ") + topics[s] + ".", true, true);
for (size_t i = 0; i < toks.size(); ++i) {
const bool last = i + 1 == toks.size();
if (last) {
out_idx[s] = batch.n_tokens;
}
common_batch_add(batch, toks[i], (llama_pos) i, { s }, last);
}
}
require(llama_decode(ctx, batch) == 0, "decode");

common_params_sampling sp;
sp.top_k = 40;
sp.penalty_last_n = 256;
sp.penalty_repeat = 1.1f;
std::vector<common_sampler *> base(n_seq);
for (int s = 0; s < n_seq; ++s) {
base[s] = common_sampler_init(model, sp);
}
std::vector<common_sampler_row> rows(n_seq);
for (int s = 0; s < n_seq; ++s) {
rows[s] = common_sampler_row_ith(ctx, out_idx[s]);
}

server_lanes lanes(n_seq - 1);
const int reps = 400;
double t_serial = 0, t_laned = 0;
std::vector<llama_token> a(n_seq), b(n_seq);
for (int rep = 0; rep < reps; ++rep) {
std::vector<common_sampler *> s1(n_seq), s2(n_seq);
for (int s = 0; s < n_seq; ++s) {
s1[s] = common_sampler_clone(base[s]);
s2[s] = common_sampler_clone(base[s]);
}
// alternate which goes first, so neither always meets a warm or cold cache
auto serial = [&] {
const double t0 = now_us();
for (int s = 0; s < n_seq; ++s) {
a[s] = common_sampler_sample_row(s1[s], rows[s]);
}
t_serial += now_us() - t0;
};
auto laned = [&] {
const double t0 = now_us();
lanes.run(n_seq, [&](size_t s) { b[s] = common_sampler_sample_row(s2[s], rows[s]); });
t_laned += now_us() - t0;
};
if (rep % 2 == 0) { serial(); laned(); } else { laned(); serial(); }
for (int s = 0; s < n_seq; ++s) {
require(a[s] == b[s], "a laned sample picks exactly the serial token");
common_sampler_free(s1[s]);
common_sampler_free(s2[s]);
}
}
std::printf("one step, %d sequences, %d reps: serial %.1f us/step, laned (%zu lanes) %.1f us/step, %.2fx\n",
n_seq, reps, t_serial / reps, lanes.size(), t_laned / reps, t_serial / t_laned);

for (auto * s : base) {
common_sampler_free(s);
}
llama_batch_free(batch);
std::printf("test-server-lanes: ok\n");
return 0;
}
5 changes: 4 additions & 1 deletion tools/server/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ endif()
target_include_directories(${TARGET} PRIVATE ../mtmd)
target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR})
target_link_libraries(${TARGET} PUBLIC llama-common mtmd ${CMAKE_THREAD_LIBS_INIT})
# Continuum fork: the server is C++20 (atomic wait/notify for the sampling lanes, CONTINUUM-ENGINE 4.7.14);
# PUBLIC so every target that includes the server's headers compiles them as written
target_compile_features(${TARGET} PUBLIC cxx_std_20)

# the faults tools/server/tests inject (server-test-faults.h); only the server test build sets it
option(LLAMA_SERVER_TEST_FAULTS "llama-server: compile in the test fault injection (tests only, never a release)" OFF)
Expand Down Expand Up @@ -69,4 +72,4 @@ add_executable(${TARGET} main.cpp)
install(TARGETS ${TARGET} RUNTIME)

target_link_libraries(${TARGET} PRIVATE llama-server-impl)
target_compile_features(${TARGET} PRIVATE cxx_std_17)
target_compile_features(${TARGET} PRIVATE cxx_std_20)
110 changes: 100 additions & 10 deletions tools/server/server-context.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <limits>
#include "server-context.h"
#include "server-lanes.h"
#include "server-view-end.h"
#include "../../src/llama-ext.h"
#include "server-train.h"
Expand Down Expand Up @@ -376,6 +377,14 @@ struct server_slot {

common_sampler_ptr smpl;

// Continuum fork (CONTINUUM-ENGINE 4.7.14): this step's sample, made on a lane before the loop that
// emits it; a sampling error is carried here and raised in this slot's own step
bool presampled = false;
llama_token presampled_id = LLAMA_TOKEN_NULL;
common_sampler_ptr presampled_save; // the speculative save point, cloned before the verify
std::vector<llama_token> presampled_accepted; // the speculative verify's accepted tokens
std::string presample_error;

llama_token sampled; // in speculative mode, this is the last accepted token

// for TTS models, this is the embd generated from prev step, decode this to generate next hidden state
Expand Down Expand Up @@ -985,6 +994,10 @@ struct server_context_impl {
// whether any configured drafter reads the prompt's tokens (the n-gram family); set at load
bool spec_reads_prompt = false;

// the lanes one step's slots sample on at once (CONTINUUM-ENGINE 4.7.14); sized at load from the
// slot count and the cores the OS reports, never more lanes than slots
std::unique_ptr<server_lanes> sample_lanes;

common_init_result_ptr llama_init;

llama_context * ctx_tgt = nullptr;
Expand Down Expand Up @@ -1420,6 +1433,12 @@ struct server_context_impl {

n_swa = params_base.swa_full ? 0 : llama_model_n_swa(model_tgt);

{
const size_t cores = std::max<size_t>(1, std::thread::hardware_concurrency());
const size_t workers = std::min<size_t>(params_base.n_parallel > 1 ? params_base.n_parallel - 1 : 0, cores - 1);
sample_lanes = std::make_unique<server_lanes>(workers);
}

spec_reads_prompt = std::any_of(params_base.speculative.types.begin(), params_base.speculative.types.end(),
[](common_speculative_type t) {
return t == COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE || t == COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K ||
Expand Down Expand Up @@ -4367,6 +4386,71 @@ struct server_context_impl {
return true;
}

// Continuum fork (CONTINUUM-ENGINE 4.7.14): every slot that samples in this view samples at once.
// Gather on this thread (one synchronize; a row is raw pointers into the context's outputs, so
// sampling from it never calls into the context), sample on the lanes (each slot's sampler is its
// own state), and the loops in post_decode then emit in slot order exactly as before. Same tokens:
// each sampler sees the same rows and its own RNG in the same order.
void presample(int32_t off, int32_t n_batch_tokens) {
auto inside = [&](int32_t idx) { return idx >= off && idx < off + n_batch_tokens; };
struct sample_job {
server_slot * slot;
bool verify; // speculative verify (MTP), else one plain sample
std::vector<common_sampler_row> rows;
};
std::vector<sample_job> jobs;
for (auto & slot : slots) {
slot.presampled = false;
slot.presample_error.clear();
if (!slot.task) {
continue;
}
const bool drafting = slot.can_speculate() && !slot.spec_draft.empty();
if (slot.state == SLOT_STATE_GENERATING && drafting && !slot.spec_i_batch.empty()) {
GGML_ASSERT(slot.spec_i_batch.size() == slot.spec_draft.size() + 1);
jobs.push_back({ &slot, true, {} });
continue;
}
if (!inside(slot.i_batch) || drafting) {
continue;
}
const bool done_prompt = slot.state == SLOT_STATE_DONE_PROMPT &&
slot.task->type != SERVER_TASK_TYPE_EMBEDDING && slot.task->type != SERVER_TASK_TYPE_RERANK;
if (slot.state == SLOT_STATE_GENERATING || done_prompt) {
jobs.push_back({ &slot, false, {} });
}
}
if (jobs.empty()) {
return;
}
for (auto & job : jobs) {
if (job.verify) {
for (const int idx : job.slot->spec_i_batch) {
job.rows.push_back(common_sampler_row_ith(ctx_tgt, idx));
}
} else {
job.rows.push_back(common_sampler_row_ith(ctx_tgt, job.slot->i_batch - off));
}
}
scoped_timer timer(t_sampl, n_sampl);
sample_lanes->run(jobs.size(), [&](size_t j) {
auto & job = jobs[j];
auto & slot = *job.slot;
try {
if (job.verify) {
slot.presampled_save.reset(common_sampler_clone(slot.smpl.get()));
slot.presampled_accepted = common_sampler_sample_and_accept_rows(slot.smpl.get(), job.rows, slot.spec_draft);
} else {
slot.presampled_id = common_sampler_sample_row(slot.smpl.get(), job.rows[0]);
common_sampler_accept(slot.smpl.get(), slot.presampled_id, true);
}
slot.presampled = true;
} catch (const std::exception & e) {
slot.presample_error = e.what(); // raised in this slot's own step, as the serial path did
}
});
}

void post_decode(int32_t n_batch_tokens, int32_t off, llama_batch & batch_view) {
// for checking if a given batch index is inside batch_view
auto is_inside_view = [&](int32_t idx) {
Expand All @@ -4383,6 +4467,8 @@ struct server_context_impl {
}
});

presample(off, n_batch_tokens);

auto accept_special_token = [&](server_slot & slot, llama_token token) {
return params_base.special ||
slot.task->params.sampling.preserved_tokens.find(token) != slot.task->params.sampling.preserved_tokens.end();
Expand Down Expand Up @@ -4436,16 +4522,16 @@ struct server_context_impl {
// shifted according to the current sub-batch
const int tok_idx = slot.i_batch - off;

llama_token id;
{
scoped_timer timer(t_sampl, n_sampl);
id = common_sampler_sample(slot.smpl.get(), slot.ctx_tgt, tok_idx);
// sampled and accepted on a lane by presample(); the predicate there mirrors this loop
if (!slot.presample_error.empty()) {
throw std::runtime_error(std::exchange(slot.presample_error, {}));
}
GGML_ASSERT(slot.presampled && "presample() must cover every slot this loop samples");
const llama_token id = slot.presampled_id;
slot.presampled = false;

slot.i_batch = -1;

common_sampler_accept(slot.smpl.get(), id, true);

// here we have synchronized the llama_context (due to the sampling above), so we can do time measurement
const int64_t t_now = ggml_time_us();

Expand Down Expand Up @@ -4498,10 +4584,14 @@ struct server_context_impl {

// verify and try to accept the draft
{
common_sampler_ptr smpl_save(common_sampler_clone(slot.smpl.get()));

GGML_ASSERT(slot.spec_i_batch.size() == n_draft + 1);
auto accepted = common_sampler_sample_and_accept_n(slot.smpl.get(), slot.ctx_tgt, slot.spec_i_batch, slot.spec_draft);
// cloned, verified and accepted on a lane by presample()
if (!slot.presample_error.empty()) {
throw std::runtime_error(std::exchange(slot.presample_error, {}));
}
GGML_ASSERT(slot.presampled && "presample() must cover every slot this loop verifies");
slot.presampled = false;
common_sampler_ptr smpl_save = std::move(slot.presampled_save);
auto accepted = std::move(slot.presampled_accepted);
slot.spec_i_batch.clear();

GGML_ASSERT(accepted.size() >= 1);
Expand Down
Loading