llama_util.h 11 KB

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