diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 35005b37e..26eff15a1 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -103,6 +103,12 @@ void drop_file_pages(const void* p, size_t n) { constexpr int kTile[] = {32, 128}; constexpr int kClasses = (int) (sizeof(kTile) / sizeof(kTile[0])) + 1; constexpr int kMaxStagedTiles = 8; // the most size classes STRATA_POLY_STAGED_TILES makes of the staged experts +// A prompt batch: at most 4,096 tokens, or kMostRows where the architecture's calls can take more (auto_rows()). +// Options::prompt_batch 0 takes up to kAutoRowsAll a call where every expert fits in VRAM beside the batch, else up +// to kAutoRowsPart, out of the expert cache for the read (widen_rows()). +constexpr int kMostRows = 8192; +constexpr int kAutoRowsAll = 8192; +constexpr int kAutoRowsPart = 4096; int tile_class(int rows) { int c = 0; @@ -894,6 +900,7 @@ Engine::~Engine() { for (void* e : gather_ev_) if (e) cudaEventDestroy((cudaEvent_t) e); for (void* p : dev_allocs_) cudaFree(p); + if (rows_wide_) cudaFree(rows_wide_); // a read that never ended (rows_malloc_) for (Kv& k : kv_) vmm_free(k); for (Seq& q : seqs_) { for (Kv& k : q.kv) vmm_free(k); @@ -906,6 +913,7 @@ Engine::~Engine() { vmm_free(carry_map_); vmm_free(prompt_map_); vmm_free(work_map_); + for (Mapped& m : grows_) vmm_free(m); for (unsigned long long h : vpool_) cuMemRelease(h); // the pool goes back to the card with the engine vpool_.clear(); for (void* p : host_allocs_) cudaFreeHost(p); @@ -2687,9 +2695,10 @@ bool Engine::mind_card_vram() { // A call of kStageRows rows or more needs the buffers lend_prompt() gave the expert cache: it takes the VRAM back, // the cache's least used experts first, and maps them again. The products' work memory (work_map_) is lent from // the start, so the first prompt takes it here. -void Engine::take_prompt() { +void Engine::take_prompt(int rows) { if (!prompt_lent_ && !work_lent_) { if (two_scratch_ && !prompt_scratch_) use_scratch(true); + if (auto_rows_ && pick_rows(rows) > rows_) widen_rows(pick_rows(rows), rows); return; } if (up_) ck(cudaStreamSynchronize(cs(up_)), "a prompt's buffers"); @@ -2721,6 +2730,7 @@ void Engine::take_prompt() { if (work_lent_) vmm_map(work_map_, work_bytes_, SIZE_MAX, "the prompt products' work memory"); prompt_lent_ = work_lent_ = false; if (two_scratch_) use_scratch(true); + if (auto_rows_ && pick_rows(rows) > rows_) widen_rows(pick_rows(rows), rows); } // Between prompts, the expert cache has the VRAM of the buffers only a prompt's calls use (alloc()), the scratch's @@ -2783,6 +2793,416 @@ void Engine::narrow_stage() { stage_cut_ = 0; } +// ---- Options::prompt_batch 0: a read's calls by the VRAM ---- +// +// A prompt read in calls of more tokens is faster (wider products, fewer launches), and its buffers take VRAM that +// the expert cache, and so the answer, does without. With every expert in VRAM the batch takes what is free beside +// them and the attention caches; without, a long read takes the VRAM from the expert cache, as take_prompt() does, +// and narrow_rows() gives it back when the read is done. A short prompt (and a call outside a read) keeps +// base_rows_. RTX 2070 Super, Inkling 2 Mini: --prompt-batch 4096 for the whole run read 8K and 32K prompts 42-67% +// faster than 1024 but 302-token ones 22% slower and wrote 3-12% slower after them (its buffers are 2.4 GiB of the +// cache's 4.4); calls that follow the read read the long prompts as fast, and the short ones and the answers as 1024. + +// The batch layout's floats for calls of `rows` tokens: a counting pass, which leaves the scratch's pointers to be +// given again (use_scratch(), or alloc()'s own pass). +size_t Engine::count_scratch(int rows) { + float* const sc = scratch_; + const int r = rows_, b = buf_rows_, rd = read_rows_; + const size_t at = scratch_at_; + if (read_rows_ <= 1) { // before alloc() settles it: as it would for these rows + const size_t most = + std::min(kReadBytes / ((size_t) streams() * n_embd_ * sizeof(float)), opt_.max_context); + read_rows_ = std::max(rows, (int) most / rows * rows); + } + rows_ = buf_rows_ = rows; + scratch_ = nullptr; + scratch_at_ = 0; + shared_scratch(); + assign_scratch(); + const size_t n = scratch_at_; + scratch_ = sc; + rows_ = r; + buf_rows_ = b; + read_rows_ = rd; + scratch_at_ = at; + return n; +} + +// Where the buffers can be mapped apart (VMM, one card, one sequence), a read's calls take from base_rows_ up to +// cap_rows_ tokens, as many as the read has, the VRAM allowing (widen_rows()): up to kAutoRowsAll where every +// expert fits beside 2 GiB, else kAutoRowsPart. Elsewhere (ROCm on Linux, which gives VRAM back only with its +// addresses) the batch is one for the run: the widest that leaves every expert, the whole context's rows and 2 GiB +// their room, else base_rows_. +void Engine::auto_batch() { + // Not on Metal, nor on a layer split (each card would size its own, and a later card's calls must take the + // first one's), nor with a drafter or the model's own block guesses +#if defined(STRATA_GPU_METAL) + return; +#endif + // (A model's own block guesses, Inkling 2's DSpark drafter, go with it: the drafter keeps nothing in the scratch + // from one call to the next, and its blocks are calls of a few tokens.) + if (split_ || draft_ || (block_guess_ && !own_blocks()) || !opt_.gpu_experts) return; + // Calls that follow the read on CUDA only: elsewhere (ROCm on Linux gives VRAM back only with its addresses, and + // ROCm on Windows is untested) one batch for the run +#if defined(STRATA_VMM_RELEASE_WITH_ADDRESSES) || defined(STRATA_USE_HIP) + const bool grows = false; +#else + const bool grows = vmm_ && opt_.batch == 0 && opt_.window < kStageRows; +#endif + size_t all = 0; + for (const Layer& L : layers_) { + if (!L.moe) continue; + if (!kernels::native_mmvq_supported((int) L.gu_type) || !kernels::native_mmvq_supported((int) L.u_type) || + !kernels::native_mmvq_supported((int) L.d_type)) { + all = SIZE_MAX; // fill_expert_cache() keeps such a layer's experts in RAM + break; + } + all += (size_t) n_expert_ * (L.gu2() + L.d_bytes); + } + size_t free_b = 0, total_b = 0; + ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); + const size_t margin = size_t(2) << 30; + const bool fits = all != SIZE_MAX && free_b > all + margin; + int cap = opt_.prompt_batch_max > 0 ? opt_.prompt_batch_max : fits ? kAutoRowsAll : kAutoRowsPart; + cap = std::min(cap, opt_.max_context); + if (cap < 2 * rows_) return; + int top = rows_; // a step of the ladder (pick_rows()) + while (2 * top <= cap) top *= 2; + cap = top; + if (grows) { + auto_rows_ = true; // (alloc() says so once it is sure) + cap_rows_ = cap; + return; + } + // one batch for the run: at most 4,096 tokens, as an explicit one (calls of more are tested only where they + // follow the read) + if (all == SIZE_MAX) return; + while (cap > 4096) cap /= 2; + const int q_max = std::max({n_embd_, n_ff_, n_ff_exp_, n_ff_shexp_, widest(), 256}); + const size_t seqs = (size_t) opt_.batch + 1; // each sequence has its own rows and rings + const size_t kv = seqs * card_row_bytes() * (size_t) opt_.max_context; + int b = rows_; + while (2 * b <= cap) b *= 2; + for (; b > rows_; b /= 2) { + const size_t rr = (size_t) b * n_used_, f = sizeof(float); + // the scratch, the experts' buffers (alloc()'s prompt buffers, their products' work at most a gate and up + // product's rows), xq_ and q8_, and the architecture's own + const size_t cost = count_scratch(b) * f + rr * (5 * (size_t) n_ff_exp_ + n_embd_ + 1) * f + + 2 * Mmq::q8_bytes((int64_t) rr, n_embd_) + Mmq::q8_bytes((int64_t) rr, n_ff_exp_) + + Mmq::q8_bytes(b, q_max) + + (size_t) b * (kernels::native_q8_1_bytes(n_embd_) + + kernels::native_q8_1_bytes((q_max + 255) / 256 * 256)) + + seqs * rows_bytes(b); + if (free_b >= all + kv + cost + margin) break; + } +#if defined(STRATA_USE_HIP) + // HIP, where the prompt's buffers are not lent (alloc()): a long read's calls get buffers of their own for the + // read, out of free VRAM and, with experts outside VRAM, out of the expert cache (rows_malloc_, widen_rows()) + // Not under WSL2 (the card through /dev/dxg, no /dev/kfd): there each cut of the cache unmapped, reserved again and + // mapped again every piece it kept, about 4 s (RX 9070 XT: an 8K prompt 711 tok/s in calls of 1,024, 576 this + // way); on native amdgpu the cut took 27-48 ms and the refill 165 ms for 3.8 GiB. Nor on Windows (untested). +#if defined(_WIN32) + const bool native = false; +#else + const bool native = access("/dev/kfd", F_OK) == 0; +#endif + if (b == rows_ && native && vmm_ && opt_.batch == 0 && opt_.window < kStageRows) { + auto_rows_ = rows_malloc_ = true; + cap_rows_ = cap; + std::fprintf(stderr, "strata-poly: prompt batch auto: %d tokens a call, up to %d for a long read\n", rows_, + cap); + return; + } +#endif + std::fprintf(stderr, "strata-poly: prompt batch auto: %d tokens a call%s\n", b, + b > rows_ ? ", every expert fits beside it" : ""); + rows_ = b; +} + +// The widest step of the ladder from base_rows_ (twice as many tokens each) that the read's tokens fill, or fill +// but for a sixteenth: a prompt of 2,048 tokens is read as 2,047, its last token alone for the logits. +int Engine::pick_rows(int want) const { + int b = base_rows_; + while (2 * b <= cap_rows_ && 2 * b - 2 * b / 16 <= want) b *= 2; + // HIP (rows_malloc_): the cut and the refill cost a second or more, which calls of 2,048 do not win back (RX 9070 XT + // under WSL2 with #302's unmap, IQ4_NL: a 2K prompt 1,191 tok/s in calls of 1,024, 669 in calls of 2,048); 4,096 + // or none + if (rows_malloc_ && b < 4 * base_rows_) b = base_rows_; + return b; +} + +// The prompt's buffers (alloc()) for calls of `rows` tokens: the experts' rows (moe_rows()), lin_raw()'s quantized +// input, the batch layout's scratch, and what the products take beside their arguments (Mmq::work(): mmq_own.cu's +// FP16 and BLAS paths: the experts', whose rows go by ids, and lin()'s, with the quantized matrices upload() kept, +// the output's only where a step can have kStageRows rows); with auto_rows_, a batch's xq_ and q8_. +Engine::PromptLayout Engine::prompt_layout(int rows) const { + PromptLayout l; + const size_t rr = (size_t) rows * n_used_; +#if !defined(STRATA_GPU_METAL) + Mmq::Work need; + const auto take = [&](uint32_t type, int64_t w_rows, int64_t w_cols, int64_t m, bool by_ids, int64_t ld) { + const Mmq::Work w = Mmq::work((int) type, w_rows, w_cols, m, by_ids, ld); + need.floats = std::max(need.floats, w.floats); + need.halves = std::max(need.halves, w.halves); + }; + for (const Layer& L : layers_) { + if (!L.mmq) continue; + if (L.mixed()) { + take(L.gu_type, n_ff_exp_, n_embd_, (int64_t) rr, true, 2 * n_ff_exp_); + take(L.u_type, n_ff_exp_, n_embd_, (int64_t) rr, true, 2 * n_ff_exp_); + } else { + take(L.gu_type, 2 * n_ff_exp_, n_embd_, (int64_t) rr, true, 2 * n_ff_exp_); + } + take(L.d_type, n_embd_, n_ff_exp_, (int64_t) rr, true, n_embd_); + } + const int most_step = (opt_.batch + 1) * (opt_.batch_mtp ? 2 : 1); + const bool wide_steps = std::max(opt_.window, most_step) >= kStageRows; + for (const Dev& d : mats_) + if (d.n_in <= q_max_ && (d.p != output_.p || wide_steps)) take(d.type, d.n_out, d.n_in, rows, false, d.n_out); + l.work_floats = need.floats; + l.work_halves = need.halves; +#endif + l.work_bytes = (l.work_floats * sizeof(float) + 255) / 256 * 256 + (l.work_halves * 2 + 255) / 256 * 256; + size_t k = 0; // rows_floats_'s step + for (int b = base_rows_; b < rows; b *= 2) ++k; + // rows_malloc_: a wider read's buffers (rows_wide_) have their scratch, xq_ and q8_ among them; base_rows_' are + // alloc()'s, as without auto + const bool wide = rows_malloc_ && rows > base_rows_, batch_xq = auto_rows_ && (!rows_malloc_ || wide); + const size_t sizes[12] = {rr * 2 * n_ff_exp_ * sizeof(float), rr * n_ff_exp_ * sizeof(float), + rr * n_embd_ * sizeof(float), rr * sizeof(float), + Mmq::q8_bytes((int64_t) rr, n_embd_), Mmq::q8_bytes((int64_t) rr, n_ff_exp_), + mixed_tiles_ ? Mmq::q8_bytes((int64_t) rr, n_embd_) : 0, Mmq::q8_bytes(rows, q_max_), + two_scratch_ || wide ? rows_floats_.at(k) * sizeof(float) : 0, + prompt_lends_ ? 0 : l.work_bytes, + batch_xq ? (size_t) rows * kernels::native_q8_1_bytes(n_embd_) : 0, + batch_xq ? (size_t) rows * kernels::native_q8_1_bytes((q_max_ + 255) / 256 * 256) : 0}; + for (int i = 0; i < 12; ++i) { + l.at[i] = l.total; + l.total += (sizes[i] + 255) / 256 * 256; + } + return l; +} + +void Engine::place_prompt(const PromptLayout& l) { + uint8_t* const base = prompt_base_; + gu_ = (float*) (base + l.at[0]); + hx_ = (float*) (base + l.at[1]); + dx_ = (float*) (base + l.at[2]); + hf_ = (float*) (base + l.at[3]); + mq_ = base + l.at[4]; + mq2_ = base + l.at[5]; + if (mixed_tiles_) mqu_ = base + l.at[6]; + mqx_ = base + l.at[7]; + if (two_scratch_) scratch_batch_ = (float*) (base + l.at[8]); + if (auto_rows_ && !rows_malloc_) { + xq_batch_ = base + l.at[10]; + q8_batch_ = base + l.at[11]; + } +#if !defined(STRATA_GPU_METAL) + uint8_t* w = work_map_.base ? (uint8_t*) work_map_.base : base + l.at[9]; + const size_t floats_bytes = (l.work_floats * sizeof(float) + 255) / 256 * 256; + mmq_->give(l.work_floats ? (float*) w : nullptr, l.work_floats, l.work_halves ? w + floats_bytes : nullptr, + l.work_halves, blas_); +#endif +} + +// A read of `want` tokens with the prompt's buffers taken (take_prompt()): calls of `rows` tokens, or of half as +// many until the VRAM is there, down to what rows_ is. The VRAM comes from what is free (beyond a quarter of the +// reserve, and the attention caches' rows for the read), and only where some experts are outside VRAM from the +// expert cache too, at most three quarters of it: on the RTX 2070 Super calls of 4,096 tokens take 2.5 GiB of its +// 4.4, and read 8K and 32K prompts faster than 2,048's half as much (pb-e2e1, pb-e2e2). Nothing here changes what a call computes, only how many tokens it takes. +bool Engine::widen_rows(int rows, int want) { + if (up_) ck(cudaStreamSynchronize(cs(up_)), "a prompt's buffers"); + ck(cudaStreamSynchronize(cs(st_)), "a prompt's buffers"); + if (rows_malloc_) { + // HIP: the read's buffers and the rings it reads into, allocated now and freed by narrow_rows(). Nothing is + // asked of the card past what it says is free less the margin: under WSL a card asked for more than it has + // does not refuse (it moved memory to RAM, or hung). + const size_t margin = std::max((size_t(std::max(reserve_mib_, 0)) << 20) / 4, size_t(512) << 20); + // A read after a wide one without end_read() between them (a prompt read in pieces) keeps the calls it has + if (rows_wide_) return false; + size_t cut = 0; // what the steps took from the expert cache so far: given back once, if none of them fits + // The free VRAM by the bytes given back: ROCm counts them a moment later (native amdgpu, an RX 9070 XT: 3,884 MiB + // free 31 ms after a 3,840 MiB cut, 4,203 MiB 5 ms later), and a query right after the cut found too little. + size_t counted = 0; + double cut_ms = 0; + for (; rows > rows_; rows /= 2) { + // (pick_rows(): 4,096 or none; 2,048 only on the cut already made for 4,096, where 4,096 did not fit) + if (rows < 4 * base_rows_ && cut == 0) break; + const PromptLayout l = prompt_layout(rows); + const size_t more = l.total + 256 + rows_bytes(rows); + size_t free_b = 0, total_b = 0; + ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); + free_b = std::max(free_b, counted); + size_t keep = margin; + if (all_cached() || !exp_ || freeze_experts_) { // the rows cover() maps for the read stay free too (a frozen + // cache does not give them up) + const int64_t kv_rows = kv_rows_for(pos_ + want); + for (const Kv& k : kv_) { + const size_t b = std::min(up_to((size_t) ((kv_rows + k.per - 1) / k.per) * k.bytes, grain_), k.reserved); + if (b > k.mapped) keep += b - k.mapped; + } + } + if (free_b < more + keep) { + const size_t short_by = more + keep - free_b; + if (!exp_ || all_cached() || freeze_experts_ || cut + short_by > (arena_.mapped + cut) / 4 * 3) continue; + const size_t mapped = arena_.mapped; + const auto t0 = std::chrono::steady_clock::now(); + shrink_cache(short_by); + const size_t got = mapped - arena_.mapped; + cut += got; + counted = free_b + got; + free_b = counted; + cut_ms += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (free_b < more + keep) continue; + } + void* p = nullptr; + if (cudaMalloc(&p, l.total + 256) != cudaSuccess) { + (void) cudaGetLastError(); + continue; + } + const int was = rows_; + rows_ = rows; + try { + resize_rows(was); + } catch (const std::runtime_error&) { + rows_ = was; + ck(cudaFree(p), "a prompt's buffers"); + continue; + } + rows_wide_ = (uint8_t*) p; + rows_cut_ = cut; + if (!pool_on_) budget_ -= std::min(budget_, cut); + prompt_base_ = rows_wide_; + place_prompt(l); + scratch_base_ = scratch_; // the batch's scratch, xq_ and q8_ in the read's buffers + scratch_ = (float*) (rows_wide_ + l.at[8]); + buf_rows_ = rows_; + scratch_at_ = 0; + shared_scratch(); + assign_scratch(); + xq_ = rows_wide_ + l.at[10]; + q8_ = rows_wide_ + l.at[11]; + prompt_scratch_ = true; // no recording made or replayed with these buffers + std::fprintf(stderr, "strata-poly: a read of %d tokens in calls of %d (%zu MiB for the read, %zu MiB of it " + "from the expert cache in %.0f ms)\n", want, rows, more >> 20, cut >> 20, cut_ms); + return true; + } + if (cut > 0) grow_cache(cut, false); + return false; + } + const size_t grain = pool_on_ ? pg_ : grain_; + const PromptLayout had = prompt_layout(rows_); + for (; rows > rows_; rows /= 2) { + const PromptLayout l = prompt_layout(rows); + const size_t pmore = up_to(l.total, grain) > prompt_map_.mapped ? up_to(l.total, grain) - prompt_map_.mapped : 0; + const size_t wmore = work_map_.base && up_to(l.work_bytes, grain) > work_map_.mapped + ? up_to(l.work_bytes, grain) - work_map_.mapped : 0; + const size_t more = pmore + wmore + rows_bytes(rows) - rows_bytes(rows_); + size_t free_b = 0, total_b = 0; + ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); + if (pool_on_) free_b = vpool_bytes(); + const size_t quarter = pool_on_ ? 0 : (size_t(std::max(reserve_mib_, 0)) << 20) / 4; + size_t keep = quarter; // with every expert cached, the rows cover() maps for the read stay free too + if (all_cached() || !exp_ || freeze_experts_) { // (a frozen cache does not give cover() its rows) + const int64_t kv_rows = kv_rows_for(pos_ + want); + for (const Kv& k : kv_) { + const size_t b = std::min(up_to((size_t) ((kv_rows + k.per - 1) / k.per) * k.bytes, grain), k.reserved); + if (b > k.mapped) keep += b - k.mapped; + } + } + size_t cut = 0; + if (free_b < more + keep) { + const size_t short_by = more + keep - free_b; + if (!exp_ || all_cached() || freeze_experts_ || short_by > arena_.mapped / 4 * 3) continue; + const size_t mapped = arena_.mapped; + shrink_cache(short_by); + cut = mapped - arena_.mapped; + } + const int was = rows_; + try { + vmm_map(prompt_map_, l.total, SIZE_MAX, "a prompt's buffers"); + if (work_map_.base && l.work_bytes > 0) vmm_map(work_map_, l.work_bytes, SIZE_MAX, "the prompt products' work memory"); + rows_ = rows; + resize_rows(was); + } catch (const std::runtime_error&) { + rows_ = was; + vmm_unmap(prompt_map_, had.total); + if (work_map_.base) vmm_unmap(work_map_, had.work_bytes); + if (cut > 0) grow_cache(cut, true); + continue; + } + if (!pool_on_) budget_ -= std::min(budget_, cut); + rows_cut_ += cut; + place_prompt(l); + use_scratch(true); + std::fprintf(stderr, "strata-poly: a read of %d tokens in calls of %d (%zu MiB more VRAM, %zu MiB of it " + "from the expert cache)\n", want, rows, more >> 20, cut >> 20); + return true; + } + return false; +} + +// The read is done: calls of base_rows_ again, and the expert cache takes back what widen_rows() took. +void Engine::narrow_rows() { + if (rows_ == base_rows_) return; + if (up_) ck(cudaStreamSynchronize(cs(up_)), "a prompt's buffers"); + ck(cudaStreamSynchronize(cs(st_)), "a prompt's buffers"); + const int was = rows_; + rows_ = base_rows_; + resize_rows(was); + if (rows_malloc_) { // alloc()'s buffers again, and the read's freed + prompt_base_ = prompt_base0_; + place_prompt(prompt_layout(rows_)); + scratch_ = scratch_base_; + buf_rows_ = rows_; + scratch_at_ = 0; + shared_scratch(); + assign_scratch(); + xq_ = xq_few_; + q8_ = q8_few_; + prompt_scratch_ = false; + ck(cudaStreamSynchronize(cs(st_)), "a prompt's buffers"); + ck(cudaFree(rows_wide_), "a prompt's buffers"); + rows_wide_ = nullptr; + if (!pool_on_) budget_ += rows_cut_; + if (exp_ && rows_cut_ > 0) { + const auto t0 = std::chrono::steady_clock::now(); + grow_cache(rows_cut_, false); + ck(cudaStreamSynchronize(cs(st_)), "the expert cache"); + std::fprintf(stderr, "strata-poly: the expert cache took back %zu MiB in %.0f ms\n", rows_cut_ >> 20, + std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + } + rows_cut_ = 0; + return; + } + const PromptLayout l = prompt_layout(rows_); + ck(cudaStreamSynchronize(cs(st_)), "a prompt's buffers"); + vmm_unmap(prompt_map_, l.total); + if (work_map_.base && !work_lent_) vmm_unmap(work_map_, l.work_bytes); + place_prompt(l); + use_scratch(prompt_scratch_); + if (!pool_on_) budget_ += rows_cut_; + // at once, not by the follower while the answer is written: on the RTX 2070 Super after an 8K prompt read in calls + // of 4,096 (2.4 GiB back) the answer's 256 tokens came at 39.7 tokens/s that way and 42.7 this way (main: 42.4), + // for 200 ms more before the first one (UD-Q2_K_XL, pb-e2e3) + if (exp_ && rows_cut_ > 0) grow_cache(rows_cut_, false); + rows_cut_ = 0; +} + +// VRAM of the sequence's own whose size follows rows_ (an architecture's resize_rows()): mapped for `bytes`, with +// addresses for `most`. +size_t Engine::seq_grows(size_t bytes, size_t most, const char* what) { + if (again_ != SIZE_MAX) throw std::logic_error("seq_grows: one sequence only"); + grows_.emplace_back(); + Mapped& m = grows_.back(); + vmm_reserve(m, most); + vmm_map(m, bytes, SIZE_MAX, what); + zero_vram((void*) m.base, m.mapped); + bufs_.push_back({(void*) m.base, bytes, 0}); + return grows_.size() - 1; +} + // The cache's VRAM and the attention caches' as they are now become the budget cover() keeps them to. void Engine::held_is_budget() { budget_ = arena_.mapped + other_rows(); @@ -3248,8 +3668,16 @@ void Engine::load(const Options& o) { if ((!opt_.kv_grow || opt_.batch > 0) && opt_.kv_resident > 0) opt_.kv_resident = 0; asked_reserve_mib_ = o.vram_reserve_mib; if (opt_.max_context < 16) throw std::runtime_error("the context must be at least 16 tokens"); - if (opt_.prompt_batch < 1 || opt_.prompt_batch > 4096) - throw std::runtime_error("a prompt batch is 1 to 4096 tokens"); + if (opt_.prompt_batch < 0 || opt_.prompt_batch > kMostRows) + throw std::runtime_error("a prompt batch is 1 to " + std::to_string(kMostRows) + " tokens, or auto"); + if (opt_.prompt_batch_max != 0 && (opt_.prompt_batch_max < 1024 || opt_.prompt_batch_max > kMostRows)) + throw std::runtime_error("the most tokens an automatic prompt batch takes is 1024 to " + + std::to_string(kMostRows)); + // Options::prompt_batch 0: the batch alloc() settles on, from 1,024 + auto_asked_ = opt_.prompt_batch == 0; + if (auto_asked_) opt_.prompt_batch = 1024; + // calls of more than 4,096 tokens only where auto takes them (CUDA, every expert in VRAM) + if (opt_.prompt_batch > 4096) throw std::runtime_error("a prompt batch is 1 to 4096 tokens, or auto"); if (opt_.stage_mib < 0) throw std::runtime_error("the staging buffer must be at least 1 MiB (0: the default)"); if (opt_.stage_ahead < 0) throw std::runtime_error("the batch size to stage ahead from cannot be negative"); if (opt_.expert_swaps < -1 || opt_.expert_swaps > 64) @@ -3779,12 +4207,21 @@ void Engine::use_scratch(bool batch) { shared_scratch(); assign_scratch(); prompt_scratch_ = batch; + if (auto_rows_ && !rows_malloc_) { + xq_ = batch ? xq_batch_ : xq_few_; + q8_ = batch ? q8_batch_ : q8_few_; + } } // The sequence's state, the caches and every buffer, once the weights are known. void Engine::alloc() { // --dump-layers prints one token's stages rows_ = opt_.dump ? 1 : std::min(opt_.prompt_batch, opt_.max_context); + auto_rows_ = false; + cap_rows_ = rows_; + if (auto_asked_ && auto_rows() && !opt_.dump && rows_ >= kStageRows) auto_batch(); + base_rows_ = rows_; + if (!auto_rows_) cap_rows_ = rows_; // one batch for the run (auto_batch() may have widened it) const size_t most = std::min(kReadBytes / ((size_t) streams() * n_embd_ * sizeof(float)), opt_.max_context); read_rows_ = rows_ < kStageRows ? rows_ : std::max(rows_, (int) most / rows_ * rows_); rec_n_ = recurrent_floats(); @@ -3856,6 +4293,8 @@ void Engine::alloc() { shared_scratch(); // the first pass only counts assign_scratch(); const size_t batch_floats = scratch_at_; + rows_floats_.assign(1, batch_floats); + for (int b = 2 * rows_; auto_rows_ && b <= cap_rows_; b *= 2) rows_floats_.push_back(count_scratch(b)); // The scratch in two layouts where the prompt's buffers are lent (below) and the architecture can: the one for // a prompt's batch is lent with them, and a call of a few tokens has a layout of its own. At a prompt batch of // 2,048 Qwen3.6's scratch is 450 MB, of which the few tokens' layout keeps some 70 (the attention's scores). @@ -3870,6 +4309,11 @@ void Engine::alloc() { #endif two_scratch_ = scratch_layouts() && mmq_ && vmm_ && !split_ && rows_ >= kStageRows && std::max(opt_.window, most_step) < kStageRows && lends; + if (auto_rows_ && !two_scratch_ && !rows_malloc_) { // one batch (the window layers' rings have addresses for more) + auto_rows_ = false; + cap_rows_ = rows_; + rows_floats_.resize(1); + } if (two_scratch_) { buf_rows_ = kStageRows - 1; scratch_at_ = 0; @@ -3884,103 +4328,66 @@ void Engine::alloc() { } const int q_max = std::max({n_embd_, n_ff_, n_ff_exp_, n_ff_shexp_, widest(), 256}); - xq_ = dmalloc(n * kernels::native_q8_1_bytes(n_embd_), "scratch"); - q8_ = dmalloc(n * kernels::native_q8_1_bytes((q_max + 255) / 256 * 256), "scratch"); - - h_r_ = (float*) hmalloc(n * streams() * n_embd_ * sizeof(float), "pinned memory"); + q_max_ = q_max; + mixed_tiles_ = mixed_tiles; + // auto_rows_: a call of a few tokens has xq_ and q8_ of its own, and a batch's are in the prompt's buffers + const size_t nx = auto_rows_ && !rows_malloc_ ? (size_t) kStageRows : n, nc = (size_t) cap_rows_; + xq_ = dmalloc(nx * kernels::native_q8_1_bytes(n_embd_), "scratch"); + q8_ = dmalloc(nx * kernels::native_q8_1_bytes((q_max + 255) / 256 * 256), "scratch"); + xq_few_ = xq_; + q8_few_ = q8_; + + h_r_ = (float*) hmalloc(nc * streams() * n_embd_ * sizeof(float), "pinned memory"); const size_t at_rows = (size_t) std::max(opt_.window, opt_.batch + 1); // window()'s tokens, step()'s at_ = (long long*) dmalloc(at_rows * 2 * sizeof(long long), "scratch"); h_at_ = (long long*) hmalloc(at_rows * 2 * sizeof(long long), "pinned memory"); - h_rl_ = (float*) hmalloc(n * n_expert_ * sizeof(float), "pinned memory"); - h_x_ = (float*) hmalloc(n * n_embd_ * sizeof(float), "pinned memory"); - h_cpu_ = (float*) hmalloc(n * n_embd_ * sizeof(float), "pinned memory"); + h_rl_ = (float*) hmalloc(nc * n_expert_ * sizeof(float), "pinned memory"); + h_x_ = (float*) hmalloc(nc * n_embd_ * sizeof(float), "pinned memory"); + h_cpu_ = (float*) hmalloc(nc * n_embd_ * sizeof(float), "pinned memory"); h_logits_ = (float*) hmalloc((size_t) n_vocab_ * sizeof(float), "pinned memory"); if (mmq_) { - const size_t rr = n * n_used_, + const size_t rr = nc * n_used_, tab = (3 * rr + 3 * (size_t) n_expert_ + 3 + kClasses * ((size_t) n_expert_ + 1) + 2 * kMaxStagedTiles * (2 * (size_t) n_expert_ + 2)) * sizeof(int32_t); - // What the products take beside their arguments (Mmq::work(): mmq_own.cu's FP16 and BLAS paths): the - // experts', whose rows go by ids, and lin()'s, with the quantized matrices upload() kept, the output's only - // where a step can have kStageRows rows. Made by the products themselves, it came out of the reserve the - // expert cache leaves, while a prompt was read: with less than that free, the first long prompt failed. - // Where the prompt's buffers are lent, it has addresses of its own (work_map_), mapped only while a prompt - // is read (take_prompt()), as those buffers are: the expert cache has it until the first prompt and between - // prompts. Elsewhere it is one of those buffers, for good. - Mmq::Work need; -#if !defined(STRATA_GPU_METAL) - const auto take = [&](uint32_t type, int64_t w_rows, int64_t w_cols, int64_t rows, bool by_ids, int64_t ld) { - const Mmq::Work w = Mmq::work((int) type, w_rows, w_cols, rows, by_ids, ld); - need.floats = std::max(need.floats, w.floats); - need.halves = std::max(need.halves, w.halves); - }; - for (const Layer& L : layers_) { - if (!L.mmq) continue; - if (L.mixed()) { - take(L.gu_type, n_ff_exp_, n_embd_, (int64_t) rr, true, 2 * n_ff_exp_); - take(L.u_type, n_ff_exp_, n_embd_, (int64_t) rr, true, 2 * n_ff_exp_); - } else { - take(L.gu_type, 2 * n_ff_exp_, n_embd_, (int64_t) rr, true, 2 * n_ff_exp_); - } - take(L.d_type, n_embd_, n_ff_exp_, (int64_t) rr, true, n_embd_); - } - const bool wide_steps = std::max(opt_.window, most_step) >= kStageRows; - for (const Dev& d : mats_) - if (d.n_in <= q_max && (d.p != output_.p || wide_steps)) - take(d.type, d.n_out, d.n_in, rows_, false, d.n_out); -#endif - const size_t floats_bytes = (need.floats * sizeof(float) + 255) / 256 * 256, - work = floats_bytes + (need.halves * 2 + 255) / 256 * 256; // The buffers only a call of kStageRows rows or more uses (moe_rows(), lin_raw()'s products), side by side: // where they can be mapped apart (VMM) and the answer's calls never have that many rows, the expert cache // has their VRAM between prompts (lend_prompt()), 300 MB of Qwen3.6's at a prompt batch of 2,048. Not on ROCm // on Linux, which gives VRAM back only with its addresses (vmm_unmap()), as the staging buffer's widening is // not: with the buffers lent, strata-poly crashed (SIGSEGV inside hipLaunchKernel, the dequantize launch of a // prompt's dense product into the lent work memory) in 15 of 16 runs of Inkling 2 Mini IQ4_NL on an RX 9070 XT - // with 2,443 of its 3,072 experts in VRAM, ROCm 7.2.4. + // with 2,443 of its 3,072 experts in VRAM, ROCm 7.2.4. (Their sizes: prompt_layout().) prompt_lends_ = lends; - const size_t sizes[] = {rr * 2 * n_ff_exp_ * sizeof(float), rr * n_ff_exp_ * sizeof(float), - rr * n_embd_ * sizeof(float), rr * sizeof(float), - Mmq::q8_bytes((int64_t) rr, n_embd_), Mmq::q8_bytes((int64_t) rr, n_ff_exp_), - mixed_tiles ? Mmq::q8_bytes((int64_t) rr, n_embd_) : 0, Mmq::q8_bytes(rows_, q_max), - two_scratch_ ? batch_floats * sizeof(float) : 0, prompt_lends_ ? 0 : work}; - size_t at[10], total = 0; - for (int i = 0; i < 10; ++i) { - at[i] = total; - total += (sizes[i] + 255) / 256 * 256; - } + const PromptLayout lay = prompt_layout(rows_); uint8_t* base = nullptr; if (prompt_lends_) { - vmm_reserve(prompt_map_, total); - vmm_map(prompt_map_, total, SIZE_MAX, "a prompt's buffers"); + // auto_rows_: addresses for the widest batch, VRAM for base_rows_ (widen_rows() maps more) + vmm_reserve(prompt_map_, auto_rows_ ? prompt_layout(cap_rows_).total : lay.total); + vmm_map(prompt_map_, lay.total, SIZE_MAX, "a prompt's buffers"); base = (uint8_t*) prompt_map_.base; - prompt_bytes_ = total; + prompt_bytes_ = lay.total; } else { - base = (uint8_t*) dmalloc(total, "scratch"); - } - gu_ = (float*) (base + at[0]); - hx_ = (float*) (base + at[1]); - dx_ = (float*) (base + at[2]); - hf_ = (float*) (base + at[3]); - mq_ = base + at[4]; - mq2_ = base + at[5]; - if (mixed_tiles) mqu_ = base + at[6]; - mqx_ = base + at[7]; - if (two_scratch_) { - scratch_batch_ = (float*) (base + at[8]); - use_scratch(false); + base = (uint8_t*) dmalloc(lay.total, "scratch"); } + prompt_base_ = prompt_base0_ = base; #if !defined(STRATA_GPU_METAL) - uint8_t* w = base + at[9]; - if (prompt_lends_ && work > 0) { - work_bytes_ = up_to(work, grain_); - vmm_reserve(work_map_, work_bytes_); - w = (uint8_t*) work_map_.base; + // What the products take beside their arguments (prompt_layout()). Made by the products themselves, it came + // out of the reserve the expert cache leaves, while a prompt was read: with less than that free, the first + // long prompt failed. Where the prompt's buffers are lent, it has addresses of its own (work_map_), mapped + // only while a prompt is read (take_prompt()), as those buffers are: the expert cache has it until the first + // prompt and between prompts. Elsewhere it is one of those buffers, for good. + if (prompt_lends_ && lay.work_bytes > 0) { + work_bytes_ = up_to(lay.work_bytes, grain_); + vmm_reserve(work_map_, auto_rows_ ? up_to(prompt_layout(cap_rows_).work_bytes, grain_) : work_bytes_); work_lent_ = true; } - mmq_->give(need.floats ? (float*) w : nullptr, need.floats, need.halves ? w + floats_bytes : nullptr, - need.halves, blas_); #endif + place_prompt(lay); + if (two_scratch_) use_scratch(false); + if (auto_rows_ && !rows_malloc_) + std::fprintf(stderr, "strata-poly: prompt batch auto: %d tokens a call, up to %d for a long read (the " + "prompt's buffers %zu MiB, %zu MiB at %d)\n", + rows_, cap_rows_, lay.total >> 20, prompt_layout(cap_rows_).total >> 20, cap_rows_); d_ids_ = (int32_t*) dmalloc(rr * sizeof(int32_t), "scratch"); d_wts_ = (float*) dmalloc(rr * sizeof(float), "scratch"); h_ids_ = (int32_t*) hmalloc(rr * sizeof(int32_t), "pinned memory"); @@ -7968,13 +8375,13 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, if (n < (n_co > 0 ? 0 : 1) || all > read_rows_) throw std::logic_error("read takes 1 to max_read() tokens, co-reads among them"); lock_idle_.store(false, std::memory_order_relaxed); - if (all >= kStageRows) take_prompt(); for (const Image& im : images_) if (im.at < pos_ + n && im.at + im.n > pos_) throw std::logic_error("read takes no rows of a picture: eval() does, a picture a call"); for (int k = 0; k < n_marks; ++k) if (marks[k].at <= (k ? marks[k - 1].at : 0) || marks[k].at >= n) throw std::logic_error("read: the marks rise, above 0 and below the tokens read"); + if (all >= kStageRows) take_prompt(all); // the calls: up to max_rows() tokens each, and none across a mark; then each co-read's, from its row 0 calls_.clear(); @@ -8304,7 +8711,9 @@ bool Engine::read_groups(const Mark* marks, int n_marks, const std::function kArenaPiece ? arena_.mapped - kArenaPiece : 0); int g = (int) std::min((size_t) n_calls, room / (per * sizeof(float))); float* base = nullptr; - const size_t most = (size_t) ((read_rows_ + rows_ - 1) / rows_) * per * sizeof(float); + // (auto_rows_: addresses for any batch's calls, the first read's or a wider one's) + const size_t most = auto_rows_ ? (size_t) (read_rows_ + cap_rows_) * (per / rows_) * sizeof(float) + : (size_t) ((read_rows_ + rows_ - 1) / rows_) * per * sizeof(float); for (; g > 1 && !(base = carry_take((size_t) g * per * sizeof(float), most)); g = (g + 1) / 2) { } g = std::max(g, 1); diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e27454..d03dcdb6b 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -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 @@ -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); @@ -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(); } @@ -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. @@ -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 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 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 @@ -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 { diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index c20d37404..db6e1b5ea 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -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 } @@ -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 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 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_); } @@ -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); @@ -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); diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 9b3b44293..611fafb9d 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -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 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 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; diff --git a/engine/src/poly/inkling2_pictures.cpp b/engine/src/poly/inkling2_pictures.cpp index 5643a9e14..8dcdb0733 100644 --- a/engine/src/poly/inkling2_pictures.cpp +++ b/engine/src/poly/inkling2_pictures.cpp @@ -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; diff --git a/engine/src/poly/logits_dump.cpp b/engine/src/poly/logits_dump.cpp index 35a7d6497..030276b23 100644 --- a/engine/src/poly/logits_dump.cpp +++ b/engine/src/poly/logits_dump.cpp @@ -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" @@ -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; diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index e7eff913c..662b4a528 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -1698,7 +1698,11 @@ void usage() { " --lock-experts keep the experts outside VRAM in RAM, so the system cannot give it to other\n" " programs: copied into pinned memory for the card where the RAM that is free\n" " holds them, else their pages in the model file locked (Linux: up to ulimit -l)\n" - " --prompt-batch N prompt tokens read at a time (default 1024); about 1.4 MiB of VRAM each\n" + " --prompt-batch N|auto|auto:N prompt tokens read at a time; about 1.4 MiB of VRAM each. auto\n" + " (the default): Inkling 2 on one CUDA card reads a long prompt in calls\n" + " of up to 4096, out of the expert cache while it is read (8192 where every\n" + " expert fits in VRAM); on ROCm one batch up to 4096 where every expert\n" + " fits beside it; else 1024. auto:N: up to N\n" " --stage-mib N VRAM the experts outside the cache pass through in a prompt batch (default\n" " 128 on an NVIDIA card where a longer read widens it, else 2048; never more\n" " than a layer's experts take); with less, more of them are copied after the\n" @@ -1824,6 +1828,7 @@ int main(int argc, char** argv) { } #endif Options o; + o.prompt_batch = 0; // auto: by the VRAM where the model can (else 1024) CacheFlags cache; Sampling s; bool want_serve = false; @@ -1909,7 +1914,21 @@ int main(int argc, char** argv) { else if (a == "--check-batch") check = std::atoi(val()); else if (a == "--check-stagger") stagger = true; else if (a == "--draft-vocab") o.draft_vocab = std::atoi(val()); - else if (a == "--prompt-batch") o.prompt_batch = std::atoi(val()); + else if (a == "--prompt-batch") { + const std::string v = val(); + if (v.rfind("auto", 0) == 0) { // auto, or auto:N for at most N tokens a call + o.prompt_batch = 0; + char* end = nullptr; + o.prompt_batch_max = v.size() > 5 && v[4] == ':' ? (int) std::strtol(v.c_str() + 5, &end, 10) : 0; + if (v.size() > 4 && (v[4] != ':' || o.prompt_batch_max < 1 || (end && *end))) + throw std::runtime_error("--prompt-batch takes N, auto or auto:N"); + } else { + char* end = nullptr; + o.prompt_batch = (int) std::strtol(v.c_str(), &end, 10); + if (o.prompt_batch < 1 || end == v.c_str() || *end) + throw std::runtime_error("--prompt-batch takes N, auto or auto:N"); + } + } else if (a == "--stage-mib") o.stage_mib = std::atoi(val()); else if (a == "--stage-ahead") o.stage_ahead = std::atoi(val()); else if (a == "--stage-read-mib") o.stage_read_mib = std::atoi(val());