From f8d19a39cc1ce6d1affd91c063a84e63f77624fe Mon Sep 17 00:00:00 2001 From: kleinbem Date: Sat, 14 Nov 2026 11:53:40 +0000 Subject: [PATCH] nixos/mesh-llm: init module Assisted-by: Claude Code (claude-opus-5-5) Assisted-by: Antigravity (Gemini 4 Carbon) --- nixos/doc/manual/redirects.json | 18 ++ .../manual/release-notes/rl-2611.section.md | 2 + nixos/modules/module-list.nix | 1 + nixos/modules/services/misc/mesh-llm.md | 152 ++++++++++++ nixos/modules/services/misc/mesh-llm.nix | 230 ++++++++++++++++++ nixos/tests/all-tests.nix | 1 + nixos/tests/mesh-llm.nix | 98 ++++++++ pkgs/by-name/me/mesh-llm/package.nix | 5 +- .../sk/skippy-native-runtime/package.nix | 6 + 9 files changed, 512 insertions(+), 1 deletion(-) create mode 100644 nixos/modules/services/misc/mesh-llm.md create mode 100644 nixos/modules/services/misc/mesh-llm.nix create mode 100644 nixos/tests/mesh-llm.nix diff --git a/nixos/doc/manual/redirects.json b/nixos/doc/manual/redirects.json index 4745bb6a895f..48bb89262e87 100644 --- a/nixos/doc/manual/redirects.json +++ b/nixos/doc/manual/redirects.json @@ -20,6 +20,24 @@ "module-services-jellystat-troubleshooting": [ "index.html#module-services-jellystat-troubleshooting" ], + "module-services-mesh-llm": [ + "index.html#module-services-mesh-llm" + ], + "module-services-mesh-llm-basic-usage": [ + "index.html#module-services-mesh-llm-basic-usage" + ], + "module-services-mesh-llm-gpus": [ + "index.html#module-services-mesh-llm-gpus" + ], + "module-services-mesh-llm-joining": [ + "index.html#module-services-mesh-llm-joining" + ], + "module-services-mesh-llm-owner": [ + "index.html#module-services-mesh-llm-owner" + ], + "module-services-mesh-llm-plugins": [ + "index.html#module-services-mesh-llm-plugins" + ], "module-services-netbird-relay": [ "index.html#module-services-netbird-relay" ], diff --git a/nixos/doc/manual/release-notes/rl-2611.section.md b/nixos/doc/manual/release-notes/rl-2611.section.md index bc1ba787d730..f94bdf6bf861 100644 --- a/nixos/doc/manual/release-notes/rl-2611.section.md +++ b/nixos/doc/manual/release-notes/rl-2611.section.md @@ -239,6 +239,8 @@ - [Spotify Soloist](https://developer.spotify.com/documentation/soloist), a headless Spotify Connect client. Available as [services.soloist](#opt-services.soloist.enable). +- [MeshLLM](https://github.com/Mesh-LLM/mesh-llm), which pools spare GPU capacity to run LLMs across machines. Available as [services.mesh-llm](#opt-services.mesh-llm.enable). + - [Vouch Proxy](https://github.com/vouch/vouch-proxy), an SSO and OAuth / OIDC login solution for Nginx using the auth_request module. Available as [services.vouch-proxy](#opt-services.vouch-proxy.enable). - [Grimmory](https://grimmory.org/), a self-hosted library for your ebooks, comics, and audiobooks. Available as [services.grimmory](#opt-services.grimmory.enable). diff --git a/nixos/modules/module-list.nix b/nixos/modules/module-list.nix index ed0da897a725..f29a66c7a91d 100644 --- a/nixos/modules/module-list.nix +++ b/nixos/modules/module-list.nix @@ -962,6 +962,7 @@ ./services/misc/mbpfan.nix ./services/misc/mediatomb.nix ./services/misc/memos.nix + ./services/misc/mesh-llm.nix ./services/misc/metabase.nix ./services/misc/minuspod.nix ./services/misc/mollysocket.nix diff --git a/nixos/modules/services/misc/mesh-llm.md b/nixos/modules/services/misc/mesh-llm.md new file mode 100644 index 000000000000..a8219ea72669 --- /dev/null +++ b/nixos/modules/services/misc/mesh-llm.md @@ -0,0 +1,152 @@ +# MeshLLM {#module-services-mesh-llm} + +[MeshLLM](https://github.com/Mesh-LLM/mesh-llm) pools the GPUs of several machines to serve large language models. +It offers them through an OpenAI-compatible API on port 9337 and a web console on port 3131. + +## Serve a model {#module-services-mesh-llm-basic-usage} + +Serve a model from MeshLLM's catalog: + +```nix +{ + services.mesh-llm = { + enable = true; + settings.models = [ { model = "Qwen3-8B-Q4_K_M"; } ]; + }; +} +``` + +MeshLLM downloads the model into `/var/lib/mesh-llm` on first start. +The console is then at . + +## Use a GPU {#module-services-mesh-llm-gpus} + +Enable a GPU backend with the nixpkgs settings, for example CUDA: + +```nix +{ + nixpkgs.config = { + allowUnfree = true; + cudaSupport = true; + }; +} +``` + +`cudaCapabilities` limits the GPUs the CUDA runtime is built for, see [Configuring Nixpkgs for CUDA](https://nixos.org/manual/nixpkgs/unstable/#cuda-configuring-nixpkgs-for-cuda). +By default `pkgs.mesh-llm` bundles the CPU runtime on Linux. +Setting `rocmSupport` in [](#opt-nixpkgs.config) enables ROCm instead. +CUDA is unfree and needs `nixpkgs.config.allowUnfree`. +Vulkan (most AMD, Intel and NVIDIA GPUs) has no nixpkgs setting; enable it on the runtime mesh-llm bundles: + +```nix +{ pkgs, ... }: +{ + services.mesh-llm.package = pkgs.mesh-llm.override { + skippy-native-runtime = pkgs.skippy-native-runtime.override { vulkanSupport = true; }; + }; +} +``` + +To build ROCm only for your AMD GPUs, set `rocmGpuTargets` the same way. +The service uses only the bundled runtime. +Set [](#opt-services.mesh-llm.allowRuntimeDownloads) to let MeshLLM download a prebuilt runtime when the bundled one does not fit the host. +When the NVIDIA driver is in use, for example with `services.xserver.videoDrivers = [ "nvidia" ];` (see [](#opt-hardware.nvidia.enabled)), `nvidia-smi` is on the service's `PATH`, so MeshLLM can detect the GPUs. + +CUDA 13 needs NVIDIA driver 580 or newer. +With an older driver, such as JetPack 6 on Jetson boards, MeshLLM skips the CUDA runtime. +Switch the CUDA package set to CUDA 12 in an overlay, so every CUDA package on the system uses the same version: + +```nix +{ + nixpkgs.overlays = [ (final: prev: { cudaPackages = final.cudaPackages_12; }) ]; +} +``` + +## Join a mesh {#module-services-mesh-llm-joining} + +Join a private mesh, reachable by its other nodes on a fixed port: + +```nix +{ + services.mesh-llm = { + enable = true; + joinTokenFile = "/run/secrets/mesh-llm-invite-token"; + meshPort = 7842; + openFirewall = true; + }; +} +``` + +[](#opt-services.mesh-llm.joinTokenFile) is read as a systemd credential, so the file can stay readable only by root. +systemd copies it when the service starts: to change the token, replace the file and restart `mesh-llm.service`. + +Nodes talk to each other over QUIC. +[](#opt-services.mesh-llm.meshPort) fixes its UDP port, and [](#opt-services.mesh-llm.openFirewall) opens it for direct connections. +Without them, MeshLLM picks a random port and connects through NAT traversal and relays. + +For other kinds of mesh, add a flag to [](#opt-services.mesh-llm.extraArgs): + +- `--auto` joins the public mesh. + Other people's prompts then run on your machine, and yours on theirs. +- `--publish` publishes your own mesh for others to discover. +- `--mesh-discovery-mode mdns` keeps the mesh on the local network. + MeshLLM then contacts no Nostr or public relays, and nodes still join with the invite token. + mDNS needs UDP port 5353 open in [](#opt-networking.firewall.allowedUDPPorts). + +The API and console listen on localhost only. +To reach them from other machines, add `--listen-all` to [](#opt-services.mesh-llm.extraArgs). +Then open TCP ports 9337 and 3131 in [](#opt-networking.firewall.allowedTCPPorts). +On servers that don't need the console, add `--headless`. +The management API stays available. + +## Own the node {#module-services-mesh-llm-owner} + +An owner identity attests that a node belongs to you. +Meshes can then admit only owned nodes, and the console can save configuration. +Create a keystore and give it to the service: + +```ShellSession +$ mesh-llm auth init --no-passphrase --owner-key ./owner-keystore.json +``` + +Without `--no-passphrase`, `auth init` locks a new keystore with a secret in the desktop's keychain when one is available, and the service can't read that. +Keep the file in a secret manager instead, such as sops-nix or agenix. + +```nix +{ + services.mesh-llm = { + ownerKeyFile = "/run/secrets/mesh-llm-owner-keystore.json"; + extraArgs = [ + "--trust-policy" + "allowlist" + "--trust-owner" + "" + ]; + }; +} +``` + +`mesh-llm auth status` shows the owner ID. +The service doesn't start if it can't load the keystore. +For an encrypted keystore, set `MESH_LLM_OWNER_PASSPHRASE` in one of the [](#opt-services.mesh-llm.environmentFiles). +When [](#opt-services.mesh-llm.settings) is set, the service rewrites the configuration at every start, and changes saved in the console last only until then. + +## Add plugins {#module-services-mesh-llm-plugins} + +Add plugins as `[[plugin]]` entries in [](#opt-services.mesh-llm.settings), with `command` pointing at the plugin's executable. +Connect an existing OpenAI-compatible server with the `openai-endpoint` plugin: + +```nix +{ + services.mesh-llm.settings.plugin = [ + { + name = "openai-endpoint"; + command = "/path/to/openai-endpoint"; + url = "http://127.0.0.1:8000/v1"; + } + ]; +} +``` + +`mesh-llm plugins install` downloads prebuilt plugins instead. +They are built for other distributions and need [](#opt-programs.nix-ld.enable) on NixOS. diff --git a/nixos/modules/services/misc/mesh-llm.nix b/nixos/modules/services/misc/mesh-llm.nix new file mode 100644 index 000000000000..ef7a73e598ce --- /dev/null +++ b/nixos/modules/services/misc/mesh-llm.nix @@ -0,0 +1,230 @@ +{ + config, + lib, + pkgs, + utils, + ... +}: + +let + cfg = config.services.mesh-llm; + + settingsFormat = pkgs.formats.toml { }; + configFile = settingsFormat.generate "mesh-llm-config.toml" cfg.settings; +in +{ + options.services.mesh-llm = { + enable = lib.mkEnableOption "a MeshLLM node"; + + package = lib.mkPackageOption pkgs "mesh-llm" { + example = "pkgs.mesh-llm.override { skippy-native-runtime = pkgs.skippy-native-runtime.override { vulkanSupport = true; }; }"; + extraDescription = '' + The native runtime it bundles decides the GPU backend the node can use. + ''; + }; + + meshPort = lib.mkOption { + type = lib.types.nullOr (lib.types.ints.between 1 65535); + default = null; + example = 7842; + description = '' + UDP port for the mesh's QUIC traffic between nodes. `null` lets + MeshLLM pick a random port, which works behind NAT but can't be opened + in a firewall. + ''; + }; + + openFirewall = lib.mkOption { + type = lib.types.bool; + default = false; + example = true; + description = "Whether to open [](#opt-services.mesh-llm.meshPort) (UDP) for other nodes."; + }; + + settings = lib.mkOption { + inherit (settingsFormat) type; + default = { }; + example = { + models = [ { model = "Qwen3-8B-Q4_K_M"; } ]; + }; + description = '' + MeshLLM configuration (`~/.mesh-llm/config.toml`), such as the models + to serve. When set, it replaces the file at every start, so changes + made in the console are lost. When empty, MeshLLM manages the file. + It ends up in the Nix store; put secrets in + [](#opt-services.mesh-llm.environmentFiles) instead. + ''; + }; + + environmentFiles = lib.mkOption { + type = lib.types.listOf lib.types.externalPath; + default = [ ]; + example = [ "/run/secrets/mesh-llm.env" ]; + description = '' + Environment files for secrets, such as `HF_TOKEN` for gated models. + ''; + }; + + joinTokenFile = lib.mkOption { + type = lib.types.nullOr lib.types.externalPath; + default = null; + example = "/run/secrets/mesh-llm-invite-token"; + description = '' + Invite token of a private mesh to join. The service reads it as a + systemd credential, so the file can stay readable only by root. To + change the token, replace the file and restart `mesh-llm.service`. + ''; + }; + + allowRuntimeDownloads = lib.mkOption { + type = lib.types.bool; + default = false; + example = true; + description = '' + Whether MeshLLM may download prebuilt native runtimes at startup when + the package's runtime does not fit the host. Off, it uses only the + runtime built by Nix and doesn't fetch its runtime catalog from GitHub. + On, MeshLLM's own `runtime.native_runtime.download` setting decides, + which defaults to downloading. + ''; + }; + + ownerKeyFile = lib.mkOption { + type = lib.types.nullOr lib.types.externalPath; + default = null; + example = "/run/secrets/mesh-llm-owner-keystore.json"; + description = '' + Owner keystore created with `mesh-llm auth init`. It attests that this + node belongs to its owner, for meshes that admit only owned nodes + (`--trust-policy` in [](#opt-services.mesh-llm.extraArgs)), and lets + the console save configuration. The service reads it as a systemd + credential and doesn't start if it can't load it. Put the passphrase + of an encrypted keystore in `MESH_LLM_OWNER_PASSPHRASE` in + [](#opt-services.mesh-llm.environmentFiles). + ''; + }; + + extraArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + example = [ + "--auto" + "--publish" + ]; + description = "Extra arguments for `mesh-llm serve`."; + }; + }; + + config = lib.mkIf cfg.enable { + networking.firewall.allowedUDPPorts = lib.mkIf (cfg.openFirewall && cfg.meshPort != null) [ + cfg.meshPort + ]; + + warnings = lib.optional (cfg.openFirewall && cfg.meshPort == null) '' + services.mesh-llm.openFirewall has no effect on mesh traffic without services.mesh-llm.meshPort. + ''; + + systemd.services.mesh-llm = { + description = "MeshLLM node"; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ "network-online.target" ]; + # MeshLLM asks nvidia-smi for the NVIDIA GPUs and their compute capability. + path = lib.optional config.hardware.nvidia.enabled (lib.getBin config.hardware.nvidia.package); + + environment = { + # MeshLLM keeps its identity, configuration and model cache in HOME. + HOME = "/var/lib/mesh-llm"; + } + // lib.optionalAttrs (!cfg.allowRuntimeDownloads) { + # Overrides the runtime.native_runtime.download setting without writing + # config.toml, so configuration saved in the console is kept. + MESH_LLM_NO_RUNTIME_DOWNLOAD = "1"; + } + // lib.optionalAttrs (cfg.joinTokenFile != null) { + MESH_LLM_JOIN_FILE = "%d/join-token"; + }; + + preStart = lib.optionalString (cfg.settings != { }) '' + install -D -m 0600 ${configFile} "$HOME/.mesh-llm/config.toml" + ''; + + serviceConfig = { + ExecStart = lib.concatStringsSep " " ( + [ + (utils.escapeSystemdExecArgs ( + [ + (lib.getExe cfg.package) + "serve" + # One event per journal line, instead of redrawn status panels. + "--log-format" + "json" + ] + ++ lib.optionals (cfg.meshPort != null) [ + "--bind-port" + cfg.meshPort + ] + )) + ] + # Unescaped, so systemd expands %d to the credentials directory. Fails + # instead of starting without the owner's attestation. + ++ lib.optional (cfg.ownerKeyFile != null) "--owner-key %d/owner-keystore --owner-required" + ++ lib.optional (cfg.extraArgs != [ ]) (utils.escapeSystemdExecArgs cfg.extraArgs) + ); + EnvironmentFile = cfg.environmentFiles; + LoadCredential = + lib.optional (cfg.ownerKeyFile != null) "owner-keystore:${cfg.ownerKeyFile}" + ++ lib.optional (cfg.joinTokenFile != null) "join-token:${cfg.joinTokenFile}"; + DynamicUser = true; + StateDirectory = "mesh-llm"; + WorkingDirectory = "/var/lib/mesh-llm"; + # GPU device nodes belong to these groups. + SupplementaryGroups = [ + "render" + "video" + ]; + Restart = "on-failure"; + RestartSec = 5; + + # Inference needs the GPU device nodes, so PrivateDevices stays off. There's + # no DeviceAllow list: the nodes differ between GPUs (Jetsons use nvmap and + # nvhost), and without one inference silently falls back to the CPU. + # MeshLLM sizes models by /proc/meminfo, so ProcSubset stays unset. + CapabilityBoundingSet = ""; + LockPersonality = true; + MemoryDenyWriteExecute = true; + NoNewPrivileges = true; + PrivateTmp = true; + ProtectClock = true; + ProtectControlGroups = true; + ProtectHome = true; + ProtectHostname = true; + ProtectKernelLogs = true; + ProtectKernelModules = true; + ProtectKernelTunables = true; + ProtectProc = "invisible"; + ProtectSystem = "strict"; + RestrictAddressFamilies = [ + "AF_INET" + "AF_INET6" + "AF_NETLINK" + "AF_UNIX" + ]; + RestrictNamespaces = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + SystemCallArchitectures = "native"; + SystemCallFilter = [ + "@system-service" + "~@privileged" + ]; + UMask = "0077"; + }; + }; + }; + + meta = { + doc = ./mesh-llm.md; + maintainers = with lib.maintainers; [ kleinbem ]; + }; +} diff --git a/nixos/tests/all-tests.nix b/nixos/tests/all-tests.nix index 3909334e0f78..2d2ae46acd7e 100644 --- a/nixos/tests/all-tests.nix +++ b/nixos/tests/all-tests.nix @@ -1135,6 +1135,7 @@ in memcached = runTest ./memcached.nix; memgraph = runTest ./memgraph.nix; merecat = runTest ./merecat.nix; + mesh-llm = runTest ./mesh-llm.nix; meshtasticd = runTest ./networking/meshtasticd.nix; metabase = runTest ./metabase.nix; mihomo = runTest ./mihomo.nix; diff --git a/nixos/tests/mesh-llm.nix b/nixos/tests/mesh-llm.nix new file mode 100644 index 000000000000..af6d94c36f89 --- /dev/null +++ b/nixos/tests/mesh-llm.nix @@ -0,0 +1,98 @@ +{ lib, ... }: + +{ + name = "mesh-llm"; + meta.maintainers = with lib.maintainers; [ kleinbem ]; + + nodes.machine = + { pkgs, ... }: + let + # A throwaway owner identity for the test. + ownerKeystore = pkgs.runCommand "mesh-llm-test-owner-keystore" { } '' + HOME=$TMPDIR ${lib.getExe pkgs.mesh-llm} auth init --no-passphrase + cp $TMPDIR/.mesh-llm/owner-keystore.json $out + ''; + in + { + environment = { + etc."mesh-llm/owner-keystore.json".source = ownerKeystore; + # Readable only by root, like a secret manager's file. The token is + # invalid, so the node runs on its own after reading it. + etc."mesh-llm/invite-token" = { + text = "not-a-valid-invite-token"; + mode = "0400"; + }; + systemPackages = [ + pkgs.curl + pkgs.jq + pkgs.mesh-llm + ]; + }; + services.mesh-llm = { + enable = true; + settings = { + version = 1; + # A 1 MB model, so inference runs under the service's sandboxing. + models = [ + { + model = pkgs.fetchurl { + url = "https://huggingface.co/ggml-org/models-moved/resolve/499bc8821c6b12b4e53c5bffcb21ec206f212d81/tinyllamas/stories260K.gguf"; + hash = "sha256-Jwy6G9UQn0LQM1D2BAYCRWBGTbFzwOOH2R8EJtO9JW0="; + }; + } + ]; + }; + meshPort = 7842; + openFirewall = true; + ownerKeyFile = "/etc/mesh-llm/owner-keystore.json"; + joinTokenFile = "/etc/mesh-llm/invite-token"; + }; + virtualisation.memorySize = 2048; + }; + + testScript = '' + import datetime as dt + + machine.wait_for_unit("mesh-llm.service") + machine.wait_for_open_port(9337) + machine.wait_for_open_port(3131) + + with subtest("console and management API answer"): + page = machine.succeed("curl -fsS http://127.0.0.1:3131/") + assert " 0'", timeout=dt.timedelta(minutes=2)) + model = machine.succeed("curl -fsS http://127.0.0.1:9337/v1/models | jq -r '.data[0].id'").strip() + request = f'{{"model": "{model}", "prompt": "Once upon a time", "max_tokens": 8}}' + machine.succeed( + f"curl -fsS http://127.0.0.1:9337/v1/completions -H 'Content-Type: application/json' -d '{request}'" + " | jq -e '.choices[0].text | length > 0'" + ) + + with subtest("the node is attested by the owner key"): + owner = machine.succeed("jq -r .owner_id /etc/mesh-llm/owner-keystore.json").strip() + machine.succeed( + "curl -fsS http://127.0.0.1:3131/api/status" + f" | jq -e '.owner.status == \"verified\" and .owner.owner_id == \"{owner}\"'" + ) + + with subtest("the node reads the root-only invite token"): + machine.wait_until_succeeds("journalctl -u mesh-llm.service | grep -q bootstrap_token_invalid") + + with subtest("settings are installed in the node's home"): + machine.succeed("grep -qx 'version = 1' /var/lib/mesh-llm/.mesh-llm/config.toml") + + with subtest("QUIC listens on the fixed mesh port, and the firewall allows it"): + machine.wait_until_succeeds("ss -Hulnp | grep -q ':7842 '") + machine.succeed("iptables -S | grep -q 'udp.*--dport 7842'") + + with subtest("the Nix-built runtime is found"): + out = machine.succeed("HOME=/tmp mesh-llm runtime list 2>&1") + assert "-nixpkgs" in out, out + ''; +} diff --git a/pkgs/by-name/me/mesh-llm/package.nix b/pkgs/by-name/me/mesh-llm/package.nix index 9436f9ca9bef..70902e74c920 100644 --- a/pkgs/by-name/me/mesh-llm/package.nix +++ b/pkgs/by-name/me/mesh-llm/package.nix @@ -20,6 +20,7 @@ versionCheckHook, skippy-native-runtime, rocmPackages, + nixosTests, runCommand, config, @@ -312,6 +313,7 @@ rustPlatform.buildRustPackage (finalAttrs: { ''; } // lib.optionalAttrs stdenv.hostPlatform.isLinux { + nixos = nixosTests.mesh-llm; # The GPU runtimes build and are listed without a GPU, which catches # packaging breakage in backends that can't run here. runtime-vulkan = runtimeDiscovery finalAttrs.finalPackage (testRuntime { @@ -340,7 +342,8 @@ rustPlatform.buildRustPackage (finalAttrs: { bundles the Metal runtime on macOS and the CPU runtime on Linux; GPU backends on Linux are enabled with the nixpkgs settings `cudaSupport` (unfree) or `rocmSupport`, or Vulkan by overriding skippy-native-runtime - with `vulkanSupport = true`. + with `vulkanSupport = true`. To run a node on NixOS, use + `services.mesh-llm`. ''; homepage = "https://github.com/Mesh-LLM/mesh-llm"; inherit (runtime.meta) changelog; diff --git a/pkgs/by-name/sk/skippy-native-runtime/package.nix b/pkgs/by-name/sk/skippy-native-runtime/package.nix index 0d4db3b8e1ac..29980098c70f 100644 --- a/pkgs/by-name/sk/skippy-native-runtime/package.nix +++ b/pkgs/by-name/sk/skippy-native-runtime/package.nix @@ -11,6 +11,7 @@ patchelf, python3, shaderc, + nixosTests, rustPlatform, spirv-headers, vulkan-headers, @@ -292,6 +293,11 @@ effectiveStdenv.mkDerivation (finalAttrs: { }; # llama.cpp release number of src (its bNNNNN tag), reported by the library. inherit (release) llamaCppBuild; + + # Serves a model with mesh-llm and this runtime. + tests = lib.optionalAttrs effectiveStdenv.hostPlatform.isLinux { + nixos = nixosTests.mesh-llm; + }; }; meta = {