Merge S25 f-halo-tps (8 commits) into S26 f-halo-s26-ovh: f-halo-int
Conflicts: mtp.cpp (the draft head: S25 converts it with --mtp-q4 first, then STRATA_Q6_PACKED packs it only while it is still Q6_K), native_dense.cpp (includes).
This commit is contained in:
commit
2f6c70f0d1
23 files changed
+1146
-43
No files matched your search
+2
-1
@@ -774,7 +774,8 @@ endif()
|
||||
# worse opt-out. `cpu_require_expert_support()` therefore refuses at startup on a CPU without the
|
||||
# features, and the fallback exists for tests, exactly as P2.S3 specifies.
|
||||
# Plan v0.3 P6: speculation components that need no GPU.
|
||||
add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp)
|
||||
add_library(strata_spec STATIC src/spec/suffix_drafter.cpp src/spec/controller.cpp src/spec/draft_policy.cpp
|
||||
src/spec/draft_source.cpp)
|
||||
target_include_directories(strata_spec PUBLIC include)
|
||||
if(STRATA_BUILD_TESTS)
|
||||
add_executable(suffix_drafter_test src/spec/suffix_drafter_test.cpp)
|
||||
|
||||
@@ -48,6 +48,20 @@ public:
|
||||
void set_prompt_len(int64_t n) { prompt_len_ = n; }
|
||||
/// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere.
|
||||
void set_max_drafts(int k) { max_drafts_ = k; }
|
||||
/// --mtp-hnorm stream (opt-in; before the first draft or prefill): pre_fc_norm_hidden normalizes each
|
||||
/// hyper-connection stream on its own, as llama.cpp's qwen4exp MTP graph does, instead of one RMS over all four.
|
||||
void set_hnorm_per_stream(bool on) { hnorm_stream_ = on; }
|
||||
bool hnorm_per_stream() const { return hnorm_stream_; }
|
||||
/// --mtp-q4 (opt-in; before load): the draft layer's Q8_0 projections and its draft head run from 4-bit (Q4_0)
|
||||
/// copies made at load/bind - fewer bytes per draft step; drafts only, the verify window decides every token.
|
||||
/// (The prompt path's batched K/V pass keeps the Q8_0 originals.)
|
||||
void set_q4(bool proj, bool head) { q4_ = proj; q4_head_ = head; }
|
||||
/// --mtp-draft-vocab FILE (opt-in; before bind): the draft head's token subset from FILE instead of
|
||||
/// rt/draft_vocab.bin (e.g. data/draft_vocab_en.bin, 40K tokens)
|
||||
void set_draft_vocab(const std::string& path) { dvocab_path_ = path; }
|
||||
/// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown)
|
||||
static bool top2_env();
|
||||
int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; }
|
||||
uint64_t vram_bytes() const { return vram_; }
|
||||
/// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it)
|
||||
const QsaState& kv_state() const { return st_; }
|
||||
@@ -130,6 +144,20 @@ private:
|
||||
int max_t_ = 0;
|
||||
int device_ = -1; ///< the device `load` ran on: the public calls switch to it (layer split)
|
||||
int max_drafts_ = 1 << 30;
|
||||
bool hnorm_stream_ = false;
|
||||
bool q4_ = false, q4_head_ = false;
|
||||
uint8_t* dense4_ = nullptr; ///< --mtp-q4: Q4_0 copies of the Q8_0 tensors
|
||||
std::vector<std::pair<std::string, uint64_t>> q4_off_;
|
||||
int dhead_type_ = -1; ///< the draft head subset's ggml type (the main head's, or Q4_0)
|
||||
std::string dvocab_path_;
|
||||
std::string vocab_file() const { return dvocab_path_.empty() ? rt_dir_ + "/draft_vocab.bin" : dvocab_path_; }
|
||||
/// a projection's weights for the draft layer's own pass: the Q4_0 copy under --mtp-q4, else the Q8_0 original
|
||||
const void* wq(const char* name, int& type) const;
|
||||
bool make_q4_dense(const std::vector<uint8_t>& blob, std::string& err);
|
||||
bool make_q4_head(std::string& err);
|
||||
void record_top2(int j);
|
||||
std::vector<int32_t> top2_, dvocab_host_;
|
||||
std::vector<float> lg_host_;
|
||||
int64_t n_vocab_ = 0;
|
||||
uint64_t vram_ = 0;
|
||||
cudaStream_t cs_ = nullptr;
|
||||
|
||||
@@ -90,6 +90,9 @@ struct WeightRef {
|
||||
const void* native_data = nullptr;
|
||||
void* native_q8_1 = nullptr;
|
||||
int native_type = -1;
|
||||
/// S23 experiment (STRATA_HC_Q8=1): a hyper-connection projection's Q8_0 bytes as the GGUF stores them, owned by
|
||||
/// NativeDense, for the verify window's read (every other path keeps the pack's BF16 `data`)
|
||||
const void* hc_q8 = nullptr;
|
||||
/// Plan v0.3 P1: false when the loader SKIPPED this tensor's canonical bytes because another form serves it
|
||||
/// (native GGUF projections, the native head). The metadata above stays valid; `data` is null.
|
||||
bool resident = true;
|
||||
|
||||
@@ -36,6 +36,11 @@ struct FusedGrArgs {
|
||||
float* rs = nullptr; ///< workspace, hc floats
|
||||
float* inject_out = nullptr; ///< hc floats (when w_inject)
|
||||
float* mixed = nullptr; ///< n_embd
|
||||
/// S23 experiment (STRATA_HC_Q8=1): the GGUF's Q8_0 projections (null: the BF16 ones above); fused_gr_read_multi
|
||||
/// only
|
||||
const uint8_t* q8_down = nullptr; ///< Q8_0 [hc_lr][hc*n_embd]
|
||||
const uint8_t* q8_up = nullptr; ///< Q8_0 [hc*n_embd][hc_lr]
|
||||
const uint8_t* q8_inject = nullptr;///< Q8_0 [hc][hc*n_embd]
|
||||
};
|
||||
|
||||
bool fused_gr_supported(int64_t n_embd, int64_t hc, int64_t hc_lr);
|
||||
|
||||
@@ -21,6 +21,11 @@ bool native_qsa_enabled();
|
||||
void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float* output,
|
||||
int n_cols, int n_rows, float epsilon, void* stream);
|
||||
|
||||
// The same per row with gamma[n_cols * groups]: row r is normalized on its own and scaled by gamma's slice
|
||||
// r % groups (the MTP's hidden input, one row per hyper-connection stream: --mtp-hnorm stream).
|
||||
void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output,
|
||||
int n_cols, int groups, int n_rows, float epsilon, void* stream);
|
||||
|
||||
// attn/output [head_dim,n_head]; q_full [2*head_dim,n_head], each row is
|
||||
// [query channels, gate channels]. Output is attn*sigmoid(second-half gate).
|
||||
// Exact output==attn is supported; all other spans must be disjoint.
|
||||
|
||||
@@ -35,6 +35,14 @@ public:
|
||||
/// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft).
|
||||
void observe(bool lookup, int t, int accepted, int match, double round_ms);
|
||||
|
||||
/// --lookup-chain: how many of `k_avail` lookup tokens to append after an MTP window of `t_mtp` tokens whose
|
||||
/// drafts all hold with probability `p_mtp` (estimated from the draft layer's own probabilities): the k with the
|
||||
/// best expected tokens per ms, E(t_mtp) + p_mtp (c + c^2 + .. + c^k) at the cost of t_mtp + k, if it beats the MTP
|
||||
/// window alone by `margin`; c = the acceptance of chained drafts by match length (their own counts). 0 = none.
|
||||
int chain(int t_mtp, double p_mtp, int k_avail, int match) const;
|
||||
/// After a chained round: the MTP window's size, the chained tokens, the window's accepted drafts, its time.
|
||||
void observe_chain(int t_mtp, int k, int accepted, int match, double round_ms);
|
||||
double chain_rate(int match) const;
|
||||
double lookup_rate(int match) const; // current q for a match length
|
||||
double cost_ms(int t) const; // measured or scaled round time of a window of t tokens
|
||||
|
||||
@@ -47,6 +55,7 @@ private:
|
||||
std::array<double, kMaxT + 1> cost_{}, cost_n_{}; // round ms by window size
|
||||
std::array<double, kMaxT + 1> mtp_tok_{}, mtp_n_{}; // tokens committed by MTP windows of that size
|
||||
std::array<double, kBuckets> ok_{}, bad_{}; // lookup drafts accepted / windows cut short, decayed
|
||||
std::array<double, kBuckets> cok_{}, cbad_{}; // chained lookup drafts, the same (reached rounds only)
|
||||
};
|
||||
|
||||
} // namespace strata::spec
|
||||
@@ -0,0 +1,62 @@
|
||||
// include/strata/spec/draft_source.hpp - a source of draft tokens beside the MTP layer (--lookup-chain).
|
||||
//
|
||||
// A source proposes how the context continues; the verify window checks the proposal, so a source can only change
|
||||
// the speed, never the output. The engine asks its sources after the MTP has drafted: the context it passes ends
|
||||
// with those MTP drafts (not yet verified), and whatever a source returns is appended to the same window.
|
||||
//
|
||||
// The built-in source is the request's own text (PromptLookupSource: the suffix drafter over prompt + output).
|
||||
// Other sources (a retrieval store over a codebase or earlier conversations) register with
|
||||
// extra_draft_sources() before the first request; the engine takes the proposal with the longest match.
|
||||
#pragma once
|
||||
|
||||
#include "strata/spec/suffix_drafter.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::spec {
|
||||
|
||||
class DraftSource {
|
||||
public:
|
||||
virtual ~DraftSource() = default;
|
||||
virtual const char* name() const = 0;
|
||||
/// A new request starts (its prompt follows through append()).
|
||||
virtual void reset() {}
|
||||
/// Committed context, in order: the request's prompt, then every token the verify windows accept.
|
||||
virtual void append(const int32_t* tokens, size_t n) { (void) tokens; (void) n; }
|
||||
/// Propose up to `max_k` tokens that follow the context. `tail` holds the context's last `n_tail` tokens (at most
|
||||
/// 64); its last `n_pending` are drafts not yet verified (never passed to append()). Writes `out`, returns how
|
||||
/// many (0 = nothing to propose) and sets `*match` to the number of trailing context tokens the proposal is based
|
||||
/// on (its confidence: the engine requires --lookup-chain-min and prefers the longest).
|
||||
virtual int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) = 0;
|
||||
};
|
||||
|
||||
/// The request's own text: the suffix drafter (prompt lookup) behind the DraftSource interface.
|
||||
class PromptLookupSource final : public DraftSource {
|
||||
public:
|
||||
explicit PromptLookupSource(SuffixDrafter& d) : d_(d) {}
|
||||
const char* name() const override { return "prompt-lookup"; }
|
||||
void reset() override { d_.reset(); }
|
||||
void append(const int32_t* tokens, size_t n) override { d_.append(tokens, n); }
|
||||
int propose(const int32_t* tail, int n_tail, int n_pending, int max_k, int32_t* out, int* match) override {
|
||||
n_pending = n_pending < n_tail ? n_pending : n_tail;
|
||||
const int k = d_.propose_after(tail + (n_tail - n_pending), n_pending, max_k, out);
|
||||
*match = k > 0 ? d_.last_match() : 0;
|
||||
return k;
|
||||
}
|
||||
|
||||
private:
|
||||
SuffixDrafter& d_;
|
||||
};
|
||||
|
||||
/// Sources besides the request's own text, asked after it (empty unless something registered one at startup).
|
||||
std::vector<std::unique_ptr<DraftSource>>& extra_draft_sources();
|
||||
|
||||
/// Ask `own` and then every extra source; the proposal with the longest match of at least `min_match` wins
|
||||
/// (ties keep the earlier source). Returns its length (0 = none); `*match` and `*source` (index: 0 = own) describe it.
|
||||
int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match,
|
||||
int32_t* out, int* match, int* source);
|
||||
|
||||
} // namespace strata::spec
|
||||
@@ -30,9 +30,15 @@ public:
|
||||
/// Write up to `max_k` proposed next tokens to `out`; returns how many (0 = no match of at least min_match).
|
||||
int propose(int max_k, int32_t* out);
|
||||
|
||||
/// --lookup-chain: as propose(), for the history followed by `extra` (the draft head's proposal for the next
|
||||
/// tokens), so the lookup continues where those drafts end. The history itself is unchanged; the extra tokens are
|
||||
/// only part of the suffix being matched and may be read back as part of a periodic continuation.
|
||||
int propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out);
|
||||
|
||||
/// Length of the match behind the last proposal (0 if none).
|
||||
int last_match() const { return last_match_; }
|
||||
size_t size() const { return hist_.size(); }
|
||||
const std::vector<int32_t>& history() const { return hist_; }
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
|
||||
+143
-16
@@ -36,11 +36,16 @@
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
#ifdef STRATA_NATIVE_EXPERTS
|
||||
#include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load
|
||||
#endif
|
||||
|
||||
namespace strata::core {
|
||||
namespace {
|
||||
|
||||
constexpr float EPS = 1e-6f;
|
||||
constexpr int GGML_Q8_0 = 8;
|
||||
constexpr int GGML_Q4_0 = 2;
|
||||
using Clock = std::chrono::steady_clock;
|
||||
double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
|
||||
|
||||
@@ -104,6 +109,7 @@ MtpDrafter::~MtpDrafter() {
|
||||
for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e);
|
||||
for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e);
|
||||
if (pf_dev_) cudaFree(pf_dev_);
|
||||
if (dense4_) cudaFree(dense4_);
|
||||
for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e);
|
||||
for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e);
|
||||
for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e);
|
||||
@@ -138,6 +144,74 @@ const void* MtpDrafter::q8(const char* name) const {
|
||||
for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off;
|
||||
return nullptr;
|
||||
}
|
||||
const void* MtpDrafter::wq(const char* name, int& type) const {
|
||||
if (dense4_ != nullptr)
|
||||
for (const auto& e : q4_off_)
|
||||
if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; }
|
||||
type = GGML_Q8_0;
|
||||
return q8(name);
|
||||
}
|
||||
|
||||
// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer
|
||||
bool MtpDrafter::make_q4_dense(const std::vector<uint8_t>& blob, std::string& err) {
|
||||
#ifdef STRATA_NATIVE_EXPERTS
|
||||
uint64_t total = 0;
|
||||
std::vector<std::pair<const Tensor*, uint64_t>> plan;
|
||||
for (const auto& t : tensors_) {
|
||||
if (t.kind != "q8_0" || t.cols % 32 != 0) continue;
|
||||
plan.push_back({&t, total});
|
||||
total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull;
|
||||
}
|
||||
std::vector<uint8_t> host((size_t) total);
|
||||
std::vector<float> row;
|
||||
const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0);
|
||||
for (const auto& [t, off] : plan) {
|
||||
row.resize((size_t) t->cols);
|
||||
const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18;
|
||||
for (int64_t r = 0; r < t->rows; ++r) {
|
||||
q8t->to_float(blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols);
|
||||
ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), host.data() + off + (uint64_t) r * out_row, 0, 1, t->cols,
|
||||
nullptr);
|
||||
}
|
||||
q4_off_.push_back({t->name, off});
|
||||
}
|
||||
if (cudaMalloc((void**) &dense4_, (size_t) total) != cudaSuccess) { err = "mtp: the Q4_0 projections do not fit"; return false; }
|
||||
cudaMemcpy(dense4_, host.data(), (size_t) total, cudaMemcpyHostToDevice);
|
||||
vram_ += total;
|
||||
std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0);
|
||||
return true;
|
||||
#else
|
||||
(void) blob;
|
||||
err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format)
|
||||
bool MtpDrafter::make_q4_head(std::string& err) {
|
||||
#ifdef STRATA_NATIVE_EXPERTS
|
||||
const int64_t N = g_->n_embd;
|
||||
const auto* tt = ggml_get_type_traits((ggml_type) head_->type());
|
||||
if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; }
|
||||
const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18;
|
||||
std::vector<uint8_t> src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row);
|
||||
if (cudaMemcpy(src.data(), dhead_, src.size(), cudaMemcpyDeviceToHost) != cudaSuccess) { err = "mtp: reading the draft head"; return false; }
|
||||
std::vector<float> row((size_t) N);
|
||||
for (int64_t r = 0; r < n_dvocab_; ++r) {
|
||||
tt->to_float(src.data() + (size_t) r * in_row, row.data(), N);
|
||||
ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), dst.data() + (size_t) r * out_row, 0, 1, N, nullptr);
|
||||
}
|
||||
// the Q4_0 rows replace the subset in place (they are smaller)
|
||||
if (cudaMemcpy(dhead_, dst.data(), dst.size(), cudaMemcpyHostToDevice) != cudaSuccess) { err = "mtp: writing the draft head"; return false; }
|
||||
dhead_type_ = GGML_Q4_0;
|
||||
std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n",
|
||||
(long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0);
|
||||
return true;
|
||||
#else
|
||||
err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
|
||||
int64_t window) {
|
||||
@@ -176,6 +250,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
|
||||
}
|
||||
cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);
|
||||
vram_ += blob.size();
|
||||
if (q4_ && !make_q4_dense(blob, err)) return false;
|
||||
}
|
||||
// ---- the 512 routed experts, one blob each
|
||||
{
|
||||
@@ -301,10 +376,44 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of
|
||||
// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance
|
||||
bool full_head_env() {
|
||||
static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }();
|
||||
return on;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool MtpDrafter::top2_env() {
|
||||
static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }();
|
||||
return on;
|
||||
}
|
||||
|
||||
// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits
|
||||
// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught.
|
||||
void MtpDrafter::record_top2(int j) {
|
||||
const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
|
||||
if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv);
|
||||
if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1);
|
||||
if (j < 0 || j >= max_t_) return;
|
||||
if (cudaMemcpy(lg_host_.data(), head_logits_, (size_t) nv * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) {
|
||||
top2_[(size_t) j] = -1;
|
||||
return;
|
||||
}
|
||||
int64_t b1 = -1, b2 = -1;
|
||||
for (int64_t i = 0; i < nv; ++i) {
|
||||
const float v = lg_host_[(size_t) i];
|
||||
if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; }
|
||||
else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i;
|
||||
}
|
||||
top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2;
|
||||
}
|
||||
|
||||
uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {
|
||||
uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);
|
||||
if (dhead_ == nullptr) {
|
||||
if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {
|
||||
if (dhead_ == nullptr && !full_head_env()) {
|
||||
if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) {
|
||||
std::fseek(f, 0, SEEK_END);
|
||||
const long size = std::ftell(f);
|
||||
std::fclose(f);
|
||||
@@ -426,9 +535,9 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float
|
||||
return false;
|
||||
}
|
||||
// the draft head's token subset, when tools/draft_vocab.py wrote one
|
||||
if (dhead_ == nullptr) {
|
||||
if (dhead_ == nullptr && !full_head_env()) {
|
||||
std::vector<uint8_t> raw;
|
||||
if (read_file(rt_dir_ + "/draft_vocab.bin", raw) && raw.size() >= 4 && raw.size() % 4 == 0) {
|
||||
if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) {
|
||||
n_dvocab_ = (int64_t) (raw.size() / 4);
|
||||
const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native head
|
||||
if (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess ||
|
||||
@@ -438,12 +547,16 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float
|
||||
return false;
|
||||
}
|
||||
cudaMemcpy(dvocab_, raw.data(), raw.size(), cudaMemcpyHostToDevice);
|
||||
dvocab_host_.resize((size_t) n_dvocab_);
|
||||
std::memcpy(dvocab_host_.data(), raw.data(), raw.size());
|
||||
strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr);
|
||||
cudaDeviceSynchronize();
|
||||
vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size();
|
||||
std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_,
|
||||
(double) (n_dvocab_ * row_bytes) / 1048576.0);
|
||||
if (head->type() == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1
|
||||
dhead_type_ = head->type();
|
||||
if (q4_head_ && !make_q4_head(err)) return false;
|
||||
if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1
|
||||
strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_,
|
||||
"MTP draft head");
|
||||
}
|
||||
@@ -466,6 +579,14 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
|
||||
const GrShapes gs{g.n_embd, g.hc, g.hc_lr};
|
||||
const int32_t* step = step_ + row0 * 4;
|
||||
const int32_t* pos = pos_ + row0 * NH;
|
||||
// --mtp-q4: each projection's format and weights for this pass (Q8_0 unless the Q4_0 copies exist)
|
||||
int wt_fc_embedding, wt_fc_hidden, wt_k_proj, wt_v_proj, wt_q_proj, wt_o_proj;
|
||||
const void* wp_fc_embedding = wq("fc_embedding.weight", wt_fc_embedding);
|
||||
const void* wp_fc_hidden = wq("fc_hidden.weight", wt_fc_hidden);
|
||||
const void* wp_k_proj = wq("self_attn.k_proj.weight", wt_k_proj);
|
||||
const void* wp_v_proj = wq("self_attn.v_proj.weight", wt_v_proj);
|
||||
const void* wp_q_proj = wq("self_attn.q_proj.weight", wt_q_proj);
|
||||
const void* wp_o_proj = wq("self_attn.o_proj.weight", wt_o_proj);
|
||||
try {
|
||||
// ---- the two input branches
|
||||
const WeightRef* we = wt_->find("token_embd.weight");
|
||||
@@ -481,12 +602,15 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
|
||||
}
|
||||
native_qsa_rms_norm_weighted(emb_, f32("pre_fc_norm_embedding.weight"), en_, (int) N, T, EPS, cs);
|
||||
native_quantize_q8_1(en_, xq_, (int) N, T, cs);
|
||||
native_mmvq(GGML_Q8_0, q8("fc_embedding.weight"), xq_, e2_, (int) N, (int) N, T, cs);
|
||||
native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs);
|
||||
native_mmvq(wt_fc_embedding, wp_fc_embedding, xq_, e2_, (int) N, (int) N, T, cs);
|
||||
if (hnorm_stream_) // --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight
|
||||
native_qsa_rms_norm_grouped(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) N, (int) HC, (int) (T * HC), EPS, cs);
|
||||
else
|
||||
native_qsa_rms_norm_weighted(Rin_, f32("pre_fc_norm_hidden.weight"), hn_, (int) (HC * N), T, EPS, cs);
|
||||
for (int c0 = 0; c0 < T * HC; c0 += 8) {
|
||||
const int nc = (int) std::min<int64_t>(8, T * HC - c0);
|
||||
native_quantize_q8_1(hn_ + (size_t) c0 * N, xq_, (int) N, nc, cs);
|
||||
native_mmvq(GGML_Q8_0, q8("fc_hidden.weight"), xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);
|
||||
native_mmvq(wt_fc_hidden, wp_fc_hidden, xq_, h2_ + (size_t) c0 * N, (int) N, (int) N, nc, cs);
|
||||
}
|
||||
add_streams_broadcast(h2_, e2_, R_, N, (int) HC, T, cs);
|
||||
// ---- the attention hyper-connection
|
||||
@@ -510,8 +634,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
|
||||
else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs);
|
||||
};
|
||||
native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);
|
||||
native_mmvq(GGML_Q8_0, q8("self_attn.k_proj.weight"), xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);
|
||||
native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);
|
||||
native_mmvq(wt_k_proj, wp_k_proj, xq_, kcur_, (int) N, (int) (NKV * HD), T, cs);
|
||||
native_mmvq(wt_v_proj, wp_v_proj, xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);
|
||||
for (int t = 0; t < T; ++t) {
|
||||
norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH);
|
||||
if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1
|
||||
@@ -530,7 +654,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
|
||||
vcur_ + t * NKV * HD, s, cs, &st_.host);
|
||||
}
|
||||
if (!full) return true;
|
||||
native_mmvq(GGML_Q8_0, q8("self_attn.q_proj.weight"), xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);
|
||||
native_mmvq(wt_q_proj, wp_q_proj, xq_, qfull_, (int) N, (int) (NH * 2 * HD), T, cs);
|
||||
for (int t = 0; t < T; ++t) {
|
||||
float* qc = qcur_ + t * NH * HD;
|
||||
if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4, (size_t) HD * 4,
|
||||
@@ -548,7 +672,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
|
||||
for (int t = 0; t < T; ++t)
|
||||
native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs);
|
||||
native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);
|
||||
native_mmvq(GGML_Q8_0, q8("self_attn.o_proj.weight"), xq_, bo_, (int) (NH * HD), (int) N, T, cs);
|
||||
native_mmvq(wt_o_proj, wp_o_proj, xq_, bo_, (int) (NH * HD), (int) N, T, cs);
|
||||
// ---- the MLP hyper-connection (the attention write folded in)
|
||||
{
|
||||
FusedGrArgs fa[kFusedGrMaxT];
|
||||
@@ -576,9 +700,9 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
|
||||
moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,
|
||||
hit_xs_, hit_scratch_, parts_, cs);
|
||||
NativeSharedWeights nsw;
|
||||
nsw.gate_type = GGML_Q8_0; nsw.gate_data = q8("mlp.shared_expert.gate_proj.weight");
|
||||
nsw.up_type = GGML_Q8_0; nsw.up_data = q8("mlp.shared_expert.up_proj.weight");
|
||||
nsw.down_type = GGML_Q8_0; nsw.down_data = q8("mlp.shared_expert.down_proj.weight");
|
||||
nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type);
|
||||
nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type);
|
||||
nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type);
|
||||
nsw.q8_1 = xq_;
|
||||
const SForm none{};
|
||||
for (int t = 0; t < T; ++t) {
|
||||
@@ -601,7 +725,8 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri
|
||||
native_quantize_q8_1(sample_, xq_, (int) N, T, cs);
|
||||
const bool sub = dhead_ != nullptr;
|
||||
const int64_t nv = sub ? n_dvocab_ : n_vocab_;
|
||||
native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs);
|
||||
native_mmvq(sub ? dhead_type_ : head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N,
|
||||
(int) nv, T, cs);
|
||||
if (coupled_rec_) {
|
||||
// coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft
|
||||
// (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)
|
||||
@@ -840,6 +965,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
|
||||
return false;
|
||||
}
|
||||
drafts[0] = ((volatile int32_t*) h_out_)[0];
|
||||
if (top2_env()) record_top2(0);
|
||||
float pj = ((volatile float*) h_prob_)[0];
|
||||
if (probs) probs[0] = pj;
|
||||
int n = 1;
|
||||
@@ -854,6 +980,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
|
||||
return false;
|
||||
}
|
||||
drafts[j] = ((volatile int32_t*) h_out_)[j];
|
||||
if (top2_env()) record_top2(j);
|
||||
pj = ((volatile float*) h_prob_)[j];
|
||||
if (probs) probs[j] = pj;
|
||||
++n;
|
||||
|
||||
@@ -7,13 +7,65 @@
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::core {
|
||||
namespace {
|
||||
// S23 experiment (STRATA_HC_Q8=1): the hyper-connection projections' Q8_0 bytes for the verify read
|
||||
bool hc_q8_requested() {
|
||||
static const bool on = [] { const char* v = std::getenv("STRATA_HC_Q8"); return v != nullptr && v[0] == '1'; }();
|
||||
return on;
|
||||
}
|
||||
bool hc_q8_name(const std::string& name) {
|
||||
if (name.rfind("blk.", 0) != 0) return false;
|
||||
static const char* suffixes[] = {".hc_attn_down.weight", ".hc_attn_up.weight", ".hc_attn_inject.weight",
|
||||
".hc_ffn_down.weight", ".hc_ffn_up.weight", ".hc_ffn_inject.weight"};
|
||||
for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true;
|
||||
return false;
|
||||
}
|
||||
// S25: the GGUF keeps the inject rows as F32 - quantized here to Q8_0 (ggml's reference rounding) so the Q8_0 read
|
||||
// covers every hc projection
|
||||
uint16_t half_bits(float f) {
|
||||
uint32_t x;
|
||||
std::memcpy(&x, &f, 4);
|
||||
const uint32_t sign = (x >> 16) & 0x8000u;
|
||||
int32_t e = (int32_t) ((x >> 23) & 0xff) - 127 + 15;
|
||||
uint32_t m = x & 0x7fffffu;
|
||||
if (e <= 0) { // subnormal or zero
|
||||
if (e < -10) return (uint16_t) sign;
|
||||
m |= 0x800000u;
|
||||
const uint32_t shift = (uint32_t) (14 - e);
|
||||
uint32_t h = m >> shift;
|
||||
const uint32_t rem = m & ((1u << shift) - 1), half = 1u << (shift - 1);
|
||||
if (rem > half || (rem == half && (h & 1u))) ++h;
|
||||
return (uint16_t) (sign | h);
|
||||
}
|
||||
if (e >= 31) return (uint16_t) (sign | 0x7c00u);
|
||||
uint32_t h = ((uint32_t) e << 10) | (m >> 13);
|
||||
const uint32_t rem = m & 0x1fffu;
|
||||
if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h;
|
||||
return (uint16_t) (sign | h);
|
||||
}
|
||||
std::vector<uint8_t> q8_0_of(const float* x, uint64_t n) {
|
||||
std::vector<uint8_t> out((size_t) (n / 32 * 34));
|
||||
for (uint64_t b = 0; b < n / 32; ++b) {
|
||||
float amax = 0.0f;
|
||||
for (int j = 0; j < 32; ++j) amax = (std::max)(amax, std::fabs(x[b * 32 + j]));
|
||||
const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f;
|
||||
uint8_t* o = out.data() + b * 34;
|
||||
const uint16_t hb = half_bits(d);
|
||||
std::memcpy(o, &hb, 2);
|
||||
for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t) (int8_t) std::lround(x[b * 32 + j] * id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) {
|
||||
const auto& name = tensor.name;
|
||||
if (name.rfind("blk.", 0) != 0) return false;
|
||||
@@ -79,7 +131,7 @@ bool NativeDense::load(const std::vector<std::string>& shards, WeightTable& tabl
|
||||
std::vector<Pending> pending;
|
||||
std::set<std::string> seen;
|
||||
int max_in = 0;
|
||||
uint64_t total = 0;
|
||||
uint64_t total = 0, hc_q8_bytes = 0;
|
||||
uint64_t split_count = 0, split_tensors = 0;
|
||||
std::set<uint64_t> split_numbers;
|
||||
bool have_architecture = false;
|
||||
@@ -192,6 +244,29 @@ bool NativeDense::load(const std::vector<std::string>& shards, WeightTable& tabl
|
||||
}
|
||||
pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data), std::move(packed)});
|
||||
}
|
||||
if (hc_q8_requested())
|
||||
for (const auto& tensor : gguf.tensors()) {
|
||||
const bool f32_inject = tensor.type == 0 && tensor.name.ends_with("_inject.weight");
|
||||
if ((tensor.type != 8 && !f32_inject) || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue;
|
||||
auto found = table.table_.find(tensor.name);
|
||||
if (found == table.table_.end() || found->second.hc_q8 != nullptr) continue;
|
||||
auto& ref = found->second;
|
||||
if (tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1 || ref.ne0 % 32 != 0) {
|
||||
err = "native dense (STRATA_HC_Q8): incompatible matrix " + tensor.name; return false;
|
||||
}
|
||||
const uint64_t bytes = (uint64_t) ref.ne0 / 32 * 34 * (uint64_t) ref.ne1;
|
||||
void* p = nullptr;
|
||||
std::vector<uint8_t> q8;
|
||||
if (f32_inject) q8 = q8_0_of((const float*) gguf.tensor_data(tensor), (uint64_t) ref.ne0 * (uint64_t) ref.ne1);
|
||||
if (cudaMalloc(&p, bytes) != cudaSuccess ||
|
||||
cudaMemcpy(p, f32_inject ? (const void*) q8.data() : gguf.tensor_data(tensor), bytes,
|
||||
cudaMemcpyHostToDevice) != cudaSuccess) {
|
||||
err = "native dense (STRATA_HC_Q8) upload " + tensor.name; return false;
|
||||
}
|
||||
ref.hc_q8 = p;
|
||||
weights_.push_back(p);
|
||||
hc_q8_bytes += bytes;
|
||||
}
|
||||
}
|
||||
if (pending.empty()) { err = "native dense: no supported GDN/QSA matrices in supplied shards"; return false; }
|
||||
void* allocation = nullptr;
|
||||
@@ -220,7 +295,10 @@ bool NativeDense::load(const std::vector<std::string>& shards, WeightTable& tabl
|
||||
std::fprintf(stderr, "native dense: STRATA_Q8_PACKED=1 packed %zu Q8_0 matrices for decode (+%.1f MiB)\n",
|
||||
packed_count, packed_bytes / 1048576.0);
|
||||
scratch_ = scratch.release();
|
||||
bytes_ = total;
|
||||
bytes_ = total + hc_q8_bytes;
|
||||
if (hc_q8_requested())
|
||||
std::fprintf(stderr, "strata: STRATA_HC_Q8=1: %.2f GiB of Q8_0 hyper-connection projections for the verify read\n",
|
||||
(double) hc_q8_bytes / 1073741824.0);
|
||||
return true;
|
||||
} catch (const std::exception& error) {
|
||||
err = std::string("native dense: ") + error.what();
|
||||
|
||||
@@ -516,6 +516,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
|
||||
a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC;
|
||||
a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data;
|
||||
a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data;
|
||||
a.q8_down = (const uint8_t*) wd[half]->hc_q8; a.q8_up = (const uint8_t*) wu[half]->hc_q8;
|
||||
a.q8_inject = (const uint8_t*) wi[half]->hc_q8;
|
||||
a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;
|
||||
a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "strata/kernels/bf16_bits.hpp"
|
||||
#include "strata/kernels/verify_kernels.hpp"
|
||||
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <atomic>
|
||||
@@ -798,6 +799,228 @@ int env_variant() {
|
||||
// per device: the variant `fused_gr_check` chose (0 = not checked yet)
|
||||
std::atomic<int> g_variant[64];
|
||||
|
||||
// ================================ S23 experiment (STRATA_HC_Q8=1): the read with the GGUF's Q8_0 projections ======
|
||||
// The pack holds the hyper-connection projections as BF16 (iq_pack.py --compat-bf16 rounds the GGUF's Q8_0 values to
|
||||
// BF16: 1.20 GiB per verify step); this read takes the Q8_0 bytes as stored (0.65 GiB - and the GGUF's own values,
|
||||
// not a rounding of them). The layout is the stream split of the v3 read above, at 4 chunks per stream: `down` runs
|
||||
// on (10 groups of 32 rows + the inject rows) x 16 chunks of 640 columns = 176 blocks, each staging its chunk of
|
||||
// R' * w_norm (unscaled) for the T tokens and writing the chunk's partial dots and sums of squares; `up` sums them
|
||||
// per stream in a fixed order, applies rs, SwiGLU-free silu, and runs the default epilogue. Another summation order
|
||||
// and other weights than the default read: an output-changing step (measured, quality-checked).
|
||||
constexpr int Q8B = 34; // Q8_0 block: fp16 d + 32 int8
|
||||
constexpr int Q8_RPW = 4; // down rows per warp
|
||||
constexpr int Q8_RG = LR / (WARPS * Q8_RPW); // 10 row groups (+1: the inject rows)
|
||||
constexpr int Q8_KC = 640, Q8_NKC = D / Q8_KC; // 16 chunks, 4 per stream
|
||||
constexpr int Q8_CPS = N / Q8_KC; // chunks per stream
|
||||
constexpr int Q8_SPB = Q8_KC / 128; // 5 steps of 4 Q8_0 blocks (8 lanes x 4 values each)
|
||||
__device__ __forceinline__ uint32_t q8_ld16(const uint8_t* p) { return *(const uint16_t*) p; }
|
||||
__device__ __forceinline__ float q8_half(uint32_t h) { return __half2float(__ushort_as_half((unsigned short) h)); }
|
||||
__device__ __forceinline__ float4 q8_four(uint32_t q, float d) {
|
||||
return make_float4(d * (float) (int8_t) (q & 255u), d * (float) (int8_t) ((q >> 8) & 255u),
|
||||
d * (float) (int8_t) ((q >> 16) & 255u), d * (float) (int8_t) (q >> 24));
|
||||
}
|
||||
|
||||
template <int T>
|
||||
__global__ void __launch_bounds__(THREADS) gr_down_q8_kernel(GrMulti m, float* __restrict__ part, float* __restrict__ ssg) {
|
||||
__shared__ __align__(16) float xs[T][Q8_KC];
|
||||
__shared__ float red[WARPS][T];
|
||||
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int rg = blockIdx.x, kc = blockIdx.y, c = kc / Q8_CPS;
|
||||
const bool inj = rg == Q8_RG;
|
||||
const int nrows = inj ? ((m.a[0].q8_inject != nullptr && warp < HC) ? 1 : 0) : Q8_RPW;
|
||||
const int row0 = inj ? warp : (rg * WARPS + warp) * Q8_RPW;
|
||||
const uint8_t* wb = inj ? m.a[0].q8_inject : m.a[0].q8_down;
|
||||
const int sub = lane & 7, bl = lane >> 3; // lanes 8b..8b+7: one Q8_0 block, 4 values each
|
||||
uint32_t q[Q8_RPW][Q8_SPB];
|
||||
float dq[Q8_RPW][Q8_SPB];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < Q8_RPW; ++r) {
|
||||
if (r >= nrows) break;
|
||||
const uint8_t* row = wb + (size_t) (row0 + r) * (D / 32) * Q8B + (size_t) kc * (Q8_KC / 32) * Q8B;
|
||||
#pragma unroll
|
||||
for (int s = 0; s < Q8_SPB; ++s) {
|
||||
const uint8_t* blk = row + (4 * s + bl) * Q8B;
|
||||
dq[r][s] = q8_half(q8_ld16(blk));
|
||||
q[r][s] = q8_ld16(blk + 2 + 4 * sub) | q8_ld16(blk + 4 + 4 * sub) << 16;
|
||||
}
|
||||
}
|
||||
float ssp[T];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < T; ++k) {
|
||||
ssp[k] = 0.0f;
|
||||
const FusedGrArgs& a = m.a[k];
|
||||
const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
|
||||
for (int i = t; i < Q8_KC / 4; i += THREADS) {
|
||||
const int col = kc * Q8_KC + 4 * i;
|
||||
float4 r = *reinterpret_cast<const float4*>(a.R + col);
|
||||
if (a.apply) {
|
||||
const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + (col - c * N));
|
||||
r.x = fmaf(b.x, gw, r.x); r.y = fmaf(b.y, gw, r.y);
|
||||
r.z = fmaf(b.z, gw, r.z); r.w = fmaf(b.w, gw, r.w);
|
||||
}
|
||||
const float4 g = *reinterpret_cast<const float4*>(a.w_norm + col);
|
||||
ssp[k] += r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w;
|
||||
*reinterpret_cast<float4*>(&xs[k][4 * i]) = make_float4(r.x * g.x, r.y * g.y, r.z * g.z, r.w * g.w);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int k = 0; k < T; ++k) {
|
||||
const float v = warp_sum(ssp[k]);
|
||||
if (lane == 0) red[warp][k] = v;
|
||||
}
|
||||
__syncthreads();
|
||||
if (rg == 0 && t < T) {
|
||||
float s = 0.0f;
|
||||
for (int w = 0; w < WARPS; ++w) s += red[w][t];
|
||||
ssg[t * Q8_NKC + kc] = s;
|
||||
}
|
||||
if (nrows == 0) return;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < Q8_RPW; ++r) {
|
||||
if (r >= nrows) break;
|
||||
float acc[T];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < T; ++k) acc[k] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int s = 0; s < Q8_SPB; ++s) {
|
||||
const float4 w = q8_four(q[r][s], dq[r][s]);
|
||||
const int v = 32 * (4 * s + bl) + 4 * sub;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < T; ++k) {
|
||||
const float4 x = *reinterpret_cast<const float4*>(&xs[k][v]);
|
||||
acc[k] = fmaf(w.x, x.x, acc[k]); acc[k] = fmaf(w.y, x.y, acc[k]);
|
||||
acc[k] = fmaf(w.z, x.z, acc[k]); acc[k] = fmaf(w.w, x.w, acc[k]);
|
||||
}
|
||||
}
|
||||
const int prow = inj ? LR + warp : row0 + r;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < T; ++k) {
|
||||
const float v = warp_sum(acc[k]);
|
||||
if (lane == 0) part[((size_t) k * Q8_NKC + kc) * PR + prow] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <int T>
|
||||
__global__ void __launch_bounds__(THREADS) gr_up_q8_kernel(GrMulti m, const float* __restrict__ part,
|
||||
const float* __restrict__ ssg) {
|
||||
__shared__ __align__(16) float lo[T][LR];
|
||||
__shared__ float rsS[T][HC];
|
||||
__shared__ float g[T][HC][UPM_COLS];
|
||||
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
|
||||
const int d0 = blockIdx.x * UPM_COLS;
|
||||
if (t < T * HC) {
|
||||
const int k = t / HC, c = t - k * HC;
|
||||
float ss = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < Q8_CPS; ++j) ss += ssg[k * Q8_NKC + c * Q8_CPS + j];
|
||||
const float r = rsqrtf(ss / (float) N + m.a[k].eps);
|
||||
rsS[k][c] = r;
|
||||
if (blockIdx.x == 0) m.a[k].rs[c] = r;
|
||||
}
|
||||
__syncthreads();
|
||||
for (int i = t; i < T * PR; i += THREADS) {
|
||||
const int k = i / PR, r = i - k * PR;
|
||||
if (r >= LR && (blockIdx.x != 0 || m.a[k].w_inject == nullptr)) continue;
|
||||
float sum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < HC; ++c) {
|
||||
float p = 0.0f;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < Q8_CPS; ++j) p += part[((size_t) k * Q8_NKC + c * Q8_CPS + j) * PR + r];
|
||||
sum = fmaf(rsS[k][c], p, sum);
|
||||
}
|
||||
if (r < LR) {
|
||||
const float x = sum / (float) HC;
|
||||
lo[k][r] = x / (1.0f + __expf(-x));
|
||||
} else {
|
||||
m.a[k].inject_out[r - LR] = sum;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
constexpr int RPW8 = HC * UPM_COLS / WARPS; // 8 rows per warp
|
||||
#pragma unroll 1
|
||||
for (int qq = 0; qq < RPW8; ++qq) {
|
||||
const int r = warp + qq * WARPS;
|
||||
const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
|
||||
const uint8_t* row = m.a[0].q8_up + (size_t) i * (LR / 32) * Q8B;
|
||||
float4 w[3];
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 3; ++s) { // lane: values 4 lane + 128 s (the third step: lanes 0-15)
|
||||
const int v = 4 * lane + 128 * s;
|
||||
if (v < LR) {
|
||||
const uint8_t* blk = row + (v >> 5) * Q8B;
|
||||
w[s] = q8_four(q8_ld16(blk + 2 + (v & 31)) | q8_ld16(blk + 4 + (v & 31)) << 16, q8_half(q8_ld16(blk)));
|
||||
} else {
|
||||
w[s] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
}
|
||||
}
|
||||
float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f;
|
||||
bool apply = false;
|
||||
if (lane < T) {
|
||||
const FusedGrArgs& a = m.a[lane];
|
||||
rv = a.R[i];
|
||||
wn = a.w_norm[i];
|
||||
apply = a.apply;
|
||||
if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; }
|
||||
}
|
||||
float mine = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < T; ++k) {
|
||||
float acc = 0.0f;
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 3; ++s) {
|
||||
const int v = 4 * lane + 128 * s;
|
||||
if (v < LR) {
|
||||
const float4 x = *reinterpret_cast<const float4*>(&lo[k][v]);
|
||||
acc = fmaf(w[s].x, x.x, acc); acc = fmaf(w[s].y, x.y, acc);
|
||||
acc = fmaf(w[s].z, x.z, acc); acc = fmaf(w[s].w, x.w, acc);
|
||||
}
|
||||
}
|
||||
acc = warp_sum(acc);
|
||||
if (lane == k) mine = acc;
|
||||
}
|
||||
if (lane < T) {
|
||||
if (apply) {
|
||||
rv = fmaf(bo, 2.0f * sigmoidf_(ip / (float) HC), rv);
|
||||
m.a[lane].R_out[i] = rv;
|
||||
}
|
||||
const float x = rv * wn * rsS[lane][c];
|
||||
g[lane][c][dd] = x * sigmoidf_(mine);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
for (int i = t; i < T * UPM_COLS; i += THREADS) {
|
||||
const int k = i / UPM_COLS, col = i - k * UPM_COLS;
|
||||
float sum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < HC; ++c) sum += g[k][c][col];
|
||||
m.a[k].mixed[d0 + col] = sum / (float) HC;
|
||||
}
|
||||
}
|
||||
|
||||
template <int T> void launch_q8_t(const GrMulti& m, float* part, float* ssg, cudaStream_t st, unsigned long long* stamp_buf,
|
||||
int stamp_i0) {
|
||||
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st);
|
||||
gr_down_q8_kernel<T><<<dim3(Q8_RG + 1, Q8_NKC), THREADS, 0, st>>>(m, part, ssg);
|
||||
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st);
|
||||
gr_up_q8_kernel<T><<<UPM_BLOCKS, THREADS, 0, st>>>(m, part, ssg);
|
||||
}
|
||||
void launch_q8(const GrMulti& m, float* scratch, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) {
|
||||
float* part = scratch;
|
||||
float* ssg = scratch + (size_t) m.T * Q8_NKC * PR;
|
||||
switch (m.T) {
|
||||
case 1: launch_q8_t<1>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
case 2: launch_q8_t<2>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
case 3: launch_q8_t<3>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
case 4: launch_q8_t<4>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
case 5: launch_q8_t<5>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
case 6: launch_q8_t<6>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
case 7: launch_q8_t<7>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
default: launch_q8_t<8>(m, part, ssg, st, stamp_buf, stamp_i0); break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,
|
||||
@@ -812,7 +1035,8 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
|
||||
const FusedGrArgs& x = a[t];
|
||||
if (!x.R || !x.w_norm || !x.w_down || !x.w_up || !x.lo || !x.rs || !x.mixed || (x.w_inject && !x.inject_out) ||
|
||||
(x.apply && (!x.bo_prev || !x.inj_prev || !x.R_out)) || x.w_down != a[0].w_down || x.w_up != a[0].w_up ||
|
||||
x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm) {
|
||||
x.w_inject != a[0].w_inject || x.w_norm != a[0].w_norm || x.q8_down != a[0].q8_down ||
|
||||
x.q8_up != a[0].q8_up || x.q8_inject != a[0].q8_inject) {
|
||||
std::fprintf(stderr, "fused_gr_read_multi: invalid arguments for token %d\n", t);
|
||||
std::exit(1);
|
||||
}
|
||||
@@ -820,6 +1044,15 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
|
||||
m.xn = xn_scratch;
|
||||
m.T = n_tok;
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
if (a[0].q8_down != nullptr && a[0].q8_up != nullptr && (a[0].w_inject == nullptr || a[0].q8_inject != nullptr)) {
|
||||
launch_q8(m, xn_scratch, st, stamp_buf, stamp_i0); // S23 experiment: STRATA_HC_Q8=1
|
||||
const cudaError_t eq = cudaGetLastError();
|
||||
if (eq != cudaSuccess) {
|
||||
std::fprintf(stderr, "fused_gr_read_multi q8: %s\n", cudaGetErrorString(eq));
|
||||
std::exit(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in)
|
||||
static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }();
|
||||
static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit
|
||||
@@ -835,6 +1068,8 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
|
||||
if (need1 <= limit &&
|
||||
cudaFuncSetAttribute(gr_down_v3_kernel<1>, cudaFuncAttributeMaxDynamicSharedMemorySize, need1) == cudaSuccess)
|
||||
split = 1;
|
||||
else if (need2 <= limit && std::getenv("STRATA_GR_V3") != nullptr && std::atoi(std::getenv("STRATA_GR_V3")) == 2)
|
||||
split = 2; // S23 experiment: STRATA_GR_V3=2 takes the two-half split anyway (gfx1151: 64 KiB)
|
||||
else if (need2 <= limit)
|
||||
// #375 (kenh0u): the S = 2 split (a 64 KB opt-in card: Turing) disagrees with itself in gr_parity
|
||||
// (graph replay vs direct call) - such a card keeps the default read until that split is fixed
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "strata/kernels/bf16_bits.hpp"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
@@ -118,6 +119,83 @@ __global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t
|
||||
if (k < n_tok) y[(size_t) k * ldy + blockIdx.x] = acc[k];
|
||||
}
|
||||
|
||||
// S25 (STRATA_MMVF_ROWS=1): RPB output rows per block. Each block read its row's weights once but all T activation
|
||||
// rows again (n_out blocks x T x n_in floats through L2 - the part that grew with T); here a block reads the
|
||||
// activations once for RPB rows. Per output, thread t still walks pairs t, t + BLOCK_SIZE, ... with the same two
|
||||
// ordered FMAs and the same warp and block reductions: bit-identical to bf16_f32_mmvf_multi_kernel.
|
||||
template <int BLOCK_SIZE, int NT, int RPB>
|
||||
__global__ void bf16_f32_mmvf_rows_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w,
|
||||
float* __restrict__ y, int64_t ldy, int n_in, int n_out, int n_tok) {
|
||||
const int t = threadIdx.x;
|
||||
const int o0 = blockIdx.x * RPB;
|
||||
__shared__ float partials[RPB][NT][32];
|
||||
if constexpr (BLOCK_SIZE > 32) {
|
||||
if (t < 32)
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPB; ++r)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k) partials[r][k][t] = 0.0f;
|
||||
__syncthreads();
|
||||
}
|
||||
float acc[RPB][NT];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPB; ++r)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k) acc[r][k] = 0.0f;
|
||||
for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {
|
||||
float2 in[NT];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k)
|
||||
if (k < n_tok) in[k] = reinterpret_cast<const float2*>(x + (size_t) k * ldx)[pair];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPB; ++r) {
|
||||
if (o0 + r >= n_out) break;
|
||||
const uint32_t weight = reinterpret_cast<const uint32_t*>(w + (size_t) (o0 + r) * n_in)[pair];
|
||||
const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16));
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k) {
|
||||
if (k < n_tok) {
|
||||
acc[r][k] = __fmaf_rn(w0, in[k].x, acc[r][k]);
|
||||
acc[r][k] = __fmaf_rn(w1, in[k].y, acc[r][k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPB; ++r)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(acc[r][k]);
|
||||
if constexpr (BLOCK_SIZE > 32) {
|
||||
if ((t & 31) == 0)
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPB; ++r)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k) partials[r][k][t / 32] = acc[r][k];
|
||||
__syncthreads();
|
||||
if (t < 32)
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPB; ++r)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k) acc[r][k] = mmvf_warp_sum(partials[r][k][t]);
|
||||
}
|
||||
if (t == 0)
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPB; ++r)
|
||||
if (o0 + r < n_out)
|
||||
#pragma unroll
|
||||
for (int k = 0; k < NT; ++k)
|
||||
if (k < n_tok) y[(size_t) k * ldy + o0 + r] = acc[r][k];
|
||||
}
|
||||
|
||||
template <int B>
|
||||
void launch_rows(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy, int n_in, int n_out, int n_tok,
|
||||
cudaStream_t st) {
|
||||
constexpr int RPB = 4;
|
||||
const unsigned nb = (unsigned) ((n_out + RPB - 1) / RPB);
|
||||
if (n_tok <= 4) bf16_f32_mmvf_rows_kernel<B, 4, RPB><<<nb, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok);
|
||||
else bf16_f32_mmvf_rows_kernel<B, 8, RPB><<<nb, B, 0, st>>>(x, ldx, w, y, ldy, n_in, n_out, n_tok);
|
||||
}
|
||||
|
||||
int mmvf_block_size(int64_t n_in) {
|
||||
int best = 32;
|
||||
int64_t best_iterations = (n_in + 63) / 64;
|
||||
@@ -140,6 +218,24 @@ void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, f
|
||||
w == nullptr || y == nullptr || (reinterpret_cast<uintptr_t>(x) & 7u) != 0)
|
||||
throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows, even n_in/ldx, aligned pointers");
|
||||
const cudaStream_t st = (cudaStream_t) stream;
|
||||
static const bool rows = [] { const char* v = std::getenv("STRATA_MMVF_ROWS"); return v && v[0] == '1'; }();
|
||||
if (rows && n_out >= 64) {
|
||||
const int ni = (int) n_in, no = (int) n_out;
|
||||
switch (mmvf_block_size(n_in)) {
|
||||
case 32: launch_rows<32>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
case 64: launch_rows<64>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
case 96: launch_rows<96>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
case 128: launch_rows<128>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
case 160: launch_rows<160>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
case 192: launch_rows<192>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
case 224: launch_rows<224>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
default: launch_rows<256>(x, ldx, w, y, ldy, ni, no, n_tok, st); break;
|
||||
}
|
||||
const cudaError_t result = cudaGetLastError();
|
||||
if (result != cudaSuccess)
|
||||
throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result));
|
||||
return;
|
||||
}
|
||||
#define STRATA_MMVF_M(N) case N: \
|
||||
if (n_tok <= 4) bf16_f32_mmvf_multi_kernel<N, 4><<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); \
|
||||
else bf16_f32_mmvf_multi_kernel<N, 8><<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); break
|
||||
|
||||
@@ -66,6 +66,31 @@ __global__ void norm(const float* input, const float* __restrict__ gamma, float*
|
||||
for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)
|
||||
output[col] = scale * input[col] * gamma[col];
|
||||
}
|
||||
// As norm, with gamma[groups * n_cols]: row r is group r % groups and reads its own slice of gamma.
|
||||
template<int BlockSize>
|
||||
__global__ void norm_grouped(const float* input, const float* __restrict__ gamma, float* output,
|
||||
int n_cols, int groups, float epsilon) {
|
||||
const int tid = threadIdx.x;
|
||||
const std::size_t row_offset = std::size_t(blockIdx.x) * n_cols;
|
||||
input += row_offset; output += row_offset;
|
||||
gamma += std::size_t(blockIdx.x % unsigned(groups)) * n_cols;
|
||||
float partial = 0.0f;
|
||||
for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize) {
|
||||
const float x = input[col];
|
||||
partial += x * x;
|
||||
}
|
||||
__shared__ float sums[32];
|
||||
partial = warp_sum(partial);
|
||||
const int lane = tid % 32;
|
||||
if (lane == 0) sums[tid / 32] = partial;
|
||||
__syncthreads();
|
||||
partial = lane < BlockSize / 32 ? sums[lane] : 0.0f;
|
||||
partial = warp_sum(partial);
|
||||
const float mean = partial / n_cols;
|
||||
const float scale = rsqrtf(mean + epsilon);
|
||||
for (std::size_t col = tid; col < std::size_t(n_cols); col += BlockSize)
|
||||
output[col] = scale * input[col] * gamma[col];
|
||||
}
|
||||
__global__ void gate(const float* attn, const float* __restrict__ q_full, float* output,
|
||||
int n_head, int head_dim) {
|
||||
const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
|
||||
@@ -117,6 +142,21 @@ void native_qsa_rms_norm_weighted(const float* input, const float* gamma, float*
|
||||
norm<1024><<<unsigned(n_rows), 1024, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols, epsilon);
|
||||
check_launch();
|
||||
}
|
||||
void native_qsa_rms_norm_grouped(const float* input, const float* gamma, float* output,
|
||||
int n_cols, int groups, int n_rows, float epsilon, void* stream) {
|
||||
if (groups < 1) throw std::invalid_argument("native QSA requires positive bounded dimensions");
|
||||
const auto count = elements(n_cols, n_rows);
|
||||
if (!std::isfinite(epsilon) || epsilon < 0.0f)
|
||||
throw std::invalid_argument("native QSA requires finite nonnegative epsilon");
|
||||
buffers(input, count * 4, gamma, std::size_t(n_cols) * groups * 4, output, stream);
|
||||
if (n_cols < 1024)
|
||||
norm_grouped<256><<<unsigned(n_rows), 256, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols,
|
||||
groups, epsilon);
|
||||
else
|
||||
norm_grouped<1024><<<unsigned(n_rows), 1024, 0, static_cast<cudaStream_t>(stream)>>>(input, gamma, output, n_cols,
|
||||
groups, epsilon);
|
||||
check_launch();
|
||||
}
|
||||
void native_qsa_gate_apply(const float* attn, const float* q_full, float* output,
|
||||
int n_head, int head_dim, void* stream) {
|
||||
const auto count = elements(head_dim, n_head);
|
||||
|
||||
@@ -80,7 +80,7 @@ __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long lo
|
||||
} else load8_q4(p, value, row, d0, out);
|
||||
}
|
||||
|
||||
template <int KV_MODE>
|
||||
template <int KV_MODE, bool LANE_CELL = false>
|
||||
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p,
|
||||
const int32_t* __restrict__ ids,
|
||||
const int32_t* __restrict__ step, int n_kv_heads,
|
||||
@@ -120,6 +120,41 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
|
||||
srow[t] = r;
|
||||
}
|
||||
__syncthreads();
|
||||
if constexpr (LANE_CELL) {
|
||||
// S25 (STRATA_ATTN_LANECELL=1): thread t scores cell t % 64 for heads 3 (t / 64) .. +2 by itself - the same
|
||||
// 8-dimension partial per former lane (the identical expression), then the former warp_sum's butterfly as
|
||||
// lane 0 ran it (a[l] += a[l + o] for o = 16 .. 1), so every score is bit-identical without 12 shuffle
|
||||
// reductions per cell
|
||||
constexpr int HPT = G * CHUNK / THREADS; // heads per thread (3)
|
||||
const int c = t % CHUNK, h0 = (t / CHUNK) * HPT;
|
||||
if (c >= n_here || srow[c] < 0) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < HPT; ++j) sp[h0 + j][c] = -FLT_MAX;
|
||||
} else {
|
||||
float a[HPT][32];
|
||||
#pragma unroll
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
float k8[8];
|
||||
load8<KV_MODE>(p, false, srow[c], l * 8, k8);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < HPT; ++j) {
|
||||
const float4 qa = *reinterpret_cast<const float4*>(&sq[h0 + j][l * 8]);
|
||||
const float4 qb = *reinterpret_cast<const float4*>(&sq[h0 + j][l * 8 + 4]);
|
||||
float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
|
||||
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
|
||||
a[j][l] = s;
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < HPT; ++j) {
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1)
|
||||
#pragma unroll
|
||||
for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o];
|
||||
sp[h0 + j][c] = a[j][0] * scale;
|
||||
}
|
||||
}
|
||||
} else
|
||||
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
|
||||
for (int c = warp; c < CHUNK; c += WARPS) {
|
||||
if (c >= n_here || srow[c] < 0) {
|
||||
@@ -227,18 +262,21 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
|
||||
const float scale = 1.0f / sqrtf((float) HD);
|
||||
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
|
||||
cudaStream_t st = (cudaStream_t) stream;
|
||||
if (kv_mode == 3)
|
||||
attn_chunk_kernel<3><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
|
||||
else if (kv_mode == 2)
|
||||
attn_chunk_kernel<2><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
|
||||
else if (kv_mode == 1)
|
||||
attn_chunk_kernel<1><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
|
||||
else
|
||||
attn_chunk_kernel<0><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
|
||||
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
|
||||
// S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)
|
||||
static const bool lane_cell = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
|
||||
#define STRATA_ATTN_LAUNCH(M, LC) attn_chunk_kernel<M, LC><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)
|
||||
if (lane_cell) {
|
||||
if (kv_mode == 3) STRATA_ATTN_LAUNCH(3, true);
|
||||
else if (kv_mode == 2) STRATA_ATTN_LAUNCH(2, true);
|
||||
else if (kv_mode == 1) STRATA_ATTN_LAUNCH(1, true);
|
||||
else STRATA_ATTN_LAUNCH(0, true);
|
||||
} else {
|
||||
if (kv_mode == 3) STRATA_ATTN_LAUNCH(3, false);
|
||||
else if (kv_mode == 2) STRATA_ATTN_LAUNCH(2, false);
|
||||
else if (kv_mode == 1) STRATA_ATTN_LAUNCH(1, false);
|
||||
else STRATA_ATTN_LAUNCH(0, false);
|
||||
}
|
||||
#undef STRATA_ATTN_LAUNCH
|
||||
attn_merge_kernel<<<dim3((unsigned) s.n_head, (unsigned) n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks,
|
||||
attn, stride);
|
||||
const cudaError_t e = cudaGetLastError();
|
||||
|
||||
@@ -180,6 +180,89 @@ __global__ void __launch_bounds__(S * RG) gdn_step_norm_multi_kernel(float* __re
|
||||
}
|
||||
}
|
||||
|
||||
// S25 (STRATA_GDN_SPLIT=1): the same recurrence with each head's 128 state columns over 4 blocks of 32 columns
|
||||
// (128 threads: the same (column, row group) threads, each with the same 32 state rows), so 4x the blocks of
|
||||
// gdn_step_norm_multi_kernel - which ran one 512-thread block per head (32 blocks) and read the 2 MB state of a layer
|
||||
// at ~60 GB/s. Every column's arithmetic is the original's; the output norm, which needs all 128 columns of a head,
|
||||
// moves to gdn_out_norm_kernel: this kernel leaves the unnormalized output `oc` in y and the second kernel sums the
|
||||
// squares by the same warps (columns 32w..32w+31, the same butterfly) in the same order.
|
||||
constexpr int GS_COLS = 32;
|
||||
__global__ void __launch_bounds__(GS_COLS * RG) gdn_step_split_kernel(float* __restrict__ state,
|
||||
const float* __restrict__ hbuf, int C,
|
||||
const float* __restrict__ gate,
|
||||
const float* __restrict__ beta,
|
||||
float* __restrict__ y, int h_k, int h_v, int T,
|
||||
const int32_t* __restrict__ n_keep,
|
||||
int t_out_begin) {
|
||||
__shared__ float sk[S], sq[S];
|
||||
__shared__ float red[RG][GS_COLS];
|
||||
const int head = blockIdx.x;
|
||||
const int c0 = blockIdx.y * GS_COLS;
|
||||
const int lc = threadIdx.x; // local column
|
||||
const int col = c0 + lc;
|
||||
const int rg = threadIdx.y;
|
||||
const int tid = rg * GS_COLS + lc;
|
||||
const int qh = head % h_k;
|
||||
const int qk = S * h_k;
|
||||
const int value_dim = S * h_v;
|
||||
const int n = n_keep ? *n_keep : T;
|
||||
float s[RPG];
|
||||
float* base = state + ((size_t) (rg * RPG) * h_v + head) * S + col;
|
||||
const size_t row_stride = (size_t) h_v * S;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) s[r] = base[r * row_stride];
|
||||
for (int t = 0; t < n; ++t) {
|
||||
const float* ht = hbuf + (size_t) t * C;
|
||||
__syncthreads();
|
||||
if (tid < S) { sk[tid] = ht[qk + qh * S + tid]; sq[tid] = ht[qh * S + tid]; }
|
||||
__syncthreads();
|
||||
const float g = __expf(gate[(size_t) t * h_v + head]);
|
||||
float kv = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
|
||||
red[rg][lc] = kv;
|
||||
__syncthreads();
|
||||
const float kv_col = red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc];
|
||||
const float delta = (ht[2 * qk + head * S + col] - g * kv_col) * beta[(size_t) t * h_v + head];
|
||||
float o = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) {
|
||||
s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
|
||||
o = fmaf(s[r], sq[rg * RPG + r], o);
|
||||
}
|
||||
__syncthreads();
|
||||
red[rg][lc] = o;
|
||||
__syncthreads();
|
||||
if (rg == 0 && t >= t_out_begin)
|
||||
y[(size_t) t * value_dim + head * S + col] =
|
||||
(red[0][lc] + red[1][lc] + red[2][lc] + red[3][lc]) * rsqrtf((float) S);
|
||||
}
|
||||
if (n_keep != nullptr && n > 0) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < RPG; ++r) base[r * row_stride] = s[r];
|
||||
}
|
||||
}
|
||||
|
||||
// y = oc * rsqrt(mean(oc^2) + eps) * gamma * sigmoid(z) per head and token, with gdn_step_norm_multi_kernel's sums
|
||||
__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
|
||||
float eps, float* __restrict__ y, int h_v, int T,
|
||||
const int32_t* __restrict__ n_keep, int t_out_begin) {
|
||||
__shared__ float wsum[S / 32];
|
||||
const int head = blockIdx.x, t = blockIdx.y + t_out_begin, col = threadIdx.x;
|
||||
const int n = n_keep ? *n_keep : T;
|
||||
if (t >= n) return;
|
||||
const int value_dim = S * h_v;
|
||||
const float oc = y[(size_t) t * value_dim + head * S + col];
|
||||
float sq_part = oc * oc;
|
||||
for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2);
|
||||
if ((col & 31) == 0) wsum[col >> 5] = sq_part;
|
||||
__syncthreads();
|
||||
const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];
|
||||
const float scale = rsqrtf(ss / (float) S + eps);
|
||||
const float zz = z[(size_t) t * value_dim + head * S + col];
|
||||
y[(size_t) t * value_dim + head * S + col] = oc * scale * gamma[col] * (1.0f / (1.0f + __expf(-zz)));
|
||||
}
|
||||
|
||||
__global__ void embedding_gather_dev_kernel(const uint8_t* __restrict__ codes, const float* __restrict__ scales,
|
||||
const float* __restrict__ offsets, const int32_t* __restrict__ tokens,
|
||||
int64_t n, int code_bits, int code_bias, int group_elems,
|
||||
@@ -417,6 +500,16 @@ void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const
|
||||
std::fprintf(stderr, "gdn_step_norm_multi: invalid arguments\n");
|
||||
std::exit(1);
|
||||
}
|
||||
static const bool split = [] { const char* v = std::getenv("STRATA_GDN_SPLIT"); return v && v[0] == '1'; }();
|
||||
if (split) {
|
||||
gdn_step_split_kernel<<<dim3((unsigned) h_v, S / GS_COLS), dim3(GS_COLS, RG), 0, (cudaStream_t) stream>>>(
|
||||
state, h, conv_channels, gate, beta, y, h_k, h_v, n_tok, n_keep, t_out_begin);
|
||||
if (n_tok > t_out_begin)
|
||||
gdn_out_norm_kernel<<<dim3((unsigned) h_v, (unsigned) (n_tok - t_out_begin)), S, 0, (cudaStream_t) stream>>>(
|
||||
z, gamma, eps, y, h_v, n_tok, n_keep, t_out_begin);
|
||||
check("gdn_step_norm_multi (split)");
|
||||
return;
|
||||
}
|
||||
gdn_step_norm_multi_kernel<<<(unsigned) h_v, dim3(S, RG), 0, (cudaStream_t) stream>>>(
|
||||
state, h, conv_channels, gate, beta, z, gamma, eps, y, h_k, h_v, n_tok, n_keep, t_out_begin);
|
||||
check("gdn_step_norm_multi");
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
#include "strata/core/layout.hpp"
|
||||
#include "strata/kernels/cpu/expert.hpp"
|
||||
#include "strata/kernels/native_qsa.hpp"
|
||||
#include "strata/kernels/native_qsa_indexer.hpp"
|
||||
#include "strata/kernels/ngram.hpp"
|
||||
#include "strata/kernels/ple.hpp"
|
||||
@@ -923,7 +924,10 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
|
||||
if (!q8) to_f16(emb, en16, nb * Nn, m.cs);
|
||||
proj(emb, en16, w_fe, e2, nb, Nn, Nn, 0);
|
||||
cudaMemcpyAsync(hn, R_rows + (size_t) b0 * HCN, (size_t) nb * HCN * 4, cudaMemcpyDeviceToDevice, m.cs);
|
||||
rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);
|
||||
if (mtp.hnorm_per_stream()) // --mtp-hnorm stream: as the drafter's own pass (mtp.cpp)
|
||||
strata::kernels::native_qsa_rms_norm_grouped(hn, w_nh, hn, (int) Nn, (int) g.hc, (int) (nb * g.hc), EPS, m.cs);
|
||||
else
|
||||
rms_rows(hn, w_nh, nb, HCN, HCN, EPS, m.cs);
|
||||
if (!q8) to_f16(hn, hn16, nb * HCN, m.cs);
|
||||
proj(hn, hn16, w_fh, h2, nb * g.hc, Nn, Nn, 1); // every stream through fc_hidden
|
||||
strata::kernels::add_streams_broadcast(h2, e2, Rm, Nn, (int) g.hc, (int) nb, m.cs);
|
||||
|
||||
+155
-9
@@ -53,6 +53,7 @@
|
||||
#include "strata/program/logits_selection.hpp"
|
||||
#include "strata/program/conv_cache.hpp"
|
||||
#include "strata/spec/draft_policy.hpp"
|
||||
#include "strata/spec/draft_source.hpp"
|
||||
#include "strata/spec/suffix_drafter.hpp"
|
||||
#include "strata/kernels/cvec.hpp"
|
||||
#include "strata/core/progress.hpp"
|
||||
@@ -410,6 +411,18 @@ struct Options {
|
||||
int suffix_draft = 3;
|
||||
/// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches.
|
||||
int mtp_max_t = 0;
|
||||
/// --lookup-chain K (opt-in, 0 = off): prompt lookup CHAINED after the MTP's proposal. The suffix drafter matches
|
||||
/// the context followed by the MTP's drafts and appends up to K of the tokens that followed that match to the same
|
||||
/// verify window (the window grows to at most 8). Greedy verification keeps the output; its own counts are kept.
|
||||
int lookup_chain = 0;
|
||||
int lookup_chain_min = 3; ///< --lookup-chain-min M: the shortest match (in tokens, drafts included) it extends on
|
||||
/// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on
|
||||
/// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py).
|
||||
bool mtp_hnorm_stream = false;
|
||||
/// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step)
|
||||
std::string mtp_q4; ///< "" (off), all, proj (the projections only) or head (the draft head only)
|
||||
/// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of <mtp>/draft_vocab.bin
|
||||
std::string mtp_draft_vocab;
|
||||
/// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the
|
||||
/// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range
|
||||
/// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request.
|
||||
@@ -508,6 +521,13 @@ void usage() {
|
||||
" --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n"
|
||||
" when it pays (default 3; 0 = MTP only)\n"
|
||||
" --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n"
|
||||
" --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n"
|
||||
" them (the window grows to at most 8; default 0 = off)\n"
|
||||
" --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n"
|
||||
" --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n"
|
||||
" (default) or one per stream (llama.cpp's MTP graph)\n"
|
||||
" --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n"
|
||||
" --mtp-draft-vocab FILE opt-in: the draft head's token subset (default <mtp>/draft_vocab.bin)\n"
|
||||
" --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n"
|
||||
" format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n"
|
||||
" --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n"
|
||||
@@ -584,6 +604,23 @@ void usage() {
|
||||
" does not fit. Same answers as --mmap-experts for the same placement.\n");
|
||||
}
|
||||
|
||||
// --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last
|
||||
int chain_tail(const strata::spec::SuffixDrafter& sfx, const int32_t* pending, int n_pending, std::vector<int32_t>& tail) {
|
||||
const std::vector<int32_t>& h = sfx.history();
|
||||
const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending));
|
||||
tail.assign(h.end() - keep, h.end());
|
||||
tail.insert(tail.end(), pending, pending + n_pending);
|
||||
return (int) tail.size();
|
||||
}
|
||||
|
||||
// --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too
|
||||
void extra_sources_reset() {
|
||||
for (auto& src : strata::spec::extra_draft_sources()) src->reset();
|
||||
}
|
||||
void extra_sources_append(const int32_t* t, size_t n) {
|
||||
for (auto& src : strata::spec::extra_draft_sources()) src->append(t, n);
|
||||
}
|
||||
|
||||
bool parse_i64_list(const char* s, std::vector<int64_t>& out, std::string& err) {
|
||||
out.clear();
|
||||
std::string text(s);
|
||||
@@ -1176,6 +1213,24 @@ int main(int argc, char** argv) {
|
||||
else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read")));
|
||||
else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft")));
|
||||
else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t")));
|
||||
else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7);
|
||||
else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min")));
|
||||
else if (a == "--mtp-hnorm") {
|
||||
const std::string v = next("--mtp-hnorm");
|
||||
if (v != "pooled" && v != "stream") {
|
||||
std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n");
|
||||
return 2;
|
||||
}
|
||||
o.mtp_hnorm_stream = v == "stream";
|
||||
}
|
||||
else if (a == "--mtp-q4") {
|
||||
o.mtp_q4 = next("--mtp-q4");
|
||||
if (o.mtp_q4 != "all" && o.mtp_q4 != "proj" && o.mtp_q4 != "head") {
|
||||
std::fprintf(stderr, "strata generate: --mtp-q4 takes all, proj or head\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab");
|
||||
else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f});
|
||||
else if (a == "--control-vector-scaled") {
|
||||
// FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive
|
||||
@@ -1506,6 +1561,11 @@ int main(int argc, char** argv) {
|
||||
o.mtp_max_t = o.spec;
|
||||
o.spec = std::min(o.spec + 2, 8); // kVerifyMaxT
|
||||
}
|
||||
// --lookup-chain (opt-in): the MTP keeps its windows; a lookup chained after its drafts may lengthen one by up to K
|
||||
if (o.lookup_chain > 0 && o.spec >= 2) {
|
||||
if (o.mtp_max_t == 0) o.mtp_max_t = o.spec;
|
||||
o.spec = std::max(o.spec, std::min(o.mtp_max_t + o.lookup_chain, 8)); // kVerifyMaxT
|
||||
}
|
||||
strata::core::layer_set_shared_early(!o.shared_late);
|
||||
if (!o.native_preset.empty()) {
|
||||
try {
|
||||
@@ -2520,6 +2580,9 @@ int main(int argc, char** argv) {
|
||||
o.mtp.clear();
|
||||
}
|
||||
if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
|
||||
mtp.set_hnorm_per_stream(o.mtp_hnorm_stream); // --mtp-hnorm stream (opt-in), before any capture
|
||||
mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head"); // before load
|
||||
if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab);
|
||||
// the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
|
||||
// so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference
|
||||
static const strata::core::ModelGeometry draft_geometry{};
|
||||
@@ -5409,12 +5472,22 @@ int main(int argc, char** argv) {
|
||||
std::vector<int32_t> drafts((size_t) S, 0), window((size_t) S), outv((size_t) S);
|
||||
std::vector<float> dprob((size_t) S, 0.0f);
|
||||
std::vector<int32_t> sbuf((size_t) S, 0);
|
||||
if (o.suffix_draft > 0) {
|
||||
const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;
|
||||
if (sfx_on) {
|
||||
sfx.reset();
|
||||
for (int64_t t : ids) sfx.append((int32_t) t);
|
||||
}
|
||||
if (o.lookup_chain > 0) {
|
||||
extra_sources_reset();
|
||||
for (int64_t t : ids) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }
|
||||
}
|
||||
bool first_window = true;
|
||||
int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;
|
||||
int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts
|
||||
int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits
|
||||
std::vector<int32_t> cbuf((size_t) S, 0), ctail;
|
||||
strata::spec::PromptLookupSource lookup_src(sfx);
|
||||
static const bool chain_fixed = std::getenv("STRATA_LOOKUP_CHAIN_FIXED") != nullptr; // no policy gate
|
||||
int64_t draft_offered = 0, draft_accepted = 0;
|
||||
// what the session holds once this request is done: the prompt read so far, then every committed token
|
||||
std::vector<int32_t> consumed;
|
||||
@@ -5461,11 +5534,29 @@ int main(int argc, char** argv) {
|
||||
if (pk.lookup) { T = pk.t; from_sfx = true; }
|
||||
}
|
||||
}
|
||||
// --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them
|
||||
int chain_n = 0, cm = 0;
|
||||
if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) {
|
||||
int csrc = -1;
|
||||
const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);
|
||||
chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1,
|
||||
std::min(o.lookup_chain, S - T), o.lookup_chain_min,
|
||||
cbuf.data(), &cm, &csrc);
|
||||
// the policy keeps the chained tokens that pay at this machine's measured window costs
|
||||
if (chain_n > 0 && !chain_fixed) {
|
||||
double p_mtp = 1.0;
|
||||
for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i];
|
||||
chain_n = policy.chain(T, p_mtp, chain_n, cm);
|
||||
}
|
||||
}
|
||||
const int T_mtp = T;
|
||||
T += chain_n;
|
||||
const bool timed_round = !first_window;
|
||||
const Clock::time_point round0 = Clock::now();
|
||||
if (p + T > o.max_context) break;
|
||||
window[0] = x;
|
||||
for (int i = 1; i < T; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1];
|
||||
for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1];
|
||||
for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i];
|
||||
drive.d.layers = 0;
|
||||
drive.d.experts = 0;
|
||||
drive.d.failed = false;
|
||||
@@ -5490,6 +5581,11 @@ int main(int argc, char** argv) {
|
||||
int a = 0;
|
||||
while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;
|
||||
if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }
|
||||
if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }
|
||||
if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) {
|
||||
++t2_rej[a];
|
||||
if (mtp.top2(a) == outv[(size_t) a]) ++t2_hit[a];
|
||||
}
|
||||
const Clock::time_point tw1 = Clock::now();
|
||||
std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate)
|
||||
bool adapt_ok = true;
|
||||
@@ -5510,7 +5606,8 @@ int main(int argc, char** argv) {
|
||||
std::printf("T %d\n", (int) outv[(size_t) i]);
|
||||
strata::core::progress_beat();
|
||||
++produced_n;
|
||||
if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);
|
||||
if (sfx_on) sfx.append(outv[(size_t) i]);
|
||||
if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);
|
||||
eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();
|
||||
}
|
||||
std::fflush(stdout);
|
||||
@@ -5537,9 +5634,12 @@ int main(int argc, char** argv) {
|
||||
std::printf("ERR %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
if (timed_round && !eos)
|
||||
if (timed_round && !eos && chain_n == 0)
|
||||
policy.observe(from_sfx, T, a, sfx_match,
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - round0).count());
|
||||
else if (timed_round && !eos) // a chained window: its MTP part, its chain, its cost
|
||||
policy.observe_chain(T_mtp, chain_n, a, cm,
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - round0).count());
|
||||
if (eos) { finish = "stop"; break; }
|
||||
if (stop_req.load()) { finish = "cancel"; break; }
|
||||
x = outv[(size_t) a];
|
||||
@@ -5692,11 +5792,17 @@ int main(int argc, char** argv) {
|
||||
// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]
|
||||
// [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)
|
||||
// [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read)
|
||||
std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld\n", (long long) produced_n,
|
||||
// [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows]
|
||||
// (only with --lookup-chain)
|
||||
char chain_txt[128] = "";
|
||||
if (o.lookup_chain > 0)
|
||||
std::snprintf(chain_txt, sizeof(chain_txt), " %lld %lld %lld %lld %lld", (long long) chain_ok,
|
||||
(long long) chain_drafts, (long long) sfx_ok, (long long) sfx_drafts, (long long) dec_windows);
|
||||
std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld%s\n", (long long) produced_n,
|
||||
(long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,
|
||||
(long long) resume, (long long) req_hits, (long long) req_look,
|
||||
(long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),
|
||||
(double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n);
|
||||
(double) (src.file_read_bytes() - file_bytes0) / 1e6, (long long) read_n, chain_txt);
|
||||
std::fflush(stdout);
|
||||
if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session
|
||||
// "12288 of 98179" when cancelled mid-read (#471), the rate from what was read
|
||||
@@ -5759,6 +5865,14 @@ int main(int argc, char** argv) {
|
||||
if (sfx_windows > 0)
|
||||
std::fprintf(stderr, "strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n",
|
||||
(long long) sfx_windows, (long long) sfx_ok, (long long) sfx_drafts);
|
||||
if (o.lookup_chain > 0)
|
||||
std::fprintf(stderr, "strata serve: lookup chain: %lld of %lld windows, %lld of %lld chained drafts accepted\n",
|
||||
(long long) chain_windows, (long long) dec_windows, (long long) chain_ok, (long long) chain_drafts);
|
||||
if (strata::core::MtpDrafter::top2_env())
|
||||
std::fprintf(stderr, "strata serve: mtp top2: rejected/runner-up by depth %lld/%lld %lld/%lld %lld/%lld %lld/%lld "
|
||||
"of %lld windows\n", (long long) t2_rej[0], (long long) t2_hit[0], (long long) t2_rej[1],
|
||||
(long long) t2_hit[1], (long long) t2_rej[2], (long long) t2_hit[2], (long long) t2_rej[3],
|
||||
(long long) t2_hit[3], (long long) dec_windows);
|
||||
for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
|
||||
std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned "
|
||||
"(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms "
|
||||
@@ -6252,10 +6366,19 @@ int main(int argc, char** argv) {
|
||||
strata::spec::DraftPolicy policy(o.spec); // MTP or lookup window (see draft_policy.hpp)
|
||||
std::vector<int32_t> sbuf((size_t) o.spec, 0);
|
||||
int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;
|
||||
if (o.suffix_draft > 0) {
|
||||
int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts
|
||||
std::vector<int32_t> cbuf((size_t) o.spec, 0), ctail;
|
||||
strata::spec::PromptLookupSource lookup_src(sfx);
|
||||
const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;
|
||||
if (sfx_on) {
|
||||
for (int64_t t : o.tokens) sfx.append((int32_t) t);
|
||||
for (int64_t t : produced) sfx.append((int32_t) t);
|
||||
}
|
||||
if (o.lookup_chain > 0) {
|
||||
extra_sources_reset();
|
||||
for (int64_t t : o.tokens) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }
|
||||
for (int64_t t : produced) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }
|
||||
}
|
||||
const double pool_ms0 = drive.cpu_ms;
|
||||
const int64_t misses0 = drive.d.multi_misses, entries0 = drive.d.multi_entries;
|
||||
while ((int64_t) produced.size() < o.max_new) {
|
||||
@@ -6276,6 +6399,22 @@ int main(int argc, char** argv) {
|
||||
if (pk.lookup) { T = pk.t; from_sfx = true; }
|
||||
}
|
||||
}
|
||||
// --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them
|
||||
int chain_n = 0, cm = 0;
|
||||
if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) {
|
||||
int csrc = -1;
|
||||
const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);
|
||||
chain_n = strata::spec::propose_from_sources(lookup_src, ctail.data(), nt, T - 1,
|
||||
std::min(o.lookup_chain, o.spec - T), o.lookup_chain_min,
|
||||
cbuf.data(), &cm, &csrc);
|
||||
if (chain_n > 0 && std::getenv("STRATA_LOOKUP_CHAIN_FIXED") == nullptr) {
|
||||
double p_mtp = 1.0;
|
||||
for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i];
|
||||
chain_n = policy.chain(T, p_mtp, chain_n, cm);
|
||||
}
|
||||
}
|
||||
const int T_mtp = T;
|
||||
T += chain_n;
|
||||
const bool timed_round = !first_window;
|
||||
++window_hist[(size_t) T];
|
||||
if (p + T > o.max_context) {
|
||||
@@ -6287,6 +6426,7 @@ int main(int argc, char** argv) {
|
||||
const size_t at = produced.size() - 1 + (size_t) i;
|
||||
int32_t d = from_sfx ? sbuf[(size_t) i - 1] : use_mtp ? drafts[(size_t) i - 1]
|
||||
: at < oracle.size() ? (int32_t) oracle[at] : 0;
|
||||
if (i >= T_mtp) d = cbuf[(size_t) (i - T_mtp)];
|
||||
if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab;
|
||||
window[(size_t) i] = d;
|
||||
}
|
||||
@@ -6336,10 +6476,12 @@ int main(int argc, char** argv) {
|
||||
drafts_ok += a;
|
||||
++accepted_hist[(size_t) a];
|
||||
if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }
|
||||
if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }
|
||||
bool eos = false;
|
||||
for (int i = 0; i <= a && (int64_t) produced.size() < o.max_new && !eos; ++i) {
|
||||
produced.push_back(outv[(size_t) i]);
|
||||
if (o.suffix_draft > 0) sfx.append(outv[(size_t) i]);
|
||||
if (sfx_on) sfx.append(outv[(size_t) i]);
|
||||
if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);
|
||||
eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();
|
||||
}
|
||||
if (eos) {
|
||||
@@ -6359,7 +6501,8 @@ int main(int argc, char** argv) {
|
||||
p += a + 1;
|
||||
const double round_ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
|
||||
total_ms += round_ms;
|
||||
if (timed_round) policy.observe(from_sfx, T, a, sfx_match, round_ms);
|
||||
if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms);
|
||||
else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms);
|
||||
if (rounds % 64 == 0)
|
||||
std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p,
|
||||
(long long) produced.size(), (long long) rounds);
|
||||
@@ -6381,6 +6524,9 @@ int main(int argc, char** argv) {
|
||||
if (o.suffix_draft > 0)
|
||||
std::printf("%-24s %lld windows, drafts accepted %lld of %lld\n", "suffix drafts", (long long) sfx_windows,
|
||||
(long long) sfx_ok, (long long) sfx_drafts);
|
||||
if (o.lookup_chain > 0)
|
||||
std::printf("%-24s %lld windows, chained drafts accepted %lld of %lld\n", "lookup chain",
|
||||
(long long) chain_windows, (long long) chain_ok, (long long) chain_drafts);
|
||||
std::printf("%-24s", "accepted per round");
|
||||
for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]);
|
||||
std::printf("\n");
|
||||
|
||||
@@ -98,4 +98,49 @@ void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double ro
|
||||
}
|
||||
}
|
||||
|
||||
double DraftPolicy::chain_rate(int match) const {
|
||||
// prior: a chained draft is a lookup continuing the MTP's drafts - weaker evidence than a plain match of that length
|
||||
constexpr double kChainPrior[kBuckets] = {0.45, 0.65, 0.8, 0.9};
|
||||
const int b = bucket(match);
|
||||
return (cok_[b] + kPriorN * kChainPrior[b]) / (cok_[b] + cbad_[b] + kPriorN);
|
||||
}
|
||||
|
||||
int DraftPolicy::chain(int t_mtp, double p_mtp, int k_avail, int match) const {
|
||||
t_mtp = std::clamp(t_mtp, 1, max_t_);
|
||||
const int kmax = std::min(k_avail, max_t_ - t_mtp);
|
||||
if (kmax <= 0) return 0;
|
||||
const double e0 = mtp_tokens(t_mtp), base = e0 / cost_ms(t_mtp), c = chain_rate(match);
|
||||
p_mtp = std::clamp(p_mtp, 0.0, 1.0);
|
||||
double gain = 0.0, ci = 1.0, best = 0.0;
|
||||
int best_k = 0;
|
||||
for (int k = 1; k <= kmax; ++k) {
|
||||
ci *= c;
|
||||
gain += ci;
|
||||
const double r = (e0 + p_mtp * gain) / cost_ms(t_mtp + k);
|
||||
if (r > best) { best = r; best_k = k; }
|
||||
}
|
||||
if (best_k > 0 && best > base * (1.0 + margin_)) return best_k;
|
||||
// as choose(): a size whose cost is only guessed is tried a few times when the continuation looks likely
|
||||
const int t_full = t_mtp + kmax;
|
||||
if (cost_n_[t_full] < kProbes && p_mtp * c >= 0.6) return kmax;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void DraftPolicy::observe_chain(int t_mtp, int k, int accepted, int match, double round_ms) {
|
||||
const int t = std::clamp(t_mtp + k, 1, kMaxT);
|
||||
if (round_ms > 0) {
|
||||
cost_[t] = cost_n_[t] > 0 ? (1.0 - kCostAlpha) * cost_[t] + kCostAlpha * round_ms : round_ms;
|
||||
cost_n_[t] += 1.0;
|
||||
}
|
||||
// the MTP part is an ordinary MTP window as far as its own drafts go
|
||||
const int mtp_acc = std::min(accepted, t_mtp - 1);
|
||||
const double got = mtp_acc + 1.0;
|
||||
mtp_tok_[t_mtp] = mtp_n_[t_mtp] > 0 ? (1.0 - kTokAlpha) * mtp_tok_[t_mtp] + kTokAlpha * got : got;
|
||||
mtp_n_[t_mtp] += 1.0;
|
||||
if (accepted < t_mtp - 1) return; // the chain was never reached: it says nothing about the lookup
|
||||
const int b = bucket(match), ok = accepted - (t_mtp - 1);
|
||||
cok_[b] = kDecay * cok_[b] + ok;
|
||||
cbad_[b] = kDecay * cbad_[b] + (ok < k ? 1.0 : 0.0);
|
||||
}
|
||||
|
||||
} // namespace strata::spec
|
||||
@@ -58,6 +58,23 @@ int main() {
|
||||
for (int i = 0; i < 3; ++i) p.observe(true, 6, 5, 40, 3.0 * cost(6)); // it turns out very expensive
|
||||
check(!p.choose(4, 5, 40).lookup, "after the probes, the measured cost decides");
|
||||
}
|
||||
{
|
||||
// --lookup-chain: rows cheap (UMA-like) and the chain always accepted -> chained; rows dear or the chain
|
||||
// always rejected -> not
|
||||
auto cheap = [](int t) { return 40.0 + 2.0 * (t - 1); };
|
||||
DraftPolicy p(8);
|
||||
for (int t = 2; t <= 8; ++t)
|
||||
for (int i = 0; i < 5; ++i) p.observe(false, t, 1, 0, cheap(t));
|
||||
for (int i = 0; i < 30; ++i) p.observe(false, 4, 2, 0, cheap(4));
|
||||
for (int i = 0; i < 30; ++i) p.observe_chain(4, 3, 6, 12, cheap(7)); // every chained token accepted
|
||||
check(p.chain(4, 0.9, 3, 12) == 3, "chain: cheap rows, always accepted -> all 3 chained");
|
||||
DraftPolicy q(8);
|
||||
for (int t = 2; t <= 8; ++t)
|
||||
for (int i = 0; i < 5; ++i) q.observe(false, t, 1, 0, cost(t));
|
||||
for (int i = 0; i < 30; ++i) q.observe_chain(4, 3, 3, 4, cost(7)); // reached, never accepted
|
||||
check(q.chain(4, 0.9, 3, 4) == 0, "chain: dear rows, never accepted -> none");
|
||||
check(q.chain(4, 0.9, 0, 4) == 0 && q.chain(8, 1.0, 3, 40) == 0, "chain: nothing proposed / no room -> none");
|
||||
}
|
||||
std::printf(g_fail ? "FAIL\n" : "PASS\n");
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// src/spec/draft_source.cpp - see include/strata/spec/draft_source.hpp.
|
||||
#include "strata/spec/draft_source.hpp"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace strata::spec {
|
||||
|
||||
std::vector<std::unique_ptr<DraftSource>>& extra_draft_sources() {
|
||||
static std::vector<std::unique_ptr<DraftSource>> sources;
|
||||
return sources;
|
||||
}
|
||||
|
||||
int propose_from_sources(DraftSource& own, const int32_t* tail, int n_tail, int n_pending, int max_k, int min_match,
|
||||
int32_t* out, int* match, int* source) {
|
||||
*match = 0;
|
||||
*source = -1;
|
||||
if (max_k <= 0) return 0;
|
||||
int best = 0;
|
||||
std::vector<int32_t> buf((size_t) max_k);
|
||||
auto ask = [&](DraftSource& s, int index) {
|
||||
int m = 0;
|
||||
const int k = s.propose(tail, n_tail, n_pending, max_k, buf.data(), &m);
|
||||
if (k <= 0 || m < min_match || m <= *match) return;
|
||||
for (int i = 0; i < k && i < max_k; ++i) out[i] = buf[(size_t) i];
|
||||
best = k < max_k ? k : max_k;
|
||||
*match = m;
|
||||
*source = index;
|
||||
};
|
||||
ask(own, 0);
|
||||
int index = 1;
|
||||
for (auto& s : extra_draft_sources())
|
||||
if (s) ask(*s, index++);
|
||||
return best;
|
||||
}
|
||||
|
||||
} // namespace strata::spec
|
||||
@@ -85,4 +85,14 @@ int SuffixDrafter::propose(int max_k, int32_t* out) {
|
||||
return k;
|
||||
}
|
||||
|
||||
int SuffixDrafter::propose_after(const int32_t* extra, int n_extra, int max_k, int32_t* out) {
|
||||
if (n_extra <= 0) return propose(max_k, out);
|
||||
// the index holds the history's trigrams only: appended without indexing, the extra tokens just form the suffix
|
||||
const size_t n0 = hist_.size();
|
||||
hist_.insert(hist_.end(), extra, extra + n_extra);
|
||||
const int k = propose(max_k, out);
|
||||
hist_.resize(n0);
|
||||
return k;
|
||||
}
|
||||
|
||||
} // namespace strata::spec
|
||||
@@ -111,6 +111,23 @@ void unit_tests() {
|
||||
int32_t out[4];
|
||||
check(d.propose(4, out) > 0, "propose after overflow of nominal capacity");
|
||||
}
|
||||
{
|
||||
// --lookup-chain: the match continues from the drafts appended to the history, which stays unchanged
|
||||
SuffixDrafter d(3, 32, 256);
|
||||
const int32_t hist[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 51, 52, 1, 2};
|
||||
d.append(hist, sizeof(hist) / sizeof(hist[0]));
|
||||
const int32_t drafts[] = {3, 4};
|
||||
int32_t out[8] = {};
|
||||
const int k = d.propose_after(drafts, 2, 3, out);
|
||||
check(k == 3 && out[0] == 5 && out[1] == 6 && out[2] == 7, "propose_after continues after the drafts");
|
||||
check(d.last_match() >= 4, "propose_after match length counts the drafts");
|
||||
check(d.size() == sizeof(hist) / sizeof(hist[0]), "propose_after leaves the history unchanged");
|
||||
const int32_t miss[] = {99, 98, 97};
|
||||
check(d.propose_after(miss, 3, 3, out) == 0, "propose_after without a match proposes nothing");
|
||||
// the plain proposal is unaffected: the history's own suffix (52, 1, 2) has no earlier occurrence
|
||||
check(d.propose(3, out) == 0, "propose after propose_after");
|
||||
check(d.propose_after(nullptr, 0, 3, out) == d.propose(3, out), "propose_after with no drafts == propose");
|
||||
}
|
||||
std::printf("suffix_drafter unit tests: %s\n", g_fail ? "FAILED" : "OK");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Reference in new issue
Block a user