Skip to content
Closed
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
65 changes: 46 additions & 19 deletions common/sampling.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -227,30 +227,27 @@ struct common_sampler {
llama_sampler_reset(chain);
}

void set_logits(struct llama_context * ctx, int idx, bool coarse = false) {
const float * sampled_probs = llama_get_sampled_probs_ith (ctx, idx);
const float * sampled_logits = llama_get_sampled_logits_ith (ctx, idx);
const llama_token * sampled_ids = llama_get_sampled_candidates_ith(ctx, idx);
void set_logits(const common_sampler_row & row, bool coarse = false) {
const float * sampled_probs = row.sampled_probs;
const float * sampled_logits = row.sampled_logits;
const llama_token * sampled_ids = row.sampled_ids;

const llama_model * model = llama_get_model(ctx);
const llama_vocab * vocab = llama_model_get_vocab(model);

const int n_vocab = llama_vocab_n_tokens(vocab);
const int n_vocab = row.n_vocab;

if (sampled_probs) {
const uint32_t sampled_probs_count = llama_get_sampled_probs_count_ith(ctx, idx);
const uint32_t sampled_probs_count = row.n_sampled_probs;
cur.resize(sampled_probs_count);
for (uint32_t i = 0; i < sampled_probs_count; ++i) {
cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], sampled_probs[i]};
}
} else if (sampled_logits) {
const uint32_t sampled_logits_count = llama_get_sampled_logits_count_ith(ctx, idx);
const uint32_t sampled_logits_count = row.n_sampled_logits;
cur.resize(sampled_logits_count);
for (uint32_t i = 0; i < sampled_logits_count; i++) {
cur[i] = llama_token_data{sampled_ids[i], sampled_logits[i], 0.0f};
}
} else {
const auto * logits = llama_get_logits_ith(ctx, idx);
const auto * logits = row.logits;
GGML_ASSERT(logits != nullptr);
if (coarse && coarse_cap > 0 && coarse_cap < (size_t) n_vocab) {
coarse_candidates(logits, n_vocab);
Expand Down Expand Up @@ -758,9 +755,30 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl) {
return gsmpl->chain;
}

llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
common_sampler_row common_sampler_row_ith(struct llama_context * ctx, int idx) {
llama_synchronize(ctx);

common_sampler_row row;
row.sampled_probs = llama_get_sampled_probs_ith (ctx, idx);
row.sampled_logits = llama_get_sampled_logits_ith (ctx, idx);
row.sampled_ids = llama_get_sampled_candidates_ith(ctx, idx);
if (row.sampled_probs) {
row.n_sampled_probs = llama_get_sampled_probs_count_ith(ctx, idx);
} else if (row.sampled_logits) {
row.n_sampled_logits = llama_get_sampled_logits_count_ith(ctx, idx);
} else {
row.logits = llama_get_logits_ith(ctx, idx);
}
row.sampled_token = llama_get_sampled_token_ith(ctx, idx);
row.n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(llama_get_model(ctx)));
return row;
}

llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) {
return common_sampler_sample_row(gsmpl, common_sampler_row_ith(ctx, idx), grammar_first);
}

llama_token common_sampler_sample_row(struct common_sampler * gsmpl, const common_sampler_row & row, bool grammar_first) {
// start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations
const auto tm = gsmpl->tm();

Expand All @@ -775,12 +793,12 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co
// FORCING (it sets every candidate but the forced token to -inf, and the forced token need not be in
// a ballpark subset); a grammar rejection below resamples over the full array
const bool forcing = rbudget && common_reasoning_budget_get_state(rbudget) == REASONING_BUDGET_FORCING;
gsmpl->set_logits(ctx, idx, /*coarse=*/!forcing && !(grammar_first && grammar_should_apply(gsmpl)));
gsmpl->set_logits(row, /*coarse=*/!forcing && !(grammar_first && grammar_should_apply(gsmpl)));

// Check if a backend sampler has already sampled a token in which case we
// return that token id directly.
{
id = llama_get_sampled_token_ith(ctx, idx);
id = row.sampled_token;

if (id != LLAMA_TOKEN_NULL) {
LOG_DBG("%s: Backend sampler selected token: '%d'. Will not run any CPU samplers\n", __func__, id);
Expand Down Expand Up @@ -829,7 +847,7 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co

// resampling:
// if the token is not valid, sample again, but first apply the grammar sampler and then the sampling chain
gsmpl->set_logits(ctx, idx);
gsmpl->set_logits(row);

llama_sampler_apply(rbudget, &cur_p);

Expand All @@ -847,14 +865,23 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co
}

std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first) {
GGML_ASSERT(idxs.size() == draft.size() + 1 && "idxs.size() must be draft.size() + 1");
std::vector<common_sampler_row> rows;
rows.reserve(idxs.size());
for (const int idx : idxs) {
rows.push_back(common_sampler_row_ith(ctx, idx));
}
return common_sampler_sample_and_accept_rows(gsmpl, rows, draft, grammar_first);
}

std::vector<llama_token> common_sampler_sample_and_accept_rows(struct common_sampler * gsmpl, const std::vector<common_sampler_row> & rows, const llama_tokens & draft, bool grammar_first) {
GGML_ASSERT(rows.size() == draft.size() + 1 && "rows.size() must be draft.size() + 1");

std::vector<llama_token> result;
result.reserve(idxs.size());
result.reserve(rows.size());

size_t i = 0;
for (; i < draft.size(); i++) {
const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
const llama_token id = common_sampler_sample_row(gsmpl, rows[i], grammar_first);

common_sampler_accept(gsmpl, id, true);

Expand All @@ -866,7 +893,7 @@ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sample
}

if (i == draft.size()) {
const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
const llama_token id = common_sampler_sample_row(gsmpl, rows[i], grammar_first);

common_sampler_accept(gsmpl, id, true);

Expand Down
22 changes: 22 additions & 0 deletions common/sampling.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,28 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl);
//
llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first = false);

// One output row's sampling input, gathered from the context by the thread that owns it. Sampling from a
// row reads no context state, so the rows of one decode step sample on many lanes at once (continuum
// CONTINUUM-ENGINE 4.7.14). common_sampler_row_ith synchronizes the context first.
struct common_sampler_row {
const float * logits = nullptr;
const float * sampled_probs = nullptr;
const float * sampled_logits = nullptr;
const llama_token * sampled_ids = nullptr;
uint32_t n_sampled_probs = 0;
uint32_t n_sampled_logits = 0;
llama_token sampled_token = LLAMA_TOKEN_NULL; // a backend sampler's choice, if any
int32_t n_vocab = 0;
};

common_sampler_row common_sampler_row_ith(struct llama_context * ctx, int idx);

// common_sampler_sample over a gathered row: touches only `gsmpl`
llama_token common_sampler_sample_row(struct common_sampler * gsmpl, const common_sampler_row & row, bool grammar_first = false);

// common_sampler_sample_and_accept_n over gathered rows (rows.size() == draft.size() + 1): touches only `gsmpl`
std::vector<llama_token> common_sampler_sample_and_accept_rows(struct common_sampler * gsmpl, const std::vector<common_sampler_row> & rows, const llama_tokens & draft, bool grammar_first = false);

// generalized version of common_sampler_sample
//
// will cross-reference the sampled tokens with a batch of draft tokens and accept those that match
Expand Down
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

# GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient)
Expand Down
142 changes: 142 additions & 0 deletions tests/test-server-lanes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// 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 <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");
}

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

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)
Loading
Loading