llama-util.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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 */) {
  154. size = file->size;
  155. int fd = fileno(file->fp);
  156. int flags = MAP_SHARED;
  157. #ifdef __linux__
  158. flags |= MAP_POPULATE;
  159. #endif
  160. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  161. if (addr == MAP_FAILED) {
  162. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  163. }
  164. if (prefetch > 0) {
  165. // Advise the kernel to preload the mapped memory
  166. if (madvise(addr, std::min(file->size, prefetch), MADV_WILLNEED)) {
  167. fprintf(stderr, "warning: madvise(.., MADV_WILLNEED) failed: %s\n",
  168. strerror(errno));
  169. }
  170. }
  171. }
  172. ~llama_mmap() {
  173. munmap(addr, size);
  174. }
  175. #elif defined(_WIN32)
  176. static constexpr bool SUPPORTED = true;
  177. llama_mmap(struct llama_file * file, bool prefetch = true) {
  178. size = file->size;
  179. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  180. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  181. DWORD error = GetLastError();
  182. if (hMapping == NULL) {
  183. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  184. }
  185. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  186. error = GetLastError();
  187. CloseHandle(hMapping);
  188. if (addr == NULL) {
  189. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  190. }
  191. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  192. if (prefetch) {
  193. // Advise the kernel to preload the mapped memory
  194. WIN32_MEMORY_RANGE_ENTRY range;
  195. range.VirtualAddress = addr;
  196. range.NumberOfBytes = (SIZE_T)size;
  197. if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  198. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  199. llama_format_win_err(GetLastError()).c_str());
  200. }
  201. }
  202. #else
  203. #pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
  204. #endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
  205. }
  206. ~llama_mmap() {
  207. if (!UnmapViewOfFile(addr)) {
  208. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  209. llama_format_win_err(GetLastError()).c_str());
  210. }
  211. }
  212. #else
  213. static constexpr bool SUPPORTED = false;
  214. llama_mmap(struct llama_file *, bool prefetch = true) {
  215. (void)prefetch;
  216. throw std::runtime_error(std::string("mmap not supported"));
  217. }
  218. #endif
  219. };
  220. // Represents some region of memory being locked using mlock or VirtualLock;
  221. // will automatically unlock on destruction.
  222. struct llama_mlock {
  223. void * addr = NULL;
  224. size_t size = 0;
  225. bool failed_already = false;
  226. llama_mlock() {}
  227. llama_mlock(const llama_mlock &) = delete;
  228. ~llama_mlock() {
  229. if (size) {
  230. raw_unlock(addr, size);
  231. }
  232. }
  233. void init(void * ptr) {
  234. LLAMA_ASSERT(addr == NULL && size == 0);
  235. addr = ptr;
  236. }
  237. void grow_to(size_t target_size) {
  238. LLAMA_ASSERT(addr);
  239. if (failed_already) {
  240. return;
  241. }
  242. size_t granularity = lock_granularity();
  243. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  244. if (target_size > size) {
  245. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  246. size = target_size;
  247. } else {
  248. failed_already = true;
  249. }
  250. }
  251. }
  252. #ifdef _POSIX_MEMLOCK_RANGE
  253. static constexpr bool SUPPORTED = true;
  254. size_t lock_granularity() {
  255. return (size_t) sysconf(_SC_PAGESIZE);
  256. }
  257. #ifdef __APPLE__
  258. #define MLOCK_SUGGESTION \
  259. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  260. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  261. #else
  262. #define MLOCK_SUGGESTION \
  263. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  264. #endif
  265. bool raw_lock(const void * addr, size_t size) {
  266. if (!mlock(addr, size)) {
  267. return true;
  268. } else {
  269. char* errmsg = std::strerror(errno);
  270. bool suggest = (errno == ENOMEM);
  271. // Check if the resource limit is fine after all
  272. struct rlimit lock_limit;
  273. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit))
  274. suggest = false;
  275. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size))
  276. suggest = false;
  277. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  278. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  279. return false;
  280. }
  281. }
  282. #undef MLOCK_SUGGESTION
  283. void raw_unlock(void * addr, size_t size) {
  284. if (munlock(addr, size)) {
  285. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  286. }
  287. }
  288. #elif defined(_WIN32)
  289. static constexpr bool SUPPORTED = true;
  290. size_t lock_granularity() {
  291. SYSTEM_INFO si;
  292. GetSystemInfo(&si);
  293. return (size_t) si.dwPageSize;
  294. }
  295. bool raw_lock(void * ptr, size_t len) {
  296. for (int tries = 1; ; tries++) {
  297. if (VirtualLock(ptr, len)) {
  298. return true;
  299. }
  300. if (tries == 2) {
  301. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  302. len, size, llama_format_win_err(GetLastError()).c_str());
  303. return false;
  304. }
  305. // It failed but this was only the first try; increase the working
  306. // set size and try again.
  307. SIZE_T min_ws_size, max_ws_size;
  308. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  309. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  310. llama_format_win_err(GetLastError()).c_str());
  311. return false;
  312. }
  313. // Per MSDN: "The maximum number of pages that a process can lock
  314. // is equal to the number of pages in its minimum working set minus
  315. // a small overhead."
  316. // Hopefully a megabyte is enough overhead:
  317. size_t increment = len + 1048576;
  318. // The minimum must be <= the maximum, so we need to increase both:
  319. min_ws_size += increment;
  320. max_ws_size += increment;
  321. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  322. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  323. llama_format_win_err(GetLastError()).c_str());
  324. return false;
  325. }
  326. }
  327. }
  328. void raw_unlock(void * ptr, size_t len) {
  329. if (!VirtualUnlock(ptr, len)) {
  330. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  331. llama_format_win_err(GetLastError()).c_str());
  332. }
  333. }
  334. #else
  335. static constexpr bool SUPPORTED = false;
  336. size_t lock_granularity() {
  337. return (size_t) 65536;
  338. }
  339. bool raw_lock(const void * addr, size_t len) {
  340. fprintf(stderr, "warning: mlock not supported on this system\n");
  341. return false;
  342. }
  343. void raw_unlock(const void * addr, size_t len) {}
  344. #endif
  345. };
  346. // Replacement for std::vector<uint8_t> that doesn't require zero-initialization.
  347. struct llama_buffer {
  348. uint8_t * addr = NULL;
  349. size_t size = 0;
  350. llama_buffer() = default;
  351. void resize(size_t len) {
  352. #ifdef GGML_USE_METAL
  353. free(addr);
  354. int result = posix_memalign((void **) &addr, getpagesize(), len);
  355. if (result == 0) {
  356. memset(addr, 0, len);
  357. }
  358. else {
  359. addr = NULL;
  360. }
  361. #else
  362. delete[] addr;
  363. addr = new uint8_t[len];
  364. #endif
  365. size = len;
  366. }
  367. ~llama_buffer() {
  368. #ifdef GGML_USE_METAL
  369. free(addr);
  370. #else
  371. delete[] addr;
  372. #endif
  373. addr = NULL;
  374. }
  375. // disable copy and move
  376. llama_buffer(const llama_buffer&) = delete;
  377. llama_buffer(llama_buffer&&) = delete;
  378. llama_buffer& operator=(const llama_buffer&) = delete;
  379. llama_buffer& operator=(llama_buffer&&) = delete;
  380. };
  381. #ifdef GGML_USE_CUBLAS
  382. #include "ggml-cuda.h"
  383. struct llama_ctx_buffer {
  384. uint8_t * addr = NULL;
  385. bool is_cuda;
  386. size_t size = 0;
  387. llama_ctx_buffer() = default;
  388. void resize(size_t size) {
  389. free();
  390. addr = (uint8_t *) ggml_cuda_host_malloc(size);
  391. if (addr) {
  392. is_cuda = true;
  393. }
  394. else {
  395. // fall back to pageable memory
  396. addr = new uint8_t[size];
  397. is_cuda = false;
  398. }
  399. this->size = size;
  400. }
  401. void free() {
  402. if (addr) {
  403. if (is_cuda) {
  404. ggml_cuda_host_free(addr);
  405. }
  406. else {
  407. delete[] addr;
  408. }
  409. }
  410. addr = NULL;
  411. }
  412. ~llama_ctx_buffer() {
  413. free();
  414. }
  415. // disable copy and move
  416. llama_ctx_buffer(const llama_ctx_buffer&) = delete;
  417. llama_ctx_buffer(llama_ctx_buffer&&) = delete;
  418. llama_ctx_buffer& operator=(const llama_ctx_buffer&) = delete;
  419. llama_ctx_buffer& operator=(llama_ctx_buffer&&) = delete;
  420. };
  421. #else
  422. typedef llama_buffer llama_ctx_buffer;
  423. #endif
  424. #endif