utils.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. #include "utils.h"
  2. #include <cassert>
  3. #include <cstring>
  4. #include <fstream>
  5. #include <regex>
  6. #include <iostream>
  7. #include <iterator>
  8. #include <queue>
  9. #include <string>
  10. #include <math.h>
  11. #if defined(_MSC_VER) || defined(__MINGW32__)
  12. #include <malloc.h> // using malloc.h with MSC/MINGW
  13. #elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  14. #include <alloca.h>
  15. #endif
  16. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  17. // determine sensible default number of threads.
  18. // std::thread::hardware_concurrency may not be equal to the number of cores, or may return 0.
  19. #ifdef __linux__
  20. std::ifstream cpuinfo("/proc/cpuinfo");
  21. params.n_threads = std::count(std::istream_iterator<std::string>(cpuinfo),
  22. std::istream_iterator<std::string>(),
  23. std::string("processor"));
  24. #endif
  25. if (params.n_threads == 0) {
  26. params.n_threads = std::max(1, (int32_t) std::thread::hardware_concurrency());
  27. }
  28. for (int i = 1; i < argc; i++) {
  29. std::string arg = argv[i];
  30. if (arg == "-s" || arg == "--seed") {
  31. params.seed = std::stoi(argv[++i]);
  32. } else if (arg == "-t" || arg == "--threads") {
  33. params.n_threads = std::stoi(argv[++i]);
  34. } else if (arg == "-p" || arg == "--prompt") {
  35. params.prompt = argv[++i];
  36. } else if (arg == "-f" || arg == "--file") {
  37. std::ifstream file(argv[++i]);
  38. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  39. if (params.prompt.back() == '\n') {
  40. params.prompt.pop_back();
  41. }
  42. } else if (arg == "-n" || arg == "--n_predict") {
  43. params.n_predict = std::stoi(argv[++i]);
  44. } else if (arg == "--top_k") {
  45. params.top_k = std::stoi(argv[++i]);
  46. } else if (arg == "-c" || arg == "--ctx_size") {
  47. params.n_ctx = std::stoi(argv[++i]);
  48. } else if (arg == "--memory_f16") {
  49. params.memory_f16 = true;
  50. } else if (arg == "--top_p") {
  51. params.top_p = std::stof(argv[++i]);
  52. } else if (arg == "--temp") {
  53. params.temp = std::stof(argv[++i]);
  54. } else if (arg == "--repeat_last_n") {
  55. params.repeat_last_n = std::stoi(argv[++i]);
  56. } else if (arg == "--repeat_penalty") {
  57. params.repeat_penalty = std::stof(argv[++i]);
  58. } else if (arg == "-b" || arg == "--batch_size") {
  59. params.n_batch = std::stoi(argv[++i]);
  60. } else if (arg == "-m" || arg == "--model") {
  61. params.model = argv[++i];
  62. } else if (arg == "-i" || arg == "--interactive") {
  63. params.interactive = true;
  64. } else if (arg == "-ins" || arg == "--instruct") {
  65. params.instruct = true;
  66. } else if (arg == "--color") {
  67. params.use_color = true;
  68. } else if (arg == "-r" || arg == "--reverse-prompt") {
  69. params.antiprompt.push_back(argv[++i]);
  70. } else if (arg == "--perplexity") {
  71. params.perplexity = true;
  72. } else if (arg == "--ignore-eos") {
  73. params.ignore_eos = true;
  74. } else if (arg == "--n_parts") {
  75. params.n_parts = std::stoi(argv[++i]);
  76. } else if (arg == "-h" || arg == "--help") {
  77. gpt_print_usage(argc, argv, params);
  78. exit(0);
  79. } else if (arg == "--random-prompt") {
  80. params.random_prompt = true;
  81. } else {
  82. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  83. gpt_print_usage(argc, argv, params);
  84. exit(0);
  85. }
  86. }
  87. return true;
  88. }
  89. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  90. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  91. fprintf(stderr, "\n");
  92. fprintf(stderr, "options:\n");
  93. fprintf(stderr, " -h, --help show this help message and exit\n");
  94. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  95. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  96. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  97. fprintf(stderr, " in interactive mode, poll user input upon seeing PROMPT (can be\n");
  98. fprintf(stderr, " specified more than once for multiple prompts).\n");
  99. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  100. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
  101. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  102. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  103. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  104. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  105. fprintf(stderr, " -f FNAME, --file FNAME\n");
  106. fprintf(stderr, " prompt file to start generation.\n");
  107. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d)\n", params.n_predict);
  108. fprintf(stderr, " --top_k N top-k sampling (default: %d)\n", params.top_k);
  109. fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", params.top_p);
  110. fprintf(stderr, " --repeat_last_n N last n tokens to consider for penalize (default: %d)\n", params.repeat_last_n);
  111. fprintf(stderr, " --repeat_penalty N penalize repeat sequence of tokens (default: %.1f)\n", params.repeat_penalty);
  112. fprintf(stderr, " -c N, --ctx_size N size of the prompt context (default: %d)\n", params.n_ctx);
  113. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating\n");
  114. fprintf(stderr, " --memory_f16 use f16 instead of f32 for memory key+value\n");
  115. fprintf(stderr, " --temp N temperature (default: %.1f)\n", params.temp);
  116. fprintf(stderr, " --n_parts N number of model parts (default: -1 = determine from dimensions)\n");
  117. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  118. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  119. fprintf(stderr, " -m FNAME, --model FNAME\n");
  120. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  121. fprintf(stderr, "\n");
  122. }
  123. std::string gpt_random_prompt(std::mt19937 & rng) {
  124. const int r = rng() % 10;
  125. switch (r) {
  126. case 0: return "So";
  127. case 1: return "Once upon a time";
  128. case 2: return "When";
  129. case 3: return "The";
  130. case 4: return "After";
  131. case 5: return "If";
  132. case 6: return "import";
  133. case 7: return "He";
  134. case 8: return "She";
  135. case 9: return "They";
  136. default: return "To";
  137. }
  138. return "The";
  139. }
  140. void replace(std::string & str, const std::string & needle, const std::string & replacement) {
  141. size_t pos = 0;
  142. while ((pos = str.find(needle, pos)) != std::string::npos) {
  143. str.replace(pos, needle.length(), replacement);
  144. pos += replacement.length();
  145. }
  146. }
  147. std::map<std::string, int32_t> json_parse(const std::string & fname) {
  148. std::map<std::string, int32_t> result;
  149. // read file into string
  150. std::string json;
  151. {
  152. std::ifstream ifs(fname);
  153. if (!ifs) {
  154. fprintf(stderr, "Failed to open %s\n", fname.c_str());
  155. exit(1);
  156. }
  157. json = std::string((std::istreambuf_iterator<char>(ifs)),
  158. (std::istreambuf_iterator<char>()));
  159. }
  160. if (json[0] != '{') {
  161. return result;
  162. }
  163. // parse json
  164. {
  165. bool has_key = false;
  166. bool in_token = false;
  167. std::string str_key = "";
  168. std::string str_val = "";
  169. int n = json.size();
  170. for (int i = 1; i < n; ++i) {
  171. if (!in_token) {
  172. if (json[i] == ' ') continue;
  173. if (json[i] == '"') {
  174. in_token = true;
  175. continue;
  176. }
  177. } else {
  178. if (json[i] == '\\' && i+1 < n) {
  179. if (has_key == false) {
  180. str_key += json[i];
  181. } else {
  182. str_val += json[i];
  183. }
  184. ++i;
  185. } else if (json[i] == '"') {
  186. if (has_key == false) {
  187. has_key = true;
  188. ++i;
  189. while (json[i] == ' ') ++i;
  190. ++i; // :
  191. while (json[i] == ' ') ++i;
  192. if (json[i] != '\"') {
  193. while (json[i] != ',' && json[i] != '}') {
  194. str_val += json[i++];
  195. }
  196. has_key = false;
  197. } else {
  198. in_token = true;
  199. continue;
  200. }
  201. } else {
  202. has_key = false;
  203. }
  204. ::replace(str_key, "\\u0120", " " ); // \u0120 -> space
  205. ::replace(str_key, "\\u010a", "\n"); // \u010a -> new line
  206. ::replace(str_key, "\\\"", "\""); // \\\" -> "
  207. try {
  208. result[str_key] = std::stoi(str_val);
  209. } catch (...) {
  210. //fprintf(stderr, "%s: ignoring key '%s' with value '%s'\n", fname.c_str(), str_key.c_str(), str_val.c_str());
  211. }
  212. str_key = "";
  213. str_val = "";
  214. in_token = false;
  215. continue;
  216. }
  217. if (has_key == false) {
  218. str_key += json[i];
  219. } else {
  220. str_val += json[i];
  221. }
  222. }
  223. }
  224. }
  225. return result;
  226. }
  227. static size_t utf8_len(char src) {
  228. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  229. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  230. return lookup[highbits];
  231. }
  232. struct llama_sp_symbol {
  233. using index = int;
  234. index prev;
  235. index next;
  236. const char * text;
  237. size_t n;
  238. };
  239. struct llama_sp_bigram {
  240. struct comparator {
  241. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  242. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  243. }
  244. };
  245. using queue_storage = std::vector<llama_sp_bigram>;
  246. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  247. llama_sp_symbol::index left;
  248. llama_sp_symbol::index right;
  249. float score;
  250. size_t size;
  251. };
  252. // original implementation:
  253. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  254. struct llama_tokenizer {
  255. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  256. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  257. // split string into utf8 chars
  258. int index = 0;
  259. size_t offs = 0;
  260. while (offs < text.size()) {
  261. llama_sp_symbol sym;
  262. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  263. sym.text = text.c_str() + offs;
  264. sym.n = char_len;
  265. offs += char_len;
  266. sym.prev = index - 1;
  267. sym.next = offs == text.size() ? -1 : index + 1;
  268. index++;
  269. symbols_.emplace_back(std::move(sym));
  270. }
  271. // seed the work queue with all possible 2-character tokens.
  272. for (size_t i = 1; i < symbols_.size(); ++i) {
  273. try_add_bigram(i - 1, i);
  274. }
  275. // keep substituting the highest frequency pairs for as long as we can.
  276. while (!work_queue_.empty()) {
  277. auto bigram = work_queue_.top();
  278. work_queue_.pop();
  279. auto & left_sym = symbols_[bigram.left];
  280. auto & right_sym = symbols_[bigram.right];
  281. // if one of the symbols already got merged, skip it.
  282. if (left_sym.n == 0 || right_sym.n == 0 ||
  283. left_sym.n + right_sym.n != bigram.size) {
  284. continue;
  285. }
  286. // merge the right sym into the left one
  287. left_sym.n += right_sym.n;
  288. right_sym.n = 0;
  289. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  290. // remove the right sym from the chain
  291. left_sym.next = right_sym.next;
  292. if (right_sym.next >= 0) {
  293. symbols_[right_sym.next].prev = bigram.left;
  294. }
  295. // find more substitutions
  296. try_add_bigram(left_sym.prev, bigram.left);
  297. try_add_bigram(bigram.left, left_sym.next);
  298. }
  299. for (int i = 0; i != -1; i = symbols_[i].next) {
  300. auto & symbol = symbols_[i];
  301. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  302. if (token == vocab_.token_to_id.end()) {
  303. // output any symbols that did not form tokens as bytes.
  304. for (int j = 0; j < (int) symbol.n; ++j) {
  305. llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  306. output.push_back(token_id);
  307. }
  308. } else {
  309. output.push_back((*token).second);
  310. }
  311. }
  312. }
  313. private:
  314. void try_add_bigram(int left, int right) {
  315. if (left == -1 || right == -1) {
  316. return;
  317. }
  318. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  319. auto token = vocab_.token_to_id.find(text);
  320. if (token == vocab_.token_to_id.end()) {
  321. return;
  322. }
  323. auto score = vocab_.score.find((*token).second);
  324. if (score == vocab_.score.end()) {
  325. return;
  326. }
  327. llama_sp_bigram bigram;
  328. bigram.left = left;
  329. bigram.right = right;
  330. bigram.score = (*score).second;
  331. bigram.size = text.size();
  332. work_queue_.push(bigram);
  333. }
  334. const llama_vocab & vocab_;
  335. std::vector<llama_sp_symbol> symbols_;
  336. llama_sp_bigram::queue work_queue_;
  337. };
  338. // TODO: temporary code duplication with llama.cpp
  339. // will resolve after #77 is merged
  340. bool llama_vocab_load(const std::string & fname, llama_vocab & vocab) {
  341. std::ifstream fin(fname, std::ios::binary);
  342. if (!fin.is_open()) {
  343. return false;
  344. }
  345. int n_vocab = 0;
  346. fin.read((char *) &n_vocab, sizeof(n_vocab));
  347. std::string word;
  348. std::vector<char> tmp(64);
  349. for (int i = 0; i < n_vocab; i++) {
  350. uint32_t len;
  351. fin.read((char *) &len, sizeof(len));
  352. word.resize(len);
  353. if (len > 0) {
  354. tmp.resize(len);
  355. fin.read(tmp.data(), len);
  356. word.assign(tmp.data(), len);
  357. } else {
  358. word.clear();
  359. }
  360. float score;
  361. fin.read((char *) &score, sizeof(score));
  362. vocab.token_to_id[word] = i;
  363. vocab.id_to_token[i] = word;
  364. vocab.score[i] = score;
  365. }
  366. return true;
  367. }
  368. std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  369. llama_tokenizer tokenizer(vocab);
  370. std::vector<llama_vocab::id> output;
  371. if (text.size() == 0) {
  372. return output;
  373. }
  374. if (bos) {
  375. output.push_back(1);
  376. }
  377. tokenizer.tokenize(text, output);
  378. return output;
  379. }
  380. void sample_top_k(std::vector<std::pair<double, llama_vocab::id>> & logits_id, int top_k) {
  381. // find the top K tokens
  382. std::partial_sort(
  383. logits_id.begin(),
  384. logits_id.begin() + top_k, logits_id.end(),
  385. [](const std::pair<double, llama_vocab::id> & a, const std::pair<double, llama_vocab::id> & b) {
  386. return a.first > b.first;
  387. });
  388. logits_id.resize(top_k);
  389. }
  390. llama_vocab::id llama_sample_top_p_top_k(
  391. const llama_vocab & vocab,
  392. const float * logits,
  393. std::vector<llama_vocab::id> & last_n_tokens,
  394. double repeat_penalty,
  395. int top_k,
  396. double top_p,
  397. double temp,
  398. std::mt19937 & rng) {
  399. int n_logits = vocab.id_to_token.size();
  400. std::vector<std::pair<double, llama_vocab::id>> logits_id;
  401. logits_id.reserve(n_logits);
  402. {
  403. const double scale = 1.0/temp;
  404. for (int i = 0; i < n_logits; ++i) {
  405. // repetition penalty from CTRL paper (https://arxiv.org/abs/1909.05858)
  406. // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
  407. if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
  408. // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
  409. if (logits[i] < 0.0) {
  410. logits_id.push_back(std::make_pair(logits[i]*scale*repeat_penalty, i));
  411. } else {
  412. logits_id.push_back(std::make_pair(logits[i]*scale/repeat_penalty, i));
  413. }
  414. } else {
  415. logits_id.push_back(std::make_pair(logits[i]*scale, i));
  416. }
  417. }
  418. }
  419. sample_top_k(logits_id, top_k);
  420. double maxl = -INFINITY;
  421. for (const auto & kv : logits_id) {
  422. maxl = std::max(maxl, kv.first);
  423. }
  424. // compute probs for the top K tokens
  425. std::vector<double> probs;
  426. probs.reserve(logits_id.size());
  427. double sum = 0.0;
  428. for (const auto & kv : logits_id) {
  429. double p = exp(kv.first - maxl);
  430. probs.push_back(p);
  431. sum += p;
  432. }
  433. // normalize the probs
  434. for (auto & p : probs) {
  435. p /= sum;
  436. }
  437. if (top_p < 1.0f) {
  438. double cumsum = 0.0f;
  439. for (int i = 0; i < (int) probs.size(); i++) {
  440. cumsum += probs[i];
  441. if (cumsum >= top_p) {
  442. probs.resize(i + 1);
  443. logits_id.resize(i + 1);
  444. break;
  445. }
  446. }
  447. cumsum = 1.0/cumsum;
  448. for (int i = 0; i < (int) probs.size(); i++) {
  449. probs[i] *= cumsum;
  450. }
  451. }
  452. //printf("\n");
  453. //for (int i = 0; i < (int) 10; i++) {
  454. // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
  455. //}
  456. //printf("\n\n");
  457. //exit(0);
  458. std::discrete_distribution<> dist(probs.begin(), probs.end());
  459. int idx = dist(rng);
  460. return logits_id[idx].second;
  461. }
  462. size_t ggml_quantize_q4_0(float * src, void * dst, int n, int k, int qk, int64_t * hist) {
  463. const int nb = k / qk;
  464. const size_t bs = (sizeof(float) + sizeof(uint8_t)*qk/2);
  465. const size_t row_size = nb*bs;
  466. assert(k % qk == 0);
  467. const size_t pp_size = qk / 2;
  468. uint8_t *pp = static_cast<uint8_t*>(alloca(pp_size));
  469. char * pdst = (char *) dst;
  470. for (int j = 0; j < n; j += k) {
  471. uint8_t * pd = (uint8_t *) (pdst + (j/k)*row_size + 0*bs);
  472. uint8_t * pb = (uint8_t *) (pdst + (j/k)*row_size + 0*bs + sizeof(float));
  473. for (int i = 0; i < nb; i++) {
  474. float amax = 0.0f; // absolute max
  475. {
  476. for (int l = 0; l < qk; l++) {
  477. const float v = src[j + i*qk + l];
  478. amax = std::max(amax, fabsf(v));
  479. }
  480. const float d = amax / ((1 << 3) - 1);
  481. const float id = d ? 1.0f/d : 0.0f;
  482. *(float *) pd = d;
  483. pd += bs;
  484. for (int l = 0; l < qk; l += 2) {
  485. const float v0 = (src[j + i*qk + l + 0])*id;
  486. const float v1 = (src[j + i*qk + l + 1])*id;
  487. const uint8_t vi0 = ((int8_t) (round(v0))) + 8;
  488. const uint8_t vi1 = ((int8_t) (round(v1))) + 8;
  489. assert(vi0 >= 0 && vi0 < 16);
  490. assert(vi1 >= 0 && vi1 < 16);
  491. hist[vi0]++;
  492. hist[vi1]++;
  493. pp[l/2] = vi0 | (vi1 << 4);
  494. }
  495. memcpy(pb, pp, pp_size);
  496. pb += bs;
  497. }
  498. }
  499. }
  500. return (n/k)*row_size;
  501. }
  502. size_t ggml_quantize_q4_1(float * src, void * dst, int n, int k, int qk, int64_t * hist) {
  503. const int nb = k / qk;
  504. const size_t bs = (2*sizeof(float) + sizeof(uint8_t)*qk/2);
  505. const size_t row_size = nb*bs;
  506. assert(k % qk == 0);
  507. const size_t pp_size = qk / 2;
  508. uint8_t *pp = static_cast<uint8_t*>(alloca(pp_size));
  509. char * pdst = (char *) dst;
  510. for (int j = 0; j < n; j += k) {
  511. uint8_t * pd = (uint8_t *) (pdst + (j/k)*row_size + 0*bs);
  512. uint8_t * pm = (uint8_t *) (pdst + (j/k)*row_size + 0*bs + sizeof(float));
  513. uint8_t * pb = (uint8_t *) (pdst + (j/k)*row_size + 0*bs + 2*sizeof(float));
  514. //printf("n = %d, k = %d, nb = %d, row_size = %d, j = %d, pm = %p, pd = %p, pb = %p\n", n, k, nb, row_size, j, pm, pd, pb);
  515. for (int i = 0; i < nb; i++) {
  516. float min = std::numeric_limits<float>::max();
  517. float max = std::numeric_limits<float>::min();
  518. {
  519. for (int l = 0; l < qk; l++) {
  520. const float v = src[j + i*qk + l];
  521. if (v < min) min = v;
  522. if (v > max) max = v;
  523. }
  524. const float d = (max - min) / ((1 << 4) - 1);
  525. const float id = d ? 1.0f/d : 0.0f;
  526. *(float *) pd = d;
  527. *(float *) pm = min;
  528. pd += bs;
  529. pm += bs;
  530. for (int l = 0; l < qk; l += 2) {
  531. const float v0 = (src[j + i*qk + l + 0] - min)*id;
  532. const float v1 = (src[j + i*qk + l + 1] - min)*id;
  533. const uint8_t vi0 = round(v0);
  534. const uint8_t vi1 = round(v1);
  535. assert(vi0 >= 0 && vi0 < 16);
  536. assert(vi1 >= 0 && vi1 < 16);
  537. hist[vi0]++;
  538. hist[vi1]++;
  539. pp[l/2] = vi0 | (vi1 << 4);
  540. }
  541. memcpy(pb, pp, pp_size);
  542. pb += bs;
  543. }
  544. }
  545. }
  546. return (n/k)*row_size;
  547. }