libref, libavx, libr4d: cfg_topk_sample's top_p and ras_pick -- Fish Audio's nucleus over the whole candidate set, cut before the top-k, and its repetition-aware choice between two draws

This commit is contained in:
zivius committed 2026-10-20 23:07:16 +02:00
1 parent 8a993b7de9
commit 0c35fc8070
14 files changed
+384 -23

No files matched your search

+81 -3
View File
@@ -622,6 +622,11 @@ __device__ uint32_t kth_key(F val, int j0, int j1, int kth, int* sh) {
// [sup_lo, sup_hi) are optional. The kept values are divided by the temperature, as libref divides:
// a multiply by its inverse rounds differently and can move a pick across a CDF boundary. A lane
// with no candidate left writes -1.
//
// `top_p` < 1 cuts the kept list where the whole candidate set's cumulative probability passes it
// (Fish Audio's draw). The normaliser is each thread's slice summed in index order, the slices
// then summed by thread 0 in thread order: index order as libref sums, associated differently,
// which in double moves a cut only for a cumulative within ~1e-16 of top_p.
constexpr int kMaxK = 256;
__global__ __launch_bounds__(kT) void cfg_topk_kernel(
@@ -629,9 +634,10 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel(
const int* __restrict__ frame, int* __restrict__ ids, int V, int K, int rep, int cond_k,
float cfg, float temp, uint64_t stream, const float* __restrict__ cfgs,
const int* __restrict__ lane, int* __restrict__ hist, int n_hist, int sup_lo, int sup_hi,
float pen) {
float pen, float top_p) {
__shared__ int sh[8];
__shared__ int s_pre[kT];
__shared__ double s_z[kT];
__shared__ float s_g[kMaxK];
__shared__ int s_i[kMaxK];
__shared__ float s_e[kMaxK];
@@ -721,8 +727,29 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel(
s_pre[rank] = mi;
}
__syncthreads();
if (top_p < 1.f) {
const float m = s_e[0] / temp;
double z = 0;
for (int j = j0; j < j1; ++j)
if (cand(j)) z += exp((double)(gval(j) / temp - m));
s_z[tid] = z;
}
__syncthreads();
if (tid == 0) {
const float m = s_e[0] / temp;
int kp = kk;
if (top_p < 1.f) {
double z = 0;
for (int t = 0; t < kT; ++t) z += s_z[t];
double cum = 0;
kp = 1;
for (int t = 0; t < kk; ++t) {
cum += exp((double)(s_e[t] / temp - m)) / z;
if (t > 0 && cum > (double)top_p) break;
kp = t + 1;
}
}
const int kk = kp;
double tot = 0;
for (int t = 0; t < kk; ++t) tot += exp((double)(s_e[t] / temp - m));
const double u = (double)rad_philox_uniform_s(seed_of(seed, ln),
@@ -820,6 +847,32 @@ __global__ __launch_bounds__(kT) void frame_mix_kernel(
}
}
// Fish Audio's repetition-aware choice between two draws, a thread a lane (libref's
// ref_ras_pick): the alternative where the first draw is in [lo, hi) and in the lane's window of
// its last `W` picks, the pick then entering the window. A lane whose window lies outside `hist`
// takes the first draw and keeps no window.
__global__ __launch_bounds__(kT) void ras_pick_kernel(
const int* __restrict__ first, const int* __restrict__ alt, const int* __restrict__ lane,
int* __restrict__ hist, int* __restrict__ ids, int n, int W, int lo, int hi, int rep,
int clear, long long n_hist) {
const int i = blockIdx.x * kT + threadIdx.x;
if (i >= n) return;
const int f = first[rep * i];
const long long L = lane[i];
int pick = f;
if (L >= 0 && (L + 1) * W <= n_hist) {
int* h = hist + L * W;
if (clear)
for (int w = 0; w < W; ++w) h[w] = -1;
if (f >= lo && f < hi)
for (int w = 0; w < W; ++w)
if (h[w] == f) { pick = alt[rep * i]; break; }
for (int w = 0; w + 1 < W; ++w) h[w] = h[w + 1];
h[W - 1] = pick;
}
for (int r = 0; r < rep; ++r) ids[rep * i + r] = pick;
}
__global__ __launch_bounds__(kT) void end_status_kernel(
const int* __restrict__ ids, const int* __restrict__ lane, int* __restrict__ status, int n,
int rep, int end) {
@@ -1303,9 +1356,11 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) {
const long long sup_lo = r4d_geti_or(a, "sup_lo", 0), sup_hi = r4d_geti_or(a, "sup_hi", 0);
const double cfg = r4d_getf(a, "cfg", 1.0), temp = r4d_getf(a, "temp", 1.0);
const double pen = r4d_getf(a, "penalty", 1.0);
/* As f32, as libref and libavx read it, so all three cut at the same value. */
const float top_p = (float)r4d_getf(a, "top_p", 1.0);
if (V <= 0 || K <= 0 || K > kMaxK || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V ||
!(temp > 0) || V > (1 << 16) * kT || sup_lo < 0 || sup_hi < sup_lo || sup_hi > V ||
!(pen > 0) || (!hist != !lane))
!(pen > 0) || (!hist != !lane) || !(top_p >= 0.f))
return R4D_NO(RAD_E_SHAPE);
long long rl = 0;
const long long ll = r4d_rows_pitch(lg, V, &rl);
@@ -1321,7 +1376,30 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) {
cfgs ? (const float*)cfgs->data : nullptr,
lane ? (const int*)lane->data : nullptr, hist ? (int*)hist->data : nullptr,
hist ? (int)(r4d_numel(hist) / V) : 0, (int)sup_lo, (int)sup_hi,
(float)pen);
(float)pen, top_p);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_ras_pick(const RadArgs* a, RadStream s) {
const RadTensor *first = r4d_opt(a, 0), *alt = r4d_opt(a, 1), *lane = r4d_opt(a, 2);
const RadTensor *hist = r4d_opt(a, 3), *ids = r4d_opt(a, 4);
if (!first || !alt || !lane || !hist || !ids) return R4D_NO(RAD_E_INVAL);
if (!is_i32(first) || !is_i32(alt) || !is_i32(lane) || !is_i32(hist) || !is_i32(ids))
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(first) || !r4d_contig(alt) || !r4d_contig(lane) || !r4d_contig(hist) ||
!r4d_contig(ids))
return R4D_NO(RAD_E_STRIDE);
const long long W = r4d_geti_or(a, "win", 0), lo = r4d_geti_or(a, "lo", 0);
const long long hi = r4d_geti_or(a, "hi", 0), rep = r4d_geti_or(a, "rep", 1);
const long long clear = r4d_geti_or(a, "clear", 0);
const long long n = r4d_numel(lane);
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
r4d_numel(first) < rep * n || r4d_numel(alt) < rep * n || r4d_numel(ids) < rep * n)
return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(ras_pick_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s,
(const int*)first->data, (const int*)alt->data, (const int*)lane->data,
(int*)hist->data, (int*)ids->data, (int)n, (int)W, (int)lo, (int)hi,
(int)rep, (int)clear, (long long)r4d_numel(hist));
return st_of(hipGetLastError());
}
+1
View File
@@ -202,6 +202,7 @@ int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream);
int r4d_rad_rvq_embed (const RadArgs*, RadStream);
int r4d_rad_frame_mix_store (const RadArgs*, RadStream);
int r4d_rad_end_status (const RadArgs*, RadStream);
int r4d_rad_ras_pick (const RadArgs*, RadStream);
int r4d_rad_frame_store (const RadArgs*, RadStream);
int r4d_rad_resample_nearest (const RadArgs*, RadStream);
int r4d_rad_fourier_embed (const RadArgs*, RadStream);
+17 -1
View File
@@ -2391,7 +2391,8 @@ static const RadOperandSpec oSnake[] = {
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
P_INTO("sup_hi"), P_F64O("penalty") };
P_INTO("sup_hi"), P_F64O("penalty"),
P_F64O("top_p") };
static const RadOperandSpec oCfgTopk[] = {
{ "logits", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 },
{ "ids", RAD_OPD_OUT, 0 }, { "cfg", RAD_OPD_IN, 1 }, { "lane", RAD_OPD_IN, 1 },
@@ -2415,6 +2416,12 @@ static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep"
static const RadOperandSpec oEndStatus[] = {
{ "ids", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "status", RAD_OPD_INOUT, 0 },
};
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
P_INTO("rep"), P_INTO("clear") };
static const RadOperandSpec oRasPick[] = {
{ "first", RAD_OPD_IN, 0 }, { "alt", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 },
{ "hist", RAD_OPD_INOUT, 0 }, { "ids", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
P_INTO("rep"), P_INTO("skip") };
static const RadOperandSpec oFrameStore[] = {
@@ -3335,6 +3342,9 @@ static const RadOpSchema kSchemas[] = {
"a frame's conditioning row (softmax-weighted planes times scale) into its lane."),
SCHEMA("end_status", pEndStatus, oEndStatus,
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]."),
SCHEMA("ras_pick", pRasPick, oRasPick,
"repetition-aware sampling: the alternative draw where the first is in [lo, hi) and in "
"the lane's window of its last picks, else the first; the pick enters the window."),
SCHEMA("frame_store", pFrameStore, oFrameStore,
"a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] "
"= codes[k, rep i] when frame >= skip and status[lane] >= 0."),
@@ -8292,6 +8302,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, 0, NOTUNE,
nullptr, nullptr, r4d_rad_end_status },
{ "ras_pick", "ras_pick", "elem",
"a repetition-aware choice between two draws a lane", "a thread a lane", "i32",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
nullptr, 0, NOTUNE,
nullptr, nullptr, r4d_rad_ras_pick },
{ "frame_store", "frame_store", "elem",
"a frame's codes into its lane's history", "a thread a (lane, code); dst contiguous", "i32",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
+97 -9
View File
@@ -5779,10 +5779,14 @@ void snake_cases(const Plugin& pl) {
}
}
/* Picks whose nucleus ended inside the top k, so that a top_p case is known to test the cut. */
int64_t g_topp_cuts = 0;
/* ref_cfg_topk_sample's rule on the host, for one lane, over f32 logits. */
int ref_pick(const std::vector<float>& lg, int64_t V, int64_t lane_row, int rep, float cfg,
int64_t K, int64_t cond_k, float temp, int64_t sup_lo, int64_t sup_hi, float pen,
std::vector<int32_t>* hist, int64_t hb, uint64_t seed, int32_t frame, uint64_t stream) {
std::vector<int32_t>* hist, int64_t hb, uint64_t seed, int32_t frame, uint64_t stream,
float top_p = 1.0f) {
std::vector<float> c((size_t)V), g((size_t)V);
for (int64_t j = 0; j < V; ++j) c[(size_t)j] = lg[(size_t)(rep * lane_row * V + j)];
if (rep == 2) {
@@ -5815,11 +5819,28 @@ int ref_pick(const std::vector<float>& lg, int64_t V, int64_t lane_row, int rep,
if (open(j)) idx.push_back(j);
}
if (idx.empty()) return -1;
const int64_t kk = std::min<int64_t>(K, (int64_t)idx.size());
double z = 0;
if (top_p < 1.0f) {
float gm = g[(size_t)idx[0]];
for (const int64_t j : idx) gm = std::max(gm, g[(size_t)j]);
for (const int64_t j : idx) z += std::exp((double)(g[(size_t)j] / temp - gm / temp));
}
int64_t kk = std::min<int64_t>(K, (int64_t)idx.size());
std::partial_sort(idx.begin(), idx.begin() + kk, idx.end(), [&](int64_t p, int64_t q) {
return g[(size_t)p] > g[(size_t)q] || (g[(size_t)p] == g[(size_t)q] && p < q);
});
const float m = g[(size_t)idx[0]] / temp;
if (top_p < 1.0f) {
double cum = 0;
int64_t keep = 1;
for (int64_t t = 0; t < kk; ++t) {
cum += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)) / z;
if (t > 0 && cum > (double)top_p) break;
keep = t + 1;
}
if (keep < kk) ++g_topp_cuts;
kk = keep;
}
double tot = 0;
std::vector<double> e((size_t)kk);
for (int64_t t = 0; t < kk; ++t) {
@@ -5844,16 +5865,26 @@ int ref_pick(const std::vector<float>& lg, int64_t V, int64_t lane_row, int rep,
void cfg_topk_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "cfg_topk_sample");
if (!r) { ok("cfg_topk_sample", false, "row absent"); return; }
struct C { int64_t V; int rep; bool hist, cfgs; int64_t sup_lo, sup_hi, cond_k; float temp; };
struct C {
int64_t V; int rep; bool hist, cfgs; int64_t sup_lo, sup_hi, cond_k; float temp;
float top_p = 1.0f; int64_t K = 50;
};
/* The last two are Fish Audio's draws (arch/fishomni): its main pick over eos and 4096
* semantic ids at temperature 0.7, nucleus 0.7, top 30, and its repetition-aware redraw at 1.0,
* 0.95, 30. */
for (const C& c : { C{ 2052, 2, true, true, 2048, 2051, 0, 0.9f },
C{ 2051, 1, true, false, 2048, 2051, 0, 0.9f },
C{ 2051, 2, false, true, 2048, 2051, 0, 0.9f },
C{ 16385, 2, false, false, 0, 0, 50, 1.0f } }) {
const int64_t n = 3, lanes = 4, K = 50;
const std::string nm = fmt("cfg_topk_sample V %lld rep %d%s%s sup [%lld, %lld) cond_k %lld",
C{ 16385, 2, false, false, 0, 0, 50, 1.0f },
C{ 4097, 1, false, false, 0, 0, 0, 0.7f, 0.7f, 30 },
C{ 4097, 1, false, false, 0, 0, 0, 1.0f, 0.95f, 30 } }) {
const int64_t n = 3, lanes = 4, K = c.K;
const std::string nm = fmt("cfg_topk_sample V %lld rep %d%s%s sup [%lld, %lld) cond_k %lld"
" top_p %g k %lld",
(long long)c.V, c.rep, c.hist ? " hist" : "",
c.cfgs ? " per-lane cfg" : "", (long long)c.sup_lo,
(long long)c.sup_hi, (long long)c.cond_k);
(long long)c.sup_hi, (long long)c.cond_k, (double)c.top_p,
(long long)K);
std::vector<int32_t> lane = { 2, 0, 3 };
std::vector<float> cfgv = { 1.0f, 3.0f, 4.0f };
std::vector<uint32_t> seed = { 7u, 0u, 0x9e3779b9u, 1u, 0xdeadbeefu, 0x12345u };
@@ -5876,6 +5907,9 @@ void cfg_topk_cases(const Plugin& pl) {
for (size_t i = 0; i < lg.size(); ++i) {
const float v = rnd() * 6.0f;
lg[i] = (i % 97 == 0) ? 5.95f : v;
/* About 19 peaks a row hold most of the mass, so the nucleus ends inside the top
* 30 and the cut is what decides the pick. */
if (c.top_p < 1.0f && i % 211 == 5) lg[i] = 12.0f + 4.0f * rnd();
}
void* dlg = up_f32(lg);
std::vector<int32_t> frame((size_t)n, f);
@@ -5888,7 +5922,7 @@ void cfg_topk_cases(const Plugin& pl) {
PI("rep", c.rep), PI("cond_k", c.cond_k), PF("cfg", 1.5),
PF("temp", c.temp), PI("stream", 3), PS("dtype", "f32"),
PI("sup_lo", c.sup_lo), PI("sup_hi", c.sup_hi),
PF("penalty", 1.1) };
PF("penalty", 1.1), PF("top_p", c.top_p) };
const int rc = launch(r, { T(dlg, RAD_F32, { c.rep * n, c.V }), T(dseed, RAD_U32, { n, 2 }),
T(dfr, RAD_I32, { n }), T(dids, RAD_I32, { c.rep * n }), tcfg,
tlane, thist },
@@ -5901,7 +5935,8 @@ void cfg_topk_cases(const Plugin& pl) {
const int want = ref_pick(lg, c.V, i, c.rep, c.cfgs ? cfgv[(size_t)i] : 1.5f, K,
c.cond_k, c.temp, c.sup_lo, c.sup_hi, 1.1f,
c.hist ? &hist : nullptr,
c.hist ? lane[(size_t)i] * c.V : -1, sd, f, 3);
c.hist ? lane[(size_t)i] * c.V : -1, sd, f, 3,
c.top_p);
for (int t = 0; t < c.rep; ++t)
if (got[(size_t)(c.rep * i + t)] != want) ++wrong;
}
@@ -5909,12 +5944,64 @@ void cfg_topk_cases(const Plugin& pl) {
}
ok((nm + " picks").c_str(), wrong == 0, fmt("%lld of %lld picks differ", (long long)wrong,
(long long)(4 * c.rep * n)));
if (c.top_p < 1.0f) {
ok((nm + " cuts").c_str(), g_topp_cuts > 0, "the nucleus never ended inside the top k");
g_topp_cuts = 0;
}
if (c.hist)
ok((nm + " history").c_str(), hist_wrong == 0,
fmt("%lld history entries differ", (long long)hist_wrong));
}
}
/* ras_pick over four picks of three lanes, the first clearing their windows: the picks and the
* windows against libref's rule on the host, exactly. Draws repeat often (a band of 6 ids) so the
* redraw is exercised, and one is outside [lo, hi) (never redrawn). */
void ras_pick_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "ras_pick");
if (!r) { ok("ras_pick", false, "row absent"); return; }
const int64_t n = 3, lanes = 4, W = 4, lo = 1, hi = 6;
std::vector<int32_t> lane = { 2, 0, 3 };
std::vector<int32_t> hist((size_t)(lanes * W), 5);
void* dlane = up_i32(lane);
void* dhist = up_i32(hist);
void* dids = dalloc((size_t)n * 4);
int64_t wrong = 0;
for (int step = 0; step < 4; ++step) {
std::vector<int32_t> first((size_t)n), alt((size_t)n);
for (int64_t i = 0; i < n; ++i) {
first[(size_t)i] = (int32_t)((step * 2 + i * 3) % 7); /* 0 is outside [lo, hi) */
alt[(size_t)i] = (int32_t)(10 + step * 3 + i);
}
void* df = up_i32(first);
void* da = up_i32(alt);
const int clear = step == 0 ? 1 : 0;
std::vector<RadParam> ps = { PI("M", n), PI("win", W), PI("lo", lo), PI("hi", hi),
PI("rep", 1), PI("clear", clear) };
const int rc = launch(r, { T(df, RAD_I32, { n }), T(da, RAD_I32, { n }),
T(dlane, RAD_I32, { n }), T(dhist, RAD_I32, { lanes, W }),
T(dids, RAD_I32, { n }) },
ps);
if (rc != RAD_OK) { ok("ras_pick", false, "rc " + std::to_string(rc)); return; }
const std::vector<int32_t> got = down_i32(dids, (size_t)n);
for (int64_t i = 0; i < n; ++i) {
int32_t* h = hist.data() + lane[(size_t)i] * W;
if (clear) for (int64_t w = 0; w < W; ++w) h[w] = -1;
int32_t pick = first[(size_t)i];
if (pick >= lo && pick < hi)
for (int64_t w = 0; w < W; ++w)
if (h[w] == pick) { pick = alt[(size_t)i]; break; }
for (int64_t w = 0; w + 1 < W; ++w) h[w] = h[w + 1];
h[W - 1] = pick;
if (got[(size_t)i] != pick) ++wrong;
}
}
ok("ras_pick picks", wrong == 0, fmt("%lld of %lld picks differ", (long long)wrong,
(long long)(4 * n)));
ok("ras_pick windows", differ(down_i32(dhist, hist.size()), hist) == 0,
"the windows differ from libref's rule");
}
/* rvq_embed: libref's two roundings, the single rounding over bf16 and f32 tables into a bf16 or
* f32 row, codes read as a block of a wider frame-major history (strides other than the dense
* plane's), and a first code outside its table leaving the row unwritten. Exact. */
@@ -24971,6 +25058,7 @@ static void device_phase(const Plugin& pl) {
if (sel("conv_t1d_bf16")) au::conv_t1d_cases(pl);
if (sel("snake_bf16")) au::snake_cases(pl);
if (sel("cfg_topk_sample")) au::cfg_topk_cases(pl);
if (sel("ras_pick")) au::ras_pick_cases(pl);
if (sel("rvq_embed_bf16")) au::rvq_embed_cases(pl);
if (sel("frame_store")) au::frame_store_cases(pl);
if (sel("iota")) au::iota_cases(pl);