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
201 changes: 201 additions & 0 deletions engine/src/inkling2/hip/ink_hip_backend.hip.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,7 @@ class HipBackend final : public InkBackend {
for (auto& p : swa_pools_) p.free_slot_pages(slot);
for (auto& p : glob_pools_) p.free_slot_pages(slot);
slots_[slot].release();
if (slot < static_cast<int>(ckpts_.size())) ckpts_[slot].valid = false; // #6627: its SWA pages are unmapped
}

void reset_slot(int slot) override {
Expand Down Expand Up @@ -997,6 +998,164 @@ class HipBackend final : public InkBackend {
}
}

// Prompt checkpoint (#6627), HIP side of the hooks in ink_backend.h. Saves the slot's position-dependent state
// at the end of a prompt, so a later prompt that extends that prompt but not the generated reply (hidden
// reasoning, a re-rendered tool call) resumes there instead of re-reading from 0:
// - SWA visits: KV is a ring of swa_win positions (page (p % swa_win) / 64, ensure_page), so the slot's mapped
// ring pages are copied to pinned host memory: 2 x n_swa_visits x 16 pages x 64 x kv_dim x 2 B per slot
// (~160 MiB at BF16 KV, half at FP8), no VRAM taken from the auto-sized pools;
// - ShortConv state (n_visits x 3 lags) goes to small device buffers, with the same copy kernels as snapshot_slot;
// - global-visit KV and the DSpark context (k_dspark_ctx_scatter) are indexed by absolute position and only
// appended, so restoring seq_len / dspark_len is enough.
// Every copy is queued on stream_ in order with the forward passes, so no host sync is needed.
static constexpr int kPromptCkptMaxSlots = 4; // pinned host RAM bound, as in the Metal backend

bool checkpoint_slot(int slot) override {
if (slot < 0 || slot >= max_slots_ || !slots_[slot].allocated || max_slots_ > kPromptCkptMaxSlots) return false;
if (swa_pools_.empty()) return false;
if (static_cast<int>(ckpts_.size()) < max_slots_) ckpts_.resize(max_slots_);
PromptCkpt& ck = ckpts_[slot];
ck.valid = false;
const int n_pools = static_cast<int>(swa_pools_.size());
const int mpp = swa_pools_[0].max_pages_per_slot;
const bool fp8 = swa_pools_[0].is_fp8;
const int kv_dim = c_.n_kv * c_.head_dim;
const size_t page_b = static_cast<size_t>(kKvPageTokens) * kv_dim * (fp8 ? 1u : 2u);
const size_t sc_page_b = static_cast<size_t>(kKvPageTokens) * sizeof(float);
if (!ck.alloc_host(static_cast<size_t>(n_pools) * mpp * page_b,
fp8 ? static_cast<size_t>(n_pools) * mpp * sc_page_b : 0)) return false;
const size_t kv_one = 3u * kv_dim * sizeof(uint16_t);
const size_t h_one = 3u * c_.hidden * sizeof(uint16_t);
if (!ck.sc_k.dev_ptr) {
if (alloc_gpu_buffer(ck.sc_k, static_cast<size_t>(c_.n_visits) * kv_one, mem_info_.is_uma) != hipSuccess ||
alloc_gpu_buffer(ck.sc_v, static_cast<size_t>(c_.n_visits) * kv_one, mem_info_.is_uma) != hipSuccess ||
alloc_gpu_buffer(ck.sc_attn, static_cast<size_t>(c_.n_visits) * h_one, mem_info_.is_uma) != hipSuccess ||
alloc_gpu_buffer(ck.sc_mlp, static_cast<size_t>(c_.n_visits) * h_one, mem_info_.is_uma) != hipSuccess) {
ck.release();
return false;
}
}
bool ok = true;
ck.phys.assign(static_cast<size_t>(n_pools) * mpp, -1);
for (int i = 0; i < n_pools && ok; ++i) {
const VisitKvPool& kvp = swa_pools_[i];
const int32_t* row = kvp.h_pt.data() + static_cast<size_t>(slot) * kvp.max_pages_per_slot;
for (int lp = 0; lp < mpp && ok;) {
const int32_t ph = row[lp];
if (ph < 0) { ++lp; continue; }
int n = 1; // one copy per run of consecutive physical pages
while (lp + n < mpp && row[lp + n] == ph + n) ++n;
for (int k = 0; k < n; ++k) ck.phys[static_cast<size_t>(i) * mpp + lp + k] = ph + k;
const size_t hp = static_cast<size_t>(i) * mpp + lp;
ok = ok && hipMemcpyAsync(ck.h_k + hp * page_b, static_cast<const uint8_t*>(kvp.k_pool.dev_ptr) + ph * page_b,
n * page_b, hipMemcpyDeviceToHost, stream_) == hipSuccess;
ok = ok && hipMemcpyAsync(ck.h_v + hp * page_b, static_cast<const uint8_t*>(kvp.v_pool.dev_ptr) + ph * page_b,
n * page_b, hipMemcpyDeviceToHost, stream_) == hipSuccess;
if (fp8) {
ok = ok && hipMemcpyAsync(ck.h_ks + hp * sc_page_b, static_cast<const uint8_t*>(kvp.k_scales.dev_ptr) + ph * sc_page_b,
n * sc_page_b, hipMemcpyDeviceToHost, stream_) == hipSuccess;
ok = ok && hipMemcpyAsync(ck.h_vs + hp * sc_page_b, static_cast<const uint8_t*>(kvp.v_scales.dev_ptr) + ph * sc_page_b,
n * sc_page_b, hipMemcpyDeviceToHost, stream_) == hipSuccess;
}
lp += n;
}
}
if (!ok) return false;
k_sconv_snapshot_pair<<<dim3((kv_dim + 255) / 256, c_.n_visits), 256, 0, stream_>>>(
reinterpret_cast<const uint16_t*>(d_sconv_k_all_.dev_ptr),
reinterpret_cast<const uint16_t*>(d_sconv_v_all_.dev_ptr),
reinterpret_cast<uint16_t*>(ck.sc_k.dev_ptr),
reinterpret_cast<uint16_t*>(ck.sc_v.dev_ptr),
slot, max_slots_, c_.n_visits, kv_dim);
k_sconv_snapshot_pair<<<dim3((c_.hidden + 255) / 256, c_.n_visits), 256, 0, stream_>>>(
reinterpret_cast<const uint16_t*>(d_sconv_attn_all_.dev_ptr),
reinterpret_cast<const uint16_t*>(d_sconv_mlp_all_.dev_ptr),
reinterpret_cast<uint16_t*>(ck.sc_attn.dev_ptr),
reinterpret_cast<uint16_t*>(ck.sc_mlp.dev_ptr),
slot, max_slots_, c_.n_visits, c_.hidden);
if (hipGetLastError() != hipSuccess) return false;
ck.seq_len = slots_[slot].seq_len;
ck.dspark_len = slots_[slot].dspark_len;
ck.valid = true;
return true;
}

bool restore_checkpoint(int slot) override {
if (slot < 0 || slot >= max_slots_ || slot >= static_cast<int>(ckpts_.size()) || !slots_[slot].allocated) return false;
PromptCkpt& ck = ckpts_[slot];
if (!ck.valid || swa_pools_.empty()) return false;
const int n_pools = static_cast<int>(swa_pools_.size());
const int mpp = swa_pools_[0].max_pages_per_slot;
if (ck.phys.size() != static_cast<size_t>(n_pools) * mpp) { ck.valid = false; return false; }
// The slot must still map the checkpointed pages (only free_slot unmaps them; grow_pool keeps indices).
for (int i = 0; i < n_pools; ++i) {
const int32_t* row = swa_pools_[i].h_pt.data() + static_cast<size_t>(slot) * swa_pools_[i].max_pages_per_slot;
for (int lp = 0; lp < mpp; ++lp) {
const int32_t want = ck.phys[static_cast<size_t>(i) * mpp + lp];
if (want >= 0 && row[lp] != want) { ck.valid = false; return false; }
}
}
const bool fp8 = swa_pools_[0].is_fp8;
const int kv_dim = c_.n_kv * c_.head_dim;
const size_t page_b = static_cast<size_t>(kKvPageTokens) * kv_dim * (fp8 ? 1u : 2u);
const size_t sc_page_b = static_cast<size_t>(kKvPageTokens) * sizeof(float);
bool ok = true;
for (int i = 0; i < n_pools && ok; ++i) {
const VisitKvPool& kvp = swa_pools_[i];
for (int lp = 0; lp < mpp && ok;) {
const int32_t ph = ck.phys[static_cast<size_t>(i) * mpp + lp];
if (ph < 0) { ++lp; continue; }
int n = 1;
while (lp + n < mpp && ck.phys[static_cast<size_t>(i) * mpp + lp + n] == ph + n) ++n;
const size_t hp = static_cast<size_t>(i) * mpp + lp;
ok = ok && hipMemcpyAsync(static_cast<uint8_t*>(kvp.k_pool.dev_ptr) + ph * page_b, ck.h_k + hp * page_b,
n * page_b, hipMemcpyHostToDevice, stream_) == hipSuccess;
ok = ok && hipMemcpyAsync(static_cast<uint8_t*>(kvp.v_pool.dev_ptr) + ph * page_b, ck.h_v + hp * page_b,
n * page_b, hipMemcpyHostToDevice, stream_) == hipSuccess;
if (fp8) {
ok = ok && hipMemcpyAsync(static_cast<uint8_t*>(kvp.k_scales.dev_ptr) + ph * sc_page_b, ck.h_ks + hp * sc_page_b,
n * sc_page_b, hipMemcpyHostToDevice, stream_) == hipSuccess;
ok = ok && hipMemcpyAsync(static_cast<uint8_t*>(kvp.v_scales.dev_ptr) + ph * sc_page_b, ck.h_vs + hp * sc_page_b,
n * sc_page_b, hipMemcpyHostToDevice, stream_) == hipSuccess;
}
lp += n;
}
}
if (!ok) { ck.valid = false; return false; }
// keep_steps = 0: the three lags come from the checkpoint (the rec arguments are not read).
k_sconv_rollback_pair<<<dim3((kv_dim + 255) / 256, c_.n_visits), 256, 0, stream_>>>(
reinterpret_cast<const uint16_t*>(ck.sc_k.dev_ptr), reinterpret_cast<const uint16_t*>(ck.sc_k.dev_ptr),
reinterpret_cast<uint16_t*>(d_sconv_k_all_.dev_ptr),
reinterpret_cast<const uint16_t*>(ck.sc_v.dev_ptr), reinterpret_cast<const uint16_t*>(ck.sc_v.dev_ptr),
reinterpret_cast<uint16_t*>(d_sconv_v_all_.dev_ptr),
slot, max_slots_, c_.n_visits, 0, kv_dim);
k_sconv_rollback_pair<<<dim3((c_.hidden + 255) / 256, c_.n_visits), 256, 0, stream_>>>(
reinterpret_cast<const uint16_t*>(ck.sc_attn.dev_ptr), reinterpret_cast<const uint16_t*>(ck.sc_attn.dev_ptr),
reinterpret_cast<uint16_t*>(d_sconv_attn_all_.dev_ptr),
reinterpret_cast<const uint16_t*>(ck.sc_mlp.dev_ptr), reinterpret_cast<const uint16_t*>(ck.sc_mlp.dev_ptr),
reinterpret_cast<uint16_t*>(d_sconv_mlp_all_.dev_ptr),
slot, max_slots_, c_.n_visits, 0, c_.hidden);
if (hipGetLastError() != hipSuccess) { ck.valid = false; return false; }
auto& sl = slots_[slot];
sl.seq_len = ck.seq_len; // forward_batch only raises seq_len (std::max), so set it back here
sl.dspark_len = std::min(sl.dspark_len, ck.dspark_len);
sl.has_snap = false;
sl.sconv_rec_n = 0;
// DSpark's adaptive draft state restarts as for a fresh prompt (as reset_slot does)
sl.dspark_ema_acc = 0.50f;
sl.dspark_last_draft = 0;
sl.dspark_last_anchor = -1;
sl.dspark_skip_rem = 0;
sl.dspark_had_rollback = false;
sl.tree_ema_gain = 1.25f;
sl.tree_cool_rem = 0;
return true;
}

void drop_checkpoint(int slot) override {
if (slot >= 0 && slot < static_cast<int>(ckpts_.size())) ckpts_[slot].valid = false;
}

bool forward_batch(const StepBatch& batch, float* logits_out, TapCapture* taps_out, std::string& err) override {
const int B_tot = batch.n_tokens;
if (B_tot <= 0) return true;
Expand Down Expand Up @@ -4436,6 +4595,8 @@ class HipBackend final : public InkBackend {
}
for (auto& sl : slots_) sl.release();
slots_.clear();
for (auto& ck : ckpts_) ck.release(); // #6627 prompt checkpoints
ckpts_.clear();
for (auto& p : swa_pools_) p.release();
for (auto& p : glob_pools_) p.release();
swa_pools_.clear(); glob_pools_.clear();
Expand Down Expand Up @@ -4543,6 +4704,46 @@ class HipBackend final : public InkBackend {
GpuBuffer d_ds_k_ptrs_[3], d_ds_v_ptrs_[3], d_ds_frnn_ptrs_;
uint64_t dspark_ptr_gen_ = 0;

// #6627 prompt checkpoint per slot (see checkpoint_slot)
struct PromptCkpt {
bool valid = false;
int seq_len = 0;
int dspark_len = 0;
std::vector<int32_t> phys; // [n_swa_visits * pages_per_slot] SWA page map at checkpoint time, -1 = unmapped
uint8_t* h_k = nullptr; // pinned host copies of the slot's SWA ring pages [n_swa_visits * pages_per_slot][page]
uint8_t* h_v = nullptr;
uint8_t* h_ks = nullptr; // FP8 KV: per-token scales of the same pages
uint8_t* h_vs = nullptr;
size_t kv_bytes = 0;
size_t sc_bytes = 0;
GpuBuffer sc_k, sc_v, sc_attn, sc_mlp; // ShortConv state [n_visits, 3, C]

static void host_free(uint8_t*& p) noexcept { if (p) { (void)hipHostFree(p); p = nullptr; } }
bool alloc_host(size_t kvb, size_t scb) noexcept {
if (kvb == kv_bytes && scb == sc_bytes && h_k) return true;
host_free(h_k); host_free(h_v); host_free(h_ks); host_free(h_vs);
kv_bytes = sc_bytes = 0;
if (hipHostMalloc(reinterpret_cast<void**>(&h_k), kvb, hipHostMallocDefault) != hipSuccess ||
hipHostMalloc(reinterpret_cast<void**>(&h_v), kvb, hipHostMallocDefault) != hipSuccess ||
(scb && hipHostMalloc(reinterpret_cast<void**>(&h_ks), scb, hipHostMallocDefault) != hipSuccess) ||
(scb && hipHostMalloc(reinterpret_cast<void**>(&h_vs), scb, hipHostMallocDefault) != hipSuccess)) {
host_free(h_k); host_free(h_v); host_free(h_ks); host_free(h_vs);
return false;
}
kv_bytes = kvb;
sc_bytes = scb;
return true;
}
void release() noexcept {
host_free(h_k); host_free(h_v); host_free(h_ks); host_free(h_vs);
kv_bytes = sc_bytes = 0;
free_gpu_buffer(sc_k); free_gpu_buffer(sc_v); free_gpu_buffer(sc_attn); free_gpu_buffer(sc_mlp);
phys.clear();
valid = false;
}
};
std::vector<PromptCkpt> ckpts_;

GpuBuffer expert_gpu_arena_;
GpuBuffer d_exp_stage_;
GpuBuffer d_exp_w13_f16_, d_exp_w2_f16_;
Expand Down
6 changes: 6 additions & 0 deletions engine/src/inkling2/ink_backend.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ class InkBackend {
// Speculative rollback: restore KV + ShortConv state to `keep_len` (requires snapshot taken before verify!)
virtual void snapshot_slot(int slot) = 0;
virtual void rollback_slot(int slot, int keep_len) = 0;
// Prompt checkpoint (#6627): save the slot's position-dependent state (SWA ring KV, ShortConv history, DSpark
// f_rnn) right after a prompt is fully read, so a later prompt that extends it can resume there even when it
// does not carry the generated tokens (hidden reasoning). Global-attention KV is append-only and needs no copy.
virtual bool checkpoint_slot(int /*slot*/) { return false; }
virtual bool restore_checkpoint(int /*slot*/) { return false; }
virtual void drop_checkpoint(int /*slot*/) {}

// Batched 48-visit forward across 1..64 active slots!
// logits_out: [batch.count_logits(), vocab_unpadded] FP32 (already softcapped by 30*tanh(z/30) and sliced to 200058).
Expand Down
Loading