llama_util.h 11 KB

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