okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7f46672a4
main
1// metal/src/engine/dflash2.inc - the DFlash2 drafter for Qwen3.8-Flash-Next on the Metal window (included at the end of window.cpp, inside 2// namespace strata::metal_engine, like prompt_chain.inc). 3// 4// The engine's other backends run core::Dflash2Drafter (src/core/dflash2.cpp: CUDA graphs over native_q8_0_mmvq). The Metal engine has its own 5// decode window, so the same class is implemented here with the same public API (generate.cpp's `--draft dflash2 --draft-model PACK` loop is 6// unchanged) and the same DF2P pack (tools/dflash2_pack.py: Q8_0 blocks, so the engine's gemv_8_* kernels read the pack as it is): 7// 8// taps the window / prompt chunk writes, after each tapped layer, the mean of the hc streams of the layer's completed output into a 9// unified-memory buffer (df2_tap, dflash2.metal); Verifier::set_taps and Prefill::set_taps reach them through window_taps / 10// prompt_taps below 11// context taps -> fc (12800 -> 2560) -> hidden_norm -> per layer K (norm + rope) and V into the ring (slot pos % 2064) 12// draft the same + the block: 8 rows, 5 layers (dynamic 2-tap conv, windowed attention over the ring + the block's keys), the head over 13// the draft vocabulary, the top-16 and the selector's walk. One command buffer per round. 14// 15// Activations are float (the CUDA drafter quantizes them to Q8_1): the Q8_0 weights are read by the engine's own GEMVs on xprep'd rows. 16 17 18// ---- taps (Window members) 19bool Window::taps_enable(const std::vector<int>& layers, std::string& err) { 20 if (taps_on_) { 21 if (layers != tap_layers_) { err = "metal taps: already on for other layers"; return false; } 22 return true; 23 } 24 if (layers.empty()) { err = "metal taps: no layers"; return false; } 25 for (int i = 0; i < 64; ++i) tap_slot_[i] = -1; 26 for (size_t i = 0; i < layers.size(); ++i) { 27 if (layers[i] < 0 || layers[i] >= 47) { err = "metal taps: layer " + std::to_string(layers[i]) + " is out of range"; return false; } 28 tap_slot_[layers[i]] = (int) i; 29 } 30 { 31 const strata_metal::MslLib L = strata_metal::lib_dflash2(engine_msl_dir()); 32 ldf2_ = cx_->compile(L.files, L.prelude); 33 } 34 tap_layers_ = layers; 35 tap_dec_ = cx_->alloc((size_t) MAXT * layers.size() * N * 4); 36 wcache_.clear(); // the windows encoded so far have no tap dispatches 37 taps_on_ = true; 38 std::fprintf(stderr, "strata metal: DFlash2 taps on (%zu layers)\n", layers.size()); 39 return true; 40} 41 42void Window::tap_dispatch(std::vector<mtl::Dispatch>& ds, int l, const mtl::Buffer& R, const mtl::Buffer& bo, const mtl::Buffer& inj, 43 const mtl::Buffer& out, int rows) { 44 const size_t nt = tap_layers_.size(); 45 struct TapArgs { uint32_t n, hc, R_stride, bo_stride, inj_stride, out_stride, out_off; } a{ 46 (uint32_t) N, (uint32_t) HC, (uint32_t) (HC * N), (uint32_t) N, (uint32_t) HC, (uint32_t) (nt * N), (uint32_t) (tap_slot_[l] * N)}; 47 mtl::Dispatch d; 48 d.p = P(ldf2_, "df2_tap", {}, "df2_tap"); 49 d.args = {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(out), mtl::Arg::V(a)}; 50 d.grid[0] = N / 256; 51 d.grid[1] = rows; 52 d.tg[0] = 256; 53 push(ds, d); 54} 55 56// hands the rows of a window / chunk that are at or after the first wanted position to the callback 57bool Window::tap_deliver(const mtl::Buffer& buf, int rows, int64_t pos0, std::string& err) { 58 if (!taps_on_ || !tap_cb_) return true; 59 const int64_t t0 = std::max<int64_t>(0, tap_first_ - pos0); 60 if (t0 >= rows) return true; 61 return tap_cb_(buf.as<float>() + (size_t) t0 * tap_layers_.size() * N, rows - t0, pos0 + t0, err); 62} 63 64mtl::Buffer& Window::tap_pro_buf(int rows) { 65 if (tap_pro_rows_ < rows) { 66 if (tap_pro_.handle) cx_->free(tap_pro_); 67 tap_pro_ = cx_->alloc((size_t) rows * tap_layers_.size() * N * 4); 68 tap_pro_rows_ = rows; 69 } 70 return tap_pro_; 71} 72 73// ---- the drafter 74namespace { 75constexpr int DF2_RING = 2064, DF2_ROWS = 8, DF2_DRAFTS = 7, DF2_CTX_MAX = 2048, DF2_TOPB = 64, DF2_MAXCH = 33; 76} 77 78struct Window::Df2 { 79 // the pack 80 std::string path; 81 mtl::Buffer xh; // half copy of the activation a matrix kernel reads (df2_f16) 82 // lineage row log (df2_log_rows): the half hidden_norm row of every context position, slot = position % ring; one buffer per parked lineage 83 mtl::Buffer rowlog; 84 struct Stash { std::vector<int32_t> hist; int64_t hi = 0, floor = 0; mtl::Buffer log; uint64_t used = 0; std::vector<uint8_t> chk; }; // chk: STRATA_DF2_CHECK_REBUILD=1 keeps the ring bytes of the stashed lineage 85 std::vector<Stash> stash; 86 uint64_t stash_tick = 0; 87 int stash_max = 4; 88 int64_t rebuilt_rows = 0, rebuilds = 0; 89 bool fuse_h = true; // the producers write the half operand themselves (STRATA_DF2_FUSE_H=0: df2_f16 dispatches) 90 int64_t floor = 0; // first ring position that belongs to the current request (a restarted lineage) 91 int ndraft = DF2_DRAFTS; // DF-04: candidates the head, top-k and selector work on (the verify prefix) 92 mtl::Buffer pack, wq; // pack: the f32 / bf16 tensors; wq: the Q8_0 matrices repacked (int8 [rows][K], then half [rows][K / 32]) 93 std::map<std::string, gguf::Tensor> ten; // offset = into wq for a matrix, into pack otherwise 94 std::map<std::string, uint64_t> scoff; // a matrix's scales in wq 95 uint64_t total = 0; 96 int L = 5, NH = 32, NKV = 8, I = 7680, window = 2048, group = 16, rank = 256, mask_token = 0; 97 float theta = 10000.0f, eps = 1e-6f; 98 std::vector<int> taps; 99 // the head over the draft vocabulary 100 int64_t nd = 0; 101 const mtl::Buffer* head_buf = nullptr; // STRATA_DF2_HEAD=native: the target's own rows (Q6_K ...) through the engine's GEMV 102 gguf::Tensor head_t; 103 mtl::Buffer own_head, vmap, hq, hsc; // hq / hsc: the draft head requantized to Q8_0 (int8 [nd][2560], half [nd][80]) 104 bool head_q8 = true; 105 bool use_map = false; 106 // state and activations 107 mtl::Buffer kring[8], vring[8]; 108 mtl::Buffer ctxpos, rtctx, dpos, rtd, bpos, rtb, anchor; 109 mtl::Buffer fcy, hctx, kc, vc, h, xn, xc, dyn, q, qn, k, v, kblk, ao, o, gate, up, sw, mlp, fn, hsel, logits, topval, toptok, tkv, tki, part, outbuf; 110 Act A_fn; // the native head only 111 std::vector<float> mask_emb; 112 std::vector<mtl::Dispatch> list[DF2_ROWS + 1]; 113 bool built[DF2_ROWS + 1] = {}; 114 bool loaded = false, bound = false; 115 uint64_t bytes = 0; 116 double gpu_ms = 0; 117 int64_t rounds = 0, steady = 0; 118 // STRATA_DF2_DUMP=<file> [STRATA_DF2_DUMP_ROUND=n]: the context rows the drafter was given and its answer at round n, for tools/dflash2/check_metal_dump.py 119 std::string dump_path; 120 int dump_round = 3; 121 std::vector<float> dump_taps, dump_anchor_emb; 122 int64_t dump_next = 0; 123 bool dump_ok = true; 124 double build_ms = 0, last_build_ms = 0, run_ms = 0, host_ms = 0; 125}; 126 127namespace { 128std::string g_df2_path; 129 130// reads the DF2P header + index; fills the config and the tensor table (offsets are from the end of the index) 131bool df2_read_index(const std::string& path, std::vector<int>& taps, std::map<std::string, gguf::Tensor>& ten, uint64_t& total, 132 uint64_t& data_off, std::map<std::string, std::string>& cfg, std::string& err) { 133 std::FILE* f = std::fopen(path.c_str(), "rb"); 134 if (!f) { err = "dflash2: cannot open " + path; return false; } 135 struct Closer { std::FILE* f; ~Closer() { std::fclose(f); } } closer{f}; 136 uint32_t hdr[3]; 137 if (std::fread(hdr, 4, 3, f) != 3 || std::memcmp(hdr, "DF2P", 4) != 0 || hdr[1] != 1) { err = "dflash2: " + path + " is not a DF2P v1 pack"; return false; } 138 std::string index(hdr[2], ' '); 139 if (std::fread(index.data(), 1, hdr[2], f) != hdr[2]) { err = "dflash2: the pack's index is cut short"; return false; } 140 data_off = 12 + hdr[2]; 141 total = 0; 142 for (size_t i = 0; i < index.size();) { 143 const size_t j = index.find('\n', i); 144 if (j == std::string::npos) break; 145 const std::string line = index.substr(i, j - i); 146 i = j + 1; 147 char a[256], b[64], c[256]; 148 long long v1, v2, v3, v4; 149 if (std::sscanf(line.c_str(), "cfg %63s %255s", b, c) == 2) { 150 cfg[b] = c; 151 if (std::string(b) == "taps") { 152 taps.clear(); 153 for (const char* q = c; *q;) { taps.push_back(std::atoi(q)); while (*q && *q != ',') ++q; if (*q == ',') ++q; } 154 } 155 } else if (std::sscanf(line.c_str(), "t %255s %63s %lld %lld %lld %lld", a, b, &v1, &v2, &v3, &v4) == 6) { 156 gguf::Tensor t; 157 t.name = a; 158 const std::string dt = b; 159 t.type = dt == "q8_0" ? ref::Q8_0 : dt == "q4_0" ? ref::Q4_0 : dt == "f32" ? ref::F32 : dt == "bf16" ? ref::BF16 : -1; 160 t.shape = {(uint64_t) v2, (uint64_t) v1}; // ggml order: [in][out] 161 t.offset = (uint64_t) v3; 162 t.bytes = (uint64_t) v4; 163 ten[t.name] = t; 164 total = std::max(total, t.offset + t.bytes); 165 } 166 } 167 if (ten.empty()) { err = "dflash2: the pack has no tensors"; return false; } 168 return true; 169} 170} // namespace 171 172bool Window::df2_open(const std::string& path, std::string& err) { 173 std::unique_ptr<Df2> d(new Df2()); 174 d->path = path; 175 uint64_t data_off = 0; 176 std::map<std::string, std::string> cfg; 177 if (!df2_read_index(path, d->taps, d->ten, d->total, data_off, cfg, err)) return false; 178 auto geti = [&](const char* k, int def) { auto it = cfg.find(k); return it == cfg.end() ? def : std::atoi(it->second.c_str()); }; 179 d->L = geti("layers", 5); d->NH = geti("heads", 32); d->NKV = geti("kv_heads", 8); d->I = geti("inter", 7680); 180 d->window = geti("window", 2048); d->group = geti("conv_group", 16); d->rank = geti("rank", 256); d->mask_token = geti("mask_token", 0); 181 if (cfg.count("rope_theta")) d->theta = (float) std::atof(cfg["rope_theta"].c_str()); 182 if (cfg.count("eps")) d->eps = (float) std::atof(cfg["eps"].c_str()); 183 if (geti("hidden", 0) != N || d->NH != 32 || d->NKV != 8 || geti("head_dim", 0) != 128 || d->rank != 256 || d->L > 8 || d->window + 16 > DF2_RING || 184 d->I != 7680 || d->group != 16 || d->taps.empty()) { 185 err = "dflash2: the pack's shape is not the Flash-Next drafter this engine was written for"; 186 return false; 187 } 188 df2_ = d.release(); 189 return true; 190} 191 192bool Window::df2_load_pack(std::string& err) { 193 Df2& d = *df2_; 194 if (d.loaded) return true; 195 const double t0 = now_ms(); 196 uint64_t data_off = 0; 197 std::vector<int> taps; 198 std::map<std::string, gguf::Tensor> ten; 199 std::map<std::string, std::string> cfg; 200 uint64_t total = 0; 201 if (!df2_read_index(d.path, taps, ten, total, data_off, cfg, err)) return false; 202 // The Q8_0 matrices are repacked once: int8 values [rows][K] and half scales [rows][K / 32] in separate runs, so a lane reads 16 contiguous 203 // bytes instead of 34-byte blocks (df2_mm). The f32 / bf16 tensors go to `pack` as they are. 204 auto up256 = [](uint64_t x) { return (x + 255) / 256 * 256; }; 205 uint64_t wq_bytes = 0, misc_bytes = 0; 206 std::map<std::string, uint64_t> woff, soff, moff; 207 auto is_codebook = [](const std::string& n) { return n.find("codebook") != std::string::npos; }; // the selector's tables are gathered by row, never repacked 208 for (const auto& [n, t] : ten) { 209 if (t.type == ref::Q4_0 && is_codebook(n)) { 210 moff[n] = misc_bytes; misc_bytes += up256(t.bytes); // Q4_0 rows of 8 blocks (144 bytes), read as they are by df2_select_q4 211 } else if (t.type == ref::Q4_0) { 212 const uint64_t K = t.shape[0], rows = t.shape[1]; 213 if (K % 32 != 0 || rows % 8 != 0) { err = "dflash2: " + n + " is not a whole number of 8-row, 32-column Q4_0 tiles"; return false; } 214 woff[n] = wq_bytes; wq_bytes += up256(rows * K / 2); // fragment-order words: [row tile][block][lane] uint32 215 soff[n] = wq_bytes; wq_bytes += up256(rows * (K / 32) * 2); // half scales [row tile][block][8 rows] 216 } else if (t.type == ref::Q8_0) { 217 const uint64_t K = t.shape[0], rows = t.shape[1]; 218 if (K % 512 != 0) { err = "dflash2: " + n + " has K = " + std::to_string(K) + ", not a multiple of 512"; return false; } 219 woff[n] = wq_bytes; wq_bytes += up256(rows * K); 220 soff[n] = wq_bytes; wq_bytes += up256(rows * (K / 32) * 2); 221 } else if (t.type == ref::F32 || t.type == ref::BF16) { 222 moff[n] = misc_bytes; misc_bytes += up256(t.bytes); 223 } else { err = "dflash2: " + n + " has an unknown type"; return false; } 224 } 225 d.wq = cx_->alloc(wq_bytes + 4096); 226 d.pack = cx_->alloc(misc_bytes + 4096); 227 if (!d.wq.handle || !d.pack.handle) { err = "dflash2: the pack does not fit in memory"; return false; } 228 std::FILE* f = std::fopen(d.path.c_str(), "rb"); 229 if (!f) { err = "dflash2: cannot open " + d.path; return false; } 230 std::vector<uint8_t> tmp; 231 for (auto& [n, t] : d.ten) { 232 tmp.resize(t.bytes); 233 fseeko(f, (off_t) (data_off + t.offset), SEEK_SET); 234 if (std::fread(tmp.data(), 1, t.bytes, f) != t.bytes) { std::fclose(f); err = "dflash2: the pack is shorter than its index"; return false; } 235 if (t.type == ref::Q4_0 && !is_codebook(n)) { 236 // Q4_0 blocks (half d, 16 bytes: byte j = element j low nibble, element j + 16 high nibble) -> the matrix units' fragment order (df2_mma4s): 237 // for a tile of 8 rows and one block, lane l (fragment row fm, columns fn, fn + 1) holds the codes of W[fm][8 s + fn + e] as nibble 2 s + e 238 const uint64_t K = t.shape[0], rows = t.shape[1], nb = K / 32, nrt = rows / 8; 239 uint32_t* qw = (uint32_t*) (d.wq.as<uint8_t>() + woff[n]); 240 uint16_t* sc = (uint16_t*) (d.wq.as<uint8_t>() + soff[n]); 241 auto code = [&](uint64_t r, uint64_t b, int j) -> uint32_t { // element j (0..31) of block b of row r 242 const uint8_t* blk = tmp.data() + (r * nb + b) * 18; 243 return j < 16 ? (blk[2 + j] & 15u) : (blk[2 + j - 16] >> 4); 244 }; 245 for (uint64_t rt = 0; rt < nrt; ++rt) 246 for (uint64_t b = 0; b < nb; ++b) { 247 for (int lane = 0; lane < 32; ++lane) { 248 const int qid = lane >> 2, fm = (qid & 4) + ((lane >> 1) & 3), fn = (qid & 2) * 2 + (lane & 1) * 2; 249 const uint64_t r = rt * 8 + fm; 250 uint32_t w = 0; 251 for (int s2 = 0; s2 < 4; ++s2) 252 for (int e = 0; e < 2; ++e) w |= code(r, b, 8 * s2 + fn + e) << (4 * (2 * s2 + e)); 253 qw[(rt * nb + b) * 32 + lane] = w; 254 } 255 for (int r8 = 0; r8 < 8; ++r8) std::memcpy(&sc[(rt * nb + b) * 8 + r8], tmp.data() + ((rt * 8 + r8) * nb + b) * 18, 2); 256 } 257 t.offset = woff[n]; 258 d.scoff[n] = soff[n]; 259 } else if (t.type == ref::Q8_0) { 260 const uint64_t K = t.shape[0], rows = t.shape[1], nb = K / 32; 261 int8_t* qs = (int8_t*) (d.wq.as<uint8_t>() + woff[n]); 262 uint16_t* sc = (uint16_t*) (d.wq.as<uint8_t>() + soff[n]); 263 for (uint64_t r = 0; r < rows; ++r) 264 for (uint64_t b = 0; b < nb; ++b) { 265 const uint8_t* src = tmp.data() + (r * nb + b) * 34; 266 std::memcpy(&sc[r * nb + b], src, 2); 267 std::memcpy(qs + r * K + b * 32, src + 2, 32); 268 } 269 t.offset = woff[n]; 270 d.scoff[n] = soff[n]; 271 } else { 272 std::memcpy(d.pack.as<uint8_t>() + moff[n], tmp.data(), t.bytes); 273 t.offset = moff[n]; 274 } 275 } 276 std::fclose(f); 277 d.bytes += d.wq.bytes + d.pack.bytes; 278 d.loaded = true; 279 std::fprintf(stderr, "strata metal: DFlash2 pack %s: %.0f MiB of matrices repacked, %.0f MiB of the rest, in %.0f ms\n", d.path.c_str(), 280 d.wq.bytes / 1048576.0, d.pack.bytes / 1048576.0, now_ms() - t0); 281 return true; 282} 283 284bool Window::df2_bind(const std::string& vocab_file, std::string& err) { 285 if (df2_ == nullptr) { err = "dflash2: no pack"; return false; } 286 Df2& d = *df2_; 287 if (d.bound) return true; 288 if (!taps_on_) { err = "dflash2: the window keeps no taps"; return false; } 289 if (!df2_load_pack(err)) return false; 290 { // the text strata_control/drafting.py looks for in the program to know that this engine reads a pack whose selector tables are Q4_0 rows 291 const auto cb = d.ten.find("candidate_selector.predecessor_codebook"); 292 if (cb != d.ten.end() && cb->second.type == ref::Q4_0) 293 std::fprintf(stderr, "strata metal: DFlash2 selector codebooks: Q4_0 rows (about 174 MiB less than bf16)\n"); 294 } 295 const double t0 = now_ms(); 296 auto A = [&](size_t bytes) { d.bytes += bytes; return cx_->alloc(bytes); }; 297 // ---- the draft vocabulary's head rows: the MTP's when it is the same list, else gathered here 298 std::vector<int32_t> vocab; 299 if (!vocab_file.empty() && vocab_file != "full") { 300 if (std::FILE* vf = std::fopen(vocab_file.c_str(), "rb")) { 301 int32_t id; 302 while (std::fread(&id, 4, 1, vf) == 1) if (id >= 0 && id < n_vocab_) vocab.push_back(id); 303 std::fclose(vf); 304 } 305 } 306 if (vocab.empty() && vocab_file != "full") vocab = dvocab_; // the MTP's list (may be empty: the whole head) 307 if (vocab.empty() && vocab_file != "full") { // no MTP loaded (--draft-fallback none) and no <mtp>/rt/draft_vocab.bin: the repository's list, as the MTP's loader falls back to 308 std::string vp = std::getenv("STRATA_METAL_DRAFT_VOCAB") ? std::getenv("STRATA_METAL_DRAFT_VOCAB") 309 : strata_metal::resource(nullptr, "data", STRATA_METAL_DATA_DEFAULT) + "/draft_vocab.bin"; 310 if (vp != "full") 311 if (std::FILE* vf = std::fopen(vp.c_str(), "rb")) { 312 int32_t id; 313 while (std::fread(&id, 4, 1, vf) == 1) if (id >= 0 && id < n_vocab_) vocab.push_back(id); 314 std::fclose(vf); 315 } 316 } 317 const gguf::Tensor& out_t = T("output.weight"); 318 { 319 const char* hm = std::getenv("STRATA_DF2_HEAD"); 320 d.head_q8 = !(hm && std::string(hm) == "native"); 321 // STRATA_DF2_HEAD=native: the target's own head, whole (the community drafter's): no draft vocabulary, no gathered copy, the engine's GEMV on the target's rows 322 if (!d.head_q8) vocab.clear(); 323 } 324 d.nd = vocab.empty() ? n_vocab_ : (int64_t) vocab.size(); 325 d.use_map = !vocab.empty(); 326 d.vmap = A(vocab.empty() ? 16 : 4 * vocab.size()); 327 if (!vocab.empty()) std::memcpy(d.vmap.ptr, vocab.data(), 4 * vocab.size()); 328 if (d.head_q8) { 329 // the head rows of the draft vocabulary requantized to Q8_0 (the target's Q6_K / ... rows dequantized first) in df2_mm's layout: 3x fewer 330 // cycles per round than the engine's GEMV on the Q6_K rows (STRATA_DF2_HEAD=native keeps those). The logits differ by the Q8_0 rounding. 331 const size_t rb = ref::row_bytes(out_t.type, N); 332 const uint64_t nrow = (uint64_t) d.nd, nb = N / 32; 333 const uint64_t nrt = (nrow + 7) / 8; 334 d.hq = A(nrt * nb * 32 * 8 + 4096); // fragment order: [row tile][block][lane] 8 int8 (uint2) 335 d.hsc = A(nrt * nb * 8 * 2 + 4096); // half scales [row tile][block][8 rows] 336 std::vector<std::thread> th; 337 const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); 338 for (unsigned k = 0; k < nth; ++k) 339 th.emplace_back([&, k] { 340 std::vector<float> tmpf(N); 341 std::vector<uint8_t> blk(nb * 34); 342 for (uint64_t i = k; i < nrow; i += nth) { 343 const uint64_t tok = vocab.empty() ? i : (uint64_t) vocab[i]; 344 ref::dequant(out_t.type, (const uint8_t*) W_.ptr + out_t.offset + tok * rb, tmpf.data(), N); 345 ref::quantize_q8_0(tmpf.data(), N, blk.data()); 346 // this row's fm in its tile; the 8 rows of a tile are written by whichever thread owns each row: lane words are filled byte by byte 347 const uint64_t rt = i / 8, fmr = i % 8; 348 for (uint64_t b = 0; b < nb; ++b) { 349 std::memcpy(d.hsc.as<uint8_t>() + ((rt * nb + b) * 8 + fmr) * 2, blk.data() + b * 34, 2); 350 const int8_t* q8 = (const int8_t*) (blk.data() + b * 34 + 2); 351 for (int lane = 0; lane < 32; ++lane) { 352 const int qid = lane >> 2, fm = (qid & 4) + ((lane >> 1) & 3), fn = (qid & 2) * 2 + (lane & 1) * 2; 353 if ((uint64_t) fm != fmr) continue; 354 int8_t* dst = (int8_t*) (d.hq.as<uint8_t>() + ((rt * nb + b) * 32 + lane) * 8); 355 for (int s2 = 0; s2 < 4; ++s2) 356 for (int e = 0; e < 2; ++e) dst[2 * s2 + e] = q8[8 * s2 + fn + e]; 357 } 358 } 359 } 360 }); 361 for (auto& x : th) x.join(); 362 } else if (!vocab.empty()) { 363 if (mhead_.handle && vocab == dvocab_) { 364 d.head_buf = &mhead_; 365 d.head_t = mhead_t_; 366 } else { 367 const size_t rb = ref::row_bytes(out_t.type, N); 368 d.own_head = A(vocab.size() * rb + 4096); 369 for (size_t i = 0; i < vocab.size(); ++i) 370 std::memcpy(d.own_head.as<uint8_t>() + i * rb, (const uint8_t*) W_.ptr + out_t.offset + (size_t) vocab[i] * rb, rb); 371 d.head_buf = &d.own_head; 372 d.head_t = out_t; 373 d.head_t.offset = 0; 374 d.head_t.shape = {(uint64_t) N, (uint64_t) vocab.size()}; 375 d.head_t.bytes = vocab.size() * rb; 376 } 377 } else { 378 d.head_buf = &W_; 379 d.head_t = out_t; 380 } 381 if ((d.nd + DF2_TOPB - 1) / DF2_TOPB > 4096) { err = "dflash2: the head has too many rows for the top-k"; return false; } 382 // ---- the mask token's embedding (constant) 383 { 384 const gguf::Tensor& te = T("token_embd.weight"); 385 const size_t rb = ref::row_bytes(te.type, N); 386 d.mask_emb.resize(N); 387 ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) d.mask_token * rb, d.mask_emb.data(), N); 388 } 389 // ---- buffers 390 for (int l = 0; l < d.L; ++l) { d.kring[l] = A((size_t) DF2_RING * 8 * 128 * 4); d.vring[l] = A((size_t) DF2_RING * 8 * 128 * 4); } 391 const size_t B = DF2_ROWS; 392 d.ctxpos = A(4 * (size_t) DF2_CTX_MAX); d.rtctx = A(4 * (size_t) DF2_CTX_MAX * 128); 393 d.dpos = A(4 * 8); d.rtd = A(4 * 8 * 128); d.bpos = A(4 * 8); d.rtb = A(4 * 8 * 128); d.anchor = A(4 * 8); 394 d.fcy = A(4 * B * N); d.hctx = A(4 * B * N); d.kc = A(4 * B * 1024); d.vc = A(4 * B * 1024); 395 d.h = A(4 * B * N); d.xn = A(4 * B * N); d.xc = A(4 * B * N); d.dyn = A(4 * B * 640); 396 d.q = A(4 * B * 4096); d.qn = A(4 * B * 4096); d.k = A(4 * B * 1024); d.v = A(4 * B * 1024); d.kblk = A(4 * B * 1024); 397 d.ao = A(4 * B * 4096); d.o = A(4 * B * N); d.gate = A(4 * B * d.I); d.up = A(4 * B * d.I); d.sw = A(4 * B * d.I); 398 d.mlp = A(4 * B * N); d.fn = A(4 * (B + 1) * N); d.hsel = A(4 * 8 * 256); 399 d.xh = A(2 * (size_t) 8 * 12800 + 4096); 400 d.logits = A(4 * (size_t) 8 * (size_t) d.nd); 401 d.topval = A(4 * DF2_DRAFTS * 16); d.toptok = A(4 * DF2_DRAFTS * 16); 402 d.tkv = A(4 * (size_t) DF2_DRAFTS * DF2_TOPB * 16); d.tki = A(4 * (size_t) DF2_DRAFTS * DF2_TOPB * 16); 403 d.part = A(4 * (size_t) DF2_MAXCH * 8 * 32 * 130); 404 d.outbuf = A(4 * 32); 405 auto act = [&](int n) { Act x; x.n = n; x.b = A(4 * ((size_t) 4 * MAXT * n + (size_t) MAXT * n / 16)); return x; }; 406 d.A_fn = act(N); 407 if (const char* e = std::getenv("STRATA_DF2_DUMP")) { d.dump_path = e; if (const char* r = std::getenv("STRATA_DF2_DUMP_ROUND")) d.dump_round = std::atoi(r); } 408 if (const char* lm = std::getenv("STRATA_DF2_LOG_MIB")) d.stash_max = std::atoi(lm) / 10; else d.stash_max = 4; // ~10.6 MiB a lineage 409 d.rowlog = A((size_t) DF2_RING * N * 2); 410 { const char* fe = std::getenv("STRATA_DF2_FUSE_H"); d.fuse_h = !(fe && fe[0] == '0'); } 411 d.bound = true; 412 std::fprintf(stderr, "strata metal: DFlash2 drafter ready (%.0f MiB: pack %.0f, %lld-token draft head %s), in %.0f ms\n", d.bytes / 1048576.0, 413 (d.wq.bytes + d.pack.bytes) / 1048576.0, (long long) d.nd, d.head_q8 ? (d.use_map ? "as Q8_0" : "as Q8_0, the whole head") : "native", now_ms() - t0); 414 return true; 415} 416 417namespace { 418// the rope table rows of `pos` (cos then sin of pos * theta^(-2i/128), the angle reduced in double): [rows][2][64] 419void df2_rope_rows(const int32_t* pos, int rows, float theta, float* table) { 420 constexpr double two_pi = 6.283185307179586476925286766559; 421 for (int r = 0; r < rows; ++r) 422 for (int i = 0; i < 64; ++i) { 423 const double inv = std::pow((double) theta, -(double) (2 * i) / 128.0); 424 double ang = (double) pos[r] * inv; 425 ang -= two_pi * std::rint(ang / two_pi); 426 table[(r * 2 + 0) * 64 + i] = (float) std::cos(ang); 427 table[(r * 2 + 1) * 64 + i] = (float) std::sin(ang); 428 } 429} 430} // namespace 431 432// df2_mm: y[c][row] = sum_k W[row][k] x[c][k] for `ncol` (1..8) float columns; the matrix is `name`'s repacked rows in wq, or (qs, sc) explicitly 433void Window::df2_mm(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& qs, size_t qs_off, const mtl::Buffer& sc, size_t sc_off, uint32_t K, uint32_t rows, 434 const mtl::Buffer& x, size_t x_off, uint32_t x_stride, const mtl::Buffer& y, size_t y_off, uint32_t y_stride, int ncol) { 435 struct MmArgs { uint32_t K, rows, y_stride, x_stride; } a{K, rows, y_stride, x_stride}; 436 mtl::Dispatch dd; 437 static const std::pair<int, int> RS = [] { 438 int r = 2, s = 8; 439 if (const char* e = std::getenv("STRATA_DF2_MM")) std::sscanf(e, "%d,%d", &r, &s); // rows per simdgroup, simdgroups per threadgroup 440 return std::make_pair(r, s); 441 }(); 442 const int R = RS.first, SGN = RS.second; 443 const std::string fn = "df2_mm_" + std::to_string(R) + "_" + std::to_string(SGN); 444 dd.p = P(ldf2_, fn, mtl::Constants().i(0, ncol), fn + "#" + std::to_string(ncol)); 445 dd.args = {mtl::Arg::B(qs, qs_off), mtl::Arg::B(sc, sc_off), mtl::Arg::B(x, x_off), mtl::Arg::B(y, y_off), mtl::Arg::V(a)}; 446 dd.grid[0] = (rows + SGN * R - 1) / (SGN * R); 447 dd.tg[0] = SGN * 32; 448 push(ds, dd); 449} 450 451// Q4_0 (fragment order) x up to 8 float columns on the matrix units: the activation is rounded to half once (df2_f16, skipped when `reuse`: the previous 452// call read the same x), then df2_mma4s (split-K over the simdgroups of a threadgroup, 2 row tiles per threadgroup, 8 simdgroups) 453void Window::df2_mm4(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& qs, size_t qs_off, const mtl::Buffer& sc, size_t sc_off, uint32_t K, uint32_t rows, 454 const mtl::Buffer& x, size_t x_off, const mtl::Buffer& y, uint32_t y_stride, int ncol, bool reuse) { 455 Df2& d = *df2_; 456 if (!reuse) { 457 const uint32_t n = (uint32_t) ncol * K; 458 mtl::Dispatch c; 459 c.p = P(ldf2_, "df2_f16", {}, "df2_f16"); 460 c.args = {mtl::Arg::B(x, x_off), mtl::Arg::B(d.xh), mtl::Arg::V(n)}; 461 c.grid[0] = (n + 255) / 256; 462 c.tg[0] = 256; 463 push(ds, c); 464 } 465 const size_t xh_off = (reuse && d.fuse_h) ? x_off / 2 : 0; // fused: the producer wrote all rows, a GEMM on rows 1.. starts at their half offset 466 struct MmaQArgs { uint32_t K, rows, y_stride, x_stride; } a{K, rows, y_stride, K}; 467 mtl::Dispatch dd; 468 dd.p = P(ldf2_, "df2_mma4s_2_8", {}, "df2_mma4s_2_8"); 469 dd.args = {mtl::Arg::B(qs, qs_off), mtl::Arg::B(sc, sc_off), mtl::Arg::B(d.xh, xh_off), mtl::Arg::B(y), mtl::Arg::V(a)}; 470 dd.grid[0] = ((rows + 7) / 8 + 1) / 2; 471 dd.tg[0] = 8 * 32; 472 push(ds, dd); 473} 474 475void Window::df2_mmn(std::vector<mtl::Dispatch>& ds, const std::string& name, const mtl::Buffer& x, size_t x_off, uint32_t x_stride, const mtl::Buffer& y, 476 uint32_t y_stride, int ncol, bool reuse) { 477 Df2& d = *df2_; 478 const gguf::Tensor& t = d.ten.at(name); 479 if (d.fuse_h && name != "fc.weight") reuse = true; // the producer of x wrote its half copy (fc reads the window's taps: converted here) 480 if (t.type == ref::Q4_0) { 481 df2_mm4(ds, d.wq, t.offset, d.wq, d.scoff.at(name), (uint32_t) t.shape[0], (uint32_t) t.shape[1], x, x_off, y, y_stride, ncol, reuse); 482 return; 483 } 484 df2_mm(ds, d.wq, t.offset, d.wq, d.scoff.at(name), (uint32_t) t.shape[0], (uint32_t) t.shape[1], x, x_off, x_stride, y, 0, y_stride, ncol); 485} 486 487void Window::df2_rms(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& x, const mtl::Buffer& y, const char* wname, int rows) { 488 Df2& d = *df2_; 489 struct RmsArgs { uint32_t n; float eps; } a{(uint32_t) N, d.eps}; 490 mtl::Dispatch dd; 491 dd.p = P(ldf2_, d.fuse_h ? "df2_rms_h" : "df2_rms", {}, d.fuse_h ? "df2_rms_h" : "df2_rms"); 492 dd.args = {mtl::Arg::B(x), mtl::Arg::B(d.pack, d.ten.at(wname).offset), mtl::Arg::B(y), mtl::Arg::V(a)}; 493 if (d.fuse_h) dd.args.push_back(mtl::Arg::B(d.xh)); 494 dd.grid[0] = rows; 495 dd.tg[0] = 256; 496 push(ds, dd); 497} 498 499// the context update of `n` rows (<= 8) whose taps start at `taps` (+ off bytes): positions at pos[0..n) (int32 buffer + off), rope table rows at rt (+ off) 500void Window::df2_ctx_list(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& taps, size_t taps_off, int n, const mtl::Buffer& pos, size_t pos_off, 501 const mtl::Buffer& rt, size_t rt_off) { 502 Df2& d = *df2_; 503 const uint32_t tap_n = (uint32_t) (d.taps.size() * N); 504 df2_mmn(ds, "fc.weight", taps, taps_off, tap_n, d.fcy, N, n); 505 df2_rms(ds, d.fcy, d.hctx, "hidden_norm.weight", n); 506 if (d.fuse_h && d.rowlog.handle) { // the lineage's row log: the half operand of the projections below 507 struct CopyArgs { uint32_t slot_mod, rows, cols; } la{(uint32_t) DF2_RING, (uint32_t) n, (uint32_t) N}; 508 mtl::Dispatch lg; 509 lg.p = P(ldf2_, "df2_log_rows", {}, "df2_log_rows"); 510 lg.args = {mtl::Arg::B(d.xh), mtl::Arg::B(d.rowlog), mtl::Arg::B(pos, pos_off), mtl::Arg::V(la)}; 511 lg.grid[0] = (n * N + 255) / 256; 512 lg.tg[0] = 256; 513 push(ds, lg); // (with its barrier: the half rows are written by the norm just before) 514 } 515 df2_kv_list(ds, n, pos, pos_off, rt, rt_off); 516} 517 518// the K and V of every layer from the half rows in d.xh (n <= 8 rows at the positions pos[0..n)): projections, k norm + rope, ring writes 519void Window::df2_kv_list(std::vector<mtl::Dispatch>& ds, int n, const mtl::Buffer& pos, size_t pos_off, const mtl::Buffer& rt, size_t rt_off) { 520 Df2& d = *df2_; 521 for (int l = 0; l < d.L; ++l) { 522 const std::string p = "layers." + std::to_string(l) + "."; 523 df2_mmn(ds, p + "self_attn.k_proj.weight", d.hctx, 0, N, d.kc, 1024, n, l > 0); 524 nb_ = true; // the V projection reads the same rows 525 df2_mmn(ds, p + "self_attn.v_proj.weight", d.hctx, 0, N, d.vc, 1024, n, true); 526 struct NrArgs { uint32_t in_stride, slot_mod, heads; float eps; uint32_t has_rope; } na{1024, (uint32_t) DF2_RING, 8, d.eps, 1}; 527 mtl::Dispatch kn; 528 kn.p = P(ldf2_, "df2_norm_rope", {}, "df2_norm_rope"); 529 kn.args = {mtl::Arg::B(d.kc), mtl::Arg::B(d.pack, d.ten.at(p + "self_attn.k_norm.weight").offset), mtl::Arg::B(pos, pos_off), mtl::Arg::B(rt, rt_off), 530 mtl::Arg::B(d.kring[l]), mtl::Arg::V(na)}; 531 kn.grid[0] = n; 532 kn.grid[1] = 8; 533 kn.tg[0] = 128; 534 push(ds, kn); 535 struct CopyArgs { uint32_t slot_mod, rows, cols; } ca{(uint32_t) DF2_RING, (uint32_t) n, 1024}; 536 mtl::Dispatch cp; 537 cp.p = P(ldf2_, "df2_copy_rows", {}, "df2_copy_rows"); 538 cp.args = {mtl::Arg::B(d.vc), mtl::Arg::B(d.vring[l]), mtl::Arg::B(pos, pos_off), mtl::Arg::V(ca)}; 539 cp.grid[0] = (n * 1024 + 255) / 256; 540 cp.tg[0] = 256; 541 nb_ = true; // beside the K write 542 push(ds, cp); 543 } 544} 545 546// the block: 8 rows (the anchor + 7 masks), h already holds their embeddings 547void Window::df2_block_list(std::vector<mtl::Dispatch>& ds) { 548 Df2& d = *df2_; 549 const int B = DF2_ROWS; 550 auto conv = [&](const mtl::Buffer& x, const mtl::Buffer& dyn, size_t dyn_off, size_t base_off, const mtl::Buffer* resid, const mtl::Buffer& out) { 551 struct ConvArgs { uint32_t rows, H, group, dyn_stride, has_resid; } a{(uint32_t) B, (uint32_t) N, (uint32_t) d.group, 640, resid ? 1u : 0u}; 552 mtl::Dispatch dd; 553 const bool hh = d.fuse_h && resid == nullptr; // the convolution that feeds a GEMM also writes the half operand 554 dd.p = P(ldf2_, hh ? "df2_conv_h" : "df2_conv", {}, hh ? "df2_conv_h" : "df2_conv"); 555 dd.args = {mtl::Arg::B(x), mtl::Arg::B(dyn, dyn_off), mtl::Arg::B(d.pack, base_off), mtl::Arg::B(resid ? *resid : x), mtl::Arg::B(out), mtl::Arg::V(a)}; 556 if (hh) dd.args.push_back(mtl::Arg::B(d.xh)); 557 dd.grid[0] = (B * N + 255) / 256; 558 dd.tg[0] = 256; 559 push(ds, dd); 560 }; 561 for (int l = 0; l < d.L; ++l) { 562 const std::string p = "layers." + std::to_string(l) + "."; 563 const size_t base_a = d.ten.at(p + "attention_conv.base_kernel").offset, base_m = d.ten.at(p + "mlp_conv.base_kernel").offset; 564 df2_rms(ds, d.h, d.xn, (p + "input_layernorm.weight").c_str(), B); 565 df2_mmn(ds, p + "attention_conv.kernel_projection.weight", d.xn, 0, N, d.dyn, 640, B); 566 conv(d.xn, d.dyn, 0, base_a, nullptr, d.xc); 567 df2_mmn(ds, p + "self_attn.q_proj.weight", d.xc, 0, N, d.q, 4096, B); 568 nb_ = true; 569 df2_mmn(ds, p + "self_attn.k_proj.weight", d.xc, 0, N, d.k, 1024, B, true); 570 nb_ = true; 571 df2_mmn(ds, p + "self_attn.v_proj.weight", d.xc, 0, N, d.v, 1024, B, true); 572 { 573 struct NrArgs { uint32_t in_stride, slot_mod, heads; float eps; uint32_t has_rope; } qa{4096, 0, 32, d.eps, 1}, ka{1024, 0, 8, d.eps, 1}; 574 mtl::Dispatch qd, kd; 575 qd.p = kd.p = P(ldf2_, "df2_norm_rope", {}, "df2_norm_rope"); 576 qd.args = {mtl::Arg::B(d.q), mtl::Arg::B(d.pack, d.ten.at(p + "self_attn.q_norm.weight").offset), mtl::Arg::B(d.bpos), mtl::Arg::B(d.rtb), 577 mtl::Arg::B(d.qn), mtl::Arg::V(qa)}; 578 qd.grid[0] = B; qd.grid[1] = 32; qd.tg[0] = 128; 579 push(ds, qd); 580 kd.args = {mtl::Arg::B(d.k), mtl::Arg::B(d.pack, d.ten.at(p + "self_attn.k_norm.weight").offset), mtl::Arg::B(d.bpos), mtl::Arg::B(d.rtb), 581 mtl::Arg::B(d.kblk), mtl::Arg::V(ka)}; 582 kd.grid[0] = B; kd.grid[1] = 8; kd.tg[0] = 128; 583 nb_ = true; 584 push(ds, kd); 585 } 586 { 587 struct AttnArgs { uint32_t ring, window; } aa{(uint32_t) DF2_RING, (uint32_t) d.window}; 588 mtl::Dispatch ap, am; 589 ap.p = P(ldf2_, "df2_attn_part", {}, "df2_attn_part"); 590 ap.args = {mtl::Arg::B(d.qn), mtl::Arg::B(d.kring[l]), mtl::Arg::B(d.vring[l]), mtl::Arg::B(d.kblk), mtl::Arg::B(d.v), 591 mtl::Arg::B(d.anchor, 4), mtl::Arg::B(d.part), mtl::Arg::V(aa)}; 592 ap.grid[0] = 8; ap.grid[1] = DF2_MAXCH; ap.tg[0] = 64; 593 push(ds, ap); 594 am.p = P(ldf2_, d.fuse_h ? "df2_attn_merge_h" : "df2_attn_merge", {}, d.fuse_h ? "df2_attn_merge_h" : "df2_attn_merge"); 595 am.args = {mtl::Arg::B(d.part), mtl::Arg::B(d.anchor, 4), mtl::Arg::B(d.ao), mtl::Arg::V(aa)}; 596 if (d.fuse_h) am.args.push_back(mtl::Arg::B(d.xh)); 597 am.grid[0] = 8 * 32; am.tg[0] = 128; 598 push(ds, am); 599 } 600 df2_mmn(ds, p + "self_attn.o_proj.weight", d.ao, 0, 4096, d.o, N, B); 601 conv(d.o, d.dyn, 320 * 4, base_a + 2 * N * 4, &d.h, d.h); 602 df2_rms(ds, d.h, d.xn, (p + "post_attention_layernorm.weight").c_str(), B); 603 df2_mmn(ds, p + "mlp_conv.kernel_projection.weight", d.xn, 0, N, d.dyn, 640, B); 604 conv(d.xn, d.dyn, 0, base_m, nullptr, d.xc); 605 df2_mmn(ds, p + "mlp.gate_proj.weight", d.xc, 0, N, d.gate, d.I, B); 606 nb_ = true; 607 df2_mmn(ds, p + "mlp.up_proj.weight", d.xc, 0, N, d.up, d.I, B, true); 608 { 609 struct SwArgs { uint32_t n; } sa{(uint32_t) (B * d.I)}; 610 mtl::Dispatch sd; 611 sd.p = P(ldf2_, d.fuse_h ? "df2_swiglu_h" : "df2_swiglu", {}, d.fuse_h ? "df2_swiglu_h" : "df2_swiglu"); 612 sd.args = {mtl::Arg::B(d.gate), mtl::Arg::B(d.up), mtl::Arg::B(d.sw), mtl::Arg::V(sa)}; 613 if (d.fuse_h) sd.args.push_back(mtl::Arg::B(d.xh)); 614 sd.grid[0] = (sa.n + 255) / 256; 615 sd.tg[0] = 256; 616 push(ds, sd); 617 } 618 df2_mmn(ds, p + "mlp.down_proj.weight", d.sw, 0, d.I, d.mlp, N, B); 619 conv(d.mlp, d.dyn, 320 * 4, base_m + 2 * N * 4, &d.h, d.h); 620 } 621 df2_rms(ds, d.h, d.fn, "norm.weight", B); 622 const int ND = d.ndraft; 623 if (d.head_q8) { 624 { // rows 1..ND of fn to half (unless the final norm wrote them), then the Q8_0 head rows on the matrix units (8 columns wide whatever ND is: the cap saves top-k and selector work) 625 if (!d.fuse_h) { 626 const uint32_t n = (uint32_t) ND * N; 627 mtl::Dispatch c; 628 c.p = P(ldf2_, "df2_f16", {}, "df2_f16"); 629 c.args = {mtl::Arg::B(d.fn, (size_t) N * 4), mtl::Arg::B(d.xh), mtl::Arg::V(n)}; 630 c.grid[0] = (n + 255) / 256; 631 c.tg[0] = 256; 632 push(ds, c); 633 } 634 struct MmaQArgs { uint32_t K, rows, y_stride, x_stride; } ha{(uint32_t) N, (uint32_t) d.nd, (uint32_t) d.nd, (uint32_t) N}; 635 mtl::Dispatch h8; 636 h8.p = P(ldf2_, "df2_mma8_2_4", {}, "df2_mma8_2_4"); 637 h8.args = {mtl::Arg::B(d.hq), mtl::Arg::B(d.hsc), mtl::Arg::B(d.xh, d.fuse_h ? (size_t) N * 2 : 0), mtl::Arg::B(d.logits), mtl::Arg::V(ha)}; 638 h8.grid[0] = (((uint32_t) d.nd + 7) / 8 + 7) / 8; 639 h8.tg[0] = 4 * 32; 640 push(ds, h8); 641 } 642 } else { 643 mtl::Dispatch xd; 644 xd.p = P(lib_, "xprep", {}, "xprep"); 645 const uint32_t nv = N, nt = MAXT; 646 xd.args = {mtl::Arg::B(d.fn, (size_t) N * 4), mtl::Arg::B(d.A_fn.b), mtl::Arg::V(nv), mtl::Arg::V(nt)}; 647 xd.tg[0] = 256; 648 xd.grid[0] = (N / 16 * MAXT + 255) / 256; 649 push(ds, xd); 650 gemv(ds, d.head_t, d.A_fn, d.logits, (size_t) d.nd, ND, 0, d.head_buf); 651 } 652 { 653 struct TkArgs { int32_t n; } ta{(int32_t) d.nd}; 654 mtl::Dispatch tp, tm; 655 tp.p = P(ldf2_, "df2_topk_part", {}, "df2_topk_part"); 656 tp.args = {mtl::Arg::B(d.logits), mtl::Arg::B(d.tkv), mtl::Arg::B(d.tki), mtl::Arg::V(ta)}; 657 tp.grid[0] = ND; tp.grid[1] = DF2_TOPB; tp.tg[0] = 256; 658 push(ds, tp); 659 struct TkMArgs { int32_t use_map; } tma{d.use_map ? 1 : 0}; 660 tm.p = P(ldf2_, "df2_topk_merge", {}, "df2_topk_merge"); 661 tm.args = {mtl::Arg::B(d.tkv), mtl::Arg::B(d.tki), mtl::Arg::B(d.vmap), mtl::Arg::B(d.topval), mtl::Arg::B(d.toptok), mtl::Arg::V(tma)}; 662 tm.grid[0] = ND; tm.tg[0] = 256; 663 push(ds, tm); 664 } 665 // the selector's hidden projection over the same 7 rows (it reads rows 1..7 of fn) 666 df2_mmn(ds, "candidate_selector.hidden_projection.weight", d.fn, (size_t) N * 4, N, d.hsel, 256, ND, d.head_q8); // (the head just rounded rows 1..ND to half) 667 { 668 struct SelArgs { uint32_t rank, rows; } sa{(uint32_t) d.rank, (uint32_t) ND}; 669 mtl::Dispatch sd; 670 { // the selector's tables: BF16 rows (the incoai pack) or Q4_0 rows (the community GGUF: 8 blocks of 18 bytes a row) 671 const gguf::Tensor& cbt = d.ten.at("candidate_selector.predecessor_codebook"); 672 if (cbt.type != d.ten.at("candidate_selector.successor_codebook").type) { std::fprintf(stderr, "strata metal: DFlash2: the two selector tables differ in type\n"); } 673 const bool cb4 = cbt.type == ref::Q4_0; 674 sd.p = P(ldf2_, cb4 ? "df2_select_q4" : "df2_select", {}, cb4 ? "df2_select_q4" : "df2_select"); 675 } 676 sd.args = {mtl::Arg::B(d.hsel), mtl::Arg::B(d.topval), mtl::Arg::B(d.toptok), 677 mtl::Arg::B(d.pack, d.ten.at("candidate_selector.predecessor_codebook").offset), 678 mtl::Arg::B(d.pack, d.ten.at("candidate_selector.successor_codebook").offset), mtl::Arg::B(d.anchor, 0), 679 mtl::Arg::B(d.outbuf, 0), mtl::Arg::B(d.outbuf, 16 * 4), mtl::Arg::V(sa)}; 680 sd.grid[0] = 1; sd.tg[0] = 256; 681 push(ds, sd); 682 } 683} 684 685// context rows of the prompt: the taps are in `taps` ([n][nt * N] floats, a Window buffer or `staging`) 686bool Window::df2_context(const mtl::Buffer& taps, size_t taps_off, int64_t n, int64_t pos0, std::string& err) { 687 Df2& d = *df2_; 688 const double tc0 = now_ms(); 689 if (!d.bound) { err = "dflash2: not bound"; return false; } 690 const size_t row_bytes = d.taps.size() * N * 4; 691 for (int64_t b0 = 0; b0 < n; b0 += DF2_CTX_MAX) { 692 const int nb = (int) std::min<int64_t>(DF2_CTX_MAX, n - b0); 693 int32_t* pos = d.ctxpos.as<int32_t>(); 694 for (int i = 0; i < nb; ++i) pos[i] = (int32_t) (pos0 + b0 + i); 695 std::vector<mtl::Dispatch> ds; 696 nb_ = false; 697 for (int g0 = 0; g0 < nb; g0 += 8) { 698 const int m = std::min(8, nb - g0); 699 df2_rope_rows(pos + g0, m, d.theta, d.rtctx.as<float>() + (size_t) g0 * 128); 700 df2_ctx_list(ds, taps, taps_off + (size_t) (b0 + g0) * row_bytes, m, d.ctxpos, (size_t) g0 * 4, d.rtctx, (size_t) g0 * 128 * 4); 701 } 702 const double tg0 = now_ms(); 703 cx_->run_graph(ds); 704 static const bool st2 = std::getenv("STRATA_DF2_STATS") != nullptr; 705 if (st2 && nb > 16) std::fprintf(stderr, "strata metal: DFlash2 context graph of %d rows: %zu dispatches, built in %.1f ms, run %.1f ms\n", nb, ds.size(), tg0 - tc0, now_ms() - tg0); 706 } 707 if (!d.dump_path.empty()) df2_dump_rows(taps, taps_off, n, pos0); 708 return true; 709} 710 711// STRATA_DF2_DUMP: keep the rows the drafter is fed (positions must run 0, 1, 2 ... without a gap) and write them with the answer of one round 712void Window::df2_dump_rows(const mtl::Buffer& taps, size_t taps_off, int64_t n, int64_t pos0) { 713 Df2& d = *df2_; 714 if (pos0 != d.dump_next) { d.dump_ok = false; return; } 715 const size_t row_floats = d.taps.size() * N; 716 const float* src = (const float*) (taps.as<uint8_t>() + taps_off); 717 d.dump_taps.insert(d.dump_taps.end(), src, src + (size_t) n * row_floats); 718 d.dump_next = pos0 + n; 719} 720 721void Window::df2_dump_write(int64_t s, int32_t anchor) { 722 Df2& d = *df2_; 723 if (!d.dump_ok || d.dump_next != s) { std::fprintf(stderr, "strata metal: STRATA_DF2_DUMP: the context rows are not 0..%lld, nothing written\n", (long long) s); return; } 724 std::FILE* f = std::fopen(d.dump_path.c_str(), "wb"); 725 if (!f) { std::fprintf(stderr, "strata metal: cannot write %s\n", d.dump_path.c_str()); return; } 726 const int32_t hdr[8] = {0x32465344, 1, (int32_t) s, anchor, (int32_t) d.nd, (int32_t) d.taps.size(), N, d.mask_token}; 727 std::fwrite(hdr, 4, 8, f); 728 std::fwrite(d.dump_taps.data(), 4, d.dump_taps.size(), f); 729 std::fwrite(d.dump_anchor_emb.data(), 4, N, f); 730 std::fwrite(d.mask_emb.data(), 4, N, f); 731 std::fwrite(d.fn.ptr, 4, (size_t) DF2_ROWS * N, f); 732 std::fwrite(d.hsel.ptr, 4, (size_t) DF2_DRAFTS * 256, f); 733 std::fwrite(d.topval.ptr, 4, DF2_DRAFTS * 16, f); 734 std::fwrite(d.toptok.ptr, 4, DF2_DRAFTS * 16, f); 735 std::fwrite(d.outbuf.ptr, 4, 32, f); 736 std::fwrite(d.vmap.ptr, 4, d.use_map ? (size_t) d.nd : 0, f); 737 std::fwrite(d.logits.ptr, 4, (size_t) DF2_DRAFTS * (size_t) d.nd, f); 738 std::fclose(f); 739 std::fprintf(stderr, "strata metal: STRATA_DF2_DUMP: %lld context rows and the answer of round %lld written to %s\n", (long long) s, (long long) d.rounds, d.dump_path.c_str()); 740} 741 742bool Window::df2_draft(int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err) { 743 Df2& d = *df2_; 744 if (!d.bound) { err = "dflash2: not bound"; return false; } 745 if (n_new < 1 || n_new > DF2_ROWS) { err = "dflash2: draft rows out of range"; return false; } 746 const double t0 = now_ms(); 747 const int64_t s = pos0 + n_new; 748 int32_t* dp = d.dpos.as<int32_t>(); 749 int32_t* bp = d.bpos.as<int32_t>(); 750 for (int i = 0; i < 8; ++i) { dp[i] = (int32_t) (pos0 + std::min(i, n_new - 1)); bp[i] = (int32_t) (s + i); } 751 int32_t* an = d.anchor.as<int32_t>(); 752 an[0] = anchor; 753 an[1] = (int32_t) s; 754 an[2] = (int32_t) d.floor; 755 df2_rope_rows(dp, 8, d.theta, d.rtd.as<float>()); 756 df2_rope_rows(bp, 8, d.theta, d.rtb.as<float>()); 757 float* h = d.h.as<float>(); 758 { 759 const gguf::Tensor& te = T("token_embd.weight"); 760 const size_t rb = ref::row_bytes(te.type, N); 761 if (const float* img = nullptr) (void) img; 762 ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) anchor * rb, h, N); 763 for (int i = 1; i < DF2_ROWS; ++i) std::memcpy(h + (size_t) i * N, d.mask_emb.data(), (size_t) N * 4); 764 } 765 if (!d.dump_path.empty()) { 766 df2_dump_rows(tap_dec_, 0, n_new, pos0); 767 d.dump_anchor_emb.assign(h, h + N); 768 } 769 d.last_build_ms = 0; 770 if (!d.built[n_new]) { 771 const double tb = now_ms(); 772 nb_ = false; 773 df2_ctx_list(d.list[n_new], tap_dec_, 0, n_new, d.dpos, 0, d.rtd, 0); 774 df2_block_list(d.list[n_new]); 775 d.built[n_new] = true; 776 d.last_build_ms = now_ms() - tb; // the list and its pipelines (compiled on first use) - once per window size, not a per-round cost 777 d.build_ms += d.last_build_ms; 778 } 779 int32_t* ot = d.outbuf.as<int32_t>(); 780 for (int i = 0; i < DF2_DRAFTS; ++i) ot[i] = -1; // (draft ids past the cap stay -1) 781 const double tr = now_ms(); 782 const double g = cx_->run_graph(d.list[n_new]); 783 const double wall = now_ms() - tr; 784 d.gpu_ms += 1000.0 * g; 785 if (d.rounds >= 1 && d.last_build_ms == 0) { d.run_ms += wall; d.host_ms += now_ms() - t0 - wall; ++d.steady; } 786 static const bool prof = std::getenv("STRATA_DF2_PROF") != nullptr; 787 static const bool stats = std::getenv("STRATA_DF2_STATS") != nullptr; // serve leaves through exit(): a periodic line instead of the destructor's 788 if (stats && d.steady > 0 && d.steady % 150 == 0) 789 std::fprintf(stderr, "strata metal: DFlash2 stats after %lld rounds: GPU %.2f ms/round, run_graph %.2f ms, host before the graph %.2f ms\n", (long long) d.steady, 790 d.gpu_ms / (double) d.rounds, d.run_ms / (double) d.steady, d.host_ms / (double) d.steady); 791 if (prof && d.rounds == 10) df2_prof(d.list[n_new]); 792 for (int i = 0; i < DF2_DRAFTS; ++i) { 793 drafts[i] = i < d.ndraft ? ot[i] : 0; // DF-04: past the cap token 0 with probability 0 794 if (probs) probs[i] = i < d.ndraft ? d.outbuf.as<float>()[16 + i] : 0.0f; 795 } 796 if (!d.dump_path.empty() && d.rounds == d.dump_round) { df2_dump_write(s, anchor); d.dump_path.clear(); } 797 ++d.rounds; 798 (void) t0; 799 return true; 800} 801 802 803// STRATA_DF2_PROF=1 (measurement): once, at the 10th round, the GPU time of each kernel class of the round alone (each class's dispatches run by themselves) 804void Window::df2_prof(const std::vector<mtl::Dispatch>& ds) { 805 Df2& d = *df2_; 806 std::map<uint64_t, std::string> tname; 807 for (const auto& [k, v] : d.ten) { 808 if (v.type != ref::Q8_0) continue; 809 std::string n = k; 810 if (n.rfind("layers.", 0) == 0) n = n.substr(n.find('.', 7) + 1); 811 tname[v.offset] = n; 812 } 813 std::map<std::string, std::vector<mtl::Dispatch>> by; 814 for (const auto& x : ds) { 815 std::string c = pkey_of_.count(x.p) ? pkey_of_[x.p] : "?"; 816 if (c.find('#') != std::string::npos) c = c.substr(0, c.find('#')); 817 if ((c.rfind("gemv_", 0) == 0 || c.rfind("df2_mm", 0) == 0) && !x.args.empty()) { 818 if (x.args[0].buf == &d.wq && tname.count(x.args[0].off)) c = "mm " + tname[x.args[0].off]; 819 else if (x.args[0].buf == &d.hq) c = "mm head"; 820 else if (x.args[0].buf == d.head_buf) c = "gemv head"; 821 } 822 mtl::Dispatch y = x; 823 y.barrier = true; 824 by[c].push_back(y); 825 } 826 auto med = [&](const std::vector<mtl::Dispatch>& v) { 827 std::vector<double> t; 828 for (int i = 0; i < 7; ++i) t.push_back(1000.0 * cx_->run_graph(v)); 829 std::sort(t.begin(), t.end()); 830 return t[3]; 831 }; 832 const double all = med(ds); 833 std::vector<std::pair<double, std::string>> rows; 834 double sum = 0; 835 for (const auto& [c, v] : by) { 836 const double m = med(v); 837 sum += m; 838 rows.push_back({m, c + " x" + std::to_string(v.size())}); 839 } 840 std::sort(rows.rbegin(), rows.rend()); 841 std::fprintf(stderr, "strata metal df2 prof: round of %zu dispatches, GPU %.3f ms; classes alone (serialized) sum %.3f ms:\n", ds.size(), all, sum); 842 for (const auto& [m, c] : rows) std::fprintf(stderr, "strata metal df2 prof: %8.3f ms %5.1f%% %s\n", m, 100.0 * m / sum, c.c_str()); 843} 844 845void Window::df2_free() { 846 if (df2_ && df2_->rounds > 0) 847 std::fprintf(stderr, "strata metal: DFlash2 %lld rounds: GPU %.2f ms/round, run_graph %.2f ms (steady, %lld rounds), host before %.2f ms, lists and pipelines built once: %.0f ms\n", 848 (long long) df2_->rounds, df2_->gpu_ms / (double) df2_->rounds, df2_->steady ? df2_->run_ms / (double) df2_->steady : 0.0, 849 (long long) df2_->steady, df2_->steady ? df2_->host_ms / (double) df2_->steady : 0.0, df2_->build_ms); 850 delete df2_; 851 df2_ = nullptr; 852} 853 854bool Window::df2_prepare(std::string& err) { 855 if (df2_ == nullptr || !df2_->bound) { err = "dflash2: not bound"; return false; } 856 Df2& d = *df2_; 857 for (int n = 1; n <= DF2_ROWS; ++n) 858 if (!d.built[n]) { 859 const double tb = now_ms(); 860 nb_ = false; 861 df2_ctx_list(d.list[n], tap_dec_, 0, n, d.dpos, 0, d.rtd, 0); 862 df2_block_list(d.list[n]); 863 d.built[n] = true; 864 d.build_ms += now_ms() - tb; 865 } 866 return true; 867} 868void Window::df2_set_cap(int n) { 869 if (df2_ == nullptr || n == df2_->ndraft) return; 870 df2_->ndraft = n; 871 for (int i = 0; i <= DF2_ROWS; ++i) { df2_->built[i] = false; df2_->list[i].clear(); } 872} 873void Window::df2_set_floor(int64_t pos) { if (df2_) df2_->floor = pos; } 874int64_t Window::df2_floor() const { return df2_ ? df2_->floor : 0; } 875 876// A restored or edited conversation: the drafter's current lineage (token history cur_hist, rows up to cur_hi) is stashed with its row log, and a 877// stashed lineage that covers the reused prefix [0, resume) of ids is swapped back in; the ring rows of the window [resume - 2047, resume) are 878// rebuilt from its log. Returns the number of rows rebuilt (0: no lineage matched, the caller restarts the ring at resume). 879int64_t Window::df2_restore_lineage(const std::vector<int32_t>& cur_hist, int64_t cur_hi, const int32_t* ids, int64_t resume, std::string& err) { 880 Df2& d = *df2_; 881 if (!d.bound || !d.fuse_h || !d.rowlog.handle || d.stash_max <= 0 || resume <= 0) return 0; 882 const uint64_t log_bytes = (uint64_t) DF2_RING * N * 2; 883 // 1. the departing lineage goes to the stash (its buffer with it) 884 if (cur_hi > 0 && !cur_hist.empty()) { 885 Df2::Stash s; 886 s.hist = cur_hist; s.hi = cur_hi; s.floor = d.floor; s.log = d.rowlog; s.used = ++d.stash_tick; 887 static const bool chk = std::getenv("STRATA_DF2_CHECK_REBUILD") != nullptr; 888 if (chk) { // test: a copy of the ring (all layers, K then V) to compare the rebuilt rows against 889 const size_t one = (size_t) DF2_RING * 1024 * 4; 890 s.chk.resize(one * 2 * (size_t) d.L); 891 for (int l = 0; l < d.L; ++l) { 892 std::memcpy(s.chk.data() + one * (size_t) (2 * l), d.kring[l].ptr, one); 893 std::memcpy(s.chk.data() + one * (size_t) (2 * l + 1), d.vring[l].ptr, one); 894 } 895 } 896 d.stash.push_back(std::move(s)); 897 d.rowlog = mtl::Buffer(); 898 } 899 // 2. the stashed lineage that covers the reused prefix: history equal to ids over [0, resume), rows [lo, resume) still in its log 900 const int64_t lo = std::max<int64_t>(0, resume - (DF2_CTX_MAX - 1)); 901 int best = -1; 902 for (size_t i = 0; i < d.stash.size(); ++i) { 903 const Df2::Stash& s = d.stash[i]; 904 int64_t k0 = 0; 905 { static const bool stv = std::getenv("STRATA_DF2_STATS") != nullptr; 906 if (stv) { while (k0 < resume && k0 < (int64_t) s.hist.size() && s.hist[(size_t) k0] == ids[k0]) ++k0; 907 std::fprintf(stderr, "strata metal: DFlash2 stash %zu: hi %lld, history %zu tokens, floor %lld, common prefix with the request %lld of %lld (window start %lld)%s", i, (long long) s.hi, s.hist.size(), (long long) s.floor, (long long) k0, (long long) resume, (long long) lo, "\n"); } } 908 if (s.hi + 256 < resume || (int64_t) s.hist.size() < resume || s.hi - DF2_RING > lo) continue; // (the last few committed rows of a finished request never got a context row: a gap of up to 256 at the end is accepted) // not covered / rows overwritten 909 int64_t k = 0; 910 while (k < resume && s.hist[(size_t) k] == ids[k]) ++k; 911 if (k < resume) continue; 912 if (best < 0 || s.used > d.stash[(size_t) best].used) best = (int) i; 913 } 914 // 3. the buffer of the new current lineage: the matching stash's, else a recycled or fresh one (evicting the least recently used over the budget) 915 Df2::Stash match; 916 if (best >= 0) { match = std::move(d.stash[(size_t) best]); d.stash.erase(d.stash.begin() + best); } 917 while ((int) d.stash.size() > d.stash_max) { 918 size_t old = 0; 919 for (size_t i = 1; i < d.stash.size(); ++i) if (d.stash[i].used < d.stash[old].used) old = i; 920 if (!d.rowlog.handle && best < 0) d.rowlog = d.stash[old].log; // recycle the evicted buffer (its rows are another lineage's; a floor guards them) 921 else cx_->free(d.stash[old].log); 922 d.stash.erase(d.stash.begin() + old); 923 } 924 if (best >= 0) { 925 if (d.rowlog.handle) cx_->free(d.rowlog); 926 d.rowlog = match.log; 927 } else if (!d.rowlog.handle) { 928 d.rowlog = cx_->alloc(log_bytes); 929 d.bytes += log_bytes; 930 } 931 if (best < 0) return 0; 932 // 4. rebuild the ring rows [from, resume) from the log (rows below the lineage's own floor were never logged) 933 const int64_t r_end = std::min<int64_t>(resume, match.hi); 934 const int64_t from = std::max<int64_t>(lo, match.floor); 935 if (from >= r_end) return 0; // nothing of this lineage is in the window (the buffer is in place; the caller restarts the ring at resume) 936 const double t0 = now_ms(); 937 int32_t* pos = d.ctxpos.as<int32_t>(); 938 std::vector<mtl::Dispatch> ds; 939 for (int64_t b0 = from; b0 < r_end; ) { 940 const int64_t nb = std::min<int64_t>(DF2_CTX_MAX, r_end - b0); 941 ds.clear(); 942 nb_ = false; 943 for (int g0 = 0; g0 < nb; g0 += 8) { 944 const int m = (int) std::min<int64_t>(8, nb - g0); 945 for (int i = 0; i < m; ++i) pos[g0 + i] = (int32_t) (b0 + g0 + i); 946 df2_rope_rows(pos + g0, m, d.theta, d.rtctx.as<float>() + (size_t) g0 * 128); 947 struct CopyArgs { uint32_t slot_mod, rows, cols; } ga{(uint32_t) DF2_RING, (uint32_t) m, (uint32_t) N}; 948 mtl::Dispatch gt; 949 gt.p = P(ldf2_, "df2_gather_rows", {}, "df2_gather_rows"); 950 gt.args = {mtl::Arg::B(d.rowlog), mtl::Arg::B(d.xh), mtl::Arg::B(d.ctxpos, (size_t) g0 * 4), mtl::Arg::V(ga)}; 951 gt.grid[0] = (m * N + 255) / 256; 952 gt.tg[0] = 256; 953 push(ds, gt); 954 df2_kv_list(ds, m, d.ctxpos, (size_t) g0 * 4, d.rtctx, (size_t) g0 * 128 * 4); 955 } 956 cx_->run_graph(ds); 957 b0 += nb; 958 } 959 if (!match.chk.empty()) { // test: the rebuilt rows against the original update's bytes 960 const size_t one = (size_t) DF2_RING * 1024 * 4; 961 int64_t bad = 0, tot = 0; 962 for (int l = 0; l < d.L; ++l) 963 for (int kv = 0; kv < 2; ++kv) { 964 const uint8_t* ref = match.chk.data() + one * (size_t) (2 * l + kv); 965 const uint8_t* got = (kv == 0 ? d.kring[l] : d.vring[l]).as<uint8_t>(); 966 for (int64_t q = from; q < r_end; ++q) { 967 const size_t off = (size_t) (q % DF2_RING) * 1024 * 4; 968 ++tot; 969 if (std::memcmp(ref + off, got + off, 1024 * 4) != 0) { 970 ++bad; 971 if (bad <= 3) { 972 double md = 0, mv = 0; const float* rf = (const float*) (ref + off); const float* gf = (const float*) (got + off); 973 for (int i = 0; i < 1024; ++i) { md = std::max(md, (double) std::fabs(rf[i] - gf[i])); mv = std::max(mv, (double) std::fabs(rf[i])); } 974 std::fprintf(stderr, "strata metal: rebuild check: layer %d %s position %lld: max |diff| %.3g, max |orig| %.3g, first values orig %.4f %.4f rebuilt %.4f %.4f%s", l, kv ? "V" : "K", (long long) q, md, mv, rf[0], rf[1], gf[0], gf[1], "\n"); 975 } 976 } 977 } 978 } 979 std::fprintf(stderr, "strata metal: DFlash2 rebuild check: %lld of %lld ring rows (K/V x layers x positions) differ from the original update%s", (long long) bad, (long long) tot, "\n"); 980 } 981 d.floor = from; 982 d.rebuilt_rows += r_end - from; 983 ++d.rebuilds; 984 static const bool st = std::getenv("STRATA_DF2_STATS") != nullptr; 985 if (st) std::fprintf(stderr, "strata metal: DFlash2 lineage restored from the row log: %lld rows [%lld, %lld) rebuilt in %.1f ms (%zu lineages stashed)\n", 986 (long long) (r_end - from), (long long) from, (long long) r_end, now_ms() - t0, d.stash.size()); 987 (void) err; 988 return r_end - from; 989} 990 991uint64_t Window::df2_bytes() const { return df2_ ? df2_->bytes : 0; } 992double Window::df2_gpu_ms() const { return df2_ ? df2_->gpu_ms : 0.0; } 993double Window::df2_last_build_ms() const { return df2_ ? df2_->last_build_ms : 0.0; } 994 995// ---- entry points for the shared host code (verify.cpp, prefill.cpp) and the drafter shim below 996bool window_taps(void* w, const std::vector<int>& layers, const float** tap_dev, std::string& err) { 997 Window* x = (Window*) w; 998 if (!x->taps_enable(layers, err)) return false; 999 *tap_dev = x->tap_dec_ptr(); 1000 return true; 1001} 1002 1003// Prefill::run's Metal side: taps for the prompt rows at positions >= first_pos (cb == nullptr: none) 1004bool prompt_taps(const std::vector<int>& layers, int64_t first_pos, const std::function<bool(const float*, int64_t, int64_t, std::string&)>& cb, 1005 std::string& err) { 1006 if (g_window == nullptr) { err = "metal prompt: the decode window is not up yet"; return false; } 1007 if (cb && !g_window->taps_enable(layers, err)) return false; 1008 g_window->taps_set_cb(first_pos, cb); 1009 return true; 1010} 1011 1012bool Window::df2_ensure(const std::string& path, std::string& err) { 1013 if (df2_ != nullptr) return true; 1014 return df2_open(path, err); 1015} 1016 1017// context rows given as a host pointer into one of the window's tap buffers (the prompt chunk's, the decode window's) or anywhere else (copied) 1018bool Window::df2_context_ptr(const float* taps, int64_t n, int64_t pos0, std::string& err) { 1019 if (df2_ == nullptr || !df2_->bound) { err = "dflash2: not bound"; return false; } 1020 const size_t row_bytes = tap_layers_.size() * N * 4; 1021 const uint8_t* p = (const uint8_t*) taps; 1022 for (mtl::Buffer* b : {&tap_pro_, &tap_dec_}) 1023 if (b->handle && p >= b->as<uint8_t>() && p + (size_t) n * row_bytes <= b->as<uint8_t>() + b->bytes) 1024 return df2_context(*b, (size_t) (p - b->as<uint8_t>()), n, pos0, err); 1025 if (df2_stage_rows_ < n + MAXT) { 1026 if (df2_stage_.handle) cx_->free(df2_stage_); 1027 df2_stage_ = cx_->alloc((size_t) (n + MAXT) * row_bytes); 1028 df2_stage_rows_ = n + MAXT; 1029 } 1030 std::memcpy(df2_stage_.ptr, taps, (size_t) n * row_bytes); 1031 return df2_context(df2_stage_, 0, n, pos0, err); 1032} 1033 1034} // namespace strata::metal_engine 1035 1036// ---- core::Dflash2Drafter on Metal: the class of include/strata/core/dflash2.hpp, backed by the Window above. load() reads the pack's index (the 1037// tap layers are asked before the window exists); bind() brings the pack and the draft head to the GPU once the window is up. 1038namespace strata::core { 1039 1040namespace { 1041std::string g_df2_pack_path; 1042} 1043 1044Dflash2Drafter::~Dflash2Drafter() {} 1045 1046bool Dflash2Drafter::load(const std::string& pack_path, int device, std::string& err) { 1047 device_ = device; 1048 std::vector<int> taps; 1049 std::map<std::string, gguf::Tensor> ten; 1050 std::map<std::string, std::string> cfg; 1051 uint64_t total = 0, data_off = 0; 1052 if (!strata::metal_engine::df2_read_index(pack_path, taps, ten, total, data_off, cfg, err)) return false; 1053 taps_ = taps; 1054 if (cfg.count("mask_token")) mask_token_ = std::atoi(cfg["mask_token"].c_str()); 1055 g_df2_pack_path = pack_path; 1056 return true; 1057} 1058 1059bool Dflash2Drafter::bind(const WeightTable&, const NativeHead*, const std::string& vocab_file, std::string& err, int /*head_device: one card on Metal*/) { 1060 strata::metal_engine::Window* w = strata::metal_engine::g_window; 1061 if (w == nullptr) { err = "dflash2: the Metal decode window is not up"; return false; } 1062 if (bound_) return true; 1063 if (!w->df2_ensure(g_df2_pack_path, err) || !w->df2_bind(vocab_file, err)) return false; 1064 vram_ = w->df2_bytes(); 1065 bound_ = true; 1066 return true; 1067} 1068 1069bool Dflash2Drafter::bind_raw(EmbedFn, const void*, int, int64_t, const std::vector<int32_t>&, std::string& err) { 1070 err = "dflash2: bind_raw is a test hook of the CUDA / HIP build"; 1071 return false; 1072} 1073 1074bool Dflash2Drafter::context(const float* taps, int64_t n, int64_t pos0, std::string& err) { 1075 strata::metal_engine::Window* w = strata::metal_engine::g_window; 1076 if (w == nullptr) { err = "dflash2: not bound"; return false; } 1077 if (!bound_) { // the prompt's taps arrive before bind() (CUDA loads the weights in load()): bring the pack up now, over the MTP's draft vocabulary 1078 if (!w->df2_ensure(g_df2_pack_path, err) || !w->df2_bind("", err)) return false; 1079 vram_ = w->df2_bytes(); 1080 bound_ = true; 1081 } 1082 if (!w->df2_context_ptr(taps, n, pos0, err)) return false; 1083 have_ctx_ = std::max<int64_t>(have_ctx_, pos0 + n); 1084 ring_hi_ = std::max<int64_t>(ring_hi_, pos0 + n); 1085 return true; 1086} 1087 1088bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err) { 1089 strata::metal_engine::Window* w = strata::metal_engine::g_window; 1090 if (w == nullptr || !bound_) { err = "dflash2: not bound"; return false; } 1091 if (taps != nullptr && taps != w->tap_dec_ptr()) { err = "dflash2: the taps are not the window's"; return false; } 1092 const auto t0 = std::chrono::steady_clock::now(); 1093 if (!w->df2_draft(n_new, pos0, anchor, drafts, probs, err)) return false; 1094 ms_draft += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() - w->df2_last_build_ms(); // (the one-time list and pipeline build is not a round cost) 1095 ms_gpu = w->df2_gpu_ms(); 1096 ++rounds; 1097 have_ctx_ = std::max<int64_t>(have_ctx_, pos0 + n_new); 1098 ring_hi_ = std::max<int64_t>(ring_hi_, pos0 + n_new); 1099 return true; 1100} 1101 1102bool Dflash2Drafter::prepare(const float*, std::string& err) { 1103 strata::metal_engine::Window* w = strata::metal_engine::g_window; 1104 if (w == nullptr || !bound_) { err = "dflash2: not bound"; return false; } 1105 return w->df2_prepare(err); 1106} 1107 1108void Dflash2Drafter::set_max_drafts(int n) { 1109 n = std::max(1, std::min(n, (int) kDrafts)); 1110 ndraft_ = n; 1111 if (strata::metal_engine::Window* w = strata::metal_engine::g_window) w->df2_set_cap(n); 1112} 1113 1114// Serve: the same bookkeeping as the CUDA drafter (src/core/dflash2.cpp). The ring has no slot tags here: a lineage change moves a floor instead, 1115// the first position written after the restart (attention never looks below it). 1116bool Dflash2Drafter::begin_request(const int32_t* ids, int64_t n, int64_t resume, bool* cold) { 1117 resume = std::max<int64_t>(0, std::min(resume, n)); 1118 int64_t lcp = 0; 1119 const int64_t lim = std::min<int64_t>((int64_t) cur_.hist.size(), resume); 1120 while (lcp < lim && cur_.hist[(size_t) lcp] == ids[lcp]) ++lcp; 1121 const bool stale = ring_hi_ > lcp && lcp < resume; 1122 bool rebuilt = false; 1123 if (stale) { 1124 // another conversation's state was restored under this one: its lineage is stashed with its row log, and the stashed lineage that matches the 1125 // reused prefix (if any) is swapped back in and its ring rows rebuilt (the Metal twin of the row log of the CUDA drafter) 1126 std::string rerr; 1127 if (strata::metal_engine::Window* w = strata::metal_engine::g_window) 1128 rebuilt = w->df2_restore_lineage(cur_.hist, ring_hi_, ids, resume, rerr) > 0; 1129 ++epoch_; 1130 ring_hi_ = rebuilt ? resume : 0; 1131 } 1132 if (rebuilt) { if (cold) *cold = false; cur_.hist.assign(ids, ids + n); return true; } // (the whole prompt: its rows reach the ring through the tap callback, which carries no tokens) 1133 if (strata::metal_engine::Window* w = strata::metal_engine::g_window) 1134 // The ring's valid rows are [floor, ring_hi): a restarted lineage (stale) has no rows below `resume`; a request that goes on from the 1135 // same history keeps the floor of its conversation (it is lowered when the request restarts earlier, never left high for a shorter prompt) 1136 w->df2_set_floor(stale ? resume : std::min<int64_t>(w->df2_floor(), resume)); 1137 if (cold) *cold = stale; 1138 cur_.hist.assign(ids, ids + n); 1139 return true; 1140} 1141 1142void Dflash2Drafter::note_rows(const int32_t* toks, int64_t n, int64_t pos0) { 1143 if (pos0 < 0) return; 1144 if ((int64_t) cur_.hist.size() > pos0) cur_.hist.resize((size_t) pos0); 1145 if ((int64_t) cur_.hist.size() < pos0) return; 1146 cur_.hist.insert(cur_.hist.end(), toks, toks + n); 1147} 1148 1149// The ring log API of the CUDA drafter (src/core/dflash2.cpp: the host log of the activation rows and the stash of parked lineages): on Metal the token 1150// history `cur_.hist` is all the Dflash2Drafter keeps, the rows are rebuilt by the window (df2_restore_lineage), so the log calls are small. 1151void Dflash2Drafter::reset() { have_ctx_ = 0; cur_.hist.clear(); ++epoch_; ring_hi_ = 0; } 1152void Dflash2Drafter::init_ring_log() {} 1153void Dflash2Drafter::copy_log_state_from(const Dflash2Drafter& src) { cur_.hist = src.cur_.hist; epoch_ = src.epoch_; ring_hi_ = src.ring_hi_; } 1154uint64_t Dflash2Drafter::ring_log_bytes() const { return 0; } 1155uint64_t Dflash2Drafter::ring_stash_bytes() const { return 0; } 1156 1157// DFlash2 for the --batch slots (f-0291-df2-mgpu: a drafter per slot, cloned from the parent, with split launch / finish and deferred rows) is a CUDA / HIP 1158// feature (a layer split); Metal has one card and no batch slot drafts (generate.cpp does not ask for them on Metal). The calls answer plainly. 1159bool Dflash2Drafter::clone_alloc(const Dflash2Drafter&, std::string& err) { err = "dflash2: batch slot drafters are not on Metal"; return false; } 1160bool Dflash2Drafter::clone_bind(const Dflash2Drafter&, std::string& err) { err = "dflash2: batch slot drafters are not on Metal"; return false; } 1161float* Dflash2Drafter::defer_rows(int64_t, int, std::string& err) { err = "dflash2: deferred rows are not on Metal"; return nullptr; } 1162bool Dflash2Drafter::catch_up(int64_t, std::string&) { return true; } 1163bool Dflash2Drafter::draft_launch(const float*, int, int64_t, int32_t, std::string& err) { err = "dflash2: the split draft is not on Metal"; return false; } 1164bool Dflash2Drafter::draft_finish(int32_t*, float*, std::string& err) { err = "dflash2: the split draft is not on Metal"; return false; } 1165 1166bool Dflash2Drafter::context_async(const float* taps, int64_t n, int64_t pos0, std::string& err) { return context(taps, n, pos0, err); } // (no overlap on Metal yet) 1167bool Dflash2Drafter::context_wait(std::string&) { return true; } 1168 1169bool Dflash2Drafter::debug_rows(std::vector<float>& rows, std::string& err) { 1170 err = "dflash2: debug_rows is not on Metal"; 1171 (void) rows; 1172 return false; 1173} 1174 1175} // namespace strata::core 1176 1177namespace strata::metal_engine {