utils.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. #include "utils.h"
  2. #include <fstream>
  3. #include <regex>
  4. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  5. for (int i = 1; i < argc; i++) {
  6. std::string arg = argv[i];
  7. if (arg == "-s" || arg == "--seed") {
  8. params.seed = std::stoi(argv[++i]);
  9. } else if (arg == "-t" || arg == "--threads") {
  10. params.n_threads = std::stoi(argv[++i]);
  11. } else if (arg == "-p" || arg == "--prompt") {
  12. params.prompt = argv[++i];
  13. } else if (arg == "-n" || arg == "--n_predict") {
  14. params.n_predict = std::stoi(argv[++i]);
  15. } else if (arg == "--top_k") {
  16. params.top_k = std::stoi(argv[++i]);
  17. } else if (arg == "--top_p") {
  18. params.top_p = std::stof(argv[++i]);
  19. } else if (arg == "--temp") {
  20. params.temp = std::stof(argv[++i]);
  21. } else if (arg == "-b" || arg == "--batch_size") {
  22. params.n_batch = std::stoi(argv[++i]);
  23. } else if (arg == "-m" || arg == "--model") {
  24. params.model = argv[++i];
  25. } else if (arg == "-h" || arg == "--help") {
  26. gpt_print_usage(argc, argv, params);
  27. exit(0);
  28. } else {
  29. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  30. gpt_print_usage(argc, argv, params);
  31. exit(0);
  32. }
  33. }
  34. return true;
  35. }
  36. void gpt_print_usage(int argc, char ** argv, const gpt_params & params) {
  37. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  38. fprintf(stderr, "\n");
  39. fprintf(stderr, "options:\n");
  40. fprintf(stderr, " -h, --help show this help message and exit\n");
  41. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
  42. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  43. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  44. fprintf(stderr, " prompt to start generation with (default: random)\n");
  45. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d)\n", params.n_predict);
  46. fprintf(stderr, " --top_k N top-k sampling (default: %d)\n", params.top_k);
  47. fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", params.top_p);
  48. fprintf(stderr, " --temp N temperature (default: %.1f)\n", params.temp);
  49. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  50. fprintf(stderr, " -m FNAME, --model FNAME\n");
  51. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  52. fprintf(stderr, "\n");
  53. }
  54. std::string gpt_random_prompt(std::mt19937 & rng) {
  55. const int r = rng() % 10;
  56. switch (r) {
  57. case 0: return "So";
  58. case 1: return "Once upon a time";
  59. case 2: return "When";
  60. case 3: return "The";
  61. case 4: return "After";
  62. case 5: return "If";
  63. case 6: return "import";
  64. case 7: return "He";
  65. case 8: return "She";
  66. case 9: return "They";
  67. default: return "To";
  68. }
  69. return "The";
  70. }
  71. void replace(std::string & str, const std::string & needle, const std::string & replacement) {
  72. size_t pos = 0;
  73. while ((pos = str.find(needle, pos)) != std::string::npos) {
  74. str.replace(pos, needle.length(), replacement);
  75. pos += replacement.length();
  76. }
  77. }
  78. std::map<std::string, int32_t> json_parse(const std::string & fname) {
  79. std::map<std::string, int32_t> result;
  80. // read file into string
  81. std::string json;
  82. {
  83. std::ifstream ifs(fname);
  84. if (!ifs) {
  85. fprintf(stderr, "Failed to open %s\n", fname.c_str());
  86. exit(1);
  87. }
  88. json = std::string((std::istreambuf_iterator<char>(ifs)),
  89. (std::istreambuf_iterator<char>()));
  90. }
  91. if (json[0] != '{') {
  92. return result;
  93. }
  94. // parse json
  95. {
  96. bool has_key = false;
  97. bool in_token = false;
  98. std::string str_key = "";
  99. std::string str_val = "";
  100. int n = json.size();
  101. for (int i = 1; i < n; ++i) {
  102. if (!in_token) {
  103. if (json[i] == ' ') continue;
  104. if (json[i] == '"') {
  105. in_token = true;
  106. continue;
  107. }
  108. } else {
  109. if (json[i] == '\\' && i+1 < n) {
  110. if (has_key == false) {
  111. str_key += json[i];
  112. } else {
  113. str_val += json[i];
  114. }
  115. ++i;
  116. } else if (json[i] == '"') {
  117. if (has_key == false) {
  118. has_key = true;
  119. ++i;
  120. while (json[i] == ' ') ++i;
  121. ++i; // :
  122. while (json[i] == ' ') ++i;
  123. if (json[i] != '\"') {
  124. while (json[i] != ',' && json[i] != '}') {
  125. str_val += json[i++];
  126. }
  127. has_key = false;
  128. } else {
  129. in_token = true;
  130. continue;
  131. }
  132. } else {
  133. has_key = false;
  134. }
  135. ::replace(str_key, "\\u0120", " " ); // \u0120 -> space
  136. ::replace(str_key, "\\u010a", "\n"); // \u010a -> new line
  137. ::replace(str_key, "\\\"", "\""); // \\\" -> "
  138. try {
  139. result[str_key] = std::stoi(str_val);
  140. } catch (...) {
  141. //fprintf(stderr, "%s: ignoring key '%s' with value '%s'\n", fname.c_str(), str_key.c_str(), str_val.c_str());
  142. }
  143. str_key = "";
  144. str_val = "";
  145. in_token = false;
  146. continue;
  147. }
  148. if (has_key == false) {
  149. str_key += json[i];
  150. } else {
  151. str_val += json[i];
  152. }
  153. }
  154. }
  155. }
  156. return result;
  157. }
  158. std::vector<gpt_vocab::id> gpt_tokenize(const gpt_vocab & vocab, const std::string & text) {
  159. std::vector<std::string> words;
  160. // first split the text into words
  161. {
  162. std::string str = text;
  163. std::string pat = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  164. std::regex re(pat);
  165. std::smatch m;
  166. while (std::regex_search(str, m, re)) {
  167. for (auto x : m) {
  168. words.push_back(x);
  169. }
  170. str = m.suffix();
  171. }
  172. }
  173. // find the longest tokens that form the words:
  174. std::vector<gpt_vocab::id> tokens;
  175. for (const auto & word : words) {
  176. if (word.size() == 0) continue;
  177. int i = 0;
  178. int n = word.size();
  179. while (i < n) {
  180. int j = n;
  181. while (j > i) {
  182. auto it = vocab.token_to_id.find(word.substr(i, j-i));
  183. if (it != vocab.token_to_id.end()) {
  184. tokens.push_back(it->second);
  185. i = j;
  186. break;
  187. }
  188. --j;
  189. }
  190. if (i == n) {
  191. break;
  192. }
  193. if (j == i) {
  194. auto sub = word.substr(i, 1);
  195. if (vocab.token_to_id.find(sub) != vocab.token_to_id.end()) {
  196. tokens.push_back(vocab.token_to_id.at(sub));
  197. } else {
  198. fprintf(stderr, "%s: unknown token '%s'\n", __func__, sub.data());
  199. }
  200. ++i;
  201. }
  202. }
  203. }
  204. return tokens;
  205. }
  206. std::vector<gpt_vocab::id> llama_tokenize(const gpt_vocab & vocab, const std::string & text, bool bos) {
  207. //auto res = gpt_tokenize(vocab, text);
  208. //if (bos) {
  209. // res.insert(res.begin(), 1); // TODO: replace with vocab.bos
  210. //}
  211. std::vector<gpt_vocab::id> res;
  212. if (bos) {
  213. res.push_back(1); // TODO: replace with vocab.bos
  214. }
  215. //find the longest token that matches the text
  216. int pos = 0;
  217. while (true) {
  218. int l = 0;
  219. int t = 0;
  220. for (const auto & kv : vocab.id_to_token) {
  221. if (kv.second.size() < l) continue;
  222. if (kv.second.size() > text.size() - pos) continue;
  223. if (text.substr(pos, kv.second.size()) == kv.second) {
  224. l = kv.second.size();
  225. t = kv.first;
  226. }
  227. }
  228. if (l == 0 && t != 13) {
  229. break;
  230. }
  231. res.push_back(t);
  232. pos += l;
  233. }
  234. return res;
  235. }
  236. bool gpt_vocab_init(const std::string & fname, gpt_vocab & vocab) {
  237. printf("%s: loading vocab from '%s'\n", __func__, fname.c_str());
  238. vocab.token_to_id = ::json_parse(fname);
  239. for (const auto & kv : vocab.token_to_id) {
  240. vocab.id_to_token[kv.second] = kv.first;
  241. }
  242. printf("%s: vocab size = %d\n", __func__, (int) vocab.token_to_id.size());
  243. // print the vocabulary
  244. //for (auto kv : vocab.token_to_id) {
  245. // printf("'%s' -> %d\n", kv.first.data(), kv.second);
  246. //}
  247. return true;
  248. }
  249. gpt_vocab::id gpt_sample_top_k_top_p(
  250. const gpt_vocab & vocab,
  251. const float * logits,
  252. int top_k,
  253. double top_p,
  254. double temp,
  255. std::mt19937 & rng) {
  256. int n_logits = vocab.id_to_token.size();
  257. std::vector<std::pair<double, gpt_vocab::id>> logits_id;
  258. logits_id.reserve(n_logits);
  259. {
  260. const double scale = 1.0/temp;
  261. for (int i = 0; i < n_logits; ++i) {
  262. logits_id.push_back(std::make_pair(logits[i]*scale, i));
  263. }
  264. }
  265. // find the top K tokens
  266. std::partial_sort(
  267. logits_id.begin(),
  268. logits_id.begin() + top_k, logits_id.end(),
  269. [](const std::pair<double, gpt_vocab::id> & a, const std::pair<double, gpt_vocab::id> & b) {
  270. return a.first > b.first;
  271. });
  272. logits_id.resize(top_k);
  273. double maxl = -INFINITY;
  274. for (const auto & kv : logits_id) {
  275. maxl = std::max(maxl, kv.first);
  276. }
  277. // compute probs for the top K tokens
  278. std::vector<double> probs;
  279. probs.reserve(logits_id.size());
  280. double sum = 0.0;
  281. for (const auto & kv : logits_id) {
  282. double p = exp(kv.first - maxl);
  283. probs.push_back(p);
  284. sum += p;
  285. }
  286. // normalize the probs
  287. for (auto & p : probs) {
  288. p /= sum;
  289. }
  290. if (top_p < 1.0f) {
  291. double cumsum = 0.0f;
  292. for (int i = 0; i < top_k; i++) {
  293. cumsum += probs[i];
  294. if (cumsum >= top_p) {
  295. top_k = i + 1;
  296. probs.resize(top_k);
  297. logits_id.resize(top_k);
  298. break;
  299. }
  300. }
  301. cumsum = 1.0/cumsum;
  302. for (int i = 0; i < (int) probs.size(); i++) {
  303. probs[i] *= cumsum;
  304. }
  305. }
  306. //printf("\n");
  307. //for (int i = 0; i < (int) probs.size(); i++) {
  308. // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
  309. //}
  310. //exit(0);
  311. std::discrete_distribution<> dist(probs.begin(), probs.end());
  312. int idx = dist(rng);
  313. return logits_id[idx].second;
  314. }
  315. size_t ggml_quantize_q4_0(float * src, void * dst, int n, int k, int qk, int64_t * hist) {
  316. const int nb = k / qk;
  317. const size_t row_size = nb*(sizeof(float) + sizeof(uint8_t)*qk/2);
  318. assert(k % qk == 0);
  319. uint8_t pp[qk/2];
  320. char * pdst = (char *) dst;
  321. for (int j = 0; j < n; j += k) {
  322. float * pd = (float *) (pdst + (j/k)*row_size);
  323. uint8_t * pb = (uint8_t *) (pd + nb);
  324. for (int i = 0; i < nb; i++) {
  325. float amax = 0.0f; // absolute max
  326. {
  327. for (int l = 0; l < qk; l++) {
  328. const float v = src[j + i*qk + l];
  329. amax = std::max(amax, fabsf(v));
  330. }
  331. const float d = amax / ((1 << 3) - 1);
  332. const float id = d ? 1.0f/d : 0.0f;
  333. pd[i] = d;
  334. for (int l = 0; l < qk; l += 2) {
  335. const float v0 = (src[j + i*qk + l + 0])*id;
  336. const float v1 = (src[j + i*qk + l + 1])*id;
  337. const uint8_t vi0 = ((int8_t) (round(v0))) + 8;
  338. const uint8_t vi1 = ((int8_t) (round(v1))) + 8;
  339. assert(vi0 >= 0 && vi0 < 16);
  340. assert(vi1 >= 0 && vi1 < 16);
  341. hist[vi0]++;
  342. hist[vi1]++;
  343. pp[l/2] = vi0 | (vi1 << 4);
  344. }
  345. memcpy(pb + i*qk/2, pp, sizeof(pp));
  346. }
  347. }
  348. }
  349. return (n/k)*row_size;
  350. }
  351. size_t ggml_quantize_q4_1(float * src, void * dst, int n, int k, int qk, int64_t * hist) {
  352. const int nb = k / qk;
  353. const size_t row_size = nb*(2*sizeof(float) + sizeof(uint8_t)*qk/2);
  354. assert(k % qk == 0);
  355. uint8_t pp[qk/2];
  356. char * pdst = (char *) dst;
  357. for (int j = 0; j < n; j += k) {
  358. float * pm = (float *) (pdst + (j/k)*row_size);
  359. float * pd = (float *) (pm + nb);
  360. uint8_t * pb = (uint8_t *) (pd + nb);
  361. //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);
  362. for (int i = 0; i < nb; i++) {
  363. float min = std::numeric_limits<float>::max();
  364. float max = std::numeric_limits<float>::min();
  365. {
  366. for (int l = 0; l < qk; l++) {
  367. const float v = src[j + i*qk + l];
  368. if (v < min) min = v;
  369. if (v > max) max = v;
  370. }
  371. const float d = (max - min) / ((1 << 4) - 1);
  372. const float id = d ? 1.0f/d : 0.0f;
  373. pm[i] = min;
  374. pd[i] = d;
  375. for (int l = 0; l < qk; l += 2) {
  376. const float v0 = (src[j + i*qk + l + 0] - min)*id;
  377. const float v1 = (src[j + i*qk + l + 1] - min)*id;
  378. const uint8_t vi0 = round(v0);
  379. const uint8_t vi1 = round(v1);
  380. assert(vi0 >= 0 && vi0 < 16);
  381. assert(vi1 >= 0 && vi1 < 16);
  382. hist[vi0]++;
  383. hist[vi1]++;
  384. pp[l/2] = vi0 | (vi1 << 4);
  385. }
  386. memcpy(pb + i*qk/2, pp, sizeof(pp));
  387. }
  388. }
  389. }
  390. return (n/k)*row_size;
  391. }