1
0

llama_util.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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, bool prefetch = true) {
  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. if (addr == MAP_FAILED) {
  158. throw format("mmap failed: %s", strerror(errno));
  159. }
  160. if (prefetch) {
  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. }
  168. ~llama_mmap() {
  169. munmap(addr, size);
  170. }
  171. #elif defined(_WIN32)
  172. static constexpr bool SUPPORTED = true;
  173. llama_mmap(struct llama_file * file, bool prefetch = true) {
  174. size = file->size;
  175. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  176. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  177. DWORD error = GetLastError();
  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. if (prefetch) {
  189. // Advise the kernel to preload the mapped memory
  190. WIN32_MEMORY_RANGE_ENTRY range;
  191. range.VirtualAddress = addr;
  192. range.NumberOfBytes = (SIZE_T)size;
  193. if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  194. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  195. llama_format_win_err(GetLastError()).c_str());
  196. }
  197. }
  198. #else
  199. #pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
  200. #endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
  201. }
  202. ~llama_mmap() {
  203. if (!UnmapViewOfFile(addr)) {
  204. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  205. llama_format_win_err(GetLastError()).c_str());
  206. }
  207. }
  208. #else
  209. static constexpr bool SUPPORTED = false;
  210. llama_mmap(struct llama_file *) {
  211. throw std::string("mmap not supported");
  212. }
  213. #endif
  214. };
  215. // Represents some region of memory being locked using mlock or VirtualLock;
  216. // will automatically unlock on destruction.
  217. struct llama_mlock {
  218. void * addr = NULL;
  219. size_t size = 0;
  220. bool failed_already = false;
  221. llama_mlock() {}
  222. llama_mlock(const llama_mlock &) = delete;
  223. ~llama_mlock() {
  224. if (size) {
  225. raw_unlock(addr, size);
  226. }
  227. }
  228. void init(void * addr) {
  229. LLAMA_ASSERT(this->addr == NULL && this->size == 0);
  230. this->addr = addr;
  231. }
  232. void grow_to(size_t target_size) {
  233. LLAMA_ASSERT(addr);
  234. if (failed_already) {
  235. return;
  236. }
  237. size_t granularity = lock_granularity();
  238. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  239. if (target_size > size) {
  240. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  241. size = target_size;
  242. } else {
  243. failed_already = true;
  244. }
  245. }
  246. }
  247. #ifdef _POSIX_MEMLOCK_RANGE
  248. static constexpr bool SUPPORTED = true;
  249. size_t lock_granularity() {
  250. return (size_t) sysconf(_SC_PAGESIZE);
  251. }
  252. #ifdef __APPLE__
  253. #define MLOCK_SUGGESTION \
  254. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  255. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  256. #else
  257. #define MLOCK_SUGGESTION \
  258. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  259. #endif
  260. bool raw_lock(const void * addr, size_t size) {
  261. if (!mlock(addr, size)) {
  262. return true;
  263. } else {
  264. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n" MLOCK_SUGGESTION,
  265. size, this->size, std::strerror(errno));
  266. return false;
  267. }
  268. }
  269. #undef MLOCK_SUGGESTION
  270. void raw_unlock(void * addr, size_t size) {
  271. if (munlock(addr, size)) {
  272. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  273. }
  274. }
  275. #elif defined(_WIN32)
  276. static constexpr bool SUPPORTED = true;
  277. size_t lock_granularity() {
  278. SYSTEM_INFO si;
  279. GetSystemInfo(&si);
  280. return (size_t) si.dwPageSize;
  281. }
  282. bool raw_lock(void * addr, size_t size) {
  283. for (int tries = 1; ; tries++) {
  284. if (VirtualLock(addr, size)) {
  285. return true;
  286. }
  287. if (tries == 2) {
  288. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  289. size, this->size, llama_format_win_err(GetLastError()).c_str());
  290. return false;
  291. }
  292. // It failed but this was only the first try; increase the working
  293. // set size and try again.
  294. SIZE_T min_ws_size, max_ws_size;
  295. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  296. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  297. llama_format_win_err(GetLastError()).c_str());
  298. return false;
  299. }
  300. // Per MSDN: "The maximum number of pages that a process can lock
  301. // is equal to the number of pages in its minimum working set minus
  302. // a small overhead."
  303. // Hopefully a megabyte is enough overhead:
  304. size_t increment = size + 1048576;
  305. // The minimum must be <= the maximum, so we need to increase both:
  306. min_ws_size += increment;
  307. max_ws_size += increment;
  308. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  309. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  310. llama_format_win_err(GetLastError()).c_str());
  311. return false;
  312. }
  313. }
  314. }
  315. void raw_unlock(void * addr, size_t size) {
  316. if (!VirtualUnlock(addr, size)) {
  317. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  318. llama_format_win_err(GetLastError()).c_str());
  319. }
  320. }
  321. #else
  322. static constexpr bool SUPPORTED = false;
  323. void raw_lock(const void * addr, size_t size) {
  324. fprintf(stderr, "warning: mlock not supported on this system\n");
  325. }
  326. void raw_unlock(const void * addr, size_t size) {}
  327. #endif
  328. };
  329. // Replacement for std::vector<uint8_t> that doesn't require zero-initialization.
  330. struct llama_buffer {
  331. uint8_t * addr = NULL;
  332. size_t size = 0;
  333. void resize(size_t size) {
  334. delete[] addr;
  335. addr = new uint8_t[size];
  336. this->size = size;
  337. }
  338. ~llama_buffer() {
  339. delete[] addr;
  340. }
  341. };
  342. #endif