Skip to content

Commit 1182cf4

Browse files
ikawrakowKawrakow
andauthored
Another bucket sort (#5109)
* Initial bucket sort * Bucket sort: slightly better version * Bucket sort: another minor improvement --------- Co-authored-by: Iwan Kawrakow <[email protected]>
1 parent fe54033 commit 1182cf4

File tree

1 file changed

+50
-3
lines changed

1 file changed

+50
-3
lines changed

llama.cpp

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7956,10 +7956,57 @@ void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * can
79567956
auto comp = [](const llama_token_data & a, const llama_token_data & b) {
79577957
return a.logit > b.logit;
79587958
};
7959-
if (k == (int) candidates->size) {
7960-
std::sort(candidates->data, candidates->data + candidates->size, comp);
7961-
} else {
7959+
if (k <= 128) {
79627960
std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
7961+
} else {
7962+
constexpr int nbuckets = 128;
7963+
constexpr float bucket_low = -10.0f;
7964+
constexpr float bucket_high = 10.0f;
7965+
constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
7966+
constexpr float bucker_inter = -bucket_low * bucket_scale;
7967+
7968+
std::vector<int> bucket_idx(candidates->size);
7969+
std::vector<int> histo(nbuckets, 0);
7970+
7971+
for (int i = 0; i < (int)candidates->size; ++i) {
7972+
const float val = candidates->data[i].logit;
7973+
int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
7974+
ib = std::max(0, std::min(nbuckets-1, ib));
7975+
bucket_idx[i] = ib;
7976+
++histo[ib];
7977+
}
7978+
int nhave = 0;
7979+
int ib = nbuckets - 1;
7980+
for ( ; ib >= 0; --ib) {
7981+
nhave += histo[ib];
7982+
if (nhave >= k) break;
7983+
}
7984+
std::vector<llama_token_data> tmp_tokens(nhave);
7985+
auto ptr = tmp_tokens.data();
7986+
std::vector<llama_token_data*> bucket_ptrs;
7987+
bucket_ptrs.reserve(nbuckets - ib);
7988+
for (int j = nbuckets - 1; j >= ib; --j) {
7989+
bucket_ptrs.push_back(ptr);
7990+
ptr += histo[j];
7991+
}
7992+
for (int i = 0; i < (int)candidates->size; ++i) {
7993+
int j = bucket_idx[i];
7994+
if (j >= ib) {
7995+
*bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
7996+
}
7997+
}
7998+
7999+
ptr = tmp_tokens.data();
8000+
int ndone = 0;
8001+
for (int j = nbuckets-1; j > ib; --j) {
8002+
std::sort(ptr, ptr + histo[j], comp);
8003+
ptr += histo[j];
8004+
ndone += histo[j];
8005+
}
8006+
std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
8007+
8008+
std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
8009+
79638010
}
79648011
candidates->sorted = true;
79658012
}

0 commit comments

Comments
 (0)