package.nix 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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/src/ggml-metal.m \
  147. --replace '[bundle pathForResource:@"ggml-metal" ofType:@"metal"];' "@\"$out/bin/ggml-metal.metal\";"
  148. substituteInPlace ./ggml/src/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_BUILD_SERVER" true)
  187. (cmakeBool "BUILD_SHARED_LIBS" (!enableStatic))
  188. (cmakeBool "CMAKE_SKIP_BUILD_RPATH" true)
  189. (cmakeBool "GGML_NATIVE" false)
  190. (cmakeBool "GGML_BLAS" useBlas)
  191. (cmakeBool "GGML_CLBLAST" useOpenCL)
  192. (cmakeBool "GGML_CUDA" useCuda)
  193. (cmakeBool "GGML_HIPBLAS" useRocm)
  194. (cmakeBool "GGML_METAL" useMetalKit)
  195. (cmakeBool "GGML_VULKAN" useVulkan)
  196. (cmakeBool "GGML_STATIC" enableStatic)
  197. ]
  198. ++ optionals useCuda [
  199. (
  200. with cudaPackages.flags;
  201. cmakeFeature "CMAKE_CUDA_ARCHITECTURES" (
  202. builtins.concatStringsSep ";" (map dropDot cudaCapabilities)
  203. )
  204. )
  205. ]
  206. ++ optionals useRocm [
  207. (cmakeFeature "CMAKE_HIP_COMPILER" "${rocmPackages.llvm.clang}/bin/clang")
  208. (cmakeFeature "CMAKE_HIP_ARCHITECTURES" (builtins.concatStringsSep ";" rocmPackages.clr.gpuTargets))
  209. ]
  210. ++ optionals useMetalKit [
  211. (lib.cmakeFeature "CMAKE_C_FLAGS" "-D__ARM_FEATURE_DOTPROD=1")
  212. (cmakeBool "GGML_METAL_EMBED_LIBRARY" (!precompileMetalShaders))
  213. ];
  214. # Environment variables needed for ROCm
  215. env = optionals useRocm {
  216. ROCM_PATH = "${rocmPackages.clr}";
  217. HIP_DEVICE_LIB_PATH = "${rocmPackages.rocm-device-libs}/amdgcn/bitcode";
  218. };
  219. # TODO(SomeoneSerge): It's better to add proper install targets at the CMake level,
  220. # if they haven't been added yet.
  221. postInstall = ''
  222. mkdir -p $out/include
  223. cp $src/include/llama.h $out/include/
  224. '';
  225. # Define the shells here, but don't add in the inputsFrom to avoid recursion.
  226. passthru = {
  227. inherit
  228. useBlas
  229. useCuda
  230. useMetalKit
  231. useMpi
  232. useOpenCL
  233. useRocm
  234. useVulkan
  235. ;
  236. shell = mkShell {
  237. name = "shell-${finalAttrs.finalPackage.name}";
  238. description = "contains numpy and sentencepiece";
  239. buildInputs = [ llama-python ];
  240. inputsFrom = [ finalAttrs.finalPackage ];
  241. shellHook = ''
  242. addToSearchPath "LD_LIBRARY_PATH" "${lib.getLib effectiveStdenv.cc.cc}/lib"
  243. '';
  244. };
  245. shell-extra = mkShell {
  246. name = "shell-extra-${finalAttrs.finalPackage.name}";
  247. description = "contains numpy, sentencepiece, torchWithoutCuda, and transformers";
  248. buildInputs = [ llama-python-extra ];
  249. inputsFrom = [ finalAttrs.finalPackage ];
  250. };
  251. };
  252. meta = {
  253. # Configurations we don't want even the CI to evaluate. Results in the
  254. # "unsupported platform" messages. This is mostly a no-op, because
  255. # cudaPackages would've refused to evaluate anyway.
  256. badPlatforms = optionals (useCuda || useOpenCL) lib.platforms.darwin;
  257. # Configurations that are known to result in build failures. Can be
  258. # overridden by importing Nixpkgs with `allowBroken = true`.
  259. broken = (useMetalKit && !effectiveStdenv.isDarwin);
  260. description = "Inference of LLaMA model in pure C/C++${descriptionSuffix}";
  261. homepage = "https://github.com/ggerganov/llama.cpp/";
  262. license = lib.licenses.mit;
  263. # Accommodates `nix run` and `lib.getExe`
  264. mainProgram = "llama-cli";
  265. # These people might respond, on the best effort basis, if you ping them
  266. # in case of Nix-specific regressions or for reviewing Nix-specific PRs.
  267. # Consider adding yourself to this list if you want to ensure this flake
  268. # stays maintained and you're willing to invest your time. Do not add
  269. # other people without their consent. Consider removing people after
  270. # they've been unreachable for long periods of time.
  271. # Note that lib.maintainers is defined in Nixpkgs, but you may just add
  272. # an attrset following the same format as in
  273. # https://github.com/NixOS/nixpkgs/blob/f36a80e54da29775c78d7eff0e628c2b4e34d1d7/maintainers/maintainer-list.nix
  274. maintainers = with lib.maintainers; [
  275. philiptaron
  276. SomeoneSerge
  277. ];
  278. # Extend `badPlatforms` instead
  279. platforms = lib.platforms.all;
  280. };
  281. }
  282. )