common.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. #include "common.h"
  2. #include <cassert>
  3. #include <iostream>
  4. #include <cstring>
  5. #include <fstream>
  6. #include <string>
  7. #include <iterator>
  8. #include <algorithm>
  9. #include <sstream>
  10. #if defined(__APPLE__) && defined(__MACH__)
  11. #include <sys/types.h>
  12. #include <sys/sysctl.h>
  13. #endif
  14. #if defined (_WIN32)
  15. #include <fcntl.h>
  16. #include <io.h>
  17. #pragma comment(lib,"kernel32.lib")
  18. extern "C" __declspec(dllimport) void* __stdcall GetStdHandle(unsigned long nStdHandle);
  19. extern "C" __declspec(dllimport) int __stdcall GetConsoleMode(void* hConsoleHandle, unsigned long* lpMode);
  20. extern "C" __declspec(dllimport) int __stdcall SetConsoleMode(void* hConsoleHandle, unsigned long dwMode);
  21. extern "C" __declspec(dllimport) int __stdcall SetConsoleCP(unsigned int wCodePageID);
  22. extern "C" __declspec(dllimport) int __stdcall SetConsoleOutputCP(unsigned int wCodePageID);
  23. extern "C" __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int CodePage, unsigned long dwFlags,
  24. const wchar_t * lpWideCharStr, int cchWideChar,
  25. char * lpMultiByteStr, int cbMultiByte,
  26. const char * lpDefaultChar, bool * lpUsedDefaultChar);
  27. #define CP_UTF8 65001
  28. #endif
  29. int32_t get_num_physical_cores() {
  30. #ifdef __linux__
  31. std::ifstream cpuinfo("/proc/cpuinfo");
  32. std::string line;
  33. while (std::getline(cpuinfo, line)) {
  34. std::size_t pos = line.find("cpu cores");
  35. if (pos != std::string::npos) {
  36. pos = line.find(": ", pos);
  37. if (pos != std::string::npos) {
  38. try {
  39. // Extract the number and return it
  40. return static_cast<int32_t>(std::stoul(line.substr(pos + 2)));
  41. } catch (const std::invalid_argument &) {
  42. // Ignore if we could not parse
  43. }
  44. }
  45. }
  46. }
  47. #elif defined(__APPLE__) && defined(__MACH__)
  48. int32_t num_physical_cores;
  49. size_t len = sizeof(num_physical_cores);
  50. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  51. if (result == 0) {
  52. return num_physical_cores;
  53. }
  54. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  55. if (result == 0) {
  56. return num_physical_cores;
  57. }
  58. #elif defined(_WIN32)
  59. //TODO: Implement
  60. #endif
  61. unsigned int n_threads = std::thread::hardware_concurrency();
  62. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  63. }
  64. void process_escapes(std::string& input) {
  65. std::size_t input_len = input.length();
  66. std::size_t output_idx = 0;
  67. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  68. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  69. switch (input[++input_idx]) {
  70. case 'n': input[output_idx++] = '\n'; break;
  71. case 'r': input[output_idx++] = '\r'; break;
  72. case 't': input[output_idx++] = '\t'; break;
  73. case '\'': input[output_idx++] = '\''; break;
  74. case '\"': input[output_idx++] = '\"'; break;
  75. case '\\': input[output_idx++] = '\\'; break;
  76. default: input[output_idx++] = '\\';
  77. input[output_idx++] = input[input_idx]; break;
  78. }
  79. } else {
  80. input[output_idx++] = input[input_idx];
  81. }
  82. }
  83. input.resize(output_idx);
  84. }
  85. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  86. bool invalid_param = false;
  87. bool escape_prompt = false;
  88. std::string arg;
  89. gpt_params default_params;
  90. for (int i = 1; i < argc; i++) {
  91. arg = argv[i];
  92. if (arg == "-s" || arg == "--seed") {
  93. #if defined(GGML_USE_CUBLAS)
  94. fprintf(stderr, "WARNING: when using cuBLAS generation results are NOT guaranteed to be reproducible.\n");
  95. #endif
  96. if (++i >= argc) {
  97. invalid_param = true;
  98. break;
  99. }
  100. params.seed = std::stoi(argv[i]);
  101. } else if (arg == "-t" || arg == "--threads") {
  102. if (++i >= argc) {
  103. invalid_param = true;
  104. break;
  105. }
  106. params.n_threads = std::stoi(argv[i]);
  107. } else if (arg == "-p" || arg == "--prompt") {
  108. if (++i >= argc) {
  109. invalid_param = true;
  110. break;
  111. }
  112. params.prompt = argv[i];
  113. } else if (arg == "-e") {
  114. escape_prompt = true;
  115. } else if (arg == "--session") {
  116. if (++i >= argc) {
  117. invalid_param = true;
  118. break;
  119. }
  120. params.path_session = argv[i];
  121. } else if (arg == "-f" || arg == "--file") {
  122. if (++i >= argc) {
  123. invalid_param = true;
  124. break;
  125. }
  126. std::ifstream file(argv[i]);
  127. if (!file) {
  128. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  129. invalid_param = true;
  130. break;
  131. }
  132. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  133. if (params.prompt.back() == '\n') {
  134. params.prompt.pop_back();
  135. }
  136. } else if (arg == "-n" || arg == "--n_predict") {
  137. if (++i >= argc) {
  138. invalid_param = true;
  139. break;
  140. }
  141. params.n_predict = std::stoi(argv[i]);
  142. } else if (arg == "--top_k") {
  143. if (++i >= argc) {
  144. invalid_param = true;
  145. break;
  146. }
  147. params.top_k = std::stoi(argv[i]);
  148. } else if (arg == "-c" || arg == "--ctx_size") {
  149. if (++i >= argc) {
  150. invalid_param = true;
  151. break;
  152. }
  153. params.n_ctx = std::stoi(argv[i]);
  154. } else if (arg == "--memory_f32") {
  155. params.memory_f16 = false;
  156. } else if (arg == "--top_p") {
  157. if (++i >= argc) {
  158. invalid_param = true;
  159. break;
  160. }
  161. params.top_p = std::stof(argv[i]);
  162. } else if (arg == "--temp") {
  163. if (++i >= argc) {
  164. invalid_param = true;
  165. break;
  166. }
  167. params.temp = std::stof(argv[i]);
  168. } else if (arg == "--tfs") {
  169. if (++i >= argc) {
  170. invalid_param = true;
  171. break;
  172. }
  173. params.tfs_z = std::stof(argv[i]);
  174. } else if (arg == "--typical") {
  175. if (++i >= argc) {
  176. invalid_param = true;
  177. break;
  178. }
  179. params.typical_p = std::stof(argv[i]);
  180. } else if (arg == "--repeat_last_n") {
  181. if (++i >= argc) {
  182. invalid_param = true;
  183. break;
  184. }
  185. params.repeat_last_n = std::stoi(argv[i]);
  186. } else if (arg == "--repeat_penalty") {
  187. if (++i >= argc) {
  188. invalid_param = true;
  189. break;
  190. }
  191. params.repeat_penalty = std::stof(argv[i]);
  192. } else if (arg == "--frequency_penalty") {
  193. if (++i >= argc) {
  194. invalid_param = true;
  195. break;
  196. }
  197. params.frequency_penalty = std::stof(argv[i]);
  198. } else if (arg == "--presence_penalty") {
  199. if (++i >= argc) {
  200. invalid_param = true;
  201. break;
  202. }
  203. params.presence_penalty = std::stof(argv[i]);
  204. } else if (arg == "--mirostat") {
  205. if (++i >= argc) {
  206. invalid_param = true;
  207. break;
  208. }
  209. params.mirostat = std::stoi(argv[i]);
  210. } else if (arg == "--mirostat_lr") {
  211. if (++i >= argc) {
  212. invalid_param = true;
  213. break;
  214. }
  215. params.mirostat_eta = std::stof(argv[i]);
  216. } else if (arg == "--mirostat_ent") {
  217. if (++i >= argc) {
  218. invalid_param = true;
  219. break;
  220. }
  221. params.mirostat_tau = std::stof(argv[i]);
  222. } else if (arg == "-b" || arg == "--batch_size") {
  223. if (++i >= argc) {
  224. invalid_param = true;
  225. break;
  226. }
  227. params.n_batch = std::stoi(argv[i]);
  228. params.n_batch = std::min(512, params.n_batch);
  229. } else if (arg == "--keep") {
  230. if (++i >= argc) {
  231. invalid_param = true;
  232. break;
  233. }
  234. params.n_keep = std::stoi(argv[i]);
  235. } else if (arg == "-m" || arg == "--model") {
  236. if (++i >= argc) {
  237. invalid_param = true;
  238. break;
  239. }
  240. params.model = argv[i];
  241. } else if (arg == "--lora") {
  242. if (++i >= argc) {
  243. invalid_param = true;
  244. break;
  245. }
  246. params.lora_adapter = argv[i];
  247. params.use_mmap = false;
  248. } else if (arg == "--lora-base") {
  249. if (++i >= argc) {
  250. invalid_param = true;
  251. break;
  252. }
  253. params.lora_base = argv[i];
  254. } else if (arg == "-i" || arg == "--interactive") {
  255. params.interactive = true;
  256. } else if (arg == "--embedding") {
  257. params.embedding = true;
  258. } else if (arg == "--interactive-first") {
  259. params.interactive_first = true;
  260. } else if (arg == "-ins" || arg == "--instruct") {
  261. params.instruct = true;
  262. } else if (arg == "--color") {
  263. params.use_color = true;
  264. } else if (arg == "--mlock") {
  265. params.use_mlock = true;
  266. } else if (arg == "--no-mmap") {
  267. params.use_mmap = false;
  268. } else if (arg == "--mtest") {
  269. params.mem_test = true;
  270. } else if (arg == "--verbose-prompt") {
  271. params.verbose_prompt = true;
  272. } else if (arg == "-r" || arg == "--reverse-prompt") {
  273. if (++i >= argc) {
  274. invalid_param = true;
  275. break;
  276. }
  277. params.antiprompt.push_back(argv[i]);
  278. } else if (arg == "--perplexity") {
  279. params.perplexity = true;
  280. } else if (arg == "--ignore-eos") {
  281. params.logit_bias[llama_token_eos()] = -INFINITY;
  282. } else if (arg == "--no-penalize-nl") {
  283. params.penalize_nl = false;
  284. } else if (arg == "-l" || arg == "--logit-bias") {
  285. if (++i >= argc) {
  286. invalid_param = true;
  287. break;
  288. }
  289. std::stringstream ss(argv[i]);
  290. llama_token key;
  291. char sign;
  292. std::string value_str;
  293. try {
  294. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  295. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  296. } else {
  297. throw std::exception();
  298. }
  299. } catch (const std::exception &e) {
  300. invalid_param = true;
  301. break;
  302. }
  303. } else if (arg == "--n_parts") {
  304. if (++i >= argc) {
  305. invalid_param = true;
  306. break;
  307. }
  308. params.n_parts = std::stoi(argv[i]);
  309. } else if (arg == "-h" || arg == "--help") {
  310. gpt_print_usage(argc, argv, default_params);
  311. exit(0);
  312. } else if (arg == "--random-prompt") {
  313. params.random_prompt = true;
  314. } else if (arg == "--in-prefix") {
  315. if (++i >= argc) {
  316. invalid_param = true;
  317. break;
  318. }
  319. params.input_prefix = argv[i];
  320. } else if (arg == "--in-suffix") {
  321. if (++i >= argc) {
  322. invalid_param = true;
  323. break;
  324. }
  325. params.input_suffix = argv[i];
  326. } else {
  327. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  328. gpt_print_usage(argc, argv, default_params);
  329. exit(1);
  330. }
  331. }
  332. if (invalid_param) {
  333. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  334. gpt_print_usage(argc, argv, default_params);
  335. exit(1);
  336. }
  337. if (escape_prompt) {
  338. process_escapes(params.prompt);
  339. }
  340. return true;
  341. }
  342. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  343. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  344. fprintf(stderr, "\n");
  345. fprintf(stderr, "options:\n");
  346. fprintf(stderr, " -h, --help show this help message and exit\n");
  347. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  348. fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
  349. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  350. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  351. fprintf(stderr, " run in interactive mode and poll user input upon seeing PROMPT (can be\n");
  352. fprintf(stderr, " specified more than once for multiple prompts).\n");
  353. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  354. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  355. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  356. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  357. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  358. fprintf(stderr, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  359. fprintf(stderr, " --session FNAME file to cache model state in (may be large!) (default: none)\n");
  360. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  361. fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  362. fprintf(stderr, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  363. fprintf(stderr, " -f FNAME, --file FNAME\n");
  364. fprintf(stderr, " prompt file to start generation.\n");
  365. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  366. fprintf(stderr, " --top_k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
  367. fprintf(stderr, " --top_p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
  368. fprintf(stderr, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
  369. fprintf(stderr, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
  370. fprintf(stderr, " --repeat_last_n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", params.repeat_last_n);
  371. fprintf(stderr, " --repeat_penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  372. fprintf(stderr, " --presence_penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
  373. fprintf(stderr, " --frequency_penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
  374. fprintf(stderr, " --mirostat N use Mirostat sampling.\n");
  375. fprintf(stderr, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  376. fprintf(stderr, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
  377. fprintf(stderr, " --mirostat_lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
  378. fprintf(stderr, " --mirostat_ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
  379. fprintf(stderr, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  380. fprintf(stderr, " modifies the likelihood of token appearing in the completion,\n");
  381. fprintf(stderr, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  382. fprintf(stderr, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  383. fprintf(stderr, " -c N, --ctx_size N size of the prompt context (default: %d)\n", params.n_ctx);
  384. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  385. fprintf(stderr, " --no-penalize-nl do not penalize newline token\n");
  386. fprintf(stderr, " --memory_f32 use f32 instead of f16 for memory key+value\n");
  387. fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  388. fprintf(stderr, " --n_parts N number of model parts (default: -1 = determine from dimensions)\n");
  389. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  390. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  391. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  392. if (llama_mlock_supported()) {
  393. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  394. }
  395. if (llama_mmap_supported()) {
  396. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  397. }
  398. fprintf(stderr, " --mtest compute maximum memory usage\n");
  399. fprintf(stderr, " --verbose-prompt print prompt before generation\n");
  400. fprintf(stderr, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  401. fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  402. fprintf(stderr, " -m FNAME, --model FNAME\n");
  403. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  404. fprintf(stderr, "\n");
  405. }
  406. std::string gpt_random_prompt(std::mt19937 & rng) {
  407. const int r = rng() % 10;
  408. switch (r) {
  409. case 0: return "So";
  410. case 1: return "Once upon a time";
  411. case 2: return "When";
  412. case 3: return "The";
  413. case 4: return "After";
  414. case 5: return "If";
  415. case 6: return "import";
  416. case 7: return "He";
  417. case 8: return "She";
  418. case 9: return "They";
  419. default: return "To";
  420. }
  421. return "The";
  422. }
  423. // TODO: not great allocating this every time
  424. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  425. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  426. std::vector<llama_token> res(text.size() + (int) add_bos);
  427. const int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  428. assert(n >= 0);
  429. res.resize(n);
  430. return res;
  431. }
  432. struct llama_context * llama_init_from_gpt_params(const gpt_params & params) {
  433. auto lparams = llama_context_default_params();
  434. lparams.n_ctx = params.n_ctx;
  435. lparams.n_parts = params.n_parts;
  436. lparams.seed = params.seed;
  437. lparams.f16_kv = params.memory_f16;
  438. lparams.use_mmap = params.use_mmap;
  439. lparams.use_mlock = params.use_mlock;
  440. lparams.logits_all = params.perplexity;
  441. lparams.embedding = params.embedding;
  442. llama_context * lctx = llama_init_from_file(params.model.c_str(), lparams);
  443. if (lctx == NULL) {
  444. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  445. return NULL;
  446. }
  447. if (!params.lora_adapter.empty()) {
  448. int err = llama_apply_lora_from_file(lctx,
  449. params.lora_adapter.c_str(),
  450. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  451. params.n_threads);
  452. if (err != 0) {
  453. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  454. return NULL;
  455. }
  456. }
  457. return lctx;
  458. }
  459. /* Keep track of current color of output, and emit ANSI code if it changes. */
  460. void set_console_color(console_state & con_st, console_color_t color) {
  461. if (con_st.use_color && con_st.color != color) {
  462. switch(color) {
  463. case CONSOLE_COLOR_DEFAULT:
  464. printf(ANSI_COLOR_RESET);
  465. break;
  466. case CONSOLE_COLOR_PROMPT:
  467. printf(ANSI_COLOR_YELLOW);
  468. break;
  469. case CONSOLE_COLOR_USER_INPUT:
  470. printf(ANSI_BOLD ANSI_COLOR_GREEN);
  471. break;
  472. }
  473. con_st.color = color;
  474. }
  475. }
  476. #if defined (_WIN32)
  477. void win32_console_init(bool enable_color) {
  478. unsigned long dwMode = 0;
  479. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  480. if (!hConOut || hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode)) {
  481. hConOut = GetStdHandle((unsigned long)-12); // STD_ERROR_HANDLE (-12)
  482. if (hConOut && (hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode))) {
  483. hConOut = 0;
  484. }
  485. }
  486. if (hConOut) {
  487. // Enable ANSI colors on Windows 10+
  488. if (enable_color && !(dwMode & 0x4)) {
  489. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  490. }
  491. // Set console output codepage to UTF8
  492. SetConsoleOutputCP(CP_UTF8);
  493. }
  494. void* hConIn = GetStdHandle((unsigned long)-10); // STD_INPUT_HANDLE (-10)
  495. if (hConIn && hConIn != (void*)-1 && GetConsoleMode(hConIn, &dwMode)) {
  496. // Set console input codepage to UTF16
  497. _setmode(_fileno(stdin), _O_WTEXT);
  498. }
  499. }
  500. // Convert a wide Unicode string to an UTF8 string
  501. void win32_utf8_encode(const std::wstring & wstr, std::string & str) {
  502. int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
  503. std::string strTo(size_needed, 0);
  504. WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
  505. str = strTo;
  506. }
  507. #endif