Skip to content
Open
16 changes: 16 additions & 0 deletions include/llama.h
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ extern "C" {

// Keep the booleans together and at the end of the struct to avoid misalignment during copy-by-value.
bool embeddings; // if true, extract embeddings (together with logits)
bool embeddings_only; // pooled embeddings without vocabulary logits or sampling
bool offload_kqv; // offload the KQV ops (including the KV cache) to GPU
bool no_perf; // measure performance timings
bool op_offload; // offload host tensor operations to device
Expand Down Expand Up @@ -725,6 +726,13 @@ extern "C" {
LLAMA_API const char * llama_model_weight_backend_name (const struct llama_model * model, size_t i);
LLAMA_API size_t llama_model_weight_backend_bytes(const struct llama_model * model, size_t i);

// Account for the allocator's actual memory pool, including pinned host buffers.
struct llama_weight_allocation {
size_t host;
size_t device;
};
LLAMA_API struct llama_weight_allocation llama_model_weight_allocation(const struct llama_model * model);

// Get the default chat template. Returns nullptr if not available
// If name is NULL, returns the default chat template
LLAMA_API const char * llama_model_chat_template(const struct llama_model * model, const char * name);
Expand Down Expand Up @@ -950,6 +958,14 @@ extern "C" {
// no_empty_stream when none is empty; otherwise exactly llama_persona_load's checks and statuses.
LLAMA_API int32_t llama_persona_bind(struct llama_context * ctx, llama_seq_id seq_id, struct llama_persona * persona);

// Continuum fork (CONTINUUM-ENGINE 4.16): her saved blocks on disk and back, so a restart demotes her instead of
// dropping her. write_file writes blocks a completed save holds (file_mismatch when none) to `path` through
// `<path>.tmp` and a rename. read_file fills a persona made by llama_persona_init on a context of the same memory
// layout, for the owner and epoch her file names; file_mismatch (another owner, epoch, layout or size) and io_error
// leave her as she was. Bind her afterwards as after a save.
LLAMA_API int32_t llama_persona_write_file(const struct llama_persona * persona, const char * path);
LLAMA_API int32_t llama_persona_read_file(struct llama_persona * persona, const char * path);

LLAMA_API const char * llama_persona_status_name(int32_t status);

// A checkpoint of a BOUND sequence at its current position, taken without moving her: her recurrent rows (every
Expand Down
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ add_library(llama
llama-batch.cpp
llama-chat.cpp
llama-context.cpp
llama-persona-file.cpp
llama-context-opt.cpp
llama-context-opt-measure.cpp
llama-context-learn.cpp
Expand Down
17 changes: 9 additions & 8 deletions src/llama-context.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#include "llama-context.h"

#include <new>
#include "llama-persona-tokens.h"
#include "llama-persona.h"

#include "ggml.h"
#include "llama-arch.h"
Expand Down Expand Up @@ -113,6 +113,10 @@ llama_context::llama_context(
cparams.yarn_attn_factor = params.yarn_attn_factor >= 0.0f ? params.yarn_attn_factor : hparams.yarn_attn_factor;
cparams.yarn_beta_fast = params.yarn_beta_fast >= 0.0f ? params.yarn_beta_fast : hparams.yarn_beta_fast;
cparams.yarn_beta_slow = params.yarn_beta_slow >= 0.0f ? params.yarn_beta_slow : hparams.yarn_beta_slow;
if (params.embeddings_only && (!params.embeddings || params.pooling_type == LLAMA_POOLING_TYPE_NONE || params.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED)) {
throw std::runtime_error("embeddings_only requires embeddings and explicit sequence pooling");
}
cparams.embeddings_only = params.embeddings_only;
cparams.embeddings = params.embeddings;
cparams.embeddings_nextn = false;
cparams.embeddings_nextn_masked = false;
Expand Down Expand Up @@ -2140,7 +2144,7 @@ uint32_t llama_context::output_reserve(int32_t n_outputs) {
const auto n_embd = hparams.n_embd;
const auto n_embd_out = hparams.n_embd_out();

bool has_logits = true;
bool has_logits = !cparams.embeddings_only;
bool has_embd = cparams.embeddings;
bool has_embd_nextn = cparams.embeddings_nextn;

Expand Down Expand Up @@ -3593,6 +3597,7 @@ llama_context_params llama_context_default_params() {
/*.abort_callback =*/ nullptr,
/*.abort_callback_data =*/ nullptr,
/*.embeddings =*/ false,
/*.embeddings_only =*/ false,
/*.offload_kqv =*/ true,
/*.no_perf =*/ true,
/*.op_offload =*/ true,
Expand Down Expand Up @@ -4293,12 +4298,8 @@ llama_context * llama_get_ctx_other(struct llama_context * ctx) {
return ctx->get_cparams().ctx_other;
}

// Continuum fork (CONTINUUM-ENGINE 4.14): the public seam of a persona's move (llama-persona-blocks.h).

struct llama_persona {
llama_persona_blocks blocks;
std::unique_ptr<llama_persona_tokens> tokens; // her token history, beside her blocks (llama-persona-tokens.h)
};
// Continuum fork (CONTINUUM-ENGINE 4.14): the public seam of a persona's move (llama-persona-blocks.h); the persona
// object itself is in llama-persona.h.

// Her owner grows her history ahead of need, between acts: an append on the hot path only writes into it.
int32_t llama_persona_grow_tokens(llama_persona * persona, size_t more_tokens, size_t more_receipts) {
Expand Down
1 change: 1 addition & 0 deletions src/llama-cparams.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ struct llama_cparams {
float yarn_beta_slow;

bool embeddings;
bool embeddings_only = false;
bool embeddings_nextn; // also extract the hidden state before the final output norm
bool embeddings_nextn_masked; // extract for only rows where batch.logits != 0
bool causal_attn;
Expand Down
17 changes: 14 additions & 3 deletions src/llama-kv-cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,8 @@ llama_kv_cache::llama_kv_cache(
const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG");
debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0;

persona_layout_id = compute_persona_layout(); // the allocation layout is immutable from here
persona_layout_id = compute_persona_layout(true); // the allocation layout is immutable from here
persona_rows_id = compute_persona_layout(false);
}

void llama_kv_cache::clear(bool data) {
Expand Down Expand Up @@ -1263,9 +1264,10 @@ static bool cells_prepared(const llama_kv_cells & cells, uint32_t size) {
// this memory's attention layout: what her rows' sizes and meaning depend on
static uint64_t kv_layout_mix(uint64_t h, uint64_t v) { return (h ^ v) * 0x100000001b3ull; }

uint64_t llama_kv_cache::compute_persona_layout() const {
uint64_t llama_kv_cache::compute_persona_layout(bool with_size) const {
uint64_t h = kv_layout_mix(0xcbf29ce484222325ull, layers.size());
h = kv_layout_mix(h, get_size());
// the stream size is part of a live move's layout; a file restores into any stream her rows fit
h = with_size ? kv_layout_mix(h, get_size()) : h;
for (const auto & layer : layers) {
h = kv_layout_mix(h, layer.il);
h = kv_layout_mix(h, layer.k ? (uint64_t) layer.k->type : 0xffu);
Expand All @@ -1281,9 +1283,18 @@ llama_persona_move llama_kv_cache::persona_prepare(llama_persona_blocks & blocks
return llama_persona_move::no_such_stream;
}
blocks.kv_layout = persona_layout();
blocks.kv_rows = persona_rows_id;
blocks.kv.cells.resize(get_size()); // once per persona, at her creation
blocks.kv.k.resize(layers.size());
blocks.kv.v.resize(layers.size());
// the row sizes a save copies (persona_check_save), recorded for a file read to check before it allocates
blocks.geometry.k_row.resize(layers.size());
blocks.geometry.v_row.resize(layers.size());
for (size_t i = 0; i < layers.size(); ++i) {
const auto & layer = layers[i];
blocks.geometry.k_row[i] = ggml_row_size(layer.k->type, layer.k->ne[0]);
blocks.geometry.v_row[i] = layer.v ? ggml_row_size(layer.v->type, layer.v->ne[0]) : 0;
}
return llama_persona_move::done;
}

Expand Down
3 changes: 2 additions & 1 deletion src/llama-kv-cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,8 @@ class llama_kv_cache : public llama_memory_i {

// this memory's persona layout fingerprint, computed once at construction (the allocation layout is immutable)
uint64_t persona_layout_id = 0;
uint64_t compute_persona_layout() const;
uint64_t persona_rows_id = 0; // the layout without the stream size: what a persona file restores against
uint64_t compute_persona_layout(bool with_size) const;

// pending stream copies that will be applied during the next update
stream_copy_info sc_info;
Expand Down
11 changes: 11 additions & 0 deletions src/llama-memory-recurrent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,17 @@ llama_persona_move llama_memory_recurrent::persona_prepare(llama_persona_blocks
blocks.rs_layout = persona_layout();
blocks.rs.r.resize(r_l.size());
blocks.rs.s.resize(s_l.size());
// the bytes a save copies for a sequence that holds state (persona_check_save), recorded for a file read to check
// before it allocates
const uint32_t n_groups = 1 + n_rs_seq;
blocks.geometry.r_bytes.resize(r_l.size());
blocks.geometry.s_bytes.resize(s_l.size());
for (size_t il = 0; il < r_l.size(); ++il) {
blocks.geometry.r_bytes[il] = r_l[il] ? ggml_row_size(r_l[il]->type, r_l[il]->ne[0]) * n_groups : 0;
}
for (size_t il = 0; il < s_l.size(); ++il) {
blocks.geometry.s_bytes[il] = s_l[il] ? ggml_row_size(s_l[il]->type, s_l[il]->ne[0]) * n_groups : 0;
}
return llama_persona_move::done;
}

Expand Down
2 changes: 2 additions & 0 deletions src/llama-memory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ const char * llama_persona_move_name(llama_persona_move m) {
case llama_persona_move::no_checkpoint: return "no_checkpoint";
case llama_persona_move::checkpoint_ahead: return "checkpoint_ahead";
case llama_persona_move::checkpoint_stale: return "checkpoint_stale";
case llama_persona_move::io_error: return "io_error";
case llama_persona_move::file_mismatch: return "file_mismatch";
}
return "unknown";
}
52 changes: 52 additions & 0 deletions src/llama-model.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <vector>

static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params & params) {
Expand Down Expand Up @@ -2663,6 +2664,45 @@ ggml_cgraph * llama_model::build_graph(const llm_graph_params & params) const {
// TODO: move reranking logic here and generalize
llm->build_dense_out(dense_2_out_layers, dense_2_out_layers_b, dense_3_out_layers);

if (params.cparams.embeddings_only) {
if (params.cparams.training || params.cparams.embeddings_nextn || !params.samplers.empty() ||
std::any_of(params.cparams.embeddings_layer_inp.begin(), params.cparams.embeddings_layer_inp.end(), [](bool enabled) { return enabled; })) {
throw std::runtime_error("embeddings_only cannot train, sample, or extract auxiliary outputs");
}
GGML_ASSERT(llm->res->t_embd_pooled != nullptr);
// Cache writes are explicit graph roots, not dependencies of cache reads.
// Preserve those roots and their original ordering when pruning logits.
const auto ancestors = [](ggml_tensor * root) {
std::unordered_set<ggml_tensor *> seen;
std::vector<ggml_tensor *> pending { root };
while (!pending.empty()) {
auto * node = pending.back();
pending.pop_back();
if (!node || !seen.insert(node).second) {
continue;
}
for (auto * src : node->src) {
pending.push_back(src);
}
}
return seen;
};
const auto logits = ancestors(llm->res->t_logits);
const auto pooled = ancestors(llm->res->t_embd_pooled);
auto * gf = llm->res->get_gf();
std::vector<ggml_tensor *> roots;
for (int i = 0; i < ggml_graph_n_nodes(gf); ++i) {
auto * node = ggml_graph_node(gf, i);
if (!logits.count(node) || pooled.count(node)) {
roots.push_back(node);
}
}
llm->res->t_logits = nullptr;
ggml_graph_clear(gf);
for (auto * root : roots) {
ggml_build_forward_expand(gf, root);
}
}
llm->res->set_outputs(params);

return llm->res->get_gf();
Expand Down Expand Up @@ -3063,6 +3103,18 @@ size_t llama_model_n_weight_backends(const llama_model * model) {
return llama_model_weight_backends(model).size();
}

llama_weight_allocation llama_model_weight_allocation(const llama_model * model) {
llama_weight_allocation allocation = {};
for (const auto & [buft, bytes] : model->memory_breakdown()) {
if (ggml_backend_buft_is_host(buft)) {
allocation.host += bytes;
} else {
allocation.device += bytes;
}
}
return allocation;
}

const char * llama_model_weight_backend_name(const llama_model * model, size_t i) {
const auto v = llama_model_weight_backends(model);
return i < v.size() ? v[i].first : nullptr;
Expand Down
16 changes: 16 additions & 0 deletions src/llama-persona-blocks.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ struct llama_rs_seq_blocks {
std::vector<std::vector<uint8_t>> s; // per layer: (1 + n_rs_seq) rows of s, group-major
};

// the byte geometry of this memory's rows, recorded once by persona_prepare from the memory's own tensors: a read of her
// file checks every length against it BEFORE allocating, so a truncated or foreign file is refused without sizing any
// buffer from what the file claims (Codex on CambrianTech/llama.cpp#155)
struct llama_persona_geometry {
std::vector<size_t> k_row; // per KV layer: bytes of one K row
std::vector<size_t> v_row; // per KV layer: bytes of one V row (0 for a layer without V)
std::vector<size_t> r_bytes; // per recurrent layer: bytes of her r rows in every snapshot group (0 without r)
std::vector<size_t> s_bytes; // per recurrent layer: bytes of her s rows in every snapshot group (0 without s)
};

// her identity travels with her blocks: the sequence her metadata is tagged with, and the layout of the memory they
// were prepared for (a fingerprint of layer count, stream size, row types and sizes, snapshot groups)
// Who a move is for: the persona and epoch whose token history the blocks belong to.
Expand All @@ -52,7 +62,11 @@ struct llama_persona_blocks {
return !owned || (owner == who.persona && owner_epoch == who.epoch);
}
uint64_t kv_layout = 0;
// the attention layout without the stream size (layers, row types and widths): a file restores her into any stream of
// this memory that holds her rows, whatever window a restart's planner chose (CONTINUUM-ENGINE 4.16)
uint64_t kv_rows = 0;
uint64_t rs_layout = 0;
llama_persona_geometry geometry;
llama_kv_stream_blocks kv;
llama_rs_seq_blocks rs;
};
Expand Down Expand Up @@ -85,6 +99,8 @@ enum class llama_persona_move {
no_checkpoint, // a rewind was asked of a checkpoint never taken
checkpoint_ahead, // a rewind was asked to a position past what she holds: a rewind never moves forward
checkpoint_stale, // her cells are not the lineage the checkpoint was taken from, or were cut at or below it since
io_error, // her blocks' file could not be written or read whole
file_mismatch, // her blocks' file is not hers or not this memory's (owner, epoch, layout, sizes): nothing was read
};

// A copy of a bound persona at one of her positions, taken WITHOUT moving her: her recurrent rows (every snapshot
Expand Down
Loading
Loading