llama_util.h 12 KB

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