package.nix 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. {
  2. lib,
  3. glibc,
  4. config,
  5. stdenv,
  6. mkShell,
  7. runCommand,
  8. cmake,
  9. ninja,
  10. pkg-config,
  11. git,
  12. python3,
  13. mpi,
  14. blas,
  15. cudaPackages,
  16. darwin,
  17. rocmPackages,
  18. vulkan-headers,
  19. vulkan-loader,
  20. clblast,
  21. useBlas ? builtins.all (x: !x) [
  22. useCuda
  23. useMetalKit
  24. useOpenCL
  25. useRocm
  26. useVulkan
  27. ] && blas.meta.available,
  28. useCuda ? config.cudaSupport,
  29. useMetalKit ? stdenv.isAarch64 && stdenv.isDarwin && !useOpenCL,
  30. useMpi ? false, # Increases the runtime closure size by ~700M
  31. useOpenCL ? false,
  32. useRocm ? config.rocmSupport,
  33. useVulkan ? false,
  34. llamaVersion ? "0.0.0", # Arbitrary version, substituted by the flake
  35. # It's necessary to consistently use backendStdenv when building with CUDA support,
  36. # otherwise we get libstdc++ errors downstream.
  37. effectiveStdenv ? if useCuda then cudaPackages.backendStdenv else stdenv,
  38. enableStatic ? effectiveStdenv.hostPlatform.isStatic,
  39. precompileMetalShaders ? false
  40. }@inputs:
  41. let
  42. inherit (lib)
  43. cmakeBool
  44. cmakeFeature
  45. optionals
  46. strings
  47. versionOlder
  48. ;
  49. stdenv = throw "Use effectiveStdenv instead";
  50. suffices =
  51. lib.optionals useBlas [ "BLAS" ]
  52. ++ lib.optionals useCuda [ "CUDA" ]
  53. ++ lib.optionals useMetalKit [ "MetalKit" ]
  54. ++ lib.optionals useMpi [ "MPI" ]
  55. ++ lib.optionals useOpenCL [ "OpenCL" ]
  56. ++ lib.optionals useRocm [ "ROCm" ]
  57. ++ lib.optionals useVulkan [ "Vulkan" ];
  58. pnameSuffix =
  59. strings.optionalString (suffices != [ ])
  60. "-${strings.concatMapStringsSep "-" strings.toLower suffices}";
  61. descriptionSuffix =
  62. strings.optionalString (suffices != [ ])
  63. ", accelerated with ${strings.concatStringsSep ", " suffices}";
  64. executableSuffix = effectiveStdenv.hostPlatform.extensions.executable;
  65. # TODO: package the Python in this repository in a Nix-like way.
  66. # It'd be nice to migrate to buildPythonPackage, as well as ensure this repo
  67. # is PEP 517-compatible, and ensure the correct .dist-info is generated.
  68. # https://peps.python.org/pep-0517/
  69. #
  70. # TODO: Package up each Python script or service appropriately, by making
  71. # them into "entrypoints"
  72. llama-python = python3.withPackages (
  73. ps: [
  74. ps.numpy
  75. ps.sentencepiece
  76. ]
  77. );
  78. # TODO(Green-Sky): find a better way to opt-into the heavy ml python runtime
  79. llama-python-extra = python3.withPackages (
  80. ps: [
  81. ps.numpy
  82. ps.sentencepiece
  83. ps.tiktoken
  84. ps.torchWithoutCuda
  85. ps.transformers
  86. ]
  87. );
  88. xcrunHost = runCommand "xcrunHost" {} ''
  89. mkdir -p $out/bin
  90. ln -s /usr/bin/xcrun $out/bin
  91. '';
  92. # apple_sdk is supposed to choose sane defaults, no need to handle isAarch64
  93. # separately
  94. darwinBuildInputs =
  95. with darwin.apple_sdk.frameworks;
  96. [
  97. Accelerate
  98. CoreVideo
  99. CoreGraphics
  100. ]
  101. ++ optionals useMetalKit [ MetalKit ];
  102. cudaBuildInputs = with cudaPackages; [
  103. cuda_cccl.dev # <nv/target>
  104. # A temporary hack for reducing the closure size, remove once cudaPackages
  105. # have stopped using lndir: https://github.com/NixOS/nixpkgs/issues/271792
  106. cuda_cudart.dev
  107. cuda_cudart.lib
  108. cuda_cudart.static
  109. libcublas.dev
  110. libcublas.lib
  111. libcublas.static
  112. ];
  113. rocmBuildInputs = with rocmPackages; [
  114. clr
  115. hipblas
  116. rocblas
  117. ];
  118. vulkanBuildInputs = [
  119. vulkan-headers
  120. vulkan-loader
  121. ];
  122. in
  123. effectiveStdenv.mkDerivation (
  124. finalAttrs: {
  125. pname = "llama-cpp${pnameSuffix}";
  126. version = llamaVersion;
  127. # Note: none of the files discarded here are visible in the sandbox or
  128. # affect the output hash. This also means they can be modified without
  129. # triggering a rebuild.
  130. src = lib.cleanSourceWith {
  131. filter =
  132. name: type:
  133. let
  134. noneOf = builtins.all (x: !x);
  135. baseName = baseNameOf name;
  136. in
  137. noneOf [
  138. (lib.hasSuffix ".nix" name) # Ignore *.nix files when computing outPaths
  139. (lib.hasSuffix ".md" name) # Ignore *.md changes whe computing outPaths
  140. (lib.hasPrefix "." baseName) # Skip hidden files and directories
  141. (baseName == "flake.lock")
  142. ];
  143. src = lib.cleanSource ../../.;
  144. };
  145. postPatch = ''
  146. substituteInPlace ./ggml-metal.m \
  147. --replace '[bundle pathForResource:@"ggml-metal" ofType:@"metal"];' "@\"$out/bin/ggml-metal.metal\";"
  148. substituteInPlace ./ggml-metal.m \
  149. --replace '[bundle pathForResource:@"default" ofType:@"metallib"];' "@\"$out/bin/default.metallib\";"
  150. '';
  151. # With PR#6015 https://github.com/ggerganov/llama.cpp/pull/6015,
  152. # `default.metallib` may be compiled with Metal compiler from XCode
  153. # and we need to escape sandbox on MacOS to access Metal compiler.
  154. # `xcrun` is used find the path of the Metal compiler, which is varible
  155. # and not on $PATH
  156. # see https://github.com/ggerganov/llama.cpp/pull/6118 for discussion
  157. __noChroot = effectiveStdenv.isDarwin && useMetalKit && precompileMetalShaders;
  158. nativeBuildInputs =
  159. [
  160. cmake
  161. ninja
  162. pkg-config
  163. git
  164. ]
  165. ++ optionals useCuda [
  166. cudaPackages.cuda_nvcc
  167. # TODO: Replace with autoAddDriverRunpath
  168. # once https://github.com/NixOS/nixpkgs/pull/275241 has been merged
  169. cudaPackages.autoAddOpenGLRunpathHook
  170. ]
  171. ++ optionals (effectiveStdenv.hostPlatform.isGnu && enableStatic) [
  172. glibc.static
  173. ] ++ optionals (effectiveStdenv.isDarwin && useMetalKit && precompileMetalShaders) [
  174. xcrunHost
  175. ];
  176. buildInputs =
  177. optionals effectiveStdenv.isDarwin darwinBuildInputs
  178. ++ optionals useCuda cudaBuildInputs
  179. ++ optionals useMpi [ mpi ]
  180. ++ optionals useOpenCL [ clblast ]
  181. ++ optionals useRocm rocmBuildInputs
  182. ++ optionals useBlas [ blas ]
  183. ++ optionals useVulkan vulkanBuildInputs;
  184. cmakeFlags =
  185. [
  186. (cmakeBool "LLAMA_NATIVE" false)
  187. (cmakeBool "LLAMA_BUILD_SERVER" true)
  188. (cmakeBool "BUILD_SHARED_LIBS" (!enableStatic))
  189. (cmakeBool "CMAKE_SKIP_BUILD_RPATH" true)
  190. (cmakeBool "LLAMA_BLAS" useBlas)
  191. (cmakeBool "LLAMA_CLBLAST" useOpenCL)
  192. (cmakeBool "LLAMA_CUDA" useCuda)
  193. (cmakeBool "LLAMA_HIPBLAS" useRocm)
  194. (cmakeBool "LLAMA_METAL" useMetalKit)
  195. (cmakeBool "LLAMA_MPI" useMpi)
  196. (cmakeBool "LLAMA_VULKAN" useVulkan)
  197. (cmakeBool "LLAMA_STATIC" enableStatic)
  198. ]
  199. ++ optionals useCuda [
  200. (
  201. with cudaPackages.flags;
  202. cmakeFeature "CMAKE_CUDA_ARCHITECTURES" (
  203. builtins.concatStringsSep ";" (map dropDot cudaCapabilities)
  204. )
  205. )
  206. ]
  207. ++ optionals useRocm [
  208. (cmakeFeature "CMAKE_HIP_COMPILER" "${rocmPackages.llvm.clang}/bin/clang")
  209. (cmakeFeature "CMAKE_HIP_ARCHITECTURES" (builtins.concatStringsSep ";" rocmPackages.clr.gpuTargets))
  210. ]
  211. ++ optionals useMetalKit [
  212. (lib.cmakeFeature "CMAKE_C_FLAGS" "-D__ARM_FEATURE_DOTPROD=1")
  213. (cmakeBool "LLAMA_METAL_EMBED_LIBRARY" (!precompileMetalShaders))
  214. ];
  215. # Environment variables needed for ROCm
  216. env = optionals useRocm {
  217. ROCM_PATH = "${rocmPackages.clr}";
  218. HIP_DEVICE_LIB_PATH = "${rocmPackages.rocm-device-libs}/amdgcn/bitcode";
  219. };
  220. # TODO(SomeoneSerge): It's better to add proper install targets at the CMake level,
  221. # if they haven't been added yet.
  222. postInstall = ''
  223. mv $out/bin/main${executableSuffix} $out/bin/llama${executableSuffix}
  224. mv $out/bin/server${executableSuffix} $out/bin/llama-server${executableSuffix}
  225. mkdir -p $out/include
  226. cp $src/llama.h $out/include/
  227. '';
  228. # Define the shells here, but don't add in the inputsFrom to avoid recursion.
  229. passthru = {
  230. inherit
  231. useBlas
  232. useCuda
  233. useMetalKit
  234. useMpi
  235. useOpenCL
  236. useRocm
  237. useVulkan
  238. ;
  239. shell = mkShell {
  240. name = "shell-${finalAttrs.finalPackage.name}";
  241. description = "contains numpy and sentencepiece";
  242. buildInputs = [ llama-python ];
  243. inputsFrom = [ finalAttrs.finalPackage ];
  244. shellHook = ''
  245. addToSearchPath "LD_LIBRARY_PATH" "${lib.getLib effectiveStdenv.cc.cc}/lib"
  246. '';
  247. };
  248. shell-extra = mkShell {
  249. name = "shell-extra-${finalAttrs.finalPackage.name}";
  250. description = "contains numpy, sentencepiece, torchWithoutCuda, and transformers";
  251. buildInputs = [ llama-python-extra ];
  252. inputsFrom = [ finalAttrs.finalPackage ];
  253. };
  254. };
  255. meta = {
  256. # Configurations we don't want even the CI to evaluate. Results in the
  257. # "unsupported platform" messages. This is mostly a no-op, because
  258. # cudaPackages would've refused to evaluate anyway.
  259. badPlatforms = optionals (useCuda || useOpenCL) lib.platforms.darwin;
  260. # Configurations that are known to result in build failures. Can be
  261. # overridden by importing Nixpkgs with `allowBroken = true`.
  262. broken = (useMetalKit && !effectiveStdenv.isDarwin);
  263. description = "Inference of LLaMA model in pure C/C++${descriptionSuffix}";
  264. homepage = "https://github.com/ggerganov/llama.cpp/";
  265. license = lib.licenses.mit;
  266. # Accommodates `nix run` and `lib.getExe`
  267. mainProgram = "llama";
  268. # These people might respond, on the best effort basis, if you ping them
  269. # in case of Nix-specific regressions or for reviewing Nix-specific PRs.
  270. # Consider adding yourself to this list if you want to ensure this flake
  271. # stays maintained and you're willing to invest your time. Do not add
  272. # other people without their consent. Consider removing people after
  273. # they've been unreachable for long periods of time.
  274. # Note that lib.maintainers is defined in Nixpkgs, but you may just add
  275. # an attrset following the same format as in
  276. # https://github.com/NixOS/nixpkgs/blob/f36a80e54da29775c78d7eff0e628c2b4e34d1d7/maintainers/maintainer-list.nix
  277. maintainers = with lib.maintainers; [
  278. philiptaron
  279. SomeoneSerge
  280. ];
  281. # Extend `badPlatforms` instead
  282. platforms = lib.platforms.all;
  283. };
  284. }
  285. )