llama-util.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /**
  2. * llama.cpp - git e782c9e735f93ab4767ffc37462c523b73a17ddc
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023 Georgi Gerganov
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. // Internal header to be included only by llama.cpp.
  27. // Contains wrappers around OS interfaces.
  28. #ifndef LLAMA_UTIL_H
  29. #define LLAMA_UTIL_H
  30. #include <cstdio>
  31. #include <cstdint>
  32. #include <cerrno>
  33. #include <cstring>
  34. #include <cstdarg>
  35. #include <cstdlib>
  36. #include <climits>
  37. #include <string>
  38. #include <vector>
  39. #include <stdexcept>
  40. #ifdef __has_include
  41. #if __has_include(<unistd.h>)
  42. #include <unistd.h>
  43. #if defined(_POSIX_MAPPED_FILES)
  44. #include <sys/mman.h>
  45. #endif
  46. #if defined(_POSIX_MEMLOCK_RANGE)
  47. #include <sys/resource.h>
  48. #endif
  49. #endif
  50. #endif
  51. #if defined(_WIN32)
  52. #define WIN32_LEAN_AND_MEAN
  53. #ifndef NOMINMAX
  54. #define NOMINMAX
  55. #endif
  56. #include <windows.h>
  57. #include <io.h>
  58. #include <stdio.h> // for _fseeki64
  59. #endif
  60. #define LLAMA_ASSERT(x) \
  61. do { \
  62. if (!(x)) { \
  63. fprintf(stderr, "LLAMA_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
  64. abort(); \
  65. } \
  66. } while (0)
  67. #ifdef __GNUC__
  68. #ifdef __MINGW32__
  69. __attribute__((format(gnu_printf, 1, 2)))
  70. #else
  71. __attribute__((format(printf, 1, 2)))
  72. #endif
  73. #endif
  74. static std::string format(const char * fmt, ...) {
  75. va_list ap, ap2;
  76. va_start(ap, fmt);
  77. va_copy(ap2, ap);
  78. int size = vsnprintf(NULL, 0, fmt, ap);
  79. LLAMA_ASSERT(size >= 0 && size < INT_MAX);
  80. std::vector<char> buf(size + 1);
  81. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  82. LLAMA_ASSERT(size2 == size);
  83. va_end(ap2);
  84. va_end(ap);
  85. return std::string(buf.data(), size);
  86. }
  87. struct llama_file {
  88. // use FILE * so we don't have to re-open the file to mmap
  89. FILE * fp;
  90. size_t size;
  91. llama_file(const char * fname, const char * mode) {
  92. fp = std::fopen(fname, mode);
  93. if (fp == NULL) {
  94. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  95. }
  96. seek(0, SEEK_END);
  97. size = tell();
  98. seek(0, SEEK_SET);
  99. }
  100. size_t tell() const {
  101. #ifdef _WIN32
  102. __int64 ret = _ftelli64(fp);
  103. #else
  104. long ret = std::ftell(fp);
  105. #endif
  106. LLAMA_ASSERT(ret != -1); // this really shouldn't fail
  107. return (size_t) ret;
  108. }
  109. void seek(size_t offset, int whence) {
  110. #ifdef _WIN32
  111. int ret = _fseeki64(fp, (__int64) offset, whence);
  112. #else
  113. int ret = std::fseek(fp, (long) offset, whence);
  114. #endif
  115. LLAMA_ASSERT(ret == 0); // same
  116. }
  117. void read_raw(void * ptr, size_t len) const {
  118. if (len == 0) {
  119. return;
  120. }
  121. errno = 0;
  122. std::size_t ret = std::fread(ptr, len, 1, fp);
  123. if (ferror(fp)) {
  124. throw std::runtime_error(format("read error: %s", strerror(errno)));
  125. }
  126. if (ret != 1) {
  127. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  128. }
  129. }
  130. std::uint32_t read_u32() {
  131. std::uint32_t ret;
  132. read_raw(&ret, sizeof(ret));
  133. return ret;
  134. }
  135. std::string read_string(std::uint32_t len) {
  136. std::vector<char> chars(len);
  137. read_raw(chars.data(), len);
  138. return std::string(chars.data(), len);
  139. }
  140. void write_raw(const void * ptr, size_t len) const {
  141. if (len == 0) {
  142. return;
  143. }
  144. errno = 0;
  145. size_t ret = std::fwrite(ptr, len, 1, fp);
  146. if (ret != 1) {
  147. throw std::runtime_error(format("write error: %s", strerror(errno)));
  148. }
  149. }
  150. void write_u32(std::uint32_t val) {
  151. write_raw(&val, sizeof(val));
  152. }
  153. ~llama_file() {
  154. if (fp) {
  155. std::fclose(fp);
  156. }
  157. }
  158. };
  159. #if defined(_WIN32)
  160. static std::string llama_format_win_err(DWORD err) {
  161. LPSTR buf;
  162. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  163. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  164. if (!size) {
  165. return "FormatMessageA failed";
  166. }
  167. std::string ret(buf, size);
  168. LocalFree(buf);
  169. return ret;
  170. }
  171. #endif
  172. struct llama_mmap {
  173. void * addr;
  174. size_t size;
  175. llama_mmap(const llama_mmap &) = delete;
  176. #ifdef _POSIX_MAPPED_FILES
  177. static constexpr bool SUPPORTED = true;
  178. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  179. size = file->size;
  180. int fd = fileno(file->fp);
  181. int flags = MAP_SHARED;
  182. // prefetch/readahead impairs performance on NUMA systems
  183. if (numa) { prefetch = 0; }
  184. #ifdef __linux__
  185. if (prefetch) { flags |= MAP_POPULATE; }
  186. #endif
  187. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  188. if (addr == MAP_FAILED) {
  189. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  190. }
  191. if (prefetch > 0) {
  192. // Advise the kernel to preload the mapped memory
  193. if (madvise(addr, std::min(file->size, prefetch), MADV_WILLNEED)) {
  194. fprintf(stderr, "warning: madvise(.., MADV_WILLNEED) failed: %s\n",
  195. strerror(errno));
  196. }
  197. }
  198. if (numa) {
  199. // advise the kernel not to use readahead
  200. // (because the next page might not belong on the same node)
  201. if (madvise(addr, file->size, MADV_RANDOM)) {
  202. fprintf(stderr, "warning: madvise(.., MADV_RANDOM) failed: %s\n",
  203. strerror(errno));
  204. }
  205. }
  206. }
  207. ~llama_mmap() {
  208. munmap(addr, size);
  209. }
  210. #elif defined(_WIN32)
  211. static constexpr bool SUPPORTED = true;
  212. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  213. (void) numa;
  214. size = file->size;
  215. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  216. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  217. DWORD error = GetLastError();
  218. if (hMapping == NULL) {
  219. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  220. }
  221. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  222. error = GetLastError();
  223. CloseHandle(hMapping);
  224. if (addr == NULL) {
  225. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  226. }
  227. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  228. if (prefetch) {
  229. // Advise the kernel to preload the mapped memory
  230. WIN32_MEMORY_RANGE_ENTRY range;
  231. range.VirtualAddress = addr;
  232. range.NumberOfBytes = (SIZE_T)size;
  233. if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  234. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  235. llama_format_win_err(GetLastError()).c_str());
  236. }
  237. }
  238. #else
  239. #pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
  240. #endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
  241. }
  242. ~llama_mmap() {
  243. if (!UnmapViewOfFile(addr)) {
  244. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  245. llama_format_win_err(GetLastError()).c_str());
  246. }
  247. }
  248. #else
  249. static constexpr bool SUPPORTED = false;
  250. llama_mmap(struct llama_file *, bool prefetch = true, bool numa = false) {
  251. (void) prefetch;
  252. (void) numa;
  253. throw std::runtime_error(std::string("mmap not supported"));
  254. }
  255. #endif
  256. };
  257. // Represents some region of memory being locked using mlock or VirtualLock;
  258. // will automatically unlock on destruction.
  259. struct llama_mlock {
  260. void * addr = NULL;
  261. size_t size = 0;
  262. bool failed_already = false;
  263. llama_mlock() {}
  264. llama_mlock(const llama_mlock &) = delete;
  265. ~llama_mlock() {
  266. if (size) {
  267. raw_unlock(addr, size);
  268. }
  269. }
  270. void init(void * ptr) {
  271. LLAMA_ASSERT(addr == NULL && size == 0);
  272. addr = ptr;
  273. }
  274. void grow_to(size_t target_size) {
  275. LLAMA_ASSERT(addr);
  276. if (failed_already) {
  277. return;
  278. }
  279. size_t granularity = lock_granularity();
  280. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  281. if (target_size > size) {
  282. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  283. size = target_size;
  284. } else {
  285. failed_already = true;
  286. }
  287. }
  288. }
  289. #ifdef _POSIX_MEMLOCK_RANGE
  290. static constexpr bool SUPPORTED = true;
  291. size_t lock_granularity() {
  292. return (size_t) sysconf(_SC_PAGESIZE);
  293. }
  294. #ifdef __APPLE__
  295. #define MLOCK_SUGGESTION \
  296. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  297. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  298. #else
  299. #define MLOCK_SUGGESTION \
  300. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  301. #endif
  302. bool raw_lock(const void * addr, size_t size) {
  303. if (!mlock(addr, size)) {
  304. return true;
  305. } else {
  306. char* errmsg = std::strerror(errno);
  307. bool suggest = (errno == ENOMEM);
  308. // Check if the resource limit is fine after all
  309. struct rlimit lock_limit;
  310. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit))
  311. suggest = false;
  312. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size))
  313. suggest = false;
  314. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  315. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  316. return false;
  317. }
  318. }
  319. #undef MLOCK_SUGGESTION
  320. void raw_unlock(void * addr, size_t size) {
  321. if (munlock(addr, size)) {
  322. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  323. }
  324. }
  325. #elif defined(_WIN32)
  326. static constexpr bool SUPPORTED = true;
  327. size_t lock_granularity() {
  328. SYSTEM_INFO si;
  329. GetSystemInfo(&si);
  330. return (size_t) si.dwPageSize;
  331. }
  332. bool raw_lock(void * ptr, size_t len) {
  333. for (int tries = 1; ; tries++) {
  334. if (VirtualLock(ptr, len)) {
  335. return true;
  336. }
  337. if (tries == 2) {
  338. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  339. len, size, llama_format_win_err(GetLastError()).c_str());
  340. return false;
  341. }
  342. // It failed but this was only the first try; increase the working
  343. // set size and try again.
  344. SIZE_T min_ws_size, max_ws_size;
  345. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  346. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  347. llama_format_win_err(GetLastError()).c_str());
  348. return false;
  349. }
  350. // Per MSDN: "The maximum number of pages that a process can lock
  351. // is equal to the number of pages in its minimum working set minus
  352. // a small overhead."
  353. // Hopefully a megabyte is enough overhead:
  354. size_t increment = len + 1048576;
  355. // The minimum must be <= the maximum, so we need to increase both:
  356. min_ws_size += increment;
  357. max_ws_size += increment;
  358. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  359. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  360. llama_format_win_err(GetLastError()).c_str());
  361. return false;
  362. }
  363. }
  364. }
  365. void raw_unlock(void * ptr, size_t len) {
  366. if (!VirtualUnlock(ptr, len)) {
  367. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  368. llama_format_win_err(GetLastError()).c_str());
  369. }
  370. }
  371. #else
  372. static constexpr bool SUPPORTED = false;
  373. size_t lock_granularity() {
  374. return (size_t) 65536;
  375. }
  376. bool raw_lock(const void * addr, size_t len) {
  377. fprintf(stderr, "warning: mlock not supported on this system\n");
  378. return false;
  379. }
  380. void raw_unlock(const void * addr, size_t len) {}
  381. #endif
  382. };
  383. // Replacement for std::vector<uint8_t> that doesn't require zero-initialization.
  384. struct llama_buffer {
  385. uint8_t * addr = NULL;
  386. size_t size = 0;
  387. llama_buffer() = default;
  388. void resize(size_t len) {
  389. #ifdef GGML_USE_METAL
  390. free(addr);
  391. int result = posix_memalign((void **) &addr, getpagesize(), len);
  392. if (result == 0) {
  393. memset(addr, 0, len);
  394. }
  395. else {
  396. addr = NULL;
  397. }
  398. #else
  399. delete[] addr;
  400. addr = new uint8_t[len];
  401. #endif
  402. size = len;
  403. }
  404. ~llama_buffer() {
  405. #ifdef GGML_USE_METAL
  406. free(addr);
  407. #else
  408. delete[] addr;
  409. #endif
  410. addr = NULL;
  411. }
  412. // disable copy and move
  413. llama_buffer(const llama_buffer&) = delete;
  414. llama_buffer(llama_buffer&&) = delete;
  415. llama_buffer& operator=(const llama_buffer&) = delete;
  416. llama_buffer& operator=(llama_buffer&&) = delete;
  417. };
  418. #ifdef GGML_USE_CUBLAS
  419. #include "ggml-cuda.h"
  420. struct llama_ctx_buffer {
  421. uint8_t * addr = NULL;
  422. bool is_cuda;
  423. size_t size = 0;
  424. llama_ctx_buffer() = default;
  425. void resize(size_t size) {
  426. free();
  427. addr = (uint8_t *) ggml_cuda_host_malloc(size);
  428. if (addr) {
  429. is_cuda = true;
  430. }
  431. else {
  432. // fall back to pageable memory
  433. addr = new uint8_t[size];
  434. is_cuda = false;
  435. }
  436. this->size = size;
  437. }
  438. void free() {
  439. if (addr) {
  440. if (is_cuda) {
  441. ggml_cuda_host_free(addr);
  442. }
  443. else {
  444. delete[] addr;
  445. }
  446. }
  447. addr = NULL;
  448. }
  449. ~llama_ctx_buffer() {
  450. free();
  451. }
  452. // disable copy and move
  453. llama_ctx_buffer(const llama_ctx_buffer&) = delete;
  454. llama_ctx_buffer(llama_ctx_buffer&&) = delete;
  455. llama_ctx_buffer& operator=(const llama_ctx_buffer&) = delete;
  456. llama_ctx_buffer& operator=(llama_ctx_buffer&&) = delete;
  457. };
  458. #else
  459. typedef llama_buffer llama_ctx_buffer;
  460. #endif
  461. #endif