diff --git a/include/llama.h b/include/llama.h index 6ff7b047fd40..42c06e4a52b0 100644 --- a/include/llama.h +++ b/include/llama.h @@ -1085,6 +1085,55 @@ extern "C" { llama_seq_id dest_seq_id, llama_state_seq_flags flags); + // Continuum fork (CONTINUUM-ENGINE 4.7.11): DEVICE SNAPSHOTS of a sequence's state, keyed by a caller + // snapshot id (the pool's identity), so a sequence can hold many. Save copies the sequence's state + // tensors into device buffers owned by the snapshot (no host bytes; the host keeps a small header); + // load copies them back; free releases them. With LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY a hybrid model + // snapshots its recurrent row only. Every call returns a typed status and never throws or aborts. + enum llama_snapshot_status { + LLAMA_SNAPSHOT_OK = 0, + LLAMA_SNAPSHOT_ABSENT = 1, // no snapshot under this id / nothing to snapshot under these flags + LLAMA_SNAPSHOT_INCOMPATIBLE = 2, // flags or tensor layout differ from the target: nothing was changed + LLAMA_SNAPSHOT_ALLOC_FAILED = 3, // device memory could not be allocated: a previous snapshot is kept + LLAMA_SNAPSHOT_COPY_FAILED = 4, // the copy itself failed; a load's target was cleared whole (it holds no one's state) + LLAMA_SNAPSHOT_TARGET_UNCLEARED = 5, // a load failed after the read began AND clearing its target failed: the + // sequence is undefined; the caller keeps custody of it (never serves, + // parks or returns it) until llama_memory_seq_rm(seq, -1, -1) succeeds + }; + + // The bytes a snapshot of `seq_id` would hold PHYSICALLY (device buffers at their alignment, ggml + // metadata, host header), so the pool reserves BEFORE anything allocates; save reports the same. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_bytes( + struct llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes); + + // Stage, copy, then publish: a failed save leaves any previous snapshot under this id loadable. While + // a replacement is staged both generations exist (the pool charges both). + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_save( + struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); + + // Validated before the live sequence is touched: refused (INCOMPATIBLE) on a flags or layout mismatch. A + // failure after the read began quarantines the target (cleared whole) and returns COPY_FAILED: the caller + // must then drop any record that the sequence holds a mind's tokens (it is cold). If the clear itself does + // not leave the sequence empty, TARGET_UNCLEARED: the caller keeps custody of the sequence until it clears. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_load( + struct llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + + // Write a FULL-sequence snapshot (saved with flags 0) as a standard state file (the format + // llama_state_seq_save_file writes and llama_state_seq_load_file reads), from the snapshot alone: + // safe on a writer thread while the context keeps decoding. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_write_file( + struct llama_context * ctx, uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens); + + // Synchronizes first: no submitted step can still read the buffers being freed. + LLAMA_API enum llama_snapshot_status llama_state_seq_snapshot_free(struct llama_context * ctx, uint64_t snapshot_id); + + // Test-only fault injection: the next `n` snapshot device allocations fail; the next `n` load commits + // fail after the read (the target is then quarantined: cleared whole, COPY_FAILED); the next `n` + // quarantine clears fail (TARGET_UNCLEARED). + LLAMA_API void llama_state_seq_snapshot_test_fail_next_allocs(int n); + LLAMA_API void llama_state_seq_snapshot_test_fail_next_load_commits(int n); + LLAMA_API void llama_state_seq_snapshot_test_fail_next_quarantine_clears(int n); + // // Decoding // diff --git a/src/llama-context.cpp b/src/llama-context.cpp index c2d348884ce9..f9b4f19b15df 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2843,10 +2843,81 @@ class llama_io_read_file : public llama_io_read_i { class llama_io_write_device : public llama_io_write_i { public: - llama_io_write_device(uint8_t * p, size_t len, llama_memory_buffers & mbufs) : ptr(p), buf_size(len), mbufs(mbufs) { + // `auto_commit`: upstream's ON_DEVICE path commits on destruction (and aborts if it cannot), unchanged. + // Snapshot paths pass false: nothing is ever allocated or copied by a destructor, whatever unwinds. + llama_io_write_device(uint8_t * p, size_t len, llama_memory_buffers & mbufs, bool auto_commit = true) + : ptr(p), buf_size(len), mbufs(mbufs), done(!auto_commit), base(p) { + } + + // where each tensor's bytes belong in the host-format stream: its offset in the header, and which + // copy tensor (buffer type, index within it, in the order commit() allocates them) holds them + struct splice { + size_t offset; + ggml_backend_buffer_type_t buft; + size_t index; + size_t size; + }; + std::vector splices() const { + std::vector out; + std::map seen; + out.reserve(winfos.size()); + for (const auto & w : winfos) { + auto * buft = ggml_backend_buffer_get_type(w.tensor->buffer); + out.push_back({ (size_t) (w.ptr - base), buft, seen[buft]++, w.size }); + } + return out; } ~llama_io_write_device() { + if (!done && commit() != commit_status::ok) { + GGML_ABORT("%s: device state write failed\n", __func__); + } + } + + enum class commit_status { ok, alloc_failed }; + + // Continuum fork: the tensors this write would copy, by identity and size (offsets are not part of + // compatibility: a recurrent sequence may occupy a different cell at load) + std::vector> layout() const { + std::vector> out; + out.reserve(winfos.size()); + for (const auto & w : winfos) { + out.emplace_back(w.tensor, w.size); + } + return out; + } + + size_t payload_bytes() const { + size_t n = 0; + for (const auto & w : winfos) { + n += w.size; + } + return n; + } + + // a dry pass: nothing is allocated or copied + void discard() { done = true; } + + // what a commit would hold PHYSICALLY: every tensor padded to its buffer type's alignment, plus the + // ggml metadata context each buffer type needs (the header is the caller's) + size_t physical_quote() const { + std::map> per; // bytes, tensors + for (const auto & w : winfos) { + auto * buft = ggml_backend_buffer_get_type(w.tensor->buffer); + auto & e = per[buft]; + e.first += GGML_PAD(w.size, ggml_backend_buft_get_alignment(buft)); + e.second += 1; + } + size_t total = 0; + for (const auto & [buft, e] : per) { + total += e.first + GGML_PAD(2*e.second*ggml_tensor_overhead(), GGML_MEM_ALIGN); + } + return total; + } + + // allocate (or reuse) the device buffers and copy the recorded tensors; never throws + commit_status commit() { + done = true; llama_memory_buffers mbufs_new; for (const auto & winfo : winfos) { @@ -2910,7 +2981,10 @@ class llama_io_write_device : public llama_io_write_i { if (!mbuf_cur.buf || mbuf_cur.total_size != mbuf.total_size) { mbuf_cur = std::move(mbuf); - mbuf_cur.buf.reset(ggml_backend_alloc_ctx_tensors_from_buft(mbuf_cur.ctx.get(), buft)); + mbuf_cur.buf.reset(test_fail_alloc() ? nullptr : ggml_backend_alloc_ctx_tensors_from_buft(mbuf_cur.ctx.get(), buft)); + if (!mbuf_cur.buf) { + return commit_status::alloc_failed; + } LLAMA_LOG_INFO("%s: allocated '%s' buffer %.3f MiB\n", __func__, ggml_backend_buft_name(buft), mbuf.total_size/1024.0/1024.0); } else { @@ -2936,6 +3010,19 @@ class llama_io_write_device : public llama_io_write_i { ggml_backend_tensor_copy(mbuf_cur.org[i], mbuf_cur.cpy[i]); } } + return commit_status::ok; + } + + // test-only fault: the next N device allocations of snapshot writes fail + static std::atomic & fail_allocs() { static std::atomic n{0}; return n; } + static bool test_fail_alloc() { + int n = fail_allocs().load(); + while (n > 0) { + if (fail_allocs().compare_exchange_weak(n, n - 1)) { + return true; + } + } + return false; } void write(const void * src, size_t size) override { @@ -2971,14 +3058,38 @@ class llama_io_write_device : public llama_io_write_i { std::vector winfos; llama_memory_buffers & mbufs; + bool done = false; + const uint8_t * base; }; class llama_io_read_device : public llama_io_read_i { public: - llama_io_read_device(const uint8_t * p, size_t len, const llama_memory_buffers & mbufs) : ptr(p), buf_size(len), mbufs(mbufs) { + // `auto_commit` as for the writer: snapshot paths never commit from a destructor. + llama_io_read_device(const uint8_t * p, size_t len, const llama_memory_buffers & mbufs, bool auto_commit = true) + : ptr(p), buf_size(len), mbufs(mbufs), done(!auto_commit) { } ~llama_io_read_device() { + if (!done && !commit()) { + GGML_ABORT("%s: memory buffer mismatch\n", __func__); + } + } + + // an aborted read: nothing is copied + void discard() { done = true; } + + // copy the stored tensors into the recorded destinations; false on any layout mismatch (checked for + // every buffer type BEFORE any copy), never throws or aborts + // test-only fault: the next N read commits fail after the metadata was read (before any copy) + static std::atomic & fail_commits() { static std::atomic n{0}; return n; } + + bool commit() { + done = true; + for (int n = fail_commits().load(); n > 0;) { + if (fail_commits().compare_exchange_weak(n, n - 1)) { + return false; + } + } llama_memory_buffers mbufs_new; for (const auto & rinfo : rinfos) { @@ -3013,18 +3124,30 @@ class llama_io_read_device : public llama_io_read_i { } for (auto & [buft, mbuf] : mbufs_new) { - const auto & mbuf_cur = mbufs.at(buft); - - if (!mbuf_cur.buf || mbuf_cur.n_tensors != mbuf.n_tensors || mbuf_cur.total_size != mbuf.total_size) { - GGML_ABORT("%s: memory buffer mismatch\n", __func__); + const auto it = mbufs.find(buft); + if (it == mbufs.end()) { + return false; + } + const auto & mbuf_cur = it->second; + if (!mbuf_cur.buf || mbuf_cur.n_tensors != mbuf.n_tensors || mbuf_cur.total_size != mbuf.total_size || + mbuf_cur.cpy.size() != mbuf.org.size()) { + return false; + } + for (size_t i = 0; i < mbuf.org.size(); ++i) { + if (ggml_nbytes(mbuf_cur.cpy[i]) != ggml_nbytes(mbuf.org[i])) { + return false; + } } + } + for (auto & [buft, mbuf] : mbufs_new) { + const auto & mbuf_cur = mbufs.at(buft); for (size_t i = 0; i < mbuf_cur.org.size(); ++i) { ggml_backend_tensor_copy(mbuf_cur.cpy[i], mbuf.org[i]); } } - GGML_ASSERT(buf_size == 0); + return buf_size == 0; } void read(void * dst, size_t size) override { @@ -3060,6 +3183,7 @@ class llama_io_read_device : public llama_io_read_i { std::vector rinfos; const llama_memory_buffers & mbufs; + bool done = false; }; size_t llama_context::state_get_size() { @@ -3165,6 +3289,211 @@ size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * sr } } +// Continuum fork: device snapshots, transactional and typed (Codex's reviews of 7ca9509f0 and be11e4448). +// Every device writer/reader here is constructed with auto_commit = false: no destructor ever allocates +// or copies on these paths, whatever unwinds. + +// What a snapshot holds physically: its device buffers, the ggml metadata contexts, and the host header. +static size_t snapshot_held_bytes(const std::vector & header, const llama_memory_buffers & bufs) { + size_t held = header.size(); + for (const auto & [buft, mbuf] : bufs) { + if (mbuf.buf) { + held += ggml_backend_buffer_get_size(mbuf.buf.get()); + } + if (mbuf.ctx) { + held += ggml_get_mem_size(mbuf.ctx.get()); + } + } + return held; +} + +llama_snapshot_status llama_context::snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * held_bytes) { + flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; + std::vector header(state_seq_get_size(seq_id, flags)); + llama_memory_buffers none; + llama_io_write_device dry(header.data(), header.size(), none, /*auto_commit=*/false); + dry.write(&io_magic, sizeof(io_magic)); + dry.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(dry, seq_id, flags); + if (dry.payload_bytes() == 0) { + return LLAMA_SNAPSHOT_ABSENT; + } + *held_bytes = header.size() + dry.physical_quote(); + return LLAMA_SNAPSHOT_OK; +} + +llama_snapshot_status llama_context::snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * held_bytes) { + flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; + // stage into separate storage; the published snapshot (if any) is untouched until this one is complete + auto staged_ptr = std::make_shared(); + device_snapshot & staged = *staged_ptr; + staged.flags = flags; + staged.header.resize(state_seq_get_size(seq_id, flags)); + llama_io_write_device io(staged.header.data(), staged.header.size(), staged.bufs, /*auto_commit=*/false); + io.write(&io_magic, sizeof(io_magic)); + io.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(io, seq_id, flags); + staged.layout = io.layout(); + for (const auto & sp : io.splices()) { + staged.splices.push_back({ sp.offset, sp.buft, sp.index, sp.size }); + } + if (io.payload_bytes() == 0) { + return LLAMA_SNAPSHOT_ABSENT; // nothing to snapshot under these flags + } + if (io.commit() != llama_io_write_device::commit_status::ok) { + return LLAMA_SNAPSHOT_ALLOC_FAILED; // the previous snapshot under this id stays loadable + } + *held_bytes = snapshot_held_bytes(staged.header, staged.bufs); + std::shared_ptr replaced; + { + std::scoped_lock lock(snapshots_mutex); + replaced = std::exchange(snapshots[snapshot_id], std::move(staged_ptr)); // publish + } + return LLAMA_SNAPSHOT_OK; // a replaced generation is freed when its last reader (a file writer) lets go +} + +llama_snapshot_status llama_context::snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { + flags |= LLAMA_STATE_SEQ_FLAGS_ON_DEVICE; + std::shared_ptr held; + { + std::scoped_lock lock(snapshots_mutex); + auto it = snapshots.find(snapshot_id); + if (it == snapshots.end()) { + return LLAMA_SNAPSHOT_ABSENT; + } + held = it->second; + } + const device_snapshot & snap = *held; + if (snap.flags != flags) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } + // validate BEFORE the live sequence is touched: a non-empty target's own layout under these flags (a + // dry, metadata-only write pass) must match the snapshot's, tensor by tensor. An EMPTY target (fresh, or + // quarantined by an earlier failure) has nothing to protect: its read allocates the cell from the + // header, and the commit verifies every size before any copy (a mismatch quarantines it again). + if (llama_memory_seq_pos_max(get_memory(), seq_id) >= 0) { + std::vector header(state_seq_get_size(seq_id, flags)); + llama_memory_buffers none; + llama_io_write_device dry(header.data(), header.size(), none, /*auto_commit=*/false); + dry.write(&io_magic, sizeof(io_magic)); + dry.write(&seq_id, sizeof(seq_id)); + state_seq_write_data(dry, seq_id, flags); + if (dry.layout() != snap.layout) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } + } + llama_io_read_device io(snap.header.data(), snap.header.size(), snap.bufs, /*auto_commit=*/false); + uint32_t magic_read; + io.read(&magic_read, sizeof(magic_read)); + llama_seq_id seq_id_read; + io.read(&seq_id_read, sizeof(seq_id_read)); + if (magic_read != io_magic) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } + // from here the read mutates the sequence's cell metadata before the data is copied: any failure + // QUARANTINES the target (cleared whole), so a caller sees a cold sequence, never a half-restored one + bool copied = false; + try { + state_seq_read_data(io, seq_id, flags); + copied = io.commit(); + } catch (...) { + copied = false; + } + if (!copied) { + return quarantine(seq_id) ? LLAMA_SNAPSHOT_COPY_FAILED : LLAMA_SNAPSHOT_TARGET_UNCLEARED; + } + return LLAMA_SNAPSHOT_OK; +} + +// Clear a sequence whose restore failed after the read began. Success is proven, not assumed: seq_rm +// reports success AND the sequence holds no position afterwards. Anything else is TARGET_UNCLEARED for the +// caller, who keeps custody of the sequence (a half-restored state must never be served or reused). +static std::atomic & quarantine_clear_failures() { + static std::atomic n{0}; + return n; +} + +bool llama_context::quarantine(llama_seq_id seq_id) { + for (int n = quarantine_clear_failures().load(); n > 0;) { + if (quarantine_clear_failures().compare_exchange_weak(n, n - 1)) { + return false; // test fault injection: the clear "fails", leaving the sequence as the failed read left it + } + } + llama_memory_t mem = get_memory(); + return llama_memory_seq_rm(mem, seq_id, -1, -1) && llama_memory_seq_pos_max(mem, seq_id) < 0; +} + +llama_snapshot_status llama_context::snapshot_free(uint64_t snapshot_id) { + std::shared_ptr gone; + { + std::scoped_lock lock(snapshots_mutex); + auto it = snapshots.find(snapshot_id); + if (it == snapshots.end()) { + return LLAMA_SNAPSHOT_ABSENT; + } + gone = std::move(it->second); + snapshots.erase(it); + } + return LLAMA_SNAPSHOT_OK; // freed now, or when a file writer still reading it lets go +} + +// Write a snapshot of a FULL sequence state (flags 0) as a standard state file, from the snapshot alone: +// it never touches the context's live state, so it runs on a writer thread while the context decodes. +// File = magic | version | n_tokens | tokens | the state stream with each tensor's bytes spliced into the +// snapshot's header at the position the writer recorded (the first 8 header bytes are the get_data +// prefix, io magic + seq id, which the file format does not carry). Host-visible buffers (unified +// memory) are written straight from the buffer; others are read through the backend. +llama_snapshot_status llama_context::snapshot_write_file(uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens) { + std::shared_ptr held; + { + std::scoped_lock lock(snapshots_mutex); + auto it = snapshots.find(snapshot_id); + if (it == snapshots.end()) { + return LLAMA_SNAPSHOT_ABSENT; + } + held = it->second; + } + const device_snapshot & snap = *held; + if ((snap.flags & ~LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) != 0) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; // a state file carries the whole sequence, not a partial state + } + const size_t prefix = sizeof(uint32_t) + sizeof(llama_seq_id); + if (snap.header.size() < prefix) { + return LLAMA_SNAPSHOT_INCOMPATIBLE; + } + FILE * f = std::fopen(filepath, "wb"); + if (f == nullptr) { + return LLAMA_SNAPSHOT_COPY_FAILED; + } + bool ok = true; + auto put = [&](const void * p, size_t n) { ok = ok && (n == 0 || std::fwrite(p, 1, n, f) == n); }; + const uint32_t magic = LLAMA_STATE_SEQ_MAGIC, version = LLAMA_STATE_SEQ_VERSION, count = (uint32_t) n_tokens; + put(&magic, sizeof(magic)); + put(&version, sizeof(version)); + put(&count, sizeof(count)); + put(tokens, sizeof(llama_token) * n_tokens); + std::vector staging; + size_t pos = prefix; + for (const auto & sp : snap.splices) { + if (sp.offset < pos || sp.offset > snap.header.size()) { ok = false; break; } + put(snap.header.data() + pos, sp.offset - pos); + pos = sp.offset; + const auto mb = snap.bufs.find(sp.buft); + if (mb == snap.bufs.end() || sp.index >= mb->second.cpy.size()) { ok = false; break; } + const ggml_tensor * t = mb->second.cpy[sp.index]; + if (ggml_backend_buffer_is_host(t->buffer)) { + put(t->data, sp.size); // unified / host memory: straight from the buffer + } else { + staging.resize(sp.size); + ggml_backend_tensor_get(t, staging.data(), 0, sp.size); + put(staging.data(), sp.size); + } + } + put(snap.header.data() + pos, snap.header.size() - std::min(pos, snap.header.size())); + ok = (std::fclose(f) == 0) && ok; + return ok ? LLAMA_SNAPSHOT_OK : LLAMA_SNAPSHOT_COPY_FAILED; +} + 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"); @@ -4199,3 +4528,52 @@ llama_memory_breakdown llama_get_memory_breakdown(const struct llama_context * c llama_context * llama_get_ctx_other(struct llama_context * ctx) { return ctx->get_cparams().ctx_other; } + + +template +static llama_snapshot_status llama_snapshot_guard(F && f) { + try { + return f(); + } catch (const std::exception & err) { + LLAMA_LOG_ERROR("%s: %s\n", __func__, err.what()); + return LLAMA_SNAPSHOT_COPY_FAILED; + } +} + +llama_snapshot_status llama_state_seq_snapshot_bytes(llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes) { + *device_bytes = 0; + return llama_snapshot_guard([&] { return ctx->snapshot_bytes(seq_id, flags, device_bytes); }); +} + +llama_snapshot_status llama_state_seq_snapshot_save(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes) { + *device_bytes = 0; + ctx->synchronize(); // the state read is the state after every submitted step + return llama_snapshot_guard([&] { return ctx->snapshot_save(seq_id, snapshot_id, flags, device_bytes); }); +} + +llama_snapshot_status llama_state_seq_snapshot_load(llama_context * ctx, llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags) { + ctx->synchronize(); + return llama_snapshot_guard([&] { return ctx->snapshot_load(seq_id, snapshot_id, flags); }); +} + +llama_snapshot_status llama_state_seq_snapshot_free(llama_context * ctx, uint64_t snapshot_id) { + ctx->synchronize(); // no submitted step may still read buffers about to be freed + return llama_snapshot_guard([&] { return ctx->snapshot_free(snapshot_id); }); +} + +llama_snapshot_status llama_state_seq_snapshot_write_file(llama_context * ctx, uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens) { + // no synchronize: this reads only the immutable snapshot, never the context's live state + return llama_snapshot_guard([&] { return ctx->snapshot_write_file(snapshot_id, filepath, tokens, n_tokens); }); +} + +void llama_state_seq_snapshot_test_fail_next_allocs(int n) { + llama_io_write_device::fail_allocs().store(n); +} + +void llama_state_seq_snapshot_test_fail_next_load_commits(int n) { + llama_io_read_device::fail_commits().store(n); +} + +void llama_state_seq_snapshot_test_fail_next_quarantine_clears(int n) { + quarantine_clear_failures().store(n); +} diff --git a/src/llama-context.h b/src/llama-context.h index 86bb220f765f..e7249b2850e0 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -13,6 +13,7 @@ #include #include +#include #include struct llama_model; @@ -515,6 +516,28 @@ struct llama_context { // keep copies of the per-sequence memory on the device std::map mem_storage; + // Continuum fork: device snapshots keyed by a caller snapshot id (llama_state_seq_snapshot_*) + struct device_snapshot { + std::vector header; // the host-side part: magic, seq id, tensor layout + llama_memory_buffers bufs; // the state itself, in device buffers + llama_state_seq_flags flags = 0; + std::vector> layout; // provenance: which tensors, how many bytes + struct splice { size_t offset; ggml_backend_buffer_type_t buft; size_t index; size_t size; }; + std::vector splices; // where each tensor's bytes go in the host-format stream + }; + // shared: a file writer on another thread keeps a snapshot alive after its id is freed or replaced + std::map> snapshots; + std::mutex snapshots_mutex; + +public: + llama_snapshot_status snapshot_bytes(llama_seq_id seq_id, llama_state_seq_flags flags, size_t * device_bytes); + llama_snapshot_status snapshot_save(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags, size_t * device_bytes); + llama_snapshot_status snapshot_load(llama_seq_id seq_id, uint64_t snapshot_id, llama_state_seq_flags flags); + bool quarantine(llama_seq_id seq_id); // clear a failed restore; true only when the sequence is empty after + llama_snapshot_status snapshot_free(uint64_t snapshot_id); + llama_snapshot_status snapshot_write_file(uint64_t snapshot_id, const char * filepath, const llama_token * tokens, size_t n_tokens); +private: + bool has_evaluated_once = false; // env: LLAMA_GRAPH_REUSE_DISABLE diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 968a9d240200..24cf2ff460ba 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -206,6 +206,7 @@ endif () llama_build(test-recurrent-state-rollback.cpp) llama_build_and_test(test-server-view-end.cpp) +llama_build(test-seq-park.cpp) # needs -m : a checkpoint as a parked sequence id (CONTINUUM-ENGINE 4.7.11) # GGML_TENSOR_FLAG_GRAD: a leaf whose gradient the backward computes, never optimized (the walk reads the cached prefix K/V gradient) llama_build_and_test(test-grad-leaf.cpp) diff --git a/tests/test-seq-park.cpp b/tests/test-seq-park.cpp new file mode 100644 index 000000000000..e1c1b5396173 --- /dev/null +++ b/tests/test-seq-park.cpp @@ -0,0 +1,357 @@ +// what this catches: a checkpoint as a PARKED SEQUENCE (CONTINUUM-ENGINE 4.7.11), by id, never +// serialized. The live sequence is copied to a parked id with llama_memory_seq_cp (attention KV cells +// shared by sequence id, the recurrent state shared and copied on the device only when the live +// sequence advances), the live sequence moves on through different tokens, then is restored from the +// parked id; its next-token logits must equal a cold run's over the same prefix. Also times park and +// restore against today's path (llama_state_seq_get_data serializing the sequence to host bytes). +// +// usage: test-seq-park -m (a hybrid or recurrent model exercises the recurrent path) +#include "arg.h" +#include "common.h" +#include "llama.h" + +#include +#include +#include +#if defined(__APPLE__) +#include +#endif +#include +#include +#include +#include + +static int64_t now_us() { + return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +static llama_context * make_ctx(const common_params & params, llama_model * model) { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = 2; // seq 0 live, seq 1 parked + cparams.n_batch = 4096; + cparams.n_ubatch = 512; + cparams.kv_unified = true; // one stream: a parked id shares the live sequence's cells + return llama_init_from_model(model, cparams); +} + +// feeds `toks` in batches of at most the context's n_batch; logits only for the last token +static bool decode(llama_context * ctx, const std::vector & toks, llama_pos p0, llama_seq_id seq) { + const size_t step = llama_n_batch(ctx); + for (size_t off = 0; off < toks.size(); off += step) { + const size_t n = std::min(step, toks.size() - off); + llama_batch batch = llama_batch_init((int32_t) n, 0, 1); + for (size_t i = 0; i < n; ++i) { + common_batch_add(batch, toks[off + i], p0 + (llama_pos) (off + i), { seq }, off + i + 1 == toks.size()); + } + const bool ok = llama_decode(ctx, batch) == 0; + llama_batch_free(batch); + if (!ok) { + return false; + } + } + return true; +} + +static std::vector last_logits(llama_context * ctx, int n_vocab) { + const float * l = llama_get_logits_ith(ctx, -1); + return std::vector(l, l + n_vocab); +} + +int main(int argc, char ** argv) { + std::setlocale(LC_NUMERIC, "C"); + common_params params; + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + common_init(); + llama_backend_init(); + llama_model * model = llama_model_load_from_file(params.model.path.c_str(), common_model_params_to_llama(params)); + if (model == nullptr) { + std::fprintf(stderr, "FAILED: model did not load\n"); + return 1; + } + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); + std::printf("model: recurrent=%d hybrid=%d\n", (int) llama_model_is_recurrent(model), (int) llama_model_is_hybrid(model)); + + // the prefix to keep (TEST_SEQ_PARK_N overrides, to measure how a checkpoint grows with context) + const int N = std::getenv("TEST_SEQ_PARK_N") ? std::atoi(std::getenv("TEST_SEQ_PARK_N")) : 300; + constexpr int M = 120; // tokens the live sequence advances through + std::vector prefix, detour; + for (int i = 0; i < N; ++i) prefix.push_back((llama_token) (1000 + (i * 7919) % 20000)); + for (int i = 0; i < M; ++i) detour.push_back((llama_token) (2000 + (i * 104729) % 20000)); + const llama_token next = 4242; + + // reference: a cold run over prefix + next + std::vector ref; + { + llama_context * ctx = make_ctx(params, model); + std::vector all = prefix; + all.push_back(next); + if (!decode(ctx, all, 0, 0)) { std::fprintf(stderr, "FAILED: reference decode\n"); return 1; } + ref = last_logits(ctx, n_vocab); + llama_free(ctx); + } + + llama_context * ctx = make_ctx(params, model); + llama_memory_t mem = llama_get_memory(ctx); + if (!decode(ctx, prefix, 0, 0)) { std::fprintf(stderr, "FAILED: prefix decode\n"); return 1; } + llama_synchronize(ctx); + + // today's checkpoint: serialize the live sequence to host bytes + const int64_t t_ser0 = now_us(); + std::vector blob(llama_state_seq_get_size(ctx, 0)); + const size_t written = llama_state_seq_get_data(ctx, blob.data(), blob.size(), 0); + const int64_t t_ser = now_us() - t_ser0; + + // the parked checkpoint: a sequence id, no bytes moved + const int64_t t_park0 = now_us(); + llama_memory_seq_cp(mem, 0, 1, -1, -1); + const int64_t t_park = now_us() - t_park0; + + // the live sequence moves on through other tokens (this is where the recurrent state is copied on + // the device, copy-on-write, inside the step's own graph) + if (!decode(ctx, detour, N, 0)) { std::fprintf(stderr, "FAILED: detour decode\n"); return 1; } + llama_synchronize(ctx); + + // restore: drop the live sequence, take the parked one's cells and state by id + const int64_t t_rest0 = now_us(); + if (!llama_memory_seq_rm(mem, 0, -1, -1)) { std::fprintf(stderr, "FAILED: seq_rm\n"); return 1; } + llama_memory_seq_cp(mem, 1, 0, -1, -1); + const int64_t t_rest = now_us() - t_rest0; + + if (!decode(ctx, { next }, N, 0)) { std::fprintf(stderr, "FAILED: restored decode\n"); return 1; } + const std::vector got = last_logits(ctx, n_vocab); + + // the server's form: a checkpoint holds only the PARTIAL state (recurrent / SWA), attention KV is + // trimmed by position. Park only the recurrent cell (an empty attention range [0, 0) copies no + // KV cells), advance, then restore the recurrent cell by id and trim attention past the prefix. + // start from a clean prefix: the recurrent state cannot be trimmed back past `next` + llama_memory_seq_rm(mem, 1, -1, -1); + llama_memory_seq_rm(mem, 0, -1, -1); + if (!decode(ctx, prefix, 0, 0)) { std::fprintf(stderr, "FAILED: second prefix decode\n"); return 1; } + llama_synchronize(ctx); + const int64_t t_ppark0 = now_us(); + llama_memory_seq_cp(mem, 0, 1, 0, 0); + const int64_t t_ppark = now_us() - t_ppark0; + const llama_pos parked_kv_max = llama_memory_seq_pos_max(mem, 1); + if (!decode(ctx, detour, N, 0)) { std::fprintf(stderr, "FAILED: second detour\n"); return 1; } + llama_synchronize(ctx); + const int64_t t_prest0 = now_us(); + llama_memory_seq_cp(mem, 1, 0, 0, 0); // the recurrent cell, by id + const bool trimmed = llama_memory_seq_rm(mem, 0, N, -1); // attention past the prefix + const int64_t t_prest = now_us() - t_prest0; + if (!trimmed) { std::fprintf(stderr, "FAILED: attention trim after the partial restore\n"); return 1; } + if (!decode(ctx, { next }, N, 0)) { std::fprintf(stderr, "FAILED: partial restored decode\n"); return 1; } + const std::vector got_partial = last_logits(ctx, n_vocab); + float max_diff_partial = 0.0f; + int argmax_partial = 0; + for (int i = 0; i < n_vocab; ++i) { + max_diff_partial = std::max(max_diff_partial, std::fabs(ref[i] - got_partial[i])); + if (got_partial[i] > got_partial[argmax_partial]) argmax_partial = i; + } + // today's partial checkpoint, for the same comparison (the size of the state it would copy) + const int64_t t_pser0 = now_us(); + std::vector pblob(llama_state_seq_get_size_ext(ctx, 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY)); + const size_t pwritten = llama_state_seq_get_data_ext(ctx, pblob.data(), pblob.size(), 0, LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY); + const int64_t t_pser = now_us() - t_pser0; + + float max_diff = 0.0f; + int argmax_ref = 0, argmax_got = 0; + for (int i = 0; i < n_vocab; ++i) { + max_diff = std::max(max_diff, std::fabs(ref[i] - got[i])); + if (ref[i] > ref[argmax_ref]) argmax_ref = i; + if (got[i] > got[argmax_got]) argmax_got = i; + } + std::printf("serialized checkpoint: %zu bytes in %lld us (host copy of the sequence)\n", written, (long long) t_ser); + std::printf("parked checkpoint: 0 bytes moved, park %lld us, restore %lld us\n", (long long) t_park, (long long) t_rest); + std::printf("restored vs cold logits: max |diff| = %.6g, argmax %d vs %d\n", max_diff, argmax_got, argmax_ref); + std::printf("partial (server form): serialized %zu bytes in %lld us; parked 0 bytes (attention cells held by the parked id: pos_max %d), park %lld us, restore %lld us\n", + pwritten, (long long) t_pser, (int) parked_kv_max, (long long) t_ppark, (long long) t_prest); + std::printf("partial restored vs cold logits: max |diff| = %.6g, argmax %d vs %d\n", max_diff_partial, argmax_partial, argmax_ref); + + llama_free(ctx); + + // ---- the revised design: the target's partial state as a DEVICE SNAPSHOT keyed by snapshot id, on a + // context with ONE sequence (no parked ids, no extra rollback rows), plus the fault replays from + // Codex's review of 7ca9509f0 + { + auto cparams = common_context_params_to_llama(params); + cparams.n_seq_max = 1; + cparams.n_batch = 4096; + cparams.n_ubatch = 512; + llama_context * sctx = llama_init_from_model(model, cparams); + llama_memory_t smem = llama_get_memory(sctx); + const auto P = LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY; + auto require = [](bool ok, const char * what) { if (!ok) { std::fprintf(stderr, "FAILED: %s\n", what); std::exit(1); } }; + auto restored_matches_cold = [&](uint64_t id, const char * what) { + require(llama_state_seq_snapshot_load(sctx, 0, id, P) == LLAMA_SNAPSHOT_OK, what); + require(llama_memory_seq_rm(smem, 0, N, -1), "trim attention after the restore"); + require(decode(sctx, { next }, N, 0), "decode after the restore"); + const std::vector got = last_logits(sctx, n_vocab); + float d = 0.0f; int am = 0; + for (int i = 0; i < n_vocab; ++i) { d = std::max(d, std::fabs(ref[i] - got[i])); if (got[i] > got[am]) am = i; } + require(am == argmax_ref && d <= 1e-2f, what); + // back to the clean prefix for the next case: the recurrent state cannot be trimmed past `next`, + // so restore the snapshot again (the mechanism under test) and trim attention + require(llama_state_seq_snapshot_load(sctx, 0, id, P) == LLAMA_SNAPSHOT_OK, "re-restore to the prefix"); + require(llama_memory_seq_rm(smem, 0, N, -1), "trim back to the prefix"); + return d; + }; + auto host_state = [&]() { // test-only witness of the live state: its serialized bytes + std::vector v(llama_state_seq_get_size_ext(sctx, 0, P)); + llama_state_seq_get_data_ext(sctx, v.data(), v.size(), 0, P); + return v; + }; + + require(decode(sctx, prefix, 0, 0), "snapshot prefix decode"); + llama_synchronize(sctx); // time the snapshot, not the prefill still in flight + size_t quoted = 0, bytes = 0; + require(llama_state_seq_snapshot_bytes(sctx, 0, P, "ed) == LLAMA_SNAPSHOT_OK && quoted > 0, "size quote before save"); + const int64_t t_s0 = now_us(); + require(llama_state_seq_snapshot_save(sctx, 0, 42, P, &bytes) == LLAMA_SNAPSHOT_OK, "save"); + const int64_t t_save = now_us() - t_s0; + require(bytes == quoted, "the physical quote equals what the save holds (the pool reserves exactly this)"); + + // 1. a failed REPLACEMENT keeps the prior snapshot loadable + require(decode(sctx, detour, N, 0), "detour"); + llama_state_seq_snapshot_test_fail_next_allocs(1); + size_t b2 = 0; + require(llama_state_seq_snapshot_save(sctx, 0, 42, P, &b2) == LLAMA_SNAPSHOT_ALLOC_FAILED, "a failed allocation is reported typed"); + // 2. an incompatible load is refused BEFORE the live sequence changes + const auto before = host_state(); + require(llama_state_seq_snapshot_load(sctx, 0, 42, LLAMA_STATE_SEQ_FLAGS_NONE) == LLAMA_SNAPSHOT_INCOMPATIBLE, "flags mismatch refused"); + require(llama_state_seq_snapshot_load(sctx, 0, 999, P) == LLAMA_SNAPSHOT_ABSENT, "an unknown id is absent"); + require(host_state() == before, "a refused load leaves the live sequence byte-identical"); + llama_synchronize(sctx); + const int64_t t_l0 = now_us(); + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_OK, "timed restore"); + const int64_t t_load = now_us() - t_l0; // the restore alone (it synchronizes on entry; nothing is in flight) + const float d1 = restored_matches_cold(42, "the prior snapshot survived the failed replacement"); + + // 2b. a failure AFTER the read began (metadata mutated, copy not done) quarantines the target: it is + // cleared whole, never half-restored; the snapshot itself is intact and restores it again + llama_state_seq_snapshot_test_fail_next_load_commits(1); + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_COPY_FAILED, "a post-read failure is typed"); + require(llama_memory_seq_pos_max(smem, 0) == -1, "the quarantined target is empty, never half-restored"); + // 2c. if the quarantine's own clear fails, the status says the target is UNDEFINED (not cold): the + // caller keeps custody until its clear succeeds (regression for Codex's review of 16a02cca6: the + // clear's result was ignored and COPY_FAILED claimed an empty target) + llama_state_seq_snapshot_test_fail_next_load_commits(1); + llama_state_seq_snapshot_test_fail_next_quarantine_clears(1); + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_TARGET_UNCLEARED, "a failed clear is reported, never claimed cold"); + require(llama_memory_seq_rm(smem, 0, -1, -1) && llama_memory_seq_pos_max(smem, 0) == -1, "the custodian clears it"); + require(llama_state_seq_snapshot_load(sctx, 0, 42, P) == LLAMA_SNAPSHOT_OK, "an empty target restores from the intact snapshot"); + // the recurrent row is back; attention for the prefix was cleared with the quarantine, so re-prefill it + // (attention is trimmed/re-built by position, as the server does) and check the next token + require(llama_memory_seq_rm(smem, 0, -1, -1), "clear for the prefix re-build"); + require(decode(sctx, prefix, 0, 0), "re-prefill after quarantine"); + llama_synchronize(sctx); + require(llama_state_seq_snapshot_save(sctx, 0, 42, P, &bytes) == LLAMA_SNAPSHOT_OK, "re-save after quarantine"); + + // 3. save / free with backend work still in flight (no explicit synchronize by the caller) + require(decode(sctx, detour, N, 0), "detour 2"); // submitted, not synchronized + size_t b3 = 0; + require(llama_state_seq_snapshot_save(sctx, 0, 70, P, &b3) == LLAMA_SNAPSHOT_OK, "save with work in flight"); + require(decode(sctx, { next }, N + M, 0), "more work in flight"); + require(llama_state_seq_snapshot_free(sctx, 70) == LLAMA_SNAPSHOT_OK, "free with work in flight"); + require(llama_state_seq_snapshot_free(sctx, 70) == LLAMA_SNAPSHOT_ABSENT, "a second free is absent, typed"); + + // 4. allocate / recycle cycles: physical footprint must not grow + auto footprint = []() -> int64_t { +#if defined(__APPLE__) + task_vm_info_data_t info; mach_msg_type_number_t n = TASK_VM_INFO_COUNT; + return task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &info, &n) == KERN_SUCCESS ? (int64_t) info.phys_footprint : -1; +#else + return -1; +#endif + }; + int64_t peak = 0; + const int64_t base = footprint(); + for (int cycle = 0; cycle < 200; ++cycle) { + size_t b4 = 0; + require(llama_state_seq_snapshot_save(sctx, 0, 100 + (uint64_t) (cycle % 4), P, &b4) == LLAMA_SNAPSHOT_OK, "cycle save"); + if (cycle % 4 == 3) { + for (uint64_t id = 100; id < 104; ++id) llama_state_seq_snapshot_free(sctx, id); + } + peak = std::max(peak, footprint()); + } + const int64_t after = footprint(); + std::printf("device snapshot (n_seq_max 1): %zu device bytes (quoted %zu), save %lld us, restore %lld us, logits max |diff| %.6g\n", + bytes, quoted, (long long) t_save, (long long) t_load, d1); + std::printf("fault replays ok: failed replacement kept the prior, incompatible/absent refused with the live state byte-identical, save/free with work in flight\n"); + std::printf("200 save/free cycles of 4 snapshots: footprint base %.1f MiB, peak %.1f MiB, after %.1f MiB\n", + base / 1048576.0, peak / 1048576.0, after / 1048576.0); + require(after - base < (int64_t) bytes, "no growth across cycles beyond one snapshot of slack"); + llama_state_seq_snapshot_free(sctx, 42); + + // 5. a page SAVED OFF THE MAIN THREAD: the main thread takes only a full-state device snapshot; + // a writer thread writes the standard state file from it WHILE the context keeps decoding. + // The file must equal llama_state_seq_save_file's byte for byte and restore a cold-equal state. + { + require(llama_memory_seq_rm(smem, 0, -1, -1), "clear for the page test"); + require(decode(sctx, prefix, 0, 0), "page prefix"); + llama_synchronize(sctx); + const std::string dir = std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp"; + const std::string sync_path = dir + "/seq-park-sync.page", snap_path = dir + "/seq-park-snap.page"; + const int64_t t_sync0 = now_us(); + require(llama_state_seq_save_file(sctx, sync_path.c_str(), 0, prefix.data(), prefix.size()) > 0, "synchronous save"); + const int64_t t_sync = now_us() - t_sync0; + size_t page_bytes = 0; + const int64_t t_snap0 = now_us(); + require(llama_state_seq_snapshot_save(sctx, 0, 500, LLAMA_STATE_SEQ_FLAGS_NONE, &page_bytes) == LLAMA_SNAPSHOT_OK, "full-state snapshot"); + const int64_t t_snap = now_us() - t_snap0; // what the main thread now pays + llama_snapshot_status written = LLAMA_SNAPSHOT_COPY_FAILED; + int64_t t_write = 0; + std::thread writer([&] { + const int64_t t0 = now_us(); + written = llama_state_seq_snapshot_write_file(sctx, 500, snap_path.c_str(), prefix.data(), prefix.size()); + t_write = now_us() - t0; + }); + require(decode(sctx, detour, N, 0), "the context keeps decoding while the page is written"); + llama_synchronize(sctx); + writer.join(); + require(written == LLAMA_SNAPSHOT_OK, "the writer thread wrote the page"); + require(llama_state_seq_snapshot_free(sctx, 500) == LLAMA_SNAPSHOT_OK, "free the page snapshot"); + auto slurp = [](const std::string & path) { + std::FILE * f = std::fopen(path.c_str(), "rb"); + std::vector v; + if (!f) return v; + std::fseek(f, 0, SEEK_END); v.resize((size_t) std::ftell(f)); std::fseek(f, 0, SEEK_SET); + const size_t got = std::fread(v.data(), 1, v.size(), f); std::fclose(f); v.resize(got); + return v; + }; + const auto a_bytes = slurp(sync_path), b_bytes = slurp(snap_path); + require(!a_bytes.empty() && a_bytes == b_bytes, "the snapshot-written page equals the synchronous page byte for byte"); + // and it restores: load into the cleared sequence, decode the next token, compare with the cold run + require(llama_memory_seq_rm(smem, 0, -1, -1), "clear before loading the page"); + std::vector back(prefix.size()); + size_t n_back = 0; + require(llama_state_seq_load_file(sctx, snap_path.c_str(), 0, back.data(), back.size(), &n_back) > 0 && n_back == prefix.size(), "load the page"); + require(decode(sctx, { next }, N, 0), "decode after loading the page"); + const std::vector got = last_logits(sctx, n_vocab); + int am = 0; float d = 0.0f; + for (int i = 0; i < n_vocab; ++i) { d = std::max(d, std::fabs(ref[i] - got[i])); if (got[i] > got[am]) am = i; } + require(am == argmax_ref && d <= 1e-2f, "the page restores the cold-run logits"); + std::printf("page save: %zu-byte file; synchronous save %lld us on the main thread vs snapshot %lld us on it + %lld us on a writer thread (decoding meanwhile); byte-identical, restores (max |diff| %.6g)\n", + a_bytes.size(), (long long) t_sync, (long long) t_snap, (long long) t_write, d); + std::remove(sync_path.c_str()); + std::remove(snap_path.c_str()); + } + llama_free(sctx); + } + + llama_model_free(model); + llama_backend_free(); + + // the same backend, the same tokens, the same positions: the restored state must be the cold one + if (argmax_partial != argmax_ref || max_diff_partial > 1e-2f) { + std::fprintf(stderr, "FAILED: the partial (recurrent-only) restore does not reproduce the cold run\n"); + return 1; + } + if (argmax_got != argmax_ref || max_diff > 1e-2f) { + std::fprintf(stderr, "FAILED: the restored sequence does not reproduce the cold run\n"); + return 1; + } + std::printf("test-seq-park: ok\n"); + return 0; +}