changh95's picture
tt-model push paddleocr-vl (container)
22e0325 verified
Raw History Blame Contribute Delete
23.3 kB
// SPDX-License-Identifier: Apache-2.0
//
// Shared on-device sampler, copied unchanged from the Qwen3-TTS bundle (tt/mk_common/kernels/sampler.hpp, owner mk-cp). See ../SAMPLER.md.
//
// Integer-only (the Tensix RISC-Vs have no FPU), header-only, C++17, no device includes: the same code is compiled
// into the BRISC / NCRISC kernels and for the host (sampler_host.cpp -> ctypes, the bit-exact reference of the tests).
// Only talker_process() uses float (the repetition penalty must round like fp32 torch: soft-float on the device).
//
// Semantics (SPEC 3.2b) on scores distributed over P participants (each owns a slice of the vocab, fp32 logits):
// local : each participant sorts its slice best-first (score descending, id ascending) and keeps <= cap
// entries (cap >= its slice size for the exact full-vocab path, >= K_MAX otherwise)
// hub merge : the P sorted lists -> the global best <= K_MAX entries (same order)
// select : greedy = first entry (argmax, lowest id on ties). Sampling: kept set = the first k entries plus every
// further entry whose score equals the k-th (HF TopK keeps ties), capped at K_MAX entries (ties past
// K_MAX are dropped, largest ids first); -inf / NaN never kept. Weights W_i = 2^30 exp((s_i - s_0)/T)
// in fixed point (s_0 = best score); top-p (when < 1) cuts like HF TopPLogitsWarper (drop ranks whose
// tail mass <= (1 - top_p) Z; rank 0 always kept); pick the smallest rank i with C_i > u Z
// (C = prefix sum of W over the kept set, u = (U + 0.5) 2^-24, U = Philox x0 >> 8).
// full vocab : top_k == 0 && top_p >= 1: two phases. Phase 1 = merge (global best s_0); phase 2: every participant
// returns Z_c = sum of W over its whole slice; the hub walks the global order until C > u Z.
// top_k == 0 && top_p < 1 is evaluated as top_k = K_MAX (documented approximation, SPEC 2.1).
// Temperature only enters the weights (x = (s_0 - s_i) / T >= 0): ordering and ties are decided on the scores as
// given (the host reference does the same: tt/mk_common/sampler_host.py).
#pragma once
#include <stdint.h>
#ifndef MKS_ALWI
#define MKS_ALWI inline __attribute__((always_inline))
#endif
namespace mks {
// ------------------------------------------------------------------------------------------------ keys
struct Entry {
uint32_t key; // order-preserving image of the fp32 score (f32_key)
uint32_t id; // vocab id
};
constexpr uint32_t KEY_NEG_INF = 0x007FFFFFu; // f32_key(-inf); NaN maps to 0 (below -inf)
constexpr uint32_t F32_NEG_INF = 0xFF800000u;
constexpr uint32_t F32_ONE = 0x3F800000u;
constexpr uint32_t INVALID = 0xFFFFFFFFu;
// order-preserving map fp32 bits -> uint32 (-0 == +0, NaN lowest)
MKS_ALWI uint32_t f32_key(uint32_t b) {
if ((b & 0x7F800000u) == 0x7F800000u && (b & 0x007FFFFFu)) {
return 0; // NaN
}
if (b == 0x80000000u) {
b = 0;
}
return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
}
MKS_ALWI uint32_t key_f32(uint32_t k) { return (k & 0x80000000u) ? (k & 0x7FFFFFFFu) : ~k; }
// a ranks before b: higher score, then lower id
MKS_ALWI bool better(const Entry& a, const Entry& b) { return a.key > b.key || (a.key == b.key && a.id < b.id); }
// ------------------------------------------------------------------------------------------------ local stage
// Sort scores bits[0..n) (fp32 bit patterns of vocab ids id0..id0+n-1) best-first into out[0..cap); returns the count.
template <typename P>
inline uint32_t local_sorted(P bits, uint32_t n, uint32_t id0, Entry* out, uint32_t cap) {
uint32_t cnt = 0;
for (uint32_t i = 0; i < n; ++i) {
const Entry e{f32_key(bits[i]), id0 + i};
uint32_t j;
if (cnt < cap) {
j = cnt++;
} else {
if (!better(e, out[cap - 1])) {
continue;
}
j = cap - 1;
}
while (j > 0 && better(e, out[j - 1])) {
out[j] = out[j - 1];
--j;
}
out[j] = e;
}
return cnt;
}
// ------------------------------------------------------------------------------------------------ Philox4x32-10
constexpr uint32_t PH_M0 = 0xD2511F53u, PH_M1 = 0xCD9E8D57u, PH_W0 = 0x9E3779B9u, PH_W1 = 0xBB67AE85u;
inline void philox4x32_10(uint32_t c[4], uint32_t k0, uint32_t k1) {
for (uint32_t r = 0; r < 10; ++r) {
if (r) {
k0 += PH_W0;
k1 += PH_W1;
}
const uint64_t p0 = (uint64_t)PH_M0 * c[0];
const uint64_t p1 = (uint64_t)PH_M1 * c[2];
const uint32_t hi0 = (uint32_t)(p0 >> 32), lo0 = (uint32_t)p0;
const uint32_t hi1 = (uint32_t)(p1 >> 32), lo1 = (uint32_t)p1;
const uint32_t n0 = hi1 ^ c[1] ^ k0, n2 = hi0 ^ c[3] ^ k1;
c[0] = n0;
c[1] = lo1;
c[2] = n2;
c[3] = lo0;
}
}
// U = x0 >> 8 of Philox(counter = (frame, codebook, 0, 0), key = (seed lo, seed hi)); u = (U + 0.5) 2^-24
inline uint32_t philox_u24(uint32_t seed_lo, uint32_t seed_hi, uint32_t frame, uint32_t codebook) {
uint32_t c[4] = {frame, codebook, 0, 0};
philox4x32_10(c, seed_lo, seed_hi);
return c[0] >> 8;
}
// ------------------------------------------------------------------------------------------------ fixed point
constexpr int64_t FIX_MAX = (int64_t)1 << 39; // |score| clamped to 2^15
// round(score * 2^24) as int64 (clamped)
inline int64_t key_fixed(uint32_t key) {
const uint32_t b = key_f32(key);
const uint32_t e = (b >> 23) & 0xFFu;
int64_t f;
if (e == 0) {
f = 0;
} else if (e == 0xFFu) {
f = FIX_MAX;
} else {
const uint64_t m = (b & 0x7FFFFFu) | 0x800000u; // value = m 2^(e - 150); F = m 2^(e - 126)
const int32_t sh = (int32_t)e - 126;
if (sh >= 0) {
f = sh > 15 ? FIX_MAX : (int64_t)(m << sh);
} else {
const int32_t r = -sh;
f = r > 40 ? 0 : (int64_t)((m + ((uint64_t)1 << (r - 1))) >> r);
}
}
return (b & 0x80000000u) ? -f : f;
}
constexpr uint32_t T1[256] = {
0x80000000u, 0x7FA765ADu, 0x7F4F08AEu, 0x7EF6E8DAu, 0x7E9F0606u, 0x7E476009u, 0x7DEFF6B6u, 0x7D98C9E6u,
0x7D41D96Eu, 0x7CEB2523u, 0x7C94ACDEu, 0x7C3E7073u, 0x7BE86FBAu, 0x7B92AA88u, 0x7B3D20B6u, 0x7AE7D21Au,
0x7A92BE8Bu, 0x7A3DE5DFu, 0x79E947EFu, 0x7994E492u, 0x7940BB9Eu, 0x78ECCCECu, 0x78991854u, 0x78459DACu,
0x77F25CCEu, 0x779F5590u, 0x774C87CCu, 0x76F9F359u, 0x76A7980Fu, 0x765575C8u, 0x76038C5Bu, 0x75B1DBA2u,
0x75606374u, 0x750F23ABu, 0x74BE1C20u, 0x746D4CACu, 0x741CB528u, 0x73CC556Du, 0x737C2D55u, 0x732C3CBAu,
0x72DC8374u, 0x728D015Du, 0x723DB650u, 0x71EEA226u, 0x719FC4B9u, 0x71511DE4u, 0x7102AD80u, 0x70B47368u,
0x70666F76u, 0x7018A185u, 0x6FCB096Fu, 0x6F7DA710u, 0x6F307A41u, 0x6EE382DEu, 0x6E96C0C3u, 0x6E4A33C9u,
0x6DFDDBCCu, 0x6DB1B8A8u, 0x6D65CA38u, 0x6D1A1057u, 0x6CCE8AE1u, 0x6C8339B2u, 0x6C381CA6u, 0x6BED3399u,
0x6BA27E65u, 0x6B57FCE9u, 0x6B0DAEFFu, 0x6AC39485u, 0x6A79AD56u, 0x6A2FF94Fu, 0x69E6784Du, 0x699D2A2Cu,
0x69540EC9u, 0x690B2601u, 0x68C26FB1u, 0x6879EBB6u, 0x683199EDu, 0x67E97A34u, 0x67A18C68u, 0x6759D065u,
0x6712460Bu, 0x66CAED35u, 0x6683C5C3u, 0x663CCF92u, 0x65F60A7Fu, 0x65AF766Au, 0x6569132Fu, 0x6522E0ADu,
0x64DCDEC3u, 0x64970D4Fu, 0x64516C2Eu, 0x640BFB41u, 0x63C6BA64u, 0x6381A978u, 0x633CC85Bu, 0x62F816EBu,
0x62B39509u, 0x626F4292u, 0x622B1F66u, 0x61E72B65u, 0x61A3666Du, 0x615FD05Eu, 0x611C6919u, 0x60D9307Bu,
0x60962665u, 0x60534AB7u, 0x60109D51u, 0x5FCE1E12u, 0x5F8BCCDBu, 0x5F49A98Cu, 0x5F07B405u, 0x5EC5EC26u,
0x5E8451D0u, 0x5E42E4E3u, 0x5E01A53Fu, 0x5DC092C7u, 0x5D7FAD59u, 0x5D3EF4D7u, 0x5CFE6923u, 0x5CBE0A1Cu,
0x5C7DD7A4u, 0x5C3DD19Cu, 0x5BFDF7E5u, 0x5BBE4A61u, 0x5B7EC8F2u, 0x5B3F7377u, 0x5B0049D4u, 0x5AC14BEAu,
0x5A82799Au, 0x5A43D2C6u, 0x5A055751u, 0x59C7071Cu, 0x5988E209u, 0x594AE7FBu, 0x590D18D3u, 0x58CF7474u,
0x5891FAC1u, 0x5854AB9Bu, 0x581786E6u, 0x57DA8C83u, 0x579DBC57u, 0x57611642u, 0x57249A29u, 0x56E847EFu,
0x56AC1F75u, 0x567020A0u, 0x56344B52u, 0x55F89F70u, 0x55BD1CDBu, 0x5581C378u, 0x55469329u, 0x550B8BD4u,
0x54D0AD5Au, 0x5495F7A1u, 0x545B6A8Bu, 0x542105FDu, 0x53E6C9DAu, 0x53ACB607u, 0x5372CA68u, 0x533906E0u,
0x52FF6B55u, 0x52C5F7AAu, 0x528CABC3u, 0x52538786u, 0x521A8AD7u, 0x51E1B59Au, 0x51A907B4u, 0x5170810Bu,
0x51382182u, 0x50FFE8FEu, 0x50C7D765u, 0x508FEC9Cu, 0x50582888u, 0x50208B0Eu, 0x4FE91413u, 0x4FB1C37Cu,
0x4F7A9930u, 0x4F439514u, 0x4F0CB70Cu, 0x4ED5FF00u, 0x4E9F6CD4u, 0x4E69006Eu, 0x4E32B9B4u, 0x4DFC988Cu,
0x4DC69CDDu, 0x4D90C68Bu, 0x4D5B157Eu, 0x4D25899Cu, 0x4CF022CAu, 0x4CBAE0EFu, 0x4C85C3F1u, 0x4C50CBB8u,
0x4C1BF829u, 0x4BE7492Bu, 0x4BB2BEA5u, 0x4B7E587Eu, 0x4B4A169Cu, 0x4B15F8E6u, 0x4AE1FF43u, 0x4AAE299Bu,
0x4A7A77D4u, 0x4A46E9D6u, 0x4A137F88u, 0x49E038D0u, 0x49AD1598u, 0x497A15C4u, 0x4947393Fu, 0x49147FEEu,
0x48E1E9BAu, 0x48AF768Au, 0x487D2646u, 0x484AF8D6u, 0x4818EE22u, 0x47E70611u, 0x47B5408Cu, 0x47839D7Bu,
0x47521CC6u, 0x4720BE55u, 0x46EF8210u, 0x46BE67E0u, 0x468D6FAEu, 0x465C9961u, 0x462BE4E2u, 0x45FB521Au,
0x45CAE0F2u, 0x459A9152u, 0x456A6323u, 0x453A564Du, 0x450A6ABBu, 0x44DAA054u, 0x44AAF702u, 0x447B6EADu,
0x444C0740u, 0x441CC0A3u, 0x43ED9AC0u, 0x43BE957Fu, 0x438FB0CBu, 0x4360EC8Du, 0x433248AEu, 0x4303C518u,
0x42D561B4u, 0x42A71E6Cu, 0x4278FB2Bu, 0x424AF7DAu, 0x421D1462u, 0x41EF50AEu, 0x41C1ACA7u, 0x41942839u,
0x4166C34Cu, 0x41397DCCu, 0x410C57A2u, 0x40DF50B8u, 0x40B268FAu, 0x4085A051u, 0x4058F6A8u, 0x402C6BE9u,
};
constexpr uint64_t LOG2E_Q31 = 3098164009ull; // round(log2(e) 2^31)
constexpr uint64_t LN2_Q25 = 23258160ull; // round(ln(2) 2^25)
constexpr uint64_t X_SAT = (uint64_t)22 << 24; // exp(-22) 2^30 < 0.5: weight 0
constexpr uint32_t W_ONE = 1u << 30;
// x = d / T in 2^-24 units (d = F_0 - F_i >= 0 in 2^-24 units), saturated at X_SAT
inline uint64_t scaled_gap(uint64_t d, uint32_t inv_t_bits) {
if (d == 0) {
return 0;
}
const uint32_t e = (inv_t_bits >> 23) & 0xFFu;
if (e == 0 || (inv_t_bits & 0x80000000u)) {
return 0; // 1/T == 0 (or negative: invalid): uniform
}
if (e == 0xFFu) {
return X_SAT;
}
if (d >= ((uint64_t)1 << 40)) {
d = ((uint64_t)1 << 40) - 1;
}
const uint32_t m = (inv_t_bits & 0x7FFFFFu) | 0x800000u; // 1/T = m 2^(e - 150)
// d m < 2^64 from 32 x 32 -> 64 pieces (d < 2^40, m < 2^24; no 64 x 64 multiply on the RV32 cores)
const uint64_t p = (uint64_t)(uint32_t)d * m + (((uint64_t)(uint32_t)(d >> 32) * m) << 32);
const int32_t sh = 150 - (int32_t)e;
uint64_t x;
if (sh <= 0) {
x = X_SAT;
} else if (sh >= 64) {
x = 0;
} else {
x = p >> sh;
}
return x < X_SAT ? x : X_SAT;
}
// round(2^30 2^(-x log2(e) 2^-24)) for x in 2^-24 units
inline uint32_t weight_q30_x(uint64_t x) {
if (x >= X_SAT) {
return 0;
}
// 32-bit operands wherever the values fit (x < 2^29, a < 2^23, a2 < 2^15, a3 < 2^7): the same values as the
// 64-bit formulas, without 64 x 64 multiplies / divisions on the RV32 cores
const uint64_t y = ((uint64_t)(uint32_t)x * (uint32_t)LOG2E_Q31) >> 31; // log2 domain, 2^-24 units
const uint32_t n = (uint32_t)(y >> 24);
const uint32_t f = (uint32_t)(y & 0xFFFFFFu);
const uint32_t f1 = f >> 16, f0 = f & 0xFFFFu;
const uint32_t a = (uint32_t)(((uint64_t)f0 * (uint32_t)LN2_Q25) >> 18); // f0 2^-24 ln2 in Q31 (< 2^23)
const uint32_t a2 = (uint32_t)(((uint64_t)a * a) >> 31);
const uint32_t a3 = (uint32_t)(((uint64_t)a2 * a) >> 31);
const uint32_t poly = (1u << 31) - a + (a2 >> 1) - ((a3 * 43691u) >> 18); // exp(-a) in Q31 (a3 / 6 exact: a3 < 2^16)
const uint32_t sh = 32 + n;
if (sh >= 63) {
return 0;
}
return (uint32_t)(((uint64_t)T1[f1] * poly + ((uint64_t)1 << (sh - 1))) >> sh);
}
MKS_ALWI uint32_t weight_q30(int64_t f0, int64_t fi, uint32_t inv_t_bits) {
return weight_q30_x(scaled_gap((uint64_t)(f0 - fi), inv_t_bits));
}
// a 2^25 > b Z (a, Z < 2^47, b < 2^25) without 128-bit arithmetic
inline bool gt_scaled(uint64_t a, uint32_t b, uint64_t z) {
const uint64_t lh = a >> 39, ll = a << 25;
const uint64_t t = (uint64_t)b * (uint32_t)z;
const uint64_t u = (uint64_t)b * (uint32_t)(z >> 32);
const uint64_t rl = t + (u << 32);
const uint64_t rh = (u >> 32) + (rl < t ? 1 : 0);
return lh > rh || (lh == rh && ll > rl);
}
// q = round(clamp(1 - top_p, 0, 1) 2^24) from the fp32 bits of top_p; returns 0 when top_p >= 1 (no nucleus cut)
inline uint32_t top_p_q24(uint32_t top_p_bits) {
if (top_p_bits & 0x80000000u) {
return 1u << 24; // top_p < 0: keep the top token only
}
if (top_p_bits >= F32_ONE) {
return 0;
}
const uint32_t e = (top_p_bits >> 23) & 0xFFu;
if (e == 0) {
return 1u << 24;
}
const uint64_t m = (top_p_bits & 0x7FFFFFu) | 0x800000u; // top_p = m 2^(e - 150); top_p 2^24 = m 2^(e - 126)
const int32_t r = 126 - (int32_t)e; // >= 0 for top_p < 1
const uint32_t p24 = r > 40 ? 0 : (uint32_t)((m + ((uint64_t)1 << r >> 1)) >> r);
return p24 >= (1u << 24) ? 0 : (1u << 24) - p24;
}
// ------------------------------------------------------------------------------------------------ hub merge
// k-way merge (loser tree) over P <= MKS_MAX_LISTS sorted lists
#ifndef MKS_MAX_LISTS
#define MKS_MAX_LISTS 128
#endif
struct Merger {
// loser tree: lose[j] (internal nodes 1 .. p2 - 1) = the loser of node j's match, w = the overall winner; a pop
// replays one match per level against the stored losers. Heads cached in local arrays (key 0 + id ~0 =
// exhausted: loses every compare).
const Entry* e[MKS_MAX_LISTS];
uint32_t n[MKS_MAX_LISTS];
uint32_t pos[MKS_MAX_LISTS];
uint32_t hk[MKS_MAX_LISTS];
uint32_t hid[MKS_MAX_LISTS];
uint16_t lose[MKS_MAX_LISTS];
uint16_t wn[MKS_MAX_LISTS]; // build scratch: winners of the internal nodes
uint32_t w;
uint32_t p2;
Entry cur; // the winner's head
MKS_ALWI bool bt(uint32_t a, uint32_t b) const { return hk[a] > hk[b] || (hk[a] == hk[b] && hid[a] < hid[b]); }
MKS_ALWI void load_head(uint32_t i) {
if (pos[i] < n[i]) {
const Entry& x = e[i][pos[i]];
hk[i] = x.key;
hid[i] = x.id;
} else {
hk[i] = 0;
hid[i] = 0xFFFFFFFFu;
}
}
// incremental setup: prepare(p), set_list(i, ...) for every i < p in any order (e.g. as lists arrive), build()
void prepare(uint32_t p) {
p2 = 1;
while (p2 < p) {
p2 <<= 1;
}
for (uint32_t i = p; i < p2; ++i) {
e[i] = nullptr;
n[i] = 0;
pos[i] = 0;
hk[i] = 0;
hid[i] = 0xFFFFFFFFu;
}
}
MKS_ALWI void set_list_head(uint32_t i, const Entry* list, uint32_t count, uint32_t key, uint32_t id) {
e[i] = list;
n[i] = count;
pos[i] = 0;
hk[i] = count ? key : 0;
hid[i] = count ? id : 0xFFFFFFFFu;
}
MKS_ALWI void set_list(uint32_t i, const Entry* list, uint32_t count) {
e[i] = list;
n[i] = count;
pos[i] = 0;
load_head(i);
}
void build() {
for (uint32_t j = p2 - 1; j >= 1; --j) {
const uint32_t l = 2 * j, r = 2 * j + 1;
const uint32_t a = l >= p2 ? l - p2 : wn[l];
const uint32_t b = r >= p2 ? r - p2 : wn[r];
if (bt(b, a)) {
wn[j] = (uint16_t)b;
lose[j] = (uint16_t)a;
} else {
wn[j] = (uint16_t)a;
lose[j] = (uint16_t)b;
}
}
w = p2 > 1 ? wn[1] : 0;
cur.key = hk[w];
cur.id = hid[w];
}
// lists[i] = (entries, count); empty / padding lists have count 0
void init(const Entry* const* lists, const uint32_t* counts, uint32_t p) {
prepare(p);
for (uint32_t i = 0; i < p; ++i) {
set_list(i, lists[i], counts[i]);
}
build();
}
MKS_ALWI bool empty() const { return pos[w] >= n[w]; }
MKS_ALWI const Entry& top() const { return cur; }
void pop() {
uint32_t x = w;
++pos[x];
load_head(x);
for (uint32_t j = (p2 + x) >> 1; j >= 1; j >>= 1) {
const uint32_t l = lose[j];
if (bt(l, x)) {
lose[j] = (uint16_t)x;
x = l;
}
}
w = x;
cur.key = hk[x];
cur.id = hid[x];
}
};
// the best <= cap entries of the merger into out; returns the count
inline uint32_t merge_take(Merger& m, Entry* out, uint32_t cap) {
uint32_t c = 0;
while (c < cap && !m.empty()) {
out[c++] = m.top();
m.pop();
}
return c;
}
// ------------------------------------------------------------------------------------------------ selection
struct Params {
uint32_t do_sample; // 0 = greedy
uint32_t inv_t_bits; // fp32 bits of 1/T
uint32_t top_k; // 0 = off (full vocab or the K_MAX approximation)
uint32_t top_p_bits; // fp32 bits of top_p (>= 1.0 = off)
};
struct Info {
uint32_t kept_k; // candidates after top-k (+ ties)
uint32_t kept_p; // after the nucleus cut
uint32_t rank; // picked rank
uint32_t w0; // reserved
uint64_t z; // sum of weights of the kept set
};
MKS_ALWI bool full_vocab(const Params& p) { return p.do_sample && p.top_k == 0 && p.top_p_bits >= F32_ONE; }
// the sampling weight of a merged entry (f0 = key_fixed of the best key)
MKS_ALWI uint32_t entry_weight(int64_t f0, uint32_t key, uint32_t inv_t_bits) {
return key <= KEY_NEG_INF ? 0 : weight_q30(f0, key_fixed(key), inv_t_bits);
}
// sampling (do_sample) part of select_topk on the best-first keys key(0 .. cnt) (cnt >= 1): the picked rank.
// W[0 .. pre) may already hold entry_weight(f0, key(i)) (a parallel helper), the rest is computed here.
template <typename KeyAt>
inline uint32_t select_topk_rank(KeyAt key, uint32_t cnt, const Params& p, uint32_t u24, uint32_t k_max, uint32_t* W,
uint32_t pre, Info* info) {
uint32_t fin = cnt < k_max ? cnt : k_max;
while (fin > 1 && key(fin - 1) <= KEY_NEG_INF) {
--fin;
}
uint32_t k = (p.top_k == 0 || p.top_k > k_max) ? k_max : p.top_k;
uint32_t kept = k < fin ? k : fin;
if (kept < fin) {
const uint32_t v = key(kept - 1);
while (kept < fin && key(kept) == v) {
++kept;
}
}
const int64_t f0 = key_fixed(key(0));
uint64_t z = 0;
for (uint32_t i = 0; i < kept; ++i) {
if (i >= pre) {
W[i] = entry_weight(f0, key(i), p.inv_t_bits);
}
z += W[i];
}
uint32_t kp = kept;
const uint32_t q = top_p_q24(p.top_p_bits);
if (q) {
// keep rank r while its tail mass T_r = z - C_{r-1} satisfies T_r 2^24 > q z (rank 0 always)
uint64_t c = W[0];
kp = 1;
while (kp < kept) {
const uint64_t tail = z - c;
if (!(tail * (1u << 24) > (uint64_t)q * z)) {
break;
}
c += W[kp];
++kp;
}
z = 0;
for (uint32_t i = 0; i < kp; ++i) {
z += W[i];
}
}
const uint32_t b = 2 * u24 + 1;
uint64_t c = 0;
uint32_t r = kp - 1;
for (uint32_t i = 0; i < kp; ++i) {
c += W[i];
if (gt_scaled(c, b, z)) {
r = i;
break;
}
}
if (info) {
info->kept_k = kept;
info->kept_p = kp;
info->rank = r;
info->z = z;
}
return r;
}
// greedy / top-k (and the top_k = 0, top_p < 1 approximation) on the merged best-first list m[0..cnt)
// (cnt = min(K_MAX, total)); W = caller scratch of >= k_max uint32
inline uint32_t select_topk(const Entry* m, uint32_t cnt, const Params& p, uint32_t u24, uint32_t k_max, uint32_t* W,
Info* info) {
if (cnt == 0) {
return INVALID;
}
if (!p.do_sample) {
if (info) {
info->kept_k = info->kept_p = 1;
info->rank = 0;
info->z = W_ONE;
}
return m[0].id;
}
return m[select_topk_rank([m](uint32_t i) { return m[i].key; }, cnt, p, u24, k_max, W, 0, info)].id;
}
// full-vocab path, phase 2 at a participant: sum of the weights of its whole sorted list relative to the global best
inline uint64_t local_weight_sum(const Entry* list, uint32_t n, int64_t f0, uint32_t inv_t_bits) {
uint64_t z = 0;
for (uint32_t i = 0; i < n; ++i) {
if (list[i].key <= KEY_NEG_INF) {
break;
}
const uint32_t w = weight_q30(f0, key_fixed(list[i].key), inv_t_bits);
if (w == 0) {
break; // sorted: every later weight is 0 too
}
z += w;
}
return z;
}
// full-vocab path at the hub: walk the global order (a fresh merger over the complete lists) until C > u Z
inline uint32_t select_full(Merger& m, uint64_t z, uint32_t u24, uint32_t inv_t_bits, Info* info) {
if (m.empty()) {
return INVALID;
}
const int64_t f0 = key_fixed(m.top().key);
const uint32_t b = 2 * u24 + 1;
uint64_t c = 0;
uint32_t r = 0, last = m.top().id;
while (!m.empty()) {
const Entry& e = m.top();
if (e.key <= KEY_NEG_INF) {
break;
}
const uint32_t w = weight_q30(f0, key_fixed(e.key), inv_t_bits);
last = e.id;
c += w;
if (gt_scaled(c, b, z)) {
break;
}
if (w == 0) {
break; // numerically exhausted: the last positive-weight entry
}
m.pop();
++r;
}
if (info) {
info->kept_k = info->kept_p = 0;
info->rank = r;
info->z = z;
}
return last;
}
// ------------------------------------------------------------------------------------------------ talker processors
// HF order on fp32 scores (bit patterns, in place) of vocab ids id0..id0+n-1: repetition penalty over the ids set in
// seen (bitmap of codebook-0 ids 0..2047, 64 words), EOS = -inf while step < min_new, ids 2048..3071 except EOS
// = -inf. The penalty rounds like torch fp32 (s * p if s < 0 else s / p): float ops (soft-float on the RISC-Vs).
template <typename P, typename S>
inline void talker_process(P bits, uint32_t n, uint32_t id0, S seen, uint32_t step, uint32_t min_new, uint32_t eos,
uint32_t pen_bits) {
union U {
uint32_t u;
float f;
};
U pen;
pen.u = pen_bits;
for (uint32_t i = 0; i < n; ++i) {
const uint32_t id = id0 + i;
if (id < 2048) {
if (pen_bits != F32_ONE && ((seen[id >> 5] >> (id & 31)) & 1u)) {
U s;
s.u = bits[i];
s.f = s.f < 0.0f ? s.f * pen.f : s.f / pen.f;
bits[i] = s.u;
}
} else if (id == eos) {
if (step < min_new) {
bits[i] = F32_NEG_INF;
}
} else if (id < 3072) {
bits[i] = F32_NEG_INF;
}
}
}
} // namespace mks