llama_util.h 11 KB

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