diff --git a/src/dsv41/ds4_iq.cu b/src/dsv41/ds4_iq.cu index e5f66887..7de79b4e 100644 --- a/src/dsv41/ds4_iq.cu +++ b/src/dsv41/ds4_iq.cu @@ -1278,7 +1278,54 @@ void mv_nc(const Jobs& J, int nj, int max_n, int max_c, cudaStream_t s) { // ---------------------------------------------------------------- whole matrices as 16-bit rows (the chunked prompt's GEMMs) // n rows of k values from `raw` (ld bytes a row): one thread a 32-value sub-block, the sub-block's codes and scales from decode<> -// (value = d s q - m of its half, ggml's dequantize_row_*), rounded to BF16 (bf16) or F16 +// (value = d s q - m of its half, ggml's dequantize_row_*), rounded to BF16 (bf16) or F16. +// The 32 values go through shared memory and are written coalesced (a warp's 32 threads cover 1024 contiguous values): a +// thread writing its own 32 values straight to dst wrote 2 bytes every 64 (a warp's store touches 32 cache lines), which +// measured 0.5 G weights/s on the R9700 - the 8K prompt's q_b stage 4 s. DS4_DQ_OLD=1 keeps the old kernel for A/B. +template +__global__ void __launch_bounds__(kThreads) dq_rows_kernel2(const uint8_t* __restrict__ raw, size_t ld, int k, int n, + uint16_t* __restrict__ dst, bool bf16) { + __shared__ uint32_t tab[Ty::TAB > 0 ? Ty::TAB : 1]; + __shared__ uint16_t sm[kThreads * 32]; + load_tab(tab); + __syncthreads(); + const int nsb = k / 32; + const size_t total = (size_t) n * (size_t) nsb; // 32-value sub-blocks + const size_t vals = (size_t) n * (size_t) k; + for (size_t base = (size_t) blockIdx.x * kThreads; base < total; base += (size_t) gridDim.x * kThreads) { + const size_t i = base + threadIdx.x; + uint16_t* o = sm + threadIdx.x * 32; + if (i < total) { + const size_t r = i / (size_t) nsb; + const int kb = (int) (i - r * (size_t) nsb); + Sub sb; + sb.m0 = sb.m1 = 0.0f; + decode(raw + r * ld, kb, tab, sb); + const float d0 = __fmul_rn(sb.d, (float) sb.s0), d1 = __fmul_rn(sb.d, (float) sb.s1); +#pragma unroll + for (int j = 0; j < 32; ++j) { + const int q = (int) (int8_t) ((uint32_t) sb.q[j >> 2] >> (8 * (j & 3))); + const float v = j < 16 ? __fsub_rn(__fmul_rn(d0, (float) q), sb.m0) : __fsub_rn(__fmul_rn(d1, (float) q), sb.m1); + o[j] = bf16 ? strata::ds4::bf16_rn(v) : __half_as_ushort(__float2half_rn(v)); + } + } else { +#pragma unroll + for (int j = 0; j < 32; ++j) o[j] = 0; + } + __syncthreads(); + // sm[m] is the block's value m (the sub-blocks are contiguous in the row-major output, rows included): write it + // a thread's 32 values apart, so a warp's stores are 512 contiguous bytes each + const size_t go = base * 32; + uint16_t* d = dst + go; +#pragma unroll + for (int j = 0; j < 32; ++j) { + const size_t m = (size_t) j * kThreads + threadIdx.x; + if (go + m < vals) d[m] = sm[m]; + } + __syncthreads(); + } +} + template __global__ void __launch_bounds__(kThreads) dq_rows_kernel(const uint8_t* __restrict__ raw, size_t ld, int k, int n, uint16_t* __restrict__ dst, bool bf16) { @@ -1309,7 +1356,13 @@ __global__ void __launch_bounds__(kThreads) dq_rows_kernel(const uint8_t* __rest bool dequant_rows(int type, const void* raw, size_t ld, int k, int n, uint16_t* dst, bool bf16, cudaStream_t s) { if (raw == nullptr || k % 256 != 0 || n <= 0) return false; const unsigned blocks = (unsigned) std::min(((size_t) n * (size_t) (k / 32) + kThreads - 1) / kThreads, 65535); -#define DS4_DQ(T) dq_rows_kernel<<>>((const uint8_t*) raw, ld, k, n, dst, bf16) + static const bool old = std::getenv("DS4_DQ_OLD") != nullptr && std::atoi(std::getenv("DS4_DQ_OLD")) != 0; +#define DS4_DQ(T) do { \ + if (old) \ + dq_rows_kernel<<>>((const uint8_t*) raw, ld, k, n, dst, bf16); \ + else \ + dq_rows_kernel2<<>>((const uint8_t*) raw, ld, k, n, dst, bf16); \ + } while (0) switch (type) { case kIQ2_XXS: DS4_DQ(kIQ2_XXS); break; case kIQ2_XS: DS4_DQ(kIQ2_XS); break; diff --git a/src/dsv41/ds4_kernels.cu b/src/dsv41/ds4_kernels.cu index 394dd7f7..ff2aefeb 100644 --- a/src/dsv41/ds4_kernels.cu +++ b/src/dsv41/ds4_kernels.cu @@ -6,6 +6,7 @@ #include "ds4_numerics.cuh" #include "ds4_q6k.cuh" #include "ds4_attn_split.cuh" +#include "ds4_wmma.cuh" #include @@ -1128,6 +1129,164 @@ __global__ void __launch_bounds__(kThreads) sparse_attn_packed_kernel(const floa } } +// DS4_FAST_ATTN=1: the chunked prompt's packed-KV attention on the matrix cores (gfx11/gfx12 WMMA; the R9700's gfx12). +// The matrix's rows are 16 heads of ONE query, so a block stages a 16-key tile once for all of them: Q (16 heads x 512 +// dims) is the A operand of the scores' product, the key tile is B, and the same tile is B of the values' product (the +// heads' softmaxes and their 512-dim outputs are its rows). The QK and PV sums are the matrix cores' order, not +// sparse_attn_packed_kernel's scalar lanes' - hence opt-in (DS4_FAST_ATTN). +// (HIP only: the CUDA build keeps the scalar kernels, so this and the dispatch below compile out there.) +#if defined(STRATA_USE_HIP) +constexpr int kFaHeads = 16; // heads a tile (the matrix's rows) +constexpr int kFaKeys = 16; // keys a tile +constexpr int kFaD = 512; // the head dim +constexpr int kFaLd = 520; // halves a tile row (512 + 8: the pad keeps the 16 rows off one bank) +__global__ void __launch_bounds__(kThreads) sparse_attn_wmma_kernel(const float* __restrict__ q, + const uint16_t* __restrict__ win, + const uint8_t* __restrict__ ckv, + const int* __restrict__ sel, int sel_stride, + AttnRows ar, const float* __restrict__ sink, + int heads, float scale, float* __restrict__ out) { + __shared__ __align__(16) uint16_t qs[kFaHeads * kFaLd]; + __shared__ __align__(16) uint16_t ks[kFaKeys * kFaLd]; + __shared__ float sc[kFaHeads][kFaKeys]; + __shared__ float part[8][kFaHeads][kFaKeys]; // (the 8 warps' 64-dim slices of the scores) + __shared__ uint16_t ps[kFaHeads][kFaKeys]; + __shared__ const uint8_t* rows[kFaKeys]; + __shared__ float m_run[kFaHeads], den[kFaHeads], ts[kFaHeads]; + const int tid = (int) threadIdx.x, wp = tid >> 5, lane = tid & 31, l16 = lane & 15, hi = lane >> 4; + const int t = blockIdx.y, hb = blockIdx.x * kFaHeads; + int n_win, n_sel, w0; + if (ar.gen) { + const long long ta = ar.t0 + t, pa = ar.p0 + ta; + const long long first = max((long long) ar.win - ar.p0, ta + 1); + w0 = (int) first; + n_win = (int) (ar.win + ta - first + 1); + n_sel = ar.R > 0 ? (int) min((long long) ar.kcap, (pa + 1) / ar.R) : 0; + } else { + n_win = ar.nwin[t], n_sel = ar.nsel[t], w0 = ar.win0[t]; + } + const uint16_t* wbase = win + (size_t) w0 * kFaD; + const int* sl = sel + (size_t) t * sel_stride; + const size_t crow = kv_row_bytes(kKvFp4, kFaD); + // the block's 16 heads' queries as FP16 (the matrix's A operand), and their running softmax state + for (int i = tid; i < kFaHeads * kFaD; i += kThreads) { + const int h = i / kFaD, c = i % kFaD; + qs[h * kFaLd + c] = __builtin_bit_cast(uint16_t, (_Float16) q[((size_t) t * heads + hb + h) * kFaD + c]); + } + if (tid < kFaHeads) { + m_run[tid] = -1e30f; + den[tid] = 0.0f; + } + f8v o[4]; +#pragma unroll + for (int f = 0; f < 4; ++f) +#pragma unroll + for (int i = 0; i < 8; ++i) o[f][i] = 0.0f; + __syncthreads(); + auto stage = [&](int t0, int n) { // the tile's n rows into ks (BF16 rows -> FP16) + const int sr = tid >> 4, part = tid & 15; + if (sr >= n) return; + const uint8_t* row = rows[sr]; + uint16_t tmp[32]; + if (t0 + sr < n_win) { + const uint4* src = (const uint4*) (row + part * 64); + const uint4 a = src[0], b = src[1], c = src[2], d = src[3]; + ((uint4*) tmp)[0] = a; + ((uint4*) tmp)[1] = b; + ((uint4*) tmp)[2] = c; + ((uint4*) tmp)[3] = d; + } else { + unpack32(row, part, (uint4*) tmp); + } + uint16_t* dst = ks + sr * kFaLd + part * 32; +#pragma unroll + for (int i = 0; i < 32; ++i) dst[i] = __builtin_bit_cast(uint16_t, (_Float16) bf16f(tmp[i])); + }; + const int total = n_win + n_sel; + for (int t0 = 0; t0 < total; t0 += kFaKeys) { + const int nt = min(kFaKeys, total - t0); + if (tid < nt) { + const int j = t0 + tid; + rows[tid] = j < n_win ? (const uint8_t*) (wbase + (size_t) j * kFaD) : ckv + (size_t) sl[j - n_win] * crow; + } + __syncthreads(); + stage(t0, nt); + __syncthreads(); + { // the scores in 8 slices of 64 dims, a warp a slice, summed in shared + f8v acc = {0, 0, 0, 0, 0, 0, 0, 0}; + const int k0 = wp * 64; + for (int kk = k0; kk < k0 + 64; kk += 16) { + h16v a, b; + const uint32_t* qa = (const uint32_t*) (qs + l16 * kFaLd + kk); + const uint32_t* kb = (const uint32_t*) (ks + l16 * kFaLd + kk); +#pragma unroll + for (int i = 0; i < 8; ++i) { // (two halves a load) + a[2 * i] = __builtin_bit_cast(_Float16, (uint16_t) (qa[i] & 0xffffu)); + a[2 * i + 1] = __builtin_bit_cast(_Float16, (uint16_t) (qa[i] >> 16)); + b[2 * i] = __builtin_bit_cast(_Float16, (uint16_t) (kb[i] & 0xffffu)); + b[2 * i + 1] = __builtin_bit_cast(_Float16, (uint16_t) (kb[i] >> 16)); + } + acc = set_wmma(a, b, acc); + } +#pragma unroll + for (int i = 0; i < 8; ++i) part[wp][set_wmma_row(i, hi)][l16] = acc[i]; + __syncthreads(); + const int h = tid >> 4, k = tid & 15; + float a = 0.0f; +#pragma unroll + for (int w = 0; w < 8; ++w) a += part[w][h][k]; + sc[h][k] = t0 + k < total ? a * scale : -INFINITY; + } + __syncthreads(); + { // the online softmax: a warp per 2 heads, a lane a key (16 lanes a head) + const int h = 2 * wp + (lane >> 4), k = lane & 15; + float m = sc[h][k]; +#pragma unroll + for (int o = 8; o > 0; o >>= 1) m = fmaxf(m, __shfl_xor_sync(0xffffffffu, m, o)); + const float mo = m_run[h], mn = fmaxf(mo, m); + const float p = expf(sc[h][k] - mn); + ps[h][k] = __builtin_bit_cast(uint16_t, (_Float16) p); + float s = p; +#pragma unroll + for (int o = 8; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if (k == 0) { + ts[h] = expf(mo - mn); + den[h] = den[h] * ts[h] + s; + m_run[h] = mn; + } + } + __syncthreads(); + const int dim0 = wp * 64; +#pragma unroll + for (int f = 0; f < 4; ++f) +#pragma unroll + for (int i = 0; i < 8; ++i) o[f][i] *= ts[set_wmma_row(i, hi)]; +#pragma unroll + for (int f = 0; f < 4; ++f) { // the values: P (16 heads x 16 keys) x V (16 keys x 64 dims this warp) + h16v a, b; + const uint32_t* pp = (const uint32_t*) ps[l16]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + a[2 * i] = __builtin_bit_cast(_Float16, (uint16_t) (pp[i] & 0xffffu)); + a[2 * i + 1] = __builtin_bit_cast(_Float16, (uint16_t) (pp[i] >> 16)); + b[2 * i] = __builtin_bit_cast(_Float16, ks[(2 * i) * kFaLd + dim0 + f * 16 + l16]); + b[2 * i + 1] = __builtin_bit_cast(_Float16, ks[(2 * i + 1) * kFaLd + dim0 + f * 16 + l16]); + } + o[f] = set_wmma(a, b, o[f]); + } + __syncthreads(); + } +#pragma unroll + for (int f = 0; f < 4; ++f) +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int h = set_wmma_row(i, hi), dm = wp * 64 + f * 16 + l16; + const float dv = den[h] + expf(sink[hb + h] - m_run[h]); + out[((size_t) t * heads + hb + h) * kFaD + dm] = o[f][i] / dv; + } +} +#endif // STRATA_USE_HIP + // the ring's rows are kKvFp8: E4M3 codes, a UE8M0 scale per 32 (decoded: exactly the BF16 values they were made from) __global__ void ring_to_ext_kernel(const uint8_t* __restrict__ ring, uint16_t* __restrict__ ext, long long p0, int n, int d) { @@ -1866,6 +2025,16 @@ bool split_enabled() { }(); return on; } +// DS4_FAST_ATTN=1: the chunked prompt's packed-KV attention on the matrix cores (sparse_attn_wmma_kernel). Opt-in: the +// QK/PV sums are the matrix cores' order, so the outputs differ from the scalar kernel's in the last places (the owner +// approved the trade for the prefill; the decode path stays on the scalar kernels). +bool fast_attn_enabled() { + static const bool on = [] { + const char* e = std::getenv("DS4_FAST_ATTN"); + return e != nullptr && std::atoi(e) != 0; + }(); + return on; +} attnsplit::AttnSplitScratch split_scratch(cudaStream_t s, int heads) { static std::mutex mu; static std::map, attnsplit::AttnSplitScratch> m; @@ -2121,9 +2290,17 @@ void sparse_attn(const float* q, const uint16_t* win, const void* ckv, const int heads, d, scale, out); return; } + // DS4_FAST_ATTN=1: the chunked prompt's matrix-core path (16 heads a block, a 16-key tile). The decode and the + // verify windows keep the scalar kernels: one query's heads are not the matrix's rows there. +#if defined(STRATA_USE_HIP) + if (fast_attn_enabled() && a.gen != 0 && T >= kFaKeys && heads % kFaHeads == 0) { + sparse_attn_wmma_kernel<<>>(q, win, (const uint8_t*) ckv, sel, sel_stride, + a, sink, heads, scale, out); + return; + } +#endif // packed rows: as many heads a block as still leaves two blocks a multiprocessor (a decoded row serves them all) - int G = heads_per_block; - if (G != 1 && G != 2 && G != 4 && G != 8) { + int G = heads_per_block; if (G != 1 && G != 2 && G != 4 && G != 8) { G = 8; while (G > 1 && (heads % G != 0 || (heads / G) * T < 2 * sm_count())) G /= 2; } diff --git a/src/dsv41/ds4_model.cu b/src/dsv41/ds4_model.cu index 9e983c6f..c926030e 100644 --- a/src/dsv41/ds4_model.cu +++ b/src/dsv41/ds4_model.cu @@ -1267,7 +1267,10 @@ struct Model::Impl { for (std::thread& t : cache_ths) if (t.joinable()) t.join(); if (ram_th.joinable()) ram_th.join(); - for (size_t i = 0; i < ram_chunks.size(); ++i) os::anon_free(ram_chunks[i], ram_chunk_bytes[i]); + for (size_t i = 0; i < ram_chunks.size(); ++i) { + if (ram_pinned) (void) cudaHostUnregister(ram_chunks[i]); + os::anon_free(ram_chunks[i], ram_chunk_bytes[i]); + } for (Dev& d : devs) { cudaSetDevice(d.id); for (void* p : d.allocs) cudaFree(p); @@ -2973,6 +2976,14 @@ struct Model::Impl { const size_t C = (size_t) chunk; c.C = chunk; c.A = std::max(64, (int) (((size_t) 8 << 20) / (size_t) HQ) / 64 * 64); + // DS4_ATTN_SLAB=N: the attention slab's rows. The dense projections (q_b, wo_a/b) are dequantized and GEMM'd + // once a slab, so a slab of 256 rows dequantizes the same weights 32 times for an 8K prompt (measured: the + // dense dequant 916 ms of the 8K prompt, rocBLAS 867 ms); a larger slab costs VRAM for c.q/c.o and the oa + // buffers (A * HQ x 4 bytes each). + if (const char* v = std::getenv("DS4_ATTN_SLAB")) { + const int a = std::atoi(v); + if (a > 0) c.A = std::max(64, std::min(chunk, a) / 64 * 64); + } // (the indexer's slab: its scores rows are the context wide - about 64 MB of them) c.AI = std::max(32, std::min(128, (int) (((size_t) 64 << 20) / (((size_t) o.max_context + 64) * 4)) / 32 * 32)); c.w16_elems = (size_t) 8 << 20; @@ -3328,8 +3339,10 @@ struct Model::Impl { } } if (in_ram && ram_pinned && store_blob == nullptr) { // (DMA'd from where it lies) - const uint8_t* p = ram_slots[(size_t) l.ram[(size_t) e]]; - for (int r = 0; r < 3; ++r) it.src[r] = p + l.lay.trellis[r] + mx_read_off(l, mi, r); + const uint8_t* p = copy_mode ? ram_part[(size_t) l.ram[(size_t) e]][0] + : ram_slots[(size_t) l.ram[(size_t) e]]; + for (int r = 0; r < 3; ++r) + it.src[r] = p + (copy_mode ? cp_lay[(size_t) l.il][(size_t) r] : l.lay.trellis[r]) + mx_read_off(l, mi, r); ++c.it_ram; return; } @@ -4316,7 +4329,11 @@ struct Model::Impl { } const uint64_t avail = ram_avail(); // (Windows: the copies are committed memory, within what its commit still has beside the other programs' margin) - const double can = std::min(avail == ~uint64_t{0} ? 1e300 : std::max(0.0, (double) avail - (double) kRamMargin), + // DS4_COPY_HUGETLB: the arena comes from the kernel's huge-page pool, which MemAvailable does not count: add + // its free bytes so the full copy is taken when the pool holds it. + static const bool huge_arena = std::getenv("DS4_COPY_HUGETLB") != nullptr && std::atoi(std::getenv("DS4_COPY_HUGETLB")) != 0; + const double pool = huge_arena ? (double) os::huge_free_bytes() : 0.0; + const double can = std::min(avail == ~uint64_t{0} ? 1e300 : std::max(0.0, (double) avail - (double) kRamMargin) + pool, commit_room()); // (auto: none - copies that all fit were measured no faster than the page cache: the CPU lane's rows are // compute-bound, ~46 GB/s from either on 2 Xeon sockets, NUMA parts included; a part copied cost decode speed @@ -4375,13 +4392,28 @@ struct Model::Impl { if (ns == 0) continue; const size_t part = cp_lay[(size_t) l.il][3], bytes = (size_t) ns * part; std::array base = {nullptr, nullptr}; + // DS4_COPY_HUGETLB=1: the arena on explicit 2 MB pages (the pool must be reserved), so a pin of it keeps + // 2 MB pages and the prompt's DMA reads stay stable (a THP arena pinned by cudaHostRegister runs in 4 KB + // pages: measured 11.9 s one prompt, 30.4 s the next for the same 140 GB) + static const bool huge = std::getenv("DS4_COPY_HUGETLB") != nullptr && std::atoi(std::getenv("DS4_COPY_HUGETLB")) != 0; bool ok = true; for (int X = 0; X < NH && ok; ++X) { - base[(size_t) X] = (uint8_t*) node_map(bytes, X, NH); + size_t got = bytes; + base[(size_t) X] = (uint8_t*) (huge ? os::huge_alloc(bytes, &got) : node_map(bytes, X, NH)); + if (huge && base[(size_t) X] == nullptr) { // no pool on this machine: the ordinary arena instead + static bool warned = false; + if (!warned) { + std::fprintf(stderr, "ds4: DS4_COPY_HUGETLB=1 but no 2 MB huge pages are free (reserve them: sysctl " + "vm.nr_hugepages=N); using the ordinary arena\n"); + warned = true; + } + got = bytes; + base[(size_t) X] = (uint8_t*) node_map(bytes, X, NH); + } ok = base[(size_t) X] != nullptr; if (ok) { ram_chunks.push_back(base[(size_t) X]); - ram_chunk_bytes.push_back(bytes); + ram_chunk_bytes.push_back(got); } } if (!ok) { @@ -4447,6 +4479,26 @@ struct Model::Impl { std::fprintf(stderr, "ds4: %zu of the CPU lane's %zu experts copied into RAM (%.1f GB, %d NUMA part%s) in %.1f s%s\n", jobs.size(), hot.size(), cb / 1e9, NH, NH > 1 ? "s" : "", (now_ms() - t0) / 1000.0, jobs.size() < hot.size() ? "; the others read in place" : ""); + // DS4_COPY_PIN=1: pin the copies, so the prompt path DMAs each expert from where it lies instead of copying it + // to the pinned staging first (measured on the R9700 box: the 8K pass streams 122 GB at 6.8 GB/s through the + // staging, where the RAM-to-staging and DMA probes are 24 and 28 GB/s). The CPU lane reads the same memory, and + // pinned 4 KB pages can cost its TLB (an earlier registration measured -15% decode), so this stays opt-in. + // DS4_COPY_PIN_RO=1: cudaHostRegisterReadOnly (the GPU only reads it). + if (const char* cp = std::getenv("DS4_COPY_PIN"); cp != nullptr && std::atoi(cp) != 0) { + const bool ro = std::getenv("DS4_COPY_PIN_RO") != nullptr && std::atoi(std::getenv("DS4_COPY_PIN_RO")) != 0; + const double tr = now_ms(); + bool ok = true; + for (size_t i = 0; i < ram_chunks.size() && ok; ++i) + ok = cudaHostRegister(ram_chunks[i], ram_chunk_bytes[i], + ro ? cudaHostRegisterReadOnly : cudaHostRegisterPortable) == cudaSuccess; + if (ok) { + ram_pinned = true; + std::fprintf(stderr, "ds4: the copied experts pinned in %.1f s (%s): the prompt path DMAs them in place\n", + (now_ms() - tr) / 1000.0, ro ? "read-only" : "read-write"); + } else { + std::fprintf(stderr, "ds4: pinning the copied experts failed: the prompt path stages them\n"); + } + } return true; } @@ -4819,8 +4871,28 @@ struct Model::Impl { std::vector> list; list.reserve(cand.size()); for (const auto& c : cand) list.push_back(c.second); + // The slots the CPU lane's experts leave over: the experts the VRAM cache holds that the profile counts least (the cache gives + // up its coldest to the CPU lane, and a store without them reads each from the SSD while the CPU lane waits - 1.8 misses a + // token on the 251 GB R9700 box, 2.9 ms of a 49 ms token), then the lane's experts the profile never saw. Last in the list: they + // take only the slots the likely ones left. DS4_STORE_SPARE=0: off. + if (!(std::getenv("DS4_STORE_SPARE") && std::atoi(std::getenv("DS4_STORE_SPARE")) == 0)) { + std::vector>> vr, zero; + for (const Layer& l : L) { + if (l.il >= g.nl) continue; + const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp; + for (int e = 0; e < l.n_exp; ++e) { + if (l.slot[(size_t) e] >= 0) vr.push_back({(double) p[e] / (double) l.blob, {l.il, e}}); + else if (p[e] == 0) zero.push_back({0.0, {l.il, e}}); + } + } + std::stable_sort(vr.begin(), vr.end(), [](const auto& a, const auto& b) { return a.first < b.first; }); + for (const auto& c : vr) list.push_back(c.second); + for (const auto& c : zero) list.push_back(c.second); + } const double t0 = now_ms(); - const size_t leave = (size_t) (std::getenv("DS4_STORE_RESERVE") ? std::atoi(std::getenv("DS4_STORE_RESERVE")) : 192) + 64; + // (with the spare experts in the list the reserve is theirs: last in the list, so the oldest ticks, so the first a demand read replaces) + const bool spare_on = !(std::getenv("DS4_STORE_SPARE") && std::atoi(std::getenv("DS4_STORE_SPARE")) == 0); + const size_t leave = spare_on ? 0 : (size_t) (std::getenv("DS4_STORE_RESERVE") ? std::atoi(std::getenv("DS4_STORE_RESERVE")) : 192) + 64; // The first 48 GB (what a store held before it could take every expert) are read before the first token; the rest of the // hottest-first list is read after it, in pieces of 128 experts on a thread of its own, behind the model's own reads (a // guess's priority) - the same bytes. Opt-in (DS4_STORE_BG=1): "ready" comes 9 s sooner on the 251 GB R9700 box (24 s against 34), but a prompt sent at @@ -6207,6 +6279,19 @@ struct Model::Impl { } if (got) blob_to_ram(l, sw_b, sw.ram); else sw.ram = -1; // (back to the file's pages then) + } else if (ok && store && l.nm == 1 && l.lay.fmt == gg::kFmtMXFP4 && !(std::getenv("DS4_STORE_PUT") && std::atoi(std::getenv("DS4_STORE_PUT")) == 0)) { + // `out` goes back to the CPU lane: its blob is in VRAM, so it is copied into a store slot now - the lane would otherwise read it from + // the SSD and wait for it (1-2 misses a token on the 251 GB R9700 box). DS4_STORE_PUT=0: off. + uint8_t* dst = store->put_begin(l.il, sw.out); + if (dst != nullptr) { + const Layer& x = member(l, 0); + cudaSetDevice(devs[(size_t) x.dev].id); + cudaStream_t cs = copy_st[(size_t) x.dev]; + const bool got = cudaMemcpyAsync(dst, x.vram_base + (size_t) l.slot[(size_t) sw.out] * unit(l), l.blob, cudaMemcpyDeviceToHost, cs) == + cudaSuccess && + cudaStreamSynchronize(cs) == cudaSuccess; + store->put_done(l.il, sw.out, got); + } } if (check_swaps) { // DS4_CHECK_SWAPS: the slot (and `out`'s RAM copy) against the model file, byte for byte std::vector dev(l.blob), h(unit(l)), file(l.blob); @@ -6257,11 +6342,15 @@ struct Model::Impl { } if (store && env_f("DS4_SETTLE_STORE", 1.0f) != 0.0f) { // the RAM store too: a window prompt fills it through the CPU // lane's picks, a chunked one streams past it - the hottest CPU-lane experts of the prompt into its free slots + // (copy_mode: an expert already in the CPU lane's RAM copy gains nothing from a second copy of the same bytes - + // measured on the R9700 12 GB cell: 4152 such experts, 40 GB read at 6.4 GB/s, 6.2 s of an 8K prompt, 0.0 store + // hits in the decode after it; the VRAM swaps above already read them from the copy) std::vector>> hot; for (const Layer& l : L) { if (l.mtp) continue; for (int e = 0; e < l.n_exp; ++e) - if (l.slot[(size_t) e] < 0 && l.heat[(size_t) e] >= 4.0f) hot.push_back({l.heat[(size_t) e], {l.il, e}}); + if (l.slot[(size_t) e] < 0 && !(copy_mode && !l.ram.empty() && l.ram[(size_t) e] >= 0) && + l.heat[(size_t) e] >= 4.0f) hot.push_back({l.heat[(size_t) e], {l.il, e}}); } std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); std::vector> list; diff --git a/src/dsv41/ds4_os.hpp b/src/dsv41/ds4_os.hpp index 916d993f..0e48e9d6 100644 --- a/src/dsv41/ds4_os.hpp +++ b/src/dsv41/ds4_os.hpp @@ -398,6 +398,45 @@ inline bool in_ram(const void* p, size_t n) { #endif } +/// Bytes free in the kernel's explicit huge-page pool (HugePages_Free x Hugepagesize); 0 elsewhere or when unreadable. +/// (MemAvailable does not count a reserved pool, so a budget that must see it - the copy arena on DS4_COPY_HUGETLB - +/// adds this.) +inline uint64_t huge_free_bytes() { +#if defined(_WIN32) + return 0; +#else + std::FILE* f = std::fopen("/proc/meminfo", "r"); + if (f == nullptr) return 0; + char line[256]; + uint64_t pages = 0, size_kb = 0; + while (std::fgets(line, sizeof line, f) != nullptr) { + unsigned long long v = 0; + if (std::sscanf(line, "HugePages_Free: %llu", &v) == 1) pages = v; + else if (std::sscanf(line, "Hugepagesize: %llu kB", &v) == 1) size_kb = v; + } + std::fclose(f); + return pages * size_kb * 1024ull; +#endif +} + +/// Anonymous memory on explicit 2 MB huge pages (MAP_HUGETLB, from the kernel's pool - reserve it first, e.g. +/// `sysctl vm.nr_hugepages=N`): rounded up to a whole number of huge pages, `*got` its size. nullptr: the pool is empty +/// or the kernel cannot. (Unlike THP, a pin of this memory keeps 2 MB pages: a DMA from it does not need 4 KB +/// translations, which is what DS4_COPY_PIN's registered arena wanted.) +inline void* huge_alloc(size_t bytes, size_t* got = nullptr) { +#if defined(_WIN32) + (void) bytes, (void) got; + return nullptr; +#else + const size_t hp = (size_t) 2 << 20; + const size_t hb = (bytes + hp - 1) / hp * hp; + void* m = ::mmap(nullptr, hb, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0); + if (m == MAP_FAILED) return nullptr; + if (got != nullptr) *got = hb; + return m; +#endif +} + /// Anonymous memory on NUMA node `node` of `nodes` (node < 0 or nodes < 2: wherever the first touch puts it), on huge /// pages where the OS gives them; nullptr if it cannot be had. inline void* anon_alloc(size_t bytes, int node, int nodes) { diff --git a/src/dsv41/ds4_store.hpp b/src/dsv41/ds4_store.hpp index ea6b1779..23c01ebf 100644 --- a/src/dsv41/ds4_store.hpp +++ b/src/dsv41/ds4_store.hpp @@ -48,7 +48,7 @@ public: enum Policy { kLru = 0, kLfu = 1 }; struct Stats { std::atomic hits{0}, misses{0}, prefetched{0}, prefetch_used{0}, prefetch_wasted{0}, evictions{0}, fails{0}; - std::atomic bytes_read{0}, wait_ns{0}, no_slot{0}, cancelled{0}; + std::atomic bytes_read{0}, wait_ns{0}, no_slot{0}, cancelled{0}, put{0}; }; struct Vis { // a slot the GPU may read from now on (dev != 0), or no longer (dev == 0) int layer = 0, e = 0; @@ -255,6 +255,52 @@ public: } return n; } + /// A slot for (layer, e) that the caller fills with the expert's blob itself (an expert the VRAM cache gives back to the CPU lane: its bytes + /// are in memory already, so no read from the SSD while the lane waits). Returns the blob's address, or nullptr (it is here already, or + /// no slot can be had). The slot is pinned and not findable until put_done(). + uint8_t* put_begin(int layer, int e) { + if (layer < 0 || layer >= (int) geo_.size() || e < 0 || e >= geo_[(size_t) layer].n_exp) return nullptr; + std::lock_guard lk(mu_); + if (where_[(size_t) layer][(size_t) e] >= 0) return nullptr; + const int s = take_slot(false); + if (s < 0) return nullptr; + Slot& sp = slots_[(size_t) s]; + if (sp.layer >= 0 && sp.expert >= 0) { + where_[(size_t) sp.layer][(size_t) sp.expert] = -1; + if (sp.prefetch) st_.prefetch_wasted.fetch_add(1, std::memory_order_relaxed); + st_.evictions.fetch_add(1, std::memory_order_relaxed); + } + sp.layer = layer; + sp.expert = e; + sp.pin = 1; + sp.prefetch = false; + sp.visible = false; + sp.tick = ++clock_; + sp.bad.store(false); + sp.cancel.store(false); + sp.left.store(1, std::memory_order_release); + sp.state.store(kLoading, std::memory_order_release); + where_[(size_t) layer][(size_t) e] = s; + st_.put.fetch_add(1, std::memory_order_relaxed); + return sp.base; + } + void put_done(int layer, int e, bool ok) { + std::lock_guard lk(mu_); + const int s = where_[(size_t) layer][(size_t) e]; + if (s < 0) return; + Slot& sp = slots_[(size_t) s]; + if (sp.pin > 0) sp.pin--; + if (ok) { + sp.left.store(0, std::memory_order_release); + sp.state.store(kReady, std::memory_order_release); + } else { + where_[(size_t) layer][(size_t) e] = -1; + sp.layer = sp.expert = -1; + sp.left.store(0, std::memory_order_release); + sp.state.store(kFree, std::memory_order_release); + free_hint_ = std::min(free_hint_, (size_t) s); + } + } /// Guesses still waiting in the queue for a layer the token is past: dropped unread (their slots free once the queue has gone by) void cancel_stale(int layer_now) { std::lock_guard lk(mu_); diff --git a/src/dsv41/ds4_wmma.cuh b/src/dsv41/ds4_wmma.cuh new file mode 100644 index 00000000..569387f9 --- /dev/null +++ b/src/dsv41/ds4_wmma.cuh @@ -0,0 +1,39 @@ +// Strata. The gfx11/gfx12 WMMA fragments one warp's 16x16x16 tile is fed and read through (the expert kernels' +// mx_set_wmma_kernel and the attention kernel's matrix-core path share this form). Each lane gives its row's (or +// column's) 16 values of a k-step - on gfx12 its half of them - and holds 8 of the 16x16 results: row set_wmma_row(i, hi), +// column lane % 16. +#pragma once +#include +#if defined(STRATA_USE_HIP) +#include + +using h16v = _Float16 __attribute__((ext_vector_type(16))); +using f8v = float __attribute__((ext_vector_type(8))); + +inline __device__ __forceinline__ f8v set_wmma(h16v a, h16v b, f8v c) { +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \ + defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#elif defined(__gfx1200__) || defined(__gfx1201__) + using h8 = _Float16 __attribute__((ext_vector_type(8))); + const int k0 = (threadIdx.x & 31) / 16 * 8; + h8 aa, bb; +#pragma unroll + for (int i = 0; i < 8; ++i) { + aa[i] = a[k0 + i]; + bb[i] = b[k0 + i]; + } + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(aa, bb, c); +#else + __builtin_trap(); + return c; +#endif +} +inline __device__ __forceinline__ int set_wmma_row(int i, int hi) { +#if defined(__gfx1200__) || defined(__gfx1201__) + return 8 * hi + i; +#else + return 2 * i + hi; +#endif +} +#endif