llama-util.h 14 KB

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