mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 23:08:36 +00:00
inkling CUDA: decode steps return the 128 best logits of each row (GPU top-K + finite flag) instead of the full 200058-float rows (#6779)
At C = 64 a decode step copied 64 x 200058 floats to the host (D2H 4.9 ms, a second copy into the caller's buffer 14 ms) and sampled on the CPU (7 ms): 26 of the 74 ms per step on an RTX 5090. Now forward_batch_cand returns, per wanted row, the 128 best token ids with their logits (larger logit first, the smaller id first on equal logits, -0 counts as +0: the order of the sampler's partial_sort) and a flag for the every-67th-logit finite check; ink_topk.cuh does it in three passes (per-slice bitonic sort of 2048 keys, two merges). 128 x 8 bytes per row. ink_serve.h samples from the candidates (sample_candidates, sharing ink_sample_top with sample_logits) when no wanted slot has a repeat/frequency/presence penalty (a penalty moves logits anywhere in the row); otherwise the full rows, as before. STRATA_INK_NO_CAND=1 forces the full rows. A backend without the feature keeps the old path (supports_candidates() is false by default). Exact: ink_topk_gpu_test (engine/tests/cuda, built by hand with nvcc) compares the GPU candidate lists with std::partial_sort (280 rows, ties, +-0, the finite flag) and the tokens sampled from them with the sampler of origin/main, same seed: 630 streams x 300 steps, temperature 0 and 0.3..1.5, top-k, top-p, min-p: 0 differ; vocabulary-sized rows 252 steps: 0 differ. compute-sanitizer memcheck, racecheck, synccheck: 0 errors. End to end (RTX 5090, SQ-20, --parallel 64, 3 alternating rounds old/new): greedy and sampled tokens identical at C = 1 / 8 / 64, 5 runs of the new engine identical to each other and to the old one. Throughput, total tok/s: C=1 131 -> 133, C=8 405-424 -> 452 (greedy) / 386-406 -> 436-441 (sampled), C=64 722-733 -> 1013-1016 (greedy) / 632-706 -> 981-984 (sampled).
This commit is contained in:
1 parent
6a26196260
commit
f42a9aa714
5 files changed
+467
-40
No files matched your search
@@ -10,6 +10,7 @@
|
||||
#include "ink_dspark.cuh"
|
||||
#include "ink_runner.cuh"
|
||||
#include "ink_spec.cuh"
|
||||
#include "ink_topk.cuh"
|
||||
#include "strata/core/arch_probe.hpp"
|
||||
#include "strata/core/volta_forever.hpp"
|
||||
|
||||
@@ -577,6 +578,31 @@ public:
|
||||
float* logits_out,
|
||||
TapCapture* taps_out,
|
||||
std::string& err) override {
|
||||
return forward_batch_impl(batch, logits_out, nullptr, taps_out, err);
|
||||
}
|
||||
|
||||
bool supports_candidates() const noexcept override { return initialized_; }
|
||||
|
||||
bool forward_batch_cand(const StepBatch& batch, CandRows& out, std::string& err) override {
|
||||
if (!initialized_) { err = "CUDA backend not initialized"; return false; }
|
||||
// the scratch is allocated before anything runs, so a failure here leaves the step untouched (the caller keeps the full-row path)
|
||||
if (!topk_.ensure(std::max(64, batch.count_logits()))) { err = "no memory for the candidate scratch"; return false; }
|
||||
const int V = model_.man.c.vocab_unpadded;
|
||||
const int nrows = batch.count_logits();
|
||||
out.rows = nrows;
|
||||
out.k = std::min(kInkCandidates, V);
|
||||
out.val.assign((size_t)nrows * kInkCandidates, 0.0f);
|
||||
out.idx.assign((size_t)nrows * kInkCandidates, 0);
|
||||
out.finite.assign((size_t)nrows, 1);
|
||||
return forward_batch_impl(batch, nullptr, &out, nullptr, err);
|
||||
}
|
||||
|
||||
bool forward_batch_impl(
|
||||
const StepBatch& batch,
|
||||
float* logits_out,
|
||||
CandRows* cand_out,
|
||||
TapCapture* taps_out,
|
||||
std::string& err) {
|
||||
if (!initialized_) {
|
||||
err = "CUDA backend not initialized";
|
||||
return false;
|
||||
@@ -618,7 +644,7 @@ public:
|
||||
// Helper: extract wanted logits rows from runner_->d_h_norm[0..M-1] into logits_out
|
||||
auto emit_selected_logits = [&](const std::vector<int>& local_idx, const std::vector<int>& dst_rows) {
|
||||
const int nw = (int)local_idx.size();
|
||||
if (nw == 0 || !logits_out) return;
|
||||
if (nw == 0 || (!logits_out && !cand_out)) return;
|
||||
const float* h_src = runner_->d_h_norm;
|
||||
if (nw == 1) {
|
||||
h_src = runner_->d_h_norm + (size_t)local_idx[0] * strata::ink::kInkHidden;
|
||||
@@ -638,6 +664,24 @@ public:
|
||||
runner_->head_logits_from(h_src, nw);
|
||||
if (hp) INK_CK(cudaStreamSynchronize(runner_->st));
|
||||
auto hq1 = hnow();
|
||||
if (cand_out) {
|
||||
// candidate rows: the 128 best (id, logit) of each wanted row and its finite flag; no full row leaves the card
|
||||
INK_CK(topk_.run(runner_->d_logits, nw, V, runner_->st));
|
||||
INK_CK(cudaStreamSynchronize(runner_->st));
|
||||
const int kc = std::min(kInkCandidates, V);
|
||||
for (int k = 0; k < nw; ++k) {
|
||||
const int dst = dst_rows[k];
|
||||
const uint64_t* keys = topk_.h_out + (size_t)k * strata::ink::kTopkCand;
|
||||
for (int j = 0; j < kc; ++j) {
|
||||
int32_t id = strata::ink::ink_topk_key_index(keys[j]);
|
||||
if (id < 0 || id >= V) id = 0; // only a NaN logit can leave a pad key here
|
||||
cand_out->val[(size_t)dst * kInkCandidates + j] = strata::ink::ink_topk_key_value(keys[j]);
|
||||
cand_out->idx[(size_t)dst * kInkCandidates + j] = id;
|
||||
}
|
||||
cand_out->finite[dst] = topk_.h_fin[k] != 0 ? 1 : 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Use pinned host staging buffer for full PCIe 5.0 DMA bandwidth (~50 GB/s vs ~12 GB/s pageable)!
|
||||
ensure_pinned_logits(nw, V);
|
||||
INK_CK(cudaMemcpyAsync(h_logits_pin_, runner_->d_logits,
|
||||
@@ -980,6 +1024,7 @@ private:
|
||||
if (d_h_sel_) { cudaFree(d_h_sel_); d_h_sel_ = nullptr; }
|
||||
if (d_sel_idx_) { cudaFree(d_sel_idx_); d_sel_idx_ = nullptr; }
|
||||
if (h_logits_pin_) { cudaFreeHost(h_logits_pin_); h_logits_pin_ = nullptr; h_logits_cap_ = 0; }
|
||||
topk_.free_all();
|
||||
model_.free_all();
|
||||
prompt_ckpts_.clear();
|
||||
initialized_ = false;
|
||||
@@ -1013,6 +1058,7 @@ private:
|
||||
float* d_h_sel_ = nullptr;
|
||||
int32_t* d_sel_idx_ = nullptr;
|
||||
float* h_logits_pin_ = nullptr;
|
||||
strata::ink::InkTopkScratch topk_; // candidate rows (ink_topk.cuh)
|
||||
int h_logits_cap_ = 0;
|
||||
std::vector<bool> slot_alloc_;
|
||||
std::vector<bool> snap_active_;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// ink_topk.cuh - exact top-128 candidates (and the finite flag) of full logit rows on the GPU, so a decode step with many slots
|
||||
// copies 128 ids + logits per row to the host instead of 200058 floats (#6779).
|
||||
//
|
||||
// Order: larger logit first, the smaller id first on equal logits (-0 counts as +0) - the order of std::partial_sort with the
|
||||
// sampler's comparator, so the host sampler sees exactly the candidates it used to compute itself. A NaN logit gets the smallest
|
||||
// key (the engine rejects non-finite rows before sampling anyway).
|
||||
//
|
||||
// How: key = (order-preserving 32-bit image of the logit) << 32 | (0xFFFFFFFF - id); the largest key is the best candidate.
|
||||
// pass 1: grid (128 slices, rows): each block sorts its 1563-element slice (2048 keys, bitonic, shared memory) and keeps 128
|
||||
// pass 2: grid (8 groups, rows): merges 16 sorted lists of 128 (2048 keys) -> 128
|
||||
// pass 3: grid (1, rows): merges 8 lists (1024 keys, padded) -> 128
|
||||
// The finite flag: every id that is a multiple of 67 (what finite_logits() in ink_serve.h looks at) must be finite.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
namespace strata {
|
||||
namespace ink {
|
||||
|
||||
constexpr int kTopkCand = 128;
|
||||
constexpr int kTopkSlices = 128; // pass-1 blocks per row
|
||||
constexpr int kTopkSortN = 2048; // keys one block sorts
|
||||
constexpr int kTopkThreads = 256;
|
||||
|
||||
__device__ __forceinline__ uint64_t ink_topk_key(float v, int idx) {
|
||||
if (v != v) return 0ull; // NaN: below every real key
|
||||
if (v == 0.0f) v = __uint_as_float(0u); // -0 -> +0 (equal logits order by id)
|
||||
uint32_t b = __float_as_uint(v);
|
||||
b ^= (b & 0x80000000u) ? 0xFFFFFFFFu : 0x80000000u;
|
||||
return ((uint64_t)b << 32) | (uint64_t)(0xFFFFFFFFu - (uint32_t)idx);
|
||||
}
|
||||
|
||||
// Bitonic sort of kTopkSortN keys in shared memory, largest first.
|
||||
__device__ __forceinline__ void ink_topk_sort2048(uint64_t* a) {
|
||||
for (int k = 2; k <= kTopkSortN; k <<= 1) {
|
||||
for (int j = k >> 1; j > 0; j >>= 1) {
|
||||
for (int i = threadIdx.x; i < kTopkSortN; i += kTopkThreads) {
|
||||
const int ixj = i ^ j;
|
||||
if (ixj > i) {
|
||||
const uint64_t x = a[i], y = a[ixj];
|
||||
const bool desc = ((i & k) == 0);
|
||||
if (desc ? (x < y) : (x > y)) { a[i] = y; a[ixj] = x; }
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pass 1: rows [nrows, V] row-major -> out[(row * kTopkSlices + slice) * 128 ..), fin[row] &= every 67th logit finite
|
||||
__global__ void __launch_bounds__(kTopkThreads) k_ink_topk_pass1(const float* __restrict__ logits, int V,
|
||||
uint64_t* __restrict__ out, int* __restrict__ fin) {
|
||||
__shared__ uint64_t s_key[kTopkSortN];
|
||||
const int row = blockIdx.y, slice = blockIdx.x;
|
||||
const int S = (V + kTopkSlices - 1) / kTopkSlices; // 1563 for V = 200058
|
||||
const int base = slice * S;
|
||||
const float* r = logits + (size_t)row * V;
|
||||
int bad = 0;
|
||||
for (int i = threadIdx.x; i < kTopkSortN; i += kTopkThreads) {
|
||||
const int g = base + i;
|
||||
uint64_t key = 0ull;
|
||||
if (i < S && g < V) {
|
||||
const float v = r[g];
|
||||
key = ink_topk_key(v, g);
|
||||
if (g % 67 == 0 && !isfinite(v)) bad = 1;
|
||||
}
|
||||
s_key[i] = key;
|
||||
}
|
||||
if (bad) atomicAnd(&fin[row], 0);
|
||||
__syncthreads();
|
||||
ink_topk_sort2048(s_key);
|
||||
uint64_t* o = out + ((size_t)row * kTopkSlices + slice) * kTopkCand;
|
||||
for (int i = threadIdx.x; i < kTopkCand; i += kTopkThreads) o[i] = s_key[i];
|
||||
}
|
||||
|
||||
// pass 2 / 3: `lists` sorted lists of 128 keys per row in `in`; groups of `m` lists (m * 128 <= 2048) -> one sorted list of 128
|
||||
__global__ void __launch_bounds__(kTopkThreads) k_ink_topk_merge(const uint64_t* __restrict__ in, int lists, int m,
|
||||
uint64_t* __restrict__ out, int groups) {
|
||||
__shared__ uint64_t s_key[kTopkSortN];
|
||||
const int row = blockIdx.y, g = blockIdx.x;
|
||||
const uint64_t* src = in + ((size_t)row * lists + (size_t)g * m) * kTopkCand;
|
||||
const int n = m * kTopkCand;
|
||||
for (int i = threadIdx.x; i < kTopkSortN; i += kTopkThreads) s_key[i] = (i < n) ? src[i] : 0ull;
|
||||
__syncthreads();
|
||||
ink_topk_sort2048(s_key);
|
||||
uint64_t* o = out + ((size_t)row * groups + g) * kTopkCand;
|
||||
for (int i = threadIdx.x; i < kTopkCand; i += kTopkThreads) o[i] = s_key[i];
|
||||
}
|
||||
|
||||
// Scratch for up to `rows` rows: pass-1 output, pass-2 output, the final lists, the flags.
|
||||
struct InkTopkScratch {
|
||||
uint64_t* d_p1 = nullptr; // rows * 128 * 128
|
||||
uint64_t* d_p2 = nullptr; // rows * 8 * 128
|
||||
uint64_t* d_out = nullptr; // rows * 128
|
||||
int* d_fin = nullptr; // rows
|
||||
uint64_t* h_out = nullptr; // pinned, rows * 128
|
||||
int* h_fin = nullptr; // pinned, rows
|
||||
int cap = 0;
|
||||
|
||||
void free_all() {
|
||||
if (d_p1) cudaFree(d_p1);
|
||||
if (d_p2) cudaFree(d_p2);
|
||||
if (d_out) cudaFree(d_out);
|
||||
if (d_fin) cudaFree(d_fin);
|
||||
if (h_out) cudaFreeHost(h_out);
|
||||
if (h_fin) cudaFreeHost(h_fin);
|
||||
d_p1 = d_p2 = d_out = nullptr; d_fin = nullptr; h_out = nullptr; h_fin = nullptr; cap = 0;
|
||||
}
|
||||
|
||||
// false when an allocation fails (the caller then keeps the full-row path)
|
||||
bool ensure(int rows) {
|
||||
if (rows <= cap) return true;
|
||||
free_all();
|
||||
const int c = rows < 64 ? 64 : rows;
|
||||
if (cudaMalloc(&d_p1, (size_t)c * kTopkSlices * kTopkCand * 8) != cudaSuccess ||
|
||||
cudaMalloc(&d_p2, (size_t)c * 8 * kTopkCand * 8) != cudaSuccess ||
|
||||
cudaMalloc(&d_out, (size_t)c * kTopkCand * 8) != cudaSuccess ||
|
||||
cudaMalloc(&d_fin, (size_t)c * sizeof(int)) != cudaSuccess ||
|
||||
cudaMallocHost(&h_out, (size_t)c * kTopkCand * 8) != cudaSuccess ||
|
||||
cudaMallocHost(&h_fin, (size_t)c * sizeof(int)) != cudaSuccess) {
|
||||
cudaGetLastError();
|
||||
free_all();
|
||||
return false;
|
||||
}
|
||||
cap = c;
|
||||
return true;
|
||||
}
|
||||
|
||||
// launches the three passes and the copy of the small results to the pinned buffers on `st` (the caller synchronizes)
|
||||
cudaError_t run(const float* d_logits, int rows, int V, cudaStream_t st) {
|
||||
// every flag starts non-zero (0x01010101); a block that sees a non-finite logit at a multiple of 67 ANDs it to 0
|
||||
cudaError_t e = cudaMemsetAsync(d_fin, 1, (size_t)rows * sizeof(int), st);
|
||||
if (e != cudaSuccess) return e;
|
||||
k_ink_topk_pass1<<<dim3(kTopkSlices, rows), kTopkThreads, 0, st>>>(d_logits, V, d_p1, d_fin);
|
||||
k_ink_topk_merge<<<dim3(8, rows), kTopkThreads, 0, st>>>(d_p1, kTopkSlices, 16, d_p2, 8);
|
||||
k_ink_topk_merge<<<dim3(1, rows), kTopkThreads, 0, st>>>(d_p2, 8, 8, d_out, 1);
|
||||
e = cudaGetLastError();
|
||||
if (e != cudaSuccess) return e;
|
||||
e = cudaMemcpyAsync(h_out, d_out, (size_t)rows * kTopkCand * 8, cudaMemcpyDeviceToHost, st);
|
||||
if (e != cudaSuccess) return e;
|
||||
return cudaMemcpyAsync(h_fin, d_fin, (size_t)rows * sizeof(int), cudaMemcpyDeviceToHost, st);
|
||||
}
|
||||
};
|
||||
|
||||
// key -> logit / id (host side)
|
||||
inline float ink_topk_key_value(uint64_t key) {
|
||||
uint32_t b = (uint32_t)(key >> 32);
|
||||
b ^= (b & 0x80000000u) ? 0x80000000u : 0xFFFFFFFFu;
|
||||
float f;
|
||||
static_assert(sizeof(f) == sizeof(b), "float is 32 bit");
|
||||
std::memcpy(&f, &b, sizeof(f));
|
||||
return f;
|
||||
}
|
||||
inline int32_t ink_topk_key_index(uint64_t key) { return (int32_t)(0xFFFFFFFFu - (uint32_t)(key & 0xFFFFFFFFu)); }
|
||||
|
||||
} // namespace ink
|
||||
} // namespace strata
|
||||
@@ -50,6 +50,16 @@ struct BackendStats {
|
||||
uint64_t expert_misses = 0; // of those, the ones not in the card
|
||||
};
|
||||
|
||||
// Candidate rows of forward_batch_cand: row r (in the order of the wanted-logits rows) holds `k` = min(kInkCandidates, vocab)
|
||||
// ids and logits in val / idx [r * kInkCandidates + 0 .. k), and finite[r] (1 = every 67th logit of the row is finite).
|
||||
struct CandRows {
|
||||
int rows = 0;
|
||||
int k = 0;
|
||||
std::vector<float> val;
|
||||
std::vector<int32_t> idx;
|
||||
std::vector<uint8_t> finite;
|
||||
};
|
||||
|
||||
class InkBackend {
|
||||
public:
|
||||
virtual ~InkBackend() = default;
|
||||
@@ -92,6 +102,19 @@ public:
|
||||
TapCapture* taps_out,
|
||||
std::string& err) = 0;
|
||||
|
||||
// The same step, but a row of logits is not copied to the host: the backend returns, per wanted row, the kInkCandidates best
|
||||
// token ids with their logits (larger logit first, the smaller id first on equal logits - the order the sampler uses) and a
|
||||
// flag telling whether the row's every 67th logit is finite (what the host check looked at). That is 128 x 8 bytes per row
|
||||
// instead of 200058 x 4, which is what limits many concurrent slots. Exact by construction: the values are the very floats
|
||||
// forward_batch would have copied. A backend that cannot do it returns false from supports_candidates() (the default).
|
||||
static constexpr int kInkCandidates = 128;
|
||||
virtual bool supports_candidates() const noexcept { return false; }
|
||||
virtual bool forward_batch_cand(const StepBatch& batch, CandRows& out, std::string& err) {
|
||||
(void)batch; (void)out;
|
||||
err = "this backend does not return candidate rows";
|
||||
return false;
|
||||
}
|
||||
|
||||
// On-device DSpark Block-8 Recurrent Markov drafting for one slot.
|
||||
// Returns number of drafted tokens (0..max_draft, typically up to 7); returns 0 if unavailable/disabled.
|
||||
virtual int dspark_draft(
|
||||
|
||||
@@ -86,6 +86,52 @@ inline void ink_top_k_ids(const float* lg, int V, int K, std::vector<int>& idx)
|
||||
}
|
||||
}
|
||||
|
||||
// The sampling step once the K best candidates are known: tv[i] is the logit of token ti[i], best first (larger logit first, the
|
||||
// smaller id first on equal logits), K = min(top_k, vocab, 128). Shared by sample_logits (candidates found on the host) and the
|
||||
// candidate rows a backend returns (forward_batch_cand), so both give the same token for the same seed.
|
||||
inline int32_t ink_sample_top(const float* tv, const int* ti, int K, const SampleOpts& s, std::mt19937_64& rng) {
|
||||
std::vector<double> p(K);
|
||||
double mx = tv[0], sum = 0.0;
|
||||
for (int i = 0; i < K; ++i) {
|
||||
p[i] = std::exp((tv[i] - mx) / static_cast<double>(s.temperature));
|
||||
sum += p[i];
|
||||
}
|
||||
for (double& x : p) x /= sum;
|
||||
int keep = K;
|
||||
if (s.min_p > 0.0f) {
|
||||
const double thr = static_cast<double>(s.min_p) * p[0];
|
||||
keep = 1;
|
||||
while (keep < K && p[keep] >= thr) ++keep;
|
||||
}
|
||||
if (s.top_p < 1.0f) {
|
||||
double c = 0.0;
|
||||
int k2 = 0;
|
||||
while (k2 < keep) {
|
||||
c += p[k2++];
|
||||
if (c >= static_cast<double>(s.top_p)) break;
|
||||
}
|
||||
keep = std::max(1, k2);
|
||||
}
|
||||
double z = 0.0;
|
||||
for (int i = 0; i < keep; ++i) z += p[i];
|
||||
std::uniform_real_distribution<double> u(0.0, z);
|
||||
const double r = u(rng);
|
||||
double c = 0.0;
|
||||
for (int i = 0; i < keep; ++i) {
|
||||
c += p[i];
|
||||
if (r <= c) return ti[i];
|
||||
}
|
||||
return ti[keep - 1];
|
||||
}
|
||||
|
||||
// Sampling from a candidate row (ink2::CandRows, `cand` = the row's kInkCandidates entries). Only for a slot without penalties:
|
||||
// a penalty changes logits anywhere in the row before the best are picked, so such a slot needs its full row.
|
||||
inline int32_t sample_candidates(const float* cv, const int32_t* ci, int V, const SampleOpts& s, std::mt19937_64& rng) {
|
||||
if (s.greedy()) return ci[0];
|
||||
const int K = std::min(std::max(1, s.top_k), std::min(V, 128));
|
||||
return ink_sample_top(cv, ci, K, s, rng);
|
||||
}
|
||||
|
||||
inline int32_t sample_logits(float* lg, int V, const SampleOpts& s, const std::vector<int32_t>& hist, std::mt19937_64& rng) {
|
||||
if (s.penalties() && s.last_n > 0) {
|
||||
size_t start = static_cast<size_t>(std::max(0, s.pen_from));
|
||||
@@ -112,38 +158,9 @@ inline int32_t sample_logits(float* lg, int V, const SampleOpts& s, const std::v
|
||||
const int K = std::min(std::max(1, s.top_k), std::min(V, 128));
|
||||
std::vector<int> idx;
|
||||
ink_top_k_ids(lg, V, K, idx);
|
||||
std::vector<double> p(K);
|
||||
double mx = lg[idx[0]], sum = 0.0;
|
||||
for (int i = 0; i < K; ++i) {
|
||||
p[i] = std::exp((lg[idx[i]] - mx) / static_cast<double>(s.temperature));
|
||||
sum += p[i];
|
||||
}
|
||||
for (double& x : p) x /= sum;
|
||||
int keep = K;
|
||||
if (s.min_p > 0.0f) {
|
||||
const double thr = static_cast<double>(s.min_p) * p[0];
|
||||
keep = 1;
|
||||
while (keep < K && p[keep] >= thr) ++keep;
|
||||
}
|
||||
if (s.top_p < 1.0f) {
|
||||
double c = 0.0;
|
||||
int k2 = 0;
|
||||
while (k2 < keep) {
|
||||
c += p[k2++];
|
||||
if (c >= static_cast<double>(s.top_p)) break;
|
||||
}
|
||||
keep = std::max(1, k2);
|
||||
}
|
||||
double z = 0.0;
|
||||
for (int i = 0; i < keep; ++i) z += p[i];
|
||||
std::uniform_real_distribution<double> u(0.0, z);
|
||||
const double r = u(rng);
|
||||
double c = 0.0;
|
||||
for (int i = 0; i < keep; ++i) {
|
||||
c += p[i];
|
||||
if (r <= c) return idx[i];
|
||||
}
|
||||
return idx[keep - 1];
|
||||
std::vector<float> tv((size_t)K);
|
||||
for (int i = 0; i < K; ++i) tv[(size_t)i] = lg[idx[(size_t)i]];
|
||||
return ink_sample_top(tv.data(), idx.data(), K, s, rng);
|
||||
}
|
||||
|
||||
inline bool finite_logits(const float* lg, int V) noexcept {
|
||||
@@ -463,6 +480,8 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend&
|
||||
// while another request decodes: cap 64 / 128 / 256 / none = decode 24 / 21 / 17 / 12.6 tok/s, prompt first token after
|
||||
// 2.75 / 1.63 / 1.05 / 0.88 s), so it is opt-in; answers are identical for every value.
|
||||
int prefill_cap = 0;
|
||||
// STRATA_INK_NO_CAND=1: always copy the full logit rows to the host (the old way) instead of the backend's candidate rows.
|
||||
bool cand_ok = !(std::getenv("STRATA_INK_NO_CAND") && std::getenv("STRATA_INK_NO_CAND")[0] == '1');
|
||||
if (const char* e = std::getenv("STRATA_INK_PREFILL_CAP"); e && *e) prefill_cap = std::max(0, std::atoi(e));
|
||||
const bool use_dspark = (cfg.draft_mode != "off") && mf.m.dspark.present && backend.dspark_ready();
|
||||
|
||||
@@ -960,11 +979,25 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend&
|
||||
if (!merged_img_embeds.empty()) batch.img_embeds = merged_img_embeds.data();
|
||||
|
||||
const int n_want = batch.count_logits();
|
||||
logits_buf.resize(static_cast<size_t>(std::max(1, n_want)) * V);
|
||||
// Candidate rows (the 128 best logits of each wanted row, exact) instead of the full 200058-float rows, when the backend can and
|
||||
// no wanted slot needs its whole row (a penalty changes logits anywhere in it). Many slots: 64 rows are 51 MB per step otherwise.
|
||||
bool use_cand = cand_ok && n_want > 0 && backend.supports_candidates();
|
||||
for (int wi = 0; use_cand && wi < n_want; ++wi) if (reqs[logit_slots[wi]].s.penalties()) use_cand = false;
|
||||
std::string ferr;
|
||||
if (!backend.forward_batch(batch, n_want > 0 ? logits_buf.data() : nullptr, nullptr, ferr)) {
|
||||
proto("ERR fatal GPU error: %s", ferr.c_str());
|
||||
return 1;
|
||||
CandRows cand;
|
||||
if (use_cand) {
|
||||
if (!backend.forward_batch_cand(batch, cand, ferr)) {
|
||||
if (cand.rows != 0) { proto("ERR fatal GPU error: %s", ferr.c_str()); return 1; }
|
||||
cand_ok = false; // nothing ran: this and every later step takes the full-row path
|
||||
use_cand = false;
|
||||
}
|
||||
}
|
||||
if (!use_cand) {
|
||||
logits_buf.resize(static_cast<size_t>(std::max(1, n_want)) * V);
|
||||
if (!backend.forward_batch(batch, n_want > 0 ? logits_buf.data() : nullptr, nullptr, ferr)) {
|
||||
proto("ERR fatal GPU error: %s", ferr.c_str());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
const double step_ms = (now_s() - t_step0) * 1000.0;
|
||||
|
||||
@@ -1004,8 +1037,8 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend&
|
||||
for (int wi = 0; wi < n_want; ++wi) {
|
||||
const int s = logit_slots[wi];
|
||||
auto& rq = reqs[s];
|
||||
float* lg = logits_buf.data() + static_cast<size_t>(wi) * V;
|
||||
if (!finite_logits(lg, V)) {
|
||||
float* lg = use_cand ? nullptr : logits_buf.data() + static_cast<size_t>(wi) * V;
|
||||
if (use_cand ? cand.finite[static_cast<size_t>(wi)] == 0 : !finite_logits(lg, V)) {
|
||||
// Purge poisoned KV/ShortConv state so subsequent retries start clean (#879)!
|
||||
rq.cached_prefix.clear();
|
||||
backend.reset_slot(rq.slot);
|
||||
@@ -1021,7 +1054,10 @@ inline int run_serve_loop(const ServeConfig& cfg, InkModelFile& mf, InkBackend&
|
||||
finish_req(rq, "length");
|
||||
continue;
|
||||
}
|
||||
int32_t tok = sample_logits(lg, V, rq.s, rq.hist, rq.rng);
|
||||
int32_t tok = use_cand
|
||||
? sample_candidates(cand.val.data() + static_cast<size_t>(wi) * InkBackend::kInkCandidates,
|
||||
cand.idx.data() + static_cast<size_t>(wi) * InkBackend::kInkCandidates, V, rq.s, rq.rng)
|
||||
: sample_logits(lg, V, rq.s, rq.hist, rq.rng);
|
||||
rq.hist.push_back(tok);
|
||||
rq.gen_ids.push_back(tok);
|
||||
rq.next_tok = tok;
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
// ink_topk_gpu_test: the GPU candidate rows (ink_topk.cuh) must be what the host sampler would have found itself, and the tokens
|
||||
// sampled from them (sample_candidates) must be the tokens of the sampler of origin/main (ink_sample_old.inc), same seed, same rows.
|
||||
// Also checks the finite flag against finite_logits(). Build by hand:
|
||||
// nvcc -O2 -std=c++17 -I engine/include -I engine/src/inkling2 -I engine/src/inkling2/cuda \
|
||||
// engine/tests/cuda/ink_topk_gpu_test.cu -o ink_topk_gpu_test (run: ./ink_topk_gpu_test; compute-sanitizer works on it)
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <numeric>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
#include "ink_serve.h"
|
||||
#include "../core/ink_sample_old.inc"
|
||||
#include "ink_topk.cuh"
|
||||
|
||||
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::printf("CUDA error %s at line %d\n", cudaGetErrorString(e_), __LINE__); return 2; } } while (0)
|
||||
|
||||
static std::vector<int> ref_top_k(const float* lg, int V, int K) {
|
||||
std::vector<int> idx(V);
|
||||
std::iota(idx.begin(), idx.end(), 0);
|
||||
std::partial_sort(idx.begin(), idx.begin() + K, idx.end(),
|
||||
[&](int a, int b) { return lg[a] > lg[b] || (lg[a] == lg[b] && a < b); });
|
||||
idx.resize(K);
|
||||
return idx;
|
||||
}
|
||||
|
||||
// row kinds: 0 random, 1 heavy ties, 2 ties across the whole row, 3 softcapped coarse grid, 4 constant, 5 two-valued, 6 with +-0 and +-inf-free extremes
|
||||
static void make_row(std::mt19937_64& rng, int kind, int V, std::vector<float>& lg) {
|
||||
lg.assign(V, 0.f);
|
||||
for (int i = 0; i < V; ++i) {
|
||||
switch (kind) {
|
||||
case 0: lg[i] = std::uniform_real_distribution<float>(-20.f, 20.f)(rng); break;
|
||||
case 1: lg[i] = (float)std::uniform_int_distribution<int>(-8, 8)(rng); break;
|
||||
case 2: lg[i] = (float)(i % 3); break;
|
||||
case 3: { float x = (float)std::uniform_int_distribution<int>(-400, 400)(rng) * 0.25f; lg[i] = 30.f * std::tanh(x / 30.f); break; }
|
||||
case 4: lg[i] = 1.25f; break;
|
||||
case 5: lg[i] = (i % 7 == 0) ? 5.f : 0.f; break;
|
||||
default: { int r = std::uniform_int_distribution<int>(0, 5)(rng); lg[i] = r == 0 ? 0.0f : r == 1 ? -0.0f : r == 2 ? -29.99f : r == 3 ? 29.99f : (float)r; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
strata::ink::InkTopkScratch sc;
|
||||
if (!sc.ensure(512)) { std::printf("no scratch\n"); return 2; }
|
||||
std::mt19937_64 rng(4242);
|
||||
long bad = 0, lists = 0;
|
||||
|
||||
auto run_rows = [&](const std::vector<std::vector<float>>& rows, int V, std::vector<uint64_t>& keys, std::vector<int>& fin) -> int {
|
||||
const int n = (int)rows.size();
|
||||
float* d = nullptr;
|
||||
CK(cudaMalloc(&d, (size_t)n * V * sizeof(float)));
|
||||
for (int r = 0; r < n; ++r) CK(cudaMemcpy(d + (size_t)r * V, rows[r].data(), (size_t)V * sizeof(float), cudaMemcpyHostToDevice));
|
||||
CK(sc.run(d, n, V, 0));
|
||||
CK(cudaStreamSynchronize(0));
|
||||
keys.assign(sc.h_out, sc.h_out + (size_t)n * strata::ink::kTopkCand);
|
||||
fin.assign(sc.h_fin, sc.h_fin + n);
|
||||
CK(cudaFree(d));
|
||||
return 0;
|
||||
};
|
||||
|
||||
// 1. candidate lists and finite flags against the host
|
||||
const int Vs[] = {10, 129, 300, 5000, 200058};
|
||||
for (int V : Vs) {
|
||||
const int kc = std::min(128, V);
|
||||
for (int kind = 0; kind < 7; ++kind) {
|
||||
std::vector<std::vector<float>> rows(8);
|
||||
for (auto& r : rows) make_row(rng, kind, V, r);
|
||||
// rows 6, 7: a non-finite logit at a multiple of 67 (flag 0) / elsewhere (flag 1, like finite_logits)
|
||||
rows[6][(size_t)(V > 67 ? 67 : 0)] = INFINITY;
|
||||
if (V > 70) rows[7][(size_t)70] = NAN; else rows[7][0] = 1.0f;
|
||||
std::vector<uint64_t> keys; std::vector<int> fin;
|
||||
if (run_rows(rows, V, keys, fin)) return 2;
|
||||
for (int r = 0; r < 8; ++r) {
|
||||
++lists;
|
||||
if (r >= 6) {
|
||||
if ((fin[r] != 0) != ink2::finite_logits(rows[r].data(), V)) { ++bad; std::printf("FINITE MISMATCH V=%d kind=%d row=%d\n", V, kind, r); }
|
||||
continue; // the top lists of non-finite rows are not compared
|
||||
}
|
||||
const std::vector<int> want = ref_top_k(rows[r].data(), V, kc);
|
||||
bool ok = (fin[r] != 0);
|
||||
for (int j = 0; j < kc && ok; ++j) {
|
||||
const uint64_t k = keys[(size_t)r * strata::ink::kTopkCand + j];
|
||||
if (strata::ink::ink_topk_key_index(k) != want[j]) ok = false;
|
||||
else if (strata::ink::ink_topk_key_value(k) != rows[r][(size_t)want[j]]) ok = false; // (-0 == +0 compares equal)
|
||||
}
|
||||
if (!ok) { ++bad; std::printf("LIST MISMATCH V=%d kind=%d row=%d\n", V, kind, r); }
|
||||
}
|
||||
}
|
||||
}
|
||||
std::printf("candidate lists: %ld rows (incl. finite flag), %ld mismatches\n", lists, bad);
|
||||
|
||||
// 2. sampled token streams: old sampler on the full rows vs sample_candidates on the GPU candidates, same seed
|
||||
const bool fast = std::getenv("INK_TOPK_TEST_FAST") != nullptr; // sanitizer runs: every 9th stream, 12 steps
|
||||
long seen = 0;
|
||||
long streams = 0, steps = 0, sbad = 0;
|
||||
const float temps[] = {0.0f, 0.3f, 0.7f, 1.0f, 1.5f};
|
||||
const int top_ks[] = {1, 5, 40, 64, 128, 500, 0};
|
||||
const float top_ps[] = {1.0f, 0.9f, 0.5f};
|
||||
const float min_ps[] = {0.0f, 0.05f};
|
||||
const int Vq[] = {10, 300, 5000};
|
||||
for (float t : temps) for (int tk : top_ks) for (float tp : top_ps) for (float mp : min_ps) for (int V : Vq) {
|
||||
if (fast && (seen++ % 9) != 0) continue;
|
||||
ink2::SampleOpts so;
|
||||
so.temperature = t; so.top_k = tk; so.top_p = tp; so.min_p = mp;
|
||||
const int kind = (int)(streams % 7);
|
||||
std::mt19937_64 rng_new(777 + streams), rng_old(777 + streams), rows_rng(99 + streams);
|
||||
++streams;
|
||||
const int n = fast ? 12 : 300;
|
||||
std::vector<std::vector<float>> rows(n);
|
||||
for (auto& r : rows) make_row(rows_rng, kind, V, r);
|
||||
std::vector<uint64_t> keys; std::vector<int> fin;
|
||||
if (run_rows(rows, V, keys, fin)) return 2;
|
||||
std::vector<int32_t> hist;
|
||||
for (int step = 0; step < n; ++step) {
|
||||
std::vector<float> cv(128, 0.f); std::vector<int32_t> ci(128, 0);
|
||||
const int kc = std::min(128, V);
|
||||
for (int j = 0; j < kc; ++j) {
|
||||
const uint64_t k = keys[(size_t)step * strata::ink::kTopkCand + j];
|
||||
cv[j] = strata::ink::ink_topk_key_value(k);
|
||||
ci[j] = strata::ink::ink_topk_key_index(k);
|
||||
}
|
||||
std::vector<float> b = rows[step];
|
||||
const int32_t tn = ink2::sample_candidates(cv.data(), ci.data(), V, so, rng_new);
|
||||
const int32_t to = ink2old::sample_logits(b.data(), V, so, hist, rng_old);
|
||||
++steps;
|
||||
if (tn != to) ++sbad;
|
||||
hist.push_back(to);
|
||||
}
|
||||
}
|
||||
std::printf("sampled streams from GPU candidates: %ld streams, %ld steps, %ld differ from the old sampler (greedy included)\n", streams, steps, sbad);
|
||||
// 3. the vocabulary-sized rows, a few steps each (all kinds, greedy and sampled)
|
||||
long vbad = 0, vsteps = 0;
|
||||
for (int kind = 0; kind < 7; ++kind) {
|
||||
for (float t : {0.0f, 0.7f, 1.0f}) {
|
||||
ink2::SampleOpts so; so.temperature = t; so.top_k = 64; so.top_p = 0.95f;
|
||||
std::mt19937_64 rng_new(31 + kind), rng_old(31 + kind), rr(7 + kind);
|
||||
std::vector<std::vector<float>> rows(12);
|
||||
for (auto& r : rows) make_row(rr, kind, 200058, r);
|
||||
std::vector<uint64_t> keys; std::vector<int> fin;
|
||||
if (run_rows(rows, 200058, keys, fin)) return 2;
|
||||
std::vector<int32_t> hist;
|
||||
for (int step = 0; step < 12; ++step) {
|
||||
std::vector<float> cv(128); std::vector<int32_t> ci(128);
|
||||
for (int j = 0; j < 128; ++j) {
|
||||
const uint64_t k = keys[(size_t)step * strata::ink::kTopkCand + j];
|
||||
cv[j] = strata::ink::ink_topk_key_value(k); ci[j] = strata::ink::ink_topk_key_index(k);
|
||||
}
|
||||
std::vector<float> b = rows[step];
|
||||
const int32_t tn = ink2::sample_candidates(cv.data(), ci.data(), 200058, so, rng_new);
|
||||
const int32_t to = ink2old::sample_logits(b.data(), 200058, so, hist, rng_old);
|
||||
++vsteps; if (tn != to) ++vbad;
|
||||
hist.push_back(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::printf("vocabulary-sized rows: %ld steps, %ld differ\n", vsteps, vbad);
|
||||
bad += sbad + vbad;
|
||||
sc.free_all();
|
||||
std::printf("ink_topk_gpu_test: %s\n", bad ? "FAILED" : "OK");
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
Reference in new issue
Block a user