utils.cpp 23 KB

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