@@ -7956,10 +7956,57 @@ void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * can
7956
7956
auto comp = [](const llama_token_data & a, const llama_token_data & b) {
7957
7957
return a.logit > b.logit;
7958
7958
};
7959
- if (k == (int) candidates->size) {
7960
- std::sort(candidates->data, candidates->data + candidates->size, comp);
7961
- } else {
7959
+ if (k <= 128) {
7962
7960
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
+
7963
8010
}
7964
8011
candidates->sorted = true;
7965
8012
}
0 commit comments