Skip to content
Draft
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
565 changes: 487 additions & 78 deletions engine/src/poly/engine.cpp

Large diffs are not rendered by default.

56 changes: 52 additions & 4 deletions engine/src/poly/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ struct Options {
bool dump = false; ///< print a checksum of every stage, for comparing against llama.cpp
// A prompt batch. More tokens a call and a larger staging buffer read a prompt faster, and both take VRAM
// that the expert cache, and so decoding, does without.
int prompt_batch = 1024; ///< prompt tokens one eval() takes; the scratch is about 1.4 MiB of VRAM a token
int prompt_batch = 1024; ///< prompt tokens one eval() takes; the scratch is about 1.4 MiB of VRAM a token;
///< 0: by the VRAM, where the architecture can (auto_rows()), else 1024
int prompt_batch_max = 0; ///< prompt_batch 0: the most tokens a call may take (0: by the card)
int stage_mib = 0; ///< the buffer the experts that are not cached pass through, never more than a
///< layer's experts take; 0: 128 where a read can widen it (stage_read_mib) on
///< CUDA, else 2048, about what a layer of Q2_K experts leaves out of the cache
Expand Down Expand Up @@ -290,8 +292,8 @@ class Engine {
/// resize); refreeze_experts() puts it back, and the resized cache is what every request reads.
void unfreeze_experts();
void refreeze_experts();
/// The most tokens one eval() takes.
int max_rows() const { return rows_; }
/// The most tokens one eval() takes. (A read's calls may take more: Options::prompt_batch 0.)
int max_rows() const { return base_rows_; }
/// Feed n tokens from position pos(). With want_logits, logits() then holds the scores of the token after the
/// last one.
void eval(const int32_t* tokens, int n, bool want_logits);
Expand Down Expand Up @@ -332,6 +334,7 @@ class Engine {
void end_read() {
if (stage_lent_) narrow_stage();
if (carry_lent_) carry_give();
if (rows_ != base_rows_) narrow_rows();
if (prompt_lends_) lend_prompt();
}

Expand Down Expand Up @@ -517,6 +520,15 @@ class Engine {
/// Whether assign_scratch() may be called again with other buf_rows_, so that the scratch has a layout for a
/// few tokens and one for a prompt's batch (use_scratch()).
virtual bool scratch_layouts() const { return false; }
/// Options::prompt_batch 0: whether the architecture's calls may take more tokens for a long read than for a
/// short one (rows_ between base_rows_ and cap_rows_; resize_rows()).
virtual bool auto_rows() const { return false; }
/// The VRAM the architecture's buffers of the sequence take for calls of `rows` tokens beyond what they take
/// for none (a window layer's ring), as resize_rows() maps it.
virtual size_t rows_bytes(int rows) const { (void) rows; return 0; }
/// rows_ is now what it is from `was`: the architecture's buffers of the sequence follow it, with what they
/// hold. Throws std::runtime_error where the VRAM is not there, and leaves them as they were.
virtual void resize_rows(int was) { (void) was; }
/// The widest input lin() gets, beside the model's width and the FFNs'.
virtual int widest() const = 0;
/// The copies of a token's embedding a layer's input starts from.
Expand Down Expand Up @@ -832,8 +844,34 @@ class Engine {
/// What take_prompt()'s cut of the expert cache gave up beyond the work memory's share (whole pieces).
size_t work_over_ = 0;
bool work_lent_ = false;
void take_prompt();
void take_prompt(int rows = 0);
void lend_prompt();
/// auto_rows_: the prompt's buffers for calls of `rows` tokens, where they are (prompt_map_), or what they need.
struct PromptLayout {
size_t at[12] = {}, total = 0; ///< gu_, hx_, dx_, hf_, mq_, mq2_, mqu_, mqx_, the batch's scratch, work, xq_, q8_
size_t work_floats = 0, work_halves = 0, work_bytes = 0;
};
PromptLayout prompt_layout(int rows) const;
void place_prompt(const PromptLayout& l); ///< the buffers at their places in prompt_map_ and work_map_
std::vector<size_t> rows_floats_; ///< the batch layout's scratch floats for base_rows_ << k rows
int q_max_ = 0;
bool mixed_tiles_ = false;
uint8_t* prompt_base_ = nullptr; ///< where the prompt's buffers start (prompt_map_, or one allocation)
uint8_t* prompt_base0_ = nullptr; ///< alloc()'s (prompt_base_ is rows_wide_ while a wide read has its own)
void* xq_few_ = nullptr; ///< auto_rows_: xq_ and q8_ for a call of a few tokens; a batch's are in prompt_map_
void* q8_few_ = nullptr;
void* xq_batch_ = nullptr;
void* q8_batch_ = nullptr;
size_t count_scratch(int rows); ///< the batch layout's floats for calls of `rows` tokens (a counting pass)
void auto_batch(); ///< alloc(): Options::prompt_batch 0's rows_, cap_rows_ and auto_rows_
size_t rows_cut_ = 0; ///< what widen_rows() took from the expert cache, for narrow_rows() to give back
int pick_rows(int want) const;
bool widen_rows(int rows, int want);
void narrow_rows();
/// auto_rows_: a buffer of the sequence's own whose VRAM follows rows_ (resize_rows()): `bytes` now, addresses
/// for `most`. Returns its index in grows_.
size_t seq_grows(size_t bytes, size_t most, const char* what);
std::vector<Mapped> grows_;
/// The scratch in two layouts (scratch_layouts()): one for a call of fewer than kStageRows tokens, which stays,
/// and one for a prompt's batch, which is part of prompt_map_ and lent with it. use_scratch(true) gives the
/// buffers their places in the prompt's, use_scratch(false) in the other. Recordings are made and replayed
Expand Down Expand Up @@ -982,6 +1020,16 @@ class Engine {
int n_expert_ = 0, n_used_ = 0, n_ff_exp_ = 0, n_ff_shexp_ = 0, n_moe_ = 0;
int rows_ = 1; ///< tokens the scratch is sized for
int read_rows_ = 1; ///< the most tokens read() takes
/// Options::prompt_batch 0 (auto_rows_): a read's calls take rows_ tokens, from base_rows_ (a call's outside a
/// read, and between reads) up to cap_rows_ (widen_rows()); else all three are the one batch.
int base_rows_ = 1, cap_rows_ = 1;
bool auto_rows_ = false;
bool auto_asked_ = false; ///< Options::prompt_batch was 0
/// auto_rows_ where the prompt's buffers are not lent (HIP): the base batch's stay where they are, and a wider read
/// gets buffers of its own (rows_wide_), allocated for the read and freed after it (widen_rows(), narrow_rows()).
bool rows_malloc_ = false;
uint8_t* rows_wide_ = nullptr;
float* scratch_base_ = nullptr; ///< rows_malloc_: the scratch while the wide buffers are in use
// read()'s calls between two layers: r_ holds two calls' rows, and with more calls than that the others'
// wait in host memory, copied out and in beside the card's work on the call between
struct Call {
Expand Down
136 changes: 132 additions & 4 deletions engine/src/poly/inkling2.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -727,12 +727,14 @@ size_t Inkling2::recurrent_floats() const { return slots_.size() * past_floats()
// ROCm on Linux gives VRAM back only with its addresses (Engine::vmm_unmap()), and a prompt's lent buffers crashed
// strata-poly there (an RX 9070 XT, Inkling 2 Mini IQ4_NL with some experts in RAM): the prompt batch's scratch stays
// out of them, in one layout as before. With the experts frozen (STRATA_FREEZE_EXPERTS, --check-batch) lend_prompt()
// lends nothing, and the small layout would only take VRAM from the expert cache for the whole run.
// lends nothing, and the small layout would only take VRAM from the expert cache for the whole run; but where a read's
// calls may take more tokens (Options::prompt_batch 0) the layouts follow them, out of the VRAM that is free.
bool Inkling2::scores_apart() const {
#ifdef STRATA_VMM_RELEASE_WITH_ADDRESSES
return false;
#else
return !ds_file_ && !freeze_experts_asked_ && mmq_ && vmm_ && !split_ && rows_ >= kStageRows;
return (!ds_file_ || auto_rows_) && (!freeze_experts_asked_ || auto_rows_) && mmq_ && vmm_ && !split_ &&
rows_ >= kStageRows;
#endif
}

Expand All @@ -753,7 +755,123 @@ bool Inkling2::every_expert_fits() const {
return (size_t) vram_free_mib() << 20 >= need;
}

bool Inkling2::scratch_layouts() const { return scores_apart() && !every_expert_fits(); }
// With Options::prompt_batch 0 the batch layout follows the read (Engine::widen_rows()) wherever it may.
bool Inkling2::scratch_layouts() const { return scores_apart() && (auto_rows_ || !every_expert_fits()); }

// The window slots' rings for calls of `rows` tokens: window_ rows and the call's.
size_t Inkling2::rows_bytes(int rows) const {
const size_t grain = auto_rows_ && !rows_malloc_ ? (pool_on_ ? pg_ : grain_) : 1;
size_t n = 0;
for (const Slot& s : slots_) n += runs(s.il) && blocks_[(size_t) s.il].swa ? 2 : 0;
const size_t ring = (size_t) std::min(opt_.max_context, window_ + rows) * kv_row();
return n * ((ring + grain - 1) / grain * grain);
}

// rows_ is now what it is from `was`: each window slot's ring takes window_ rows and a call's, and the last keep_
// positions before pos_ move to their places in it (the rows past them are of no position the next call reads). VRAM
// for a wider ring first: where it is not there, every ring stays as it was.
void Inkling2::resize_rows(int was) {
(void) was;
const int r = std::min(opt_.max_context, window_ + rows_);
if (rows_malloc_) { // HIP: a wide read's rings in one allocation of their own, the alloc()'s ones kept aside
if (r == ring_) return;
const size_t row = kv_row(), ring = (size_t) r * row;
ck(cudaStreamSynchronize(cs(st_)), "the attention cache");
std::vector<uint16_t**> caches;
for (Slot& s : slots_)
if (s.keys && blocks_[(size_t) s.il].swa) caches.push_back(&s.keys), caches.push_back(&s.vals);
uint8_t* wide = nullptr;
if (r > ring_) {
void* p = nullptr;
if (cudaMalloc(&p, caches.size() * ring) != cudaSuccess) {
(void) cudaGetLastError();
throw std::runtime_error("no VRAM for a wide read's rings");
}
wide = (uint8_t*) p;
zero_vram(wide, caches.size() * ring);
ring_homes_.clear();
}
// the copies first, then the pointers: a copy that fails leaves every slot where it was
const int old = ring_;
try {
for (size_t i = 0; i < caches.size(); ++i) {
uint8_t* const from = (uint8_t*) *caches[i];
uint8_t* const to = wide ? wide + i * ring : (uint8_t*) ring_homes_.at(i);
ring_ = old;
window_runs(pos_, [&](size_t place, size_t at, size_t m) {
ck(cudaMemcpyAsync(ring_tmp_ + place * row, from + at * row, m * row, cudaMemcpyDeviceToDevice,
cs(st_)),
"the attention cache");
});
ring_ = r;
window_runs(pos_, [&](size_t place, size_t at, size_t m) {
ck(cudaMemcpyAsync(to + at * row, ring_tmp_ + place * row, m * row, cudaMemcpyDeviceToDevice,
cs(st_)),
"the attention cache");
});
}
} catch (...) {
ring_ = old;
if (wide) cudaFree(wide);
throw;
}
for (size_t i = 0; i < caches.size(); ++i) {
uint16_t* const to = wide ? (uint16_t*) (wide + i * ring) : ring_homes_.at(i);
if (wide) ring_homes_.push_back(*caches[i]);
*caches[i] = to;
}
ring_ = r;
if (!wide) { // back home: the wide rings go
ck(cudaStreamSynchronize(cs(st_)), "the attention cache");
ck(cudaFree(ring_wide_), "the attention cache");
ring_wide_ = nullptr;
ring_homes_.clear();
} else {
ring_wide_ = wide;
}
return;
}
if (r == ring_ || rings_.empty()) {
ring_ = r;
return;
}
const size_t row = kv_row();
ck(cudaStreamSynchronize(cs(st_)), "the attention cache");
if (r > ring_) {
std::vector<size_t> had;
try {
for (size_t i : rings_) {
Mapped& m = grows_[i];
had.push_back(m.mapped);
vmm_map(m, (size_t) r * row, SIZE_MAX, "the attention cache");
zero_vram((uint8_t*) m.base + had.back(), m.mapped - had.back());
}
} catch (const std::runtime_error&) {
ck(cudaStreamSynchronize(cs(st_)), "the attention cache");
for (size_t j = 0; j < had.size(); ++j) vmm_unmap(grows_[rings_[j]], had[j]);
throw;
}
}
const int old = ring_;
for (size_t i : rings_) {
uint8_t* const cache = (uint8_t*) grows_[i].base;
ring_ = old;
window_runs(pos_, [&](size_t place, size_t at, size_t m) {
ck(cudaMemcpyAsync(ring_tmp_ + place * row, cache + at * row, m * row, cudaMemcpyDeviceToDevice, cs(st_)),
"the attention cache");
});
ring_ = r;
window_runs(pos_, [&](size_t place, size_t at, size_t m) {
ck(cudaMemcpyAsync(cache + at * row, ring_tmp_ + place * row, m * row, cudaMemcpyDeviceToDevice, cs(st_)),
"the attention cache");
});
}
ring_ = r;
if (r < old) {
ck(cudaStreamSynchronize(cs(st_)), "the attention cache");
for (size_t i : rings_) vmm_unmap(grows_[i], (size_t) r * row);
}
}

int Inkling2::widest() const { return std::max(n_head_ * head_dim_, 2 * n_embd_); }

Expand All @@ -768,9 +886,18 @@ void Inkling2::alloc_caches() {
if (!runs(s.il)) continue;
s.past = st;
st += past_floats();
if (blocks_[(size_t) s.il].swa) {
if (blocks_[(size_t) s.il].swa && auto_rows_ && !rows_malloc_) {
// the ring follows the read's calls (resize_rows()): addresses for the widest
const size_t most = (size_t) std::min(opt_.max_context, window_ + cap_rows_) * row;
for (uint16_t** c : {&s.keys, &s.vals}) {
rings_.push_back(seq_grows((size_t) ring_ * row, most, "the attention cache"));
*c = (uint16_t*) grows_[rings_.back()].base;
}
if (!ring_tmp_) ring_tmp_ = (uint8_t*) dmalloc((size_t) keep_ * row, "the attention cache");
} else if (blocks_[(size_t) s.il].swa) {
s.keys = (uint16_t*) seq_alloc((size_t) ring_ * row, "the attention cache");
s.vals = (uint16_t*) seq_alloc((size_t) ring_ * row, "the attention cache");
if (rows_malloc_ && !ring_tmp_) ring_tmp_ = (uint8_t*) dmalloc((size_t) keep_ * row, "the attention cache");
} else {
s.keys = (uint16_t*) kv_alloc(row, 1);
s.vals = (uint16_t*) kv_alloc(row, 1);
Expand Down Expand Up @@ -883,6 +1010,7 @@ void Inkling2::assign_scratch() {
}

Inkling2::~Inkling2() {
if (ring_wide_) cudaFree(ring_wide_); // a read that never ended (rows_malloc_)
if (side_) cudaStreamSynchronize(cs(side_));
for (void* e : {side_go_, side_done_})
if (e) cudaEventDestroy((cudaEvent_t) e);
Expand Down
7 changes: 7 additions & 0 deletions engine/src/poly/inkling2.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ class Inkling2 final : public Engine {
bool scratch_layouts() const override;
bool scores_apart() const; ///< the attention's scores outside the scratch, for its two layouts to share
bool every_expert_fits() const;
bool auto_rows() const override { return true; }
size_t rows_bytes(int rows) const override;
void resize_rows(int was) override;
std::vector<size_t> rings_; ///< auto_rows_: the window slots' keys and values, as Engine::grows_ has them
uint8_t* ring_tmp_ = nullptr; ///< resize_rows()'s copy of a ring's kept rows
uint8_t* ring_wide_ = nullptr; ///< Engine::rows_malloc_: a wide read's rings, each window slot's keys and values
std::vector<uint16_t*> ring_homes_; ///< and the alloc_caches() rings they stand in for, in that order
int widest() const override;
int streams() const override { return 1; }
void layer_head(Layer& L, int il, int n) override;
Expand Down
4 changes: 2 additions & 2 deletions engine/src/poly/inkling2_pictures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ int64_t Inkling2::whole(int64_t at, int64_t m) const {
if (at >= im.at + im.n) continue;
if (at < im.at) return std::min(m, im.at - at);
if (at != im.at) throw std::logic_error("a sequence cannot go on from the middle of a picture");
if (im.n > rows_)
if (im.n > max_rows())
throw std::runtime_error("a picture of " + std::to_string(im.n) + " rows is more than a prompt batch (" +
std::to_string(rows_) + "): raise --prompt-batch or lower the picture's tokens");
std::to_string(max_rows()) + "): raise --prompt-batch or lower the picture's tokens");
return im.n;
}
return m;
Expand Down
9 changes: 7 additions & 2 deletions engine/src/poly/logits_dump.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const char* const kUsage =
" --out DIR where the .f32 files go (default .)\n"
" --vocab N write a row's first N scores (Inkling 2: 200058, the unpadded vocabulary)\n"
" --max-context N the engine's context (default 4096)\n"
" --prompt-batch N the prompt's tokens a call, as strata-poly's\n"
" --prompt-batch N|auto|auto:N the prompt's tokens a call, as strata-poly's (default 1024)\n"
" --kv fp16|fp8 the attention caches' format, as strata-poly's\n"
" --threads N the CPU experts' threads\n"
" --no-graphs no recorded launches\n"
Expand Down Expand Up @@ -150,7 +150,12 @@ int main(int argc, char** argv) {
else if (a == "--out") out = val();
else if (a == "--vocab") vocab = number(a, val(), 0);
else if (a == "--max-context") o.max_context = number(a, val(), 1);
else if (a == "--prompt-batch") o.prompt_batch = number(a, val(), 1);
else if (a == "--prompt-batch") {
const std::string v = val();
if (v == "auto") o.prompt_batch = 0;
else if (v.rfind("auto:", 0) == 0) o.prompt_batch = 0, o.prompt_batch_max = number(a, v.c_str() + 5, 1);
else o.prompt_batch = number(a, v.c_str(), 1);
}
else if (a == "--kv") {
const std::string f = val();
if (f == "fp16") o.kv_format = strata::poly::KvFmt::kFp16;
Expand Down
Loading
Loading