Skip to content

armgit / PS5LM

Public Imported from GitHub
0

llama.cpp on a jailbroken PS5: run any GGUF model natively on the console, starting with Qwen 3.8

Fleet: one model across several consoles over RPC, as its own build (#35)

Nicholas Tindlea90b66c82cd6
diff --git a/.github/workflows/fleet-host.yml b/.github/workflows/fleet-host.yml
new file mode 100644
index 0000000..b4b41bc
--- /dev/null
+++ b/.github/workflows/fleet-host.yml
@@ -0,0 +1,65 @@
+name: Fleet validation (not PS5 hardware)
+on:
+ pull_request:
+ paths:
+ - 'fleet/**'
+ - 'patches/*.patch'
+ - 'patches/fleet/**'
+ - 'ps5/app/fleet_worker*'
+ - 'tests/fleet*'
+ - 'tests/test_fleet_*'
+ - 'tests/make_fleet_fixture.py'
+ - 'tests/requirements-fleet.txt'
+ - 'scripts/build-fleet-host.sh'
+ - 'scripts/test-fleet.sh'
+ - 'third_party/llama.cpp'
+ - '.github/workflows/fleet-host.yml'
+ push:
+ branches: [main, 'fleet/**']
+ paths:
+ - 'fleet/**'
+ - 'patches/*.patch'
+ - 'patches/fleet/**'
+ - 'ps5/app/fleet_worker*'
+ - 'tests/fleet*'
+ - 'tests/test_fleet_*'
+ - 'tests/make_fleet_fixture.py'
+ - 'tests/requirements-fleet.txt'
+ - 'scripts/build-fleet-host.sh'
+ - 'scripts/test-fleet.sh'
+ - 'third_party/llama.cpp'
+ - '.github/workflows/fleet-host.yml'
+permissions:
+ contents: read
+concurrency:
+ group: fleet-host-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+jobs:
+ host-rpc:
+ name: Host safety tests and real two-worker CPU RPC
+ runs-on: ubuntu-24.04
+ timeout-minutes: 25
+ env:
+ CMAKE_BUILD_PARALLEL_LEVEL: '2'
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
+ with:
+ python-version: '3.12'
+ - name: Pinned llama.cpp only (no PS5 SDK or driver download)
+ run: git submodule update --init --depth 1 third_party/llama.cpp
+ - name: Host build prerequisites (no trained model download)
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends cmake ninja-build g++
+ python -m pip install --disable-pip-version-check -r tests/requirements-fleet.txt
+ - name: Safety tests, RPC regressions and deterministic fleet inference
+ run: scripts/test-fleet.sh --rpc
+ - name: State the validation boundary
+ if: always()
+ run: |
+ echo '## Fleet host validation' >> "$GITHUB_STEP_SUMMARY"
+ echo 'Tests use a generated, untrained GGUF and loopback CPU workers; no console or trained model download is required.' >> "$GITHUB_STEP_SUMMARY"
+ echo 'This job does not cross-compile the PS5 title or validate PS5 Vulkan, hardware memory, or multi-console performance.' >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/native-build.yml b/.github/workflows/native-build.yml
index 45a7c93..8934aa3 100644
--- a/.github/workflows/native-build.yml
+++ b/.github/workflows/native-build.yml
@@ -30,8 +30,13 @@ jobs:
build/model_plan_test
ps5-title:
- name: Full PS5 title cross-build and static package checks
+ name: Full PS5 title cross-build and static package checks (${{ matrix.variant }})
runs-on: ubuntu-24.04
+ strategy:
+ fail-fast: false
+ matrix:
+ # fleet: PS5LM_FLEET=1, the RPC worker build released as ps5lm-app-fleet (docs/FLEET.md)
+ variant: [default, fleet]
timeout-minutes: 45
container:
# Official Debian image; trixie supplies compatible LLVM19/SPIRV host tools.
@@ -44,6 +49,7 @@ jobs:
DEBIAN_FRONTEND: noninteractive
BUILD_JOBS: '2'
LLVM_CONFIG: /usr/bin/llvm-config-19
+ PS5LM_FLEET: ${{ matrix.variant == 'fleet' && '1' || '0' }}
steps:
- name: Public cross-build prerequisites
run: |
@@ -69,7 +75,7 @@ jobs:
- name: State the full-build validation boundary
if: always()
run: |
- echo '## Native PS5 title cross-build' >> "$GITHUB_STEP_SUMMARY"
- echo 'Builds the pinned public SDK/runtime, patched RADV, UI and existing app title; checks ELF/FSELF structure.' >> "$GITHUB_STEP_SUMMARY"
+ echo "## Native PS5 title cross-build (${{ matrix.variant }})" >> "$GITHUB_STEP_SUMMARY"
+ echo 'Builds the pinned public SDK/runtime, patched RADV, UI and app title; checks ELF/FSELF structure.' >> "$GITHUB_STEP_SUMMARY"
echo 'Build tools and checksum-verified public SDK/driver dependencies download; no model or proprietary firmware is needed.' >> "$GITHUB_STEP_SUMMARY"
echo 'This is static cross-build validation, not console boot, Vulkan execution, PS5 emulation or model inference.' >> "$GITHUB_STEP_SUMMARY"
diff --git a/.gitignore b/.gitignore
index 1920350..743212d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,7 @@ models/
# the app's home screen backgrounds, made from ps5/app/sce_sys/source by scripts/build-app.sh
ps5/app/sce_sys/*.dds
+
+# Python bytecode from the fleet controller and its tests
+__pycache__/
+*.pyc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e020aef..f14b264 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ v0.1.x are the upstream payload releases by cobanov.
## [Unreleased]
### Added
+- **Fleet, experimental: one model across several consoles.** A PC runs the controller
+ (`python3 -m fleet serve`) and one llama-server; each PS5 runs the fleet build of the app as an
+ RPC worker that holds a contiguous run of the model's layers on its GPU. Dense `llama` and `qwen2`
+ GGUFs only for now; Qwen 3.8's `qwen35` layout is refused by the planner. The fleet build is a
+ separate zip, `ps5lm-app-fleet-vX.Y.Z.zip` (`PS5LM_FLEET=1 scripts/build-app.sh`); the normal
+ app has no RPC code. A worker starts only when `/data/PS5LM/fleet-worker.txt` names the
+ console's own private address, a port below 40000 (the PS5 refuses higher ones) and the
+ acknowledgement, because RPC has no authentication:
+ keep it on an isolated network. `docs/FLEET.md` is the guide. By @ntindle in #35.
- **An opt-in endpoint for the model's own numbers**: `POST /v1/introspect` answers with the whole
logit row at the positions you name, the top candidates with their probabilities, the entropy, and
one row of a named graph tensor (`l_out`, `ffn_swiglu`, `ffn_out`, `attn_out`, `attn_norm`, `ffn_norm`,
diff --git a/README.md b/README.md
index aa30ce8..4767617 100644
--- a/README.md
+++ b/README.md
@@ -169,6 +169,18 @@ ggml-vulkan on [PS5_Vulkan](https://github.com/mihawk-99/PS5_Vulkan)'s RADV, bui
a Home Assistant integration that wakes the console from rest mode, starts PS5LM, waits for the
model and puts the console back to sleep when done, with the model and console readings as sensors.
+## Experimental multi-console fleet
+
+[Fleet](docs/FLEET.md) splits one dense `llama`/`qwen2` GGUF across several
+consoles over llama.cpp's RPC, controlled by one PC: one model across their
+memory, not a copy on each. It is a separate build of the app, released as
+`ps5lm-app-fleet-vX.Y.Z.zip` next to the normal zip; the normal app has no RPC
+code. Two-worker CPU inference is tested in CI, the fleet title cross-builds
+there, and a PS5 worker has served a model together with a PC, but it is
+**experimental**: Qwen 3.8's `qwen35` layout is not admitted by
+this first planner yet, and RPC has no authentication, so it belongs on an
+isolated network you trust. See [validation and limits](docs/FLEET-VALIDATION.md).
+
## Thanks
- [abhi245y](https://github.com/abhi245y), who built the native GPU app this one grew from (PS5LM Plus).
diff --git a/docs/CI.md b/docs/CI.md
index 3e12f55..c0d53e7 100644
--- a/docs/CI.md
+++ b/docs/CI.md
@@ -9,10 +9,16 @@ are cancelled. There are two independent jobs:
GGUF `model_plan_test.cpp`, and regressions for dashboard compiler job limits
and propagation of failed background compilers. No submodule or model download
is needed for these checks.
-- **Full PS5 title cross-build** (45-minute limit, two compiler jobs): bootstrap
- the public SDK, reproduce clean-room `libc.prx`, build patched RADV and the
- existing llama-server/native dashboard, package the title folder, and inspect
- its ELF/FSELF structure and integrity. It does not execute the resulting title.
+- **Full PS5 title cross-build** (45-minute limit, two compiler jobs), once for
+ each build variant: `default`, and `fleet` with `PS5LM_FLEET=1` (the RPC worker
+ build, [FLEET.md](FLEET.md)). Each bootstraps the public SDK, reproduces
+ clean-room `libc.prx`, builds patched RADV and llama-server/native dashboard,
+ packages the title folder, and inspects its ELF/FSELF structure and integrity.
+ It does not execute the resulting title.
+
+[`fleet-host.yml`](../.github/workflows/fleet-host.yml) runs the fleet's host tests
+and a real two-worker CPU RPC inference (`scripts/test-fleet.sh --rpc`), only when
+the fleet's own files or the llama.cpp patches change.
The second job downloads build tools, source dependencies and checksum-verified
public SDK archives. It does **not** download a trained model or proprietary
diff --git a/docs/FLEET-VALIDATION.md b/docs/FLEET-VALIDATION.md
new file mode 100644
index 0000000..ec5e859
--- /dev/null
+++ b/docs/FLEET-VALIDATION.md
@@ -0,0 +1,251 @@
+# Fleet validation — 2026-10-21–22
+
+> A record of the original validation. Since then the RPC patches moved to
+> `patches/fleet/` and the worker to the `PS5LM_FLEET=1` build, and
+> `scripts/test-fleet-native.sh` and `test-fleet-title.sh` were folded into
+> `PS5LM_FLEET=1 scripts/test-native-build.sh` ([FLEET.md](FLEET.md)).
+
+## Result
+
+A working host-side increment: **one model split over two real CPU RPC processes**,
+including the actual `python3 -m fleet serve` path. Experimental PS5 worker source
+is integrated. **The complete RPC-enabled native PS5 title now cross-builds and
+passes static ELF/FSELF validation. No console inference has been tested.**
+At the time of the initial local validation below, no public listener or console
+deployment was performed. Hosted CI results are reported separately in the PR
+checks. This is not a hardware-validated PS5 release.
+
+## Revisions
+
+| Component | Commit |
+|---|---|
+| PS5LM base | `c4595784ce75c1d58777b11ef812d3e087e74296` |
+| llama.cpp | `04f7226a2c12c7f382c545a6db5a034266aa53cb` |
+| ps5-homebrew-ui | `bf44d80384d5b8f8f4f213cf98d748887211328d` |
+
+All existing llama.cpp patches 0001–0009 and new patches 0010–0012 were applied.
+`fleet-build.json` records the exact patch hashes and local host binary checksum.
+The wire protocol remains upstream RPC 8.0.0; a handshake is not revision
+attestation. Both ends must be built from the same sources.
+
+## Passed
+
+Final aggregate command (Linux sandbox, no system-wide package installation):
+
+```sh
+CMAKE="$PWD/.deps/host-tools/cmake/data/bin/cmake" \
+NINJA="$PWD/.deps/host-tools/bin/ninja" \
+scripts/test-fleet.sh --rpc
+```
+
+Public CMake 4.4.4 and Ninja 1.13.2 wheels were installed under `.deps/host-tools`
+because those host tools were absent. On a normal configured system the command
+is simply `scripts/test-fleet.sh --rpc`. NumPy and PyYAML supply fixture generation only.
+
+| Check | Outcome / scope |
+|---|---|
+| Python unit/security suite | **52 passed**: GGUF parsing, unsafe/unknown layouts, download policy/framing/cleanup (mocked HTTPS), budgets, KV, split mapping, preflight failures, binary verification, SIGTERM child cleanup |
+| Worker configuration | **43 checks passed**, no listener |
+| Worker runtime/file tests | **19 checks passed**, fake ggml backend, no GPU/socket |
+| Worker sanitizers | ASan + UBSan passed; LeakSanitizer disabled because sandbox ptrace prevents it |
+| Worker compile | Linux C++17 compile against real pinned ggml headers with `-Wall -Wextra -Werror` |
+| Existing model planner | Original `model_plan_test` synthetic-header test passed |
+| CPU/RPC build | llama-server, llama-cli, ggml-rpc-server, test-rpc-multi-server built |
+| Upstream RPC regression | `test-rpc-multi-server` **passed** |
+| Server-side NO_COMM regression | Rank 0 and rank 1 peer commands refused; ordinary device-count RPC remained usable; test ports loopback/reserved |
+| Real two-worker inference | **Passed**, not mocked; actual tensor allocation and graph execution on both processes |
+| Actual fleet CLI | **Passed** manifest → preflight → plan → llama-server → inference with new workers |
+| Cleanliness | `git diff --check`, shell/Python syntax checks passed; no leftover llama-server/RPC test processes |
+
+### Inference evidence
+
+Fixture: 231,136-byte, four-block dense `llama` GGUF with deterministic random
+**untrained** weights, 32-dimensional embeddings, 4 query heads, 2 KV heads,
+256-token model context. It is generated locally by `tests/make_fleet_fixture.py`;
+no trained model was downloaded. Tests used context 128, one sequence, FP16 KV,
+two CPU RPC workers, and tensor-split `3,7`.
+
+Verbose direct-RPC logs assign:
+
+| Logical layer | Device |
+|---|---|
+| Blocks 0, 1 | RPC0 (worker A) |
+| Blocks 2, 3 | RPC1 (worker B) |
+| Output slot 4 | RPC1 |
+
+Each direct worker made 3 buffer allocations and 9 graph compute/recompute calls.
+The local reference, direct two-worker execution, and actual fleet CLI all
+returned token IDs:
+
+```text
+282, 131, 193, 131, 193, 131, 193, 131
+```
+
+All 40 top-five log-probability values per run matched the local baseline, with
+maximum absolute error **0.0** here (test tolerance `1e-5`). This proves the tested
+execution path, not useful text quality, larger-model correctness or performance.
+
+Evidence is in `build/fleet-final-validation.log`, `build/fleet-smoke/result.json`,
+its worker/controller logs and JSON responses, plus
+`build/fleet-host/fleet-build.json`. Re-running the scripts regenerates this
+evidence locally; generated models, binaries, logs and SDK archives are not
+committed to the repository.
+
+## CI preparation — 2026-10-22
+
+Re-ran `scripts/test-fleet.sh --rpc` successfully after adding the bounded
+GitHub Actions workflow: the same 52 Python, 43 configuration and 19 runtime
+checks passed, as did both RPC regressions and the actual fleet CLI inference
+comparison (maximum log-probability error 0.0). The workflow passed actionlint
+v1.7.7 and YAML permission/event checks. Actions use verified commit pins;
+the fixture dependencies are pinned in `tests/requirements-fleet.txt`. This is local pre-publication evidence;
+refer to the PR checks for the hosted run.
+
+### Hosted dependency correction — 2026-10-22
+
+The first fork run built all C++ targets and passed the safety/RPC regression
+checks, but fixture generation exposed a missing transitive `gguf` import:
+PyYAML. The workflow now installs a pinned fixture requirements file, and the
+test script checks imports before compiling. The complete suite was re-run
+successfully in a fresh Python virtual environment containing only those
+requirements; both inference comparisons again had maximum error 0.0. See the
+PR/fork Actions run for the hosted result on the current commit.
+
+## Initial full PS5 title build attempt — 2026-10-21
+
+The upstream tree had no checked-in CI workflow. Its documented route is a Linux
+cross-build using PS5_Vulkan, its pinned forks, RADV and homebrew SDK tooling.
+The workflow now separates host inference, native-object compilation and the
+full-title cross-build. The first two jobs alone do not prove a title build. The evidence below records the initial local
+full-title build attempt; the SDK/runtime gaps were subsequently resolved for
+the native-object gate below.
+
+1. Ran `bash scripts/build-app.sh`: stopped because UI submodule was uninitialized.
+2. Initialized its pinned commit and read its `AGENTS.md`; reran the official build.
+3. The upstream OpenGL SDK endpoint returned **HTTP 404**:
+ `https://github.com/blackbearreloaded/ps5-opengl/releases/download/v1.0.0/ps5-opengl-sdk-1.0.0.tar.gz`
+4. Followed the alternative already documented in `docs/BUILDING.md`:
+ `https://github.com/MyLuxy/overdrive-deps/releases/download/ps5-opengl-v1.0.0/ps5-opengl-sdk-1.0.0.tar.gz`
+5. Downloaded exactly 226,263,775 bytes, bounded by 250 MB / 120 seconds. Computed
+ archive SHA-256 matched the submodule's pinned value:
+ `f93643c04c843d56143b00951df1f8042ea7706ae9f19e4e9abf158e1ead77c5`.
+6. Ran official `fetch-opengl-sdk.sh`: extraction and pinned manifest verification
+ passed (manifest SHA-256
+ `f4b91f672be037fbac3f82494f1225deaf4c227a03f37ac3ffa56abb213b943f`).
+7. Reran official `scripts/build-app.sh`: **exit 2**, exact next blocker:
+ `.deps/src/PS5_Vulkan/.deps/native/radv-release/lib/libvulkan_radeon.ps5.a` missing.
+
+At that initial attempt, also absent under `.deps/src/PS5_Vulkan`:
+`build/host/ps5-native-tool`,
+`runtime/libc.prx`, `.deps/native/ps5-payload-sdk/bin/prospero-lld` and its C++
+headers. The compiler did not run in that initial full-title attempt. Downloading
+the standalone legacy payload SDK
+would not replace the native Vulkan title dependencies. No unverified PS5 binary
+is included.
+
+Reproduction: follow `docs/BUILDING.md` to prepare the pinned PS5_Vulkan/Mesa/SDK
+sources and host packages, apply `patches/mesa`, run PS5_Vulkan's
+`tools/setup-native-dependencies.sh`, `tools/build-radv.sh release` and `make app`,
+then run this repository's `scripts/build-app.sh`. The verified OpenGL mirror
+resolves the removed archive, not the remaining RADV setup.
+
+Build evidence: `build/fleet-ps5-build-attempt*.log`,
+`build/fleet-opengl-mirror-download.log`, `build/fleet-opengl-mirror-verify.log`.
+
+## Native-target follow-up — 2026-10-22
+
+Using the public documented bootstrap (not a proprietary SDK or firmware dump):
+
+| Component | Pinned input |
+|---|---|
+| PS5_Vulkan | `f410e67a0241b3e8edcdbcd2a9b285dfc4a412ed` |
+| PS5_PayloadSDK fork | `b83202be73e930050e00de0f1b4d9ec46c0391bf` |
+| Base homebrew SDK v0.42 archive SHA-256 | `8cfbc7cd5811e719eb4f0c47eea668d3dc7b40bc8ab11c4a5031d40c23ec02da` |
+| zlib 1.3.2 archive SHA-256 | `bb329a0a2cd0274d05519d61c667c062e06990d72e125ee2dfa8de64f0119d16` |
+
+`fleet_worker.cpp`, patched `ggml-rpc.cpp`, and patched `transport.cpp` compile
+successfully through PS5LM's actual `ps5cxx` wrapper. Target macros include
+`__PROSPERO__`, `__SCE__` and `__FreeBSD__=9`; outputs are x86-64 relocatable ELF
+objects, not executable PS5 titles. The worker's compile uses `-Werror`.
+
+The clean-room runtime reproducer builds two copies and verifies upstream's
+recorded hashes, including signed `libc.prx`:
+`e6ff45d16adf687855cc3b33b0c8a4132b6504360b221e0a34c7e99fb3ba0036`.
+No Sony implementation or console dump is downloaded. Local Clang 19 validation
+passed; the repeatable `scripts/test-fleet-native.sh` also passed from a fresh
+dependency cache using Clang 18.1.8, which is the object-only CI compiler family.
+The separate native job's status is in the fork Actions checks.
+
+The object-only check must not be described as a full build, console boot,
+Vulkan validation or PS5 emulation. The full-title follow-up below is separate. [QEMU's
+documented system/user modes](FLEET.md#ps5-target-compile-and-runtime-check-no-console)
+do not provide the PS5-specific AGC/loader/direct-memory environment, so a generic
+Linux/FreeBSD VM is not an equivalent hardware gate.
+
+## Full native title cross-build — 2026-10-22
+
+`scripts/test-fleet-title.sh` passed locally using public Debian 13/Clang 19
+packages and the documented upstream build scripts:
+
+- Mesa base `1ba9874f478657ccf6da72ce55f0260164cc0bd0` plus all three `patches/mesa`
+ commits yields deterministic source revision
+ `9e0a7c63bc6d4b6bcb60831163bb3fe9f46e91ea`.
+- All 389 host shader-tool tasks and 794 PS5 RADV tasks completed; the archive
+ includes the actual PS5 winsys, not a stub or host Vulkan replacement.
+- The real title CMake build exposed `strnlen` hidden by `_XOPEN_SOURCE=600`.
+ Patch 0011 replaces it with the equivalent bounded C++ scan. The faster native
+ check now uses those actual CMake feature-test macros, so it catches regressions.
+- The patched Vulkan/RPC/server libraries and native console dashboard compiled
+ and linked into a complete title folder. Optional downloaded browser assets
+ are omitted, not the console UI. No trained model or proprietary firmware
+ was downloaded.
+- `eboot.elf` and `eboot.bin` both pass upstream `tools/inspect.sh` with zero
+ static errors: FreeBSD OSABI 9, ABI 2, type `0xfe10`, aligned LOADs and required
+ process metadata. The native tool's FSELF check also reports valid integrity.
+
+The first local passing `eboot.bin` was 100,329,398 bytes, SHA-256
+`58a2bd3aec133b8d1bffe7a63f534fb3ff8271857ca3bf74b595055b263a0317`.
+That identifies this local artifact, not a promise of bit-identical builds across
+paths/compiler versions. Only the upstream clean-room runtime has a fixed
+reproduction checksum. Package binaries, SDKs and logs are not committed.
+
+Evidence: `build/fleet-native-full/title-validation.log` and
+`build/fleet-title/result.json`. Reproduce using the package list in the
+workflow's digest-pinned Debian `ps5-title` job and `scripts/test-fleet-title.sh`.
+The fresh hosted run, rather than this local cache-backed aggregate, establishes
+whether the entire CI bootstrap works from scratch; see fork Actions results.
+
+This is a real cross-build/package check, **not a console boot or hardware test**.
+
+## Review fixes and remaining boundaries
+
+Independent review plus real host execution found and corrected:
+- Missing binary checksum in the host manifest.
+- Wrapper SIGTERM orphaning the server.
+- 16-node plans exceeding the pinned CLI's accepted split count (now max 15).
+- Unmodeled shared RoPE weight duplication (those layouts now rejected).
+- Confusing RPC buffer names with CLI device names (actual names RPC0, RPC1).
+- Server peer-communication commands opening an additional wildcard listener
+ (server-side NO_COMM rejection plus forced worker/controller setting).
+- PS5/BSD socket `sin_len` initialization and SIGPIPE portability concerns.
+
+Not verified: actual console boot/runtime import resolution, driver/device memory allocations,
+Vulkan kernels, actual worker-screen rendering, real network drops on PS5,
+thermal behaviour, sustained inference, large GGUF models or multi-console
+performance. Fresh HTTPS GGUF acquisition is covered by offline downloader
+tests, not a live download/inference integration run. The OpenGL SDK download is
+separate and does not validate the model acquisition path.
+
+Qwen 3.8 27B is **not supported by this fleet estimator**: PS5LM lists its GGUF
+architecture as `qwen35`, whose hybrid/recurrent memory model is intentionally not
+guessed. See `FLEET.md` for the narrow supported layouts and extension path.
+
+## Next hardware gate
+
+With a title built as above: use an isolated wired network, two consoles,
+one controller and a small admitted dense model. Verify both RPC handshakes,
+actual per-device allocation logs, identical greedy output against a local
+reference, memory high-water marks, disconnect/close recovery and title restarts
+between models. Only then test a model too large for one console; use measured
+memory reserves and benchmark prefill/decode separately. Nothing in the current
+host results substitutes for that gate.
diff --git a/docs/FLEET.md b/docs/FLEET.md
new file mode 100644
index 0000000..c63a903
--- /dev/null
+++ b/docs/FLEET.md
@@ -0,0 +1,258 @@
+# Experimental fleet: one model, several PS5 workers
+
+**Status: host controller and an opt-in PS5 worker in a separate fleet build of
+the title; CPU RPC inference and the fleet title's cross-build are tested in CI.
+On hardware, one PS5 worker has served one model together with a Linux CPU
+worker (2026-11-01, below); more consoles at once are not validated by the
+maintainers.** This is not a performance claim. The default
+PS5LM title has no RPC code; releases ship the fleet build as its own zip,
+`ps5lm-app-fleet-vX.Y.Z.zip`.
+
+## Architecture
+
+```
+GGUF file / public HTTPS URL
+ |
+ Linux/macOS controller: bounded download + SHA256 + GGUF inspection
+ | contiguous layer/KV capacity plan
+ one llama-server (API bound to 127.0.0.1)
+ / \
+ llama.cpp RPC llama.cpp RPC
+ PS5 A: Vulkan layers 0..k PS5 B: Vulkan layers k+1..L + output
+```
+
+This is **model parallelism, not load balancing**. A request needs every selected
+worker. The host holds the complete GGUF on disk, loads input/shared tensors
+locally, and upstream llama.cpp transfers the assigned tensors to each RPC
+backend. There is no separate shard-file format, full-model replica per worker,
+custom activation protocol, or independent model server on each console. RPC
+also manages the distributed computation and per-layer KV cache. Transfers may
+return through the controller; this does not promise direct PS5-to-PS5 pipelines.
+
+The pinned dependency already supplies this machinery. We keep its wire format
+(RPC **8.0.0**) and use `--split-mode layer`, an explicit RPC-only device list,
+and `--tensor-split`. Midpoint boundaries reproduce the pinned loader's `L+1`
+logical slots (the extra slot is output), avoiding floating-point boundary drift.
+Host accelerators are not silently added. The planner minimises the maximum
+estimated memory utilisation for the **given node order**, not latency or tokens/s.
+
+### Deliberately narrow model admission
+
+- 2–15 selected workers, exactly one device per endpoint, at least one repeating
+ layer per worker. The pinned CLI rejects 16 tensor-split entries.
+- Complete, single-file, little-endian GGUF v3, **dense `llama` or `qwen2`**
+ layouts, at most 512 layers, known tensor encodings and validated shapes.
+- One sequence, FP16 K/V cache, fixed context no greater than training context.
+ KV is rounded up to 256 tokens conservatively. Flash attention, automatic fit,
+ lazy loading and opportunistic host-operation offload are disabled.
+- Unknown architectures, hybrid/recurrent state, MoE, split GGUF, missing tensors,
+ unsupported quantizations and replicated RoPE weight tensors fail closed.
+- Budgets include exact inspected weight spans, tied-output duplication, estimated
+ per-layer KV and operator-selected reserves. Reserves must cover allocations,
+ dequantization, activation/compute buffers and backend overhead. A successful
+ plan **is not an allocation guarantee or reservation**. Live memory can change.
+
+**Why not the README's Qwen 3.8 27B yet?** `docs/MODELS.md` identifies that model's
+architecture as `qwen35`. PS5LM's normal single-console planner has broader
+architecture support than this first fleet estimator. The fleet does not yet
+model Qwen35's hybrid/recurrent state and placement, so it rejects that model
+rather than extrapolating a dense-transformer KV formula. Next step is a
+Qwen35-specific inspector/placement test against the pinned loader, followed by
+small real RPC inference and two-console validation. This is not a claim that
+upstream RPC itself cannot run it.
+
+## Security boundary — read before enabling workers
+
+Upstream explicitly calls RPC experimental and insecure. It has **no
+authentication or encryption** and is not an ordinary safe inference API.
+Anyone who can reach it must be treated as trusted with the worker process and
+memory. IP validation is not authentication.
+
+- Use an isolated, trusted wired LAN/VLAN with access limited to the controller.
+ No guest/shared LAN, port forwarding, public interface, public proxy or tunnel.
+- The worker requires an explicit numeric private IPv4 bind, high port and a
+ written acknowledgement. No wildcard `0.0.0.0` or hostname is accepted.
+- `GGML_RPC_NO_COMM=1` is forced by this integration. `patches/fleet/0002` makes the server
+ reject `COMM_INIT` before opening the extra wildcard peer listener in upstream
+ tensor-parallel code. This fleet uses layer splitting, not those collectives.
+- `patches/fleet/0001` initializes BSD socket lengths and suppresses SIGPIPE portably.
+ Neither patch makes arbitrary RPC requests safe. Keep the network isolated.
+- Workers have no disk tensor cache; normal PS5LM API, model auto-load and
+ downloads are disabled in worker mode. There is one controller per worker.
+- The host API is hard-bound to loopback; the CLI starts a foreground process,
+ cleans it up on Ctrl+C/SIGTERM, and does not deploy consoles, modify firewall
+ rules, create credentials, enroll nodes or persist a background service.
+
+## Revisions and build
+
+Developed on PS5LM `c4595784ce75c1d58777b11ef812d3e087e74296`, with llama.cpp
+`04f7226a2c12c7f382c545a6db5a034266aa53cb` and UI
+`bf44d80384d5b8f8f4f213cf98d748887211328d`. Build host and workers from the same
+checkout and patch set. The host manifest checks the local binary checksum and
+llama revision. A remote handshake checks **protocol compatibility**, not a remote
+Git revision or source attestation; the operator must deploy matching builds.
+
+### Host (CPU + RPC)
+
+Python 3.10+, a C++17 compiler, CMake, Ninja and Git are required. NumPy and
+PyYAML are needed only to generate the tiny test fixture, not for the controller.
+
+```sh
+git submodule update --init --depth 1 third_party/llama.cpp
+scripts/build-fleet-host.sh
+# build/fleet-host/bin/{llama-server,ggml-rpc-server,...}
+# build/fleet-host/fleet-build.json (revision, patches, binary SHA256)
+```
+
+The host script applies the repository's numbered llama.cpp patches and
+`patches/fleet`, disables
+GPU backends and RDMA, and builds the RPC tools plus the upstream multi-server
+regression. It does not fetch model weights or start a listener. Set `CMAKE`,
+`NINJA` or `CMAKE_BUILD_PARALLEL_LEVEL` for local tool locations/resources.
+
+### PS5 worker title — the fleet build
+
+Follow [BUILDING.md](BUILDING.md) to prepare PS5_Vulkan, its pinned PS5_Mesa and
+PS5_PayloadSDK forks, patched RADV, native packaging tool, `libc.prx` and the
+checksum-pinned ps5-opengl SDK. Then:
+
+```sh
+git submodule update --init --depth 1
+PS5LM_FLEET=1 scripts/build-app.sh
+```
+
+`PS5LM_FLEET=1` is what makes it the fleet build: llama.cpp with `GGML_RPC=ON`
+(`GGML_RPC_RDMA=OFF`) and `patches/fleet` on top of the numbered patches, and
+the title with `fleet_worker.cpp` and the worker's startup mode in `main.cpp`.
+Without it, `scripts/build-app.sh` builds the default title with none of that,
+and takes `patches/fleet` back out of the llama.cpp checkout if a fleet build
+left it there. Both variants have the same title ID, so installing one replaces
+the other; settings and models in `/data/PS5LM` stay. `scripts/release-app.sh`
+names the zip after the variant the last build made.
+
+CI builds both variants on every pull request: `native-build.yml` runs
+`scripts/test-native-build.sh` once as is and once with `PS5LM_FLEET=1`, each
+with the structural ELF/FSELF checks ([CI.md](CI.md)). That proves the fleet
+title links, not that it boots, that its Vulkan results are right, or that a
+real multi-console run works. QEMU is not a substitute: its
+[x86 system models](https://www.qemu.org/docs/master/system/target-i386.html)
+and [Linux/BSD user modes](https://www.qemu.org/docs/master/user/main.html)
+provide no PS5 loader, AGC or direct memory.
+
+On a console (2026-11-01): the fleet build on one PS5 (worker on
+port 8082) and `ggml-rpc-server` on a Linux PC's CPU, with
+`python3 -m fleet serve` on that PC, served `qwen2.5-0.5b-instruct-q4_k_m.gguf`
+with blocks 0–22 on the PS5 and block 23 plus the output on the PC, and
+answered a chat request correctly. This run found the 40000 port limit below;
+the worker writes its own and ggml's messages to `/data/PS5LM/app.log`.
+
+## Configure workers (only after building and validating the title)
+
+On each console, explicitly create `/data/PS5LM/fleet-worker.txt` containing
+**that console's own private IP**, port 1024–39999, and the exact acknowledgement:
+
+```text
+192.168.50.21:30052
+I_UNDERSTAND_RPC_IS_UNAUTHENTICATED
+```
+
+The port must be below 40000: a PS5 title gets "Permission denied" for 40000
+and up (measured on a console), so upstream's default 50052 cannot work there.
+Workers on a PC or Mac (`ggml-rpc-server`) can keep 50052.
+
+Restart PS5LM. It displays an experimental worker screen, not “Ready”: upstream
+has no ready callback, so the host must successfully handshake. A malformed,
+unreadable, non-regular or oversized config fails closed without starting the
+normal model server. No config keeps ordinary PS5LM behaviour. Remove this file
+and restart to return to single-console serving.
+
+**Restart the worker title between different model runs and after errors.**
+PS5LM documents retained Vulkan memory after in-process unload; this increment
+does not promise safe hot reload. Stop through the normal title-close / existing
+quit-file mechanism. A worker failure fails the whole model; no failover/resume
+is implemented.
+
+## Plan and serve from the controller
+
+Copy `fleet/nodes.example.json`, replace endpoints, and set conservative host and
+worker memory/reserve values from measurements. The example's 10 GiB worker
+budget with 2 GiB reserve is **an operator example, not measured fleet capacity**.
+`memory_mib` is the total allowed budget before subtracting `reserve_mib`.
+Do not run the normal local PS5 model alongside a worker.
+
+```sh
+# Offline capacity estimate from an already downloaded model:
+python3 -m fleet plan --model /models/model.gguf \
+ --nodes my-nodes.json --context 4096 --plan-out plan.json
+
+# The model argument also accepts a public HTTPS URL:
+python3 -m fleet plan --model 'https://example.org/model.gguf' \
+ --sha256 <expected-full-file-sha256> --nodes my-nodes.json --context 4096
+
+# Explicitly opt in after isolating/trusting the network:
+python3 -m fleet serve --model /models/model.gguf \
+ --nodes my-nodes.json --context 4096 --ack-insecure-rpc --plan-out run-plan.json
+```
+
+`plan` never connects to workers and reports `operator_budgets_only`. A URL is
+fully downloaded before inspection; the downloader validates public HTTPS and
+redirect destinations, pins DNS to the TLS connection, bounds bytes/time/disk,
+streams to a partial file and hashes the complete file. No gated model token,
+remote code, pickle or arbitrary extraction is supported. Prefer an expected
+`--sha256`; without it the digest records identity but not publisher authenticity.
+Default download limit is 32 GiB, with `--max-download-gib` available up to 128.
+Model URLs are not automatically downloaded in CI.
+
+`serve` validates the local binary manifest, performs the upstream RPC handshake,
+requires exactly the requested device order/topology, caps every operator budget
+by reported live free memory, and repeats preflight after acquisition. It then
+recomputes the plan and launches a single llama-server. It does **not** execute
+an old JSON plan as trusted instructions. Wait for llama-server readiness:
+
+```sh
+curl --fail http://127.0.0.1:8081/health
+curl --fail http://127.0.0.1:8081/completion \
+ -H 'Content-Type: application/json' \
+ -d '{"prompt":"The capital of France is", "n_predict":16, "temperature":0}'
+```
+
+Review server logs for actual device/layer allocation. Model-load failure,
+unsupported operations, worker disconnect or OOM is not converted into a
+successful fleet deployment. A snapshot/printed plan does not mean inference
+has started. Input and unsupported-operation work can still occur on the host;
+backend behaviour and memory must be checked on real consoles.
+
+## Tests / CI
+
+```sh
+scripts/test-fleet.sh # offline Python, C++ config/runtime, existing planner
+python3 -m pip install -r tests/requirements-fleet.txt # fixture only; use a venv
+scripts/test-fleet.sh --rpc # build + real localhost RPC regression/inference
+```
+
+The smoke creates a **231 KB, deterministic, untrained** four-layer GGUF. It runs
+a local CPU reference, two CPU RPC processes, and the actual `python -m fleet
+serve` CLI. It checks token IDs, assigned layers and per-worker computation.
+This proves a real distributed execution path on host CPUs, not useful language
+quality, PS5 GPU operation, large-model scaling or network speed. Tests use
+loopback only and clean up their child processes.
+
+`.github/workflows/fleet-host.yml` runs these checks on pull requests and pushes
+on `main` or `fleet/**`, using ordinary Ubuntu hosted runners, read-only
+repository permissions and per-ref cancellation. The host job has two parallel
+compiler processes and a 25-minute timeout; the separate native-object/runtime
+job has a 15-minute timeout. Full title CI uses a digest-pinned official Debian
+container on an ordinary Ubuntu runner, a two-CPU quota and a 45-minute timeout.
+Actions are pinned to commits; fixture dependencies are version-pinned.
+Jobs check out the pinned submodules they need and install public build tools.
+The host job downloads no trained model, PS5 SDK or driver. The native job does
+fetch the pinned public homebrew SDK and source dependencies, but no proprietary
+firmware, trained model, OpenGL SDK or RADV driver. The full-title job also
+builds patched RADV, downloads the checksum-verified OpenGL SDK and public
+ps5-exporter payload for packaging, and builds presentation assets. No secrets,
+`pull_request_target`, private runners or console are required.
+
+The inspected upstream revision had no checked-in workflow to reuse. This new
+workflow separates host inference, native-object compilation and full title
+cross-building. All three remain separate from the hardware gate. See the
+validation report for local evidence and the PR checks for hosted results.
diff --git a/fleet/__init__.py b/fleet/__init__.py
new file mode 100644
index 0000000..142cfe4
--- /dev/null
+++ b/fleet/__init__.py
@@ -0,0 +1 @@
+"""Experimental PS5LM layer fleet controller (standard library only)."""
diff --git a/fleet/__main__.py b/fleet/__main__.py
new file mode 100644
index 0000000..ef2d7cd
--- /dev/null
+++ b/fleet/__main__.py
@@ -0,0 +1,3 @@
+from .controller import main
+
+raise SystemExit(main())
diff --git a/fleet/controller.py b/fleet/controller.py
new file mode 100644
index 0000000..16958a7
--- /dev/null
+++ b/fleet/controller.py
@@ -0,0 +1,202 @@
+"""Host CLI: acquire one GGUF, estimate a split, and serve through real RPC.
+
+No node enrollment, payload deployment or network listener changes are performed.
+SPDX-License-Identifier: GPL-3.0-or-later
+"""
+from __future__ import annotations
+
+import argparse
+import copy
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import signal
+import subprocess
+import sys
+
+from .models import ModelError, fetch_model, inspect_file
+from .planner import FleetError, MIB, inventory, plan
+
+LLAMA_REVISION = '04f7226a2c12c7f382c545a6db5a034266aa53cb'
+ROOT = Path(__file__).resolve().parents[1]
+DEFAULT_BINARY = ROOT / 'build/fleet-host/bin/llama-server'
+
+
+def child_environment():
+ # Environment CLI overrides could enable unrelated endpoints, routers, models
+ # or caches. Do not silently let them invalidate the checked placement.
+ env = {k: v for k, v in os.environ.items() if not k.startswith('LLAMA_ARG_')}
+ env['GGML_RPC_NO_RDMA'] = '1'
+ env['GGML_RPC_NO_COMM'] = '1'
+ return env
+
+
+def command(binary, model_path, placement, port=8081):
+ nodes = placement['nodes']
+ return [str(Path(binary).resolve()), '--model', str(Path(model_path).resolve()),
+ '--rpc', ','.join(n['endpoint'] for n in nodes),
+ '--device', ','.join(n['device'] for n in nodes),
+ '--gpu-layers', 'all', '--split-mode', 'layer',
+ '--tensor-split', ','.join(str(v) for v in placement['tensor_split']),
+ '--fit', 'off', '--ctx-size', str(placement['context_tokens']), '--parallel', '1',
+ '--cache-type-k', 'f16', '--cache-type-v', 'f16', '--flash-attn', 'off',
+ '--load-mode', 'mmap', '--lazy-mode', 'off', '--no-op-offload',
+ '--batch-size', '128', '--ubatch-size', '128', '--no-warmup',
+ '--host', '127.0.0.1', '--port', str(port)]
+
+
+def probe(binary, config, timeout=20):
+ """Use the pinned client's own RPC handshake, never implement a second protocol.
+
+ An offline node, incompatible server, unexpected device topology or timeout
+ is an error. Free memory is a snapshot, not a reservation.
+ """
+ config = copy.deepcopy(inventory(config))
+ args = [str(Path(binary).resolve()), '--rpc', ','.join(n['endpoint'] for n in config['nodes']), '--list-devices']
+ try:
+ result = subprocess.run(args, capture_output=True, text=True, timeout=timeout, env=child_environment())
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise FleetError(f'RPC preflight failed ({type(exc).__name__}); no model server started') from exc
+ if result.returncode:
+ raise FleetError(f'RPC preflight exited {result.returncode}; check worker/revision/network.\n' + result.stderr[-2000:])
+ matches = re.findall(r'^\s*(RPC[0-9]+): ([0-9.]+:[0-9]+) \(([0-9]+) MiB, ([0-9]+) MiB free\)\s*$',
+ result.stdout, re.MULTILINE)
+ if len(matches) != len(config['nodes']):
+ raise FleetError('Expected exactly one RPC device per endpoint; refusing to guess topology')
+ for index, (node, match) in enumerate(zip(config['nodes'], matches)):
+ name, address, total_text, free_text = match
+ if name != f'RPC{index}' or address != node['endpoint']:
+ raise FleetError(f'{node["id"]}: RPC device order/endpoint differs from the requested inventory')
+ total, free = int(total_text), int(free_text)
+ if not 0 < free <= total:
+ raise FleetError(f'{node["id"]}: worker did not report valid free memory')
+ node['memory_mib'] = min(node['memory_mib'], free)
+ return config
+
+
+def checksum(path):
+ digest = hashlib.sha256()
+ with Path(path).open('rb') as stream:
+ for chunk in iter(lambda: stream.read(MIB), b''):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def read_json(path):
+ if Path(path).stat().st_size > MIB:
+ raise FleetError('JSON configuration exceeds 1 MiB')
+ return json.loads(Path(path).read_text())
+
+
+def verify_binary(binary):
+ binary = Path(binary).resolve()
+ if not binary.is_file() or not os.access(binary, os.X_OK):
+ raise FleetError(f'No executable at {binary}; run scripts/build-fleet-host.sh first')
+ manifest = binary.parent.parent / 'fleet-build.json'
+ if not manifest.is_file():
+ raise FleetError(f'Missing build manifest {manifest}; use scripts/build-fleet-host.sh')
+ data = read_json(manifest)
+ if data.get('llama_revision') != LLAMA_REVISION:
+ raise FleetError('Host build revision differs from the pinned PS5 worker; rebuild both together')
+ if data.get('server_sha256') != checksum(binary):
+ raise FleetError('Host binary checksum differs from fleet-build.json; rebuild the host')
+
+
+class _StopSignal(Exception):
+ def __init__(self, signum):
+ self.signum = signum
+
+
+def run_foreground(argv):
+ """Own the server until exit; wrapper SIGTERM must not orphan RPC users."""
+ child = None
+
+ def stop(signum, _frame):
+ raise _StopSignal(signum)
+
+ previous = signal.signal(signal.SIGTERM, stop)
+ try:
+ child = subprocess.Popen(argv, env=child_environment())
+ return child.wait()
+ except KeyboardInterrupt:
+ return 130
+ except _StopSignal as exc:
+ return 128 + exc.signum
+ finally:
+ signal.signal(signal.SIGTERM, previous)
+ if child is not None and child.poll() is None:
+ child.terminate()
+ try:
+ child.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ child.kill()
+ child.wait()
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description='Experimental PS5LM single-model layer fleet (not a load balancer)')
+ parser.add_argument('action', choices=('plan', 'serve'))
+ parser.add_argument('--model', required=True, help='single-file local GGUF or public HTTPS URL')
+ parser.add_argument('--nodes', required=True, help='inventory JSON; see fleet/nodes.example.json')
+ parser.add_argument('--context', type=int, default=4096, help='total context for one sequence, default 4096')
+ parser.add_argument('--binary', default=str(DEFAULT_BINARY))
+ parser.add_argument('--cache-dir', default=str(ROOT / 'models/fleet-cache'))
+ parser.add_argument('--sha256', help='optional expected full-file SHA256')
+ parser.add_argument('--max-download-gib', type=int, default=32)
+ parser.add_argument('--port', type=int, default=8081, help='controller API port, localhost only')
+ parser.add_argument('--plan-out', help='write reviewed JSON plan (not executable state)')
+ parser.add_argument('--ack-insecure-rpc', action='store_true',
+ help='acknowledge RPC is unauthenticated and all endpoints are on an isolated trusted network')
+ args = parser.parse_args(argv)
+ try:
+ if not 1 <= args.port <= 65535 or not 1 <= args.max_download_gib <= 128:
+ raise FleetError('Port must be 1..65535 and download limit 1..128 GiB')
+ if args.sha256 and not re.fullmatch(r'[0-9a-fA-F]{64}', args.sha256):
+ raise FleetError('--sha256 must contain exactly 64 hexadecimal characters')
+ config = inventory(read_json(args.nodes))
+ if args.action == 'serve':
+ if not args.ack_insecure_rpc:
+ raise FleetError('Serving requires --ack-insecure-rpc; isolate and trust every RPC peer first')
+ verify_binary(args.binary)
+ # Fail early, before downloading a large model. Probe again immediately
+ # before execution because downloading/hashing may take a long time.
+ config = probe(args.binary, config)
+ if args.model.startswith('https://'):
+ path, digest = fetch_model(args.model, args.cache_dir, max_bytes=args.max_download_gib * 1024**3,
+ max_cache_bytes=max(64, args.max_download_gib) * 1024**3, max_seconds=3600)
+ elif '://' in args.model:
+ raise FleetError('Only local paths and public HTTPS model URLs are accepted')
+ else:
+ path = Path(args.model).resolve()
+ # Reject devices/directories before hashing, and inspect metadata first.
+ inspect_file(path)
+ digest = checksum(path)
+ if args.sha256 and digest.lower() != args.sha256.lower():
+ raise FleetError('Full model SHA256 does not match --sha256; no server started')
+ model = inspect_file(path)
+ if args.action == 'serve':
+ config = probe(args.binary, config)
+ placement = plan(model, config, args.context)
+ placement.update(model_path=str(Path(path).resolve()), model_sha256=digest,
+ llama_revision=LLAMA_REVISION,
+ memory_source='min(operator_budget,live_RPC_snapshot)' if args.action == 'serve' else 'operator_budgets_only')
+ placement['argv'] = command(args.binary, path, placement, args.port)
+ encoded = json.dumps(placement, indent=2) + '\n'
+ if args.plan_out:
+ Path(args.plan_out).write_text(encoded)
+ print(encoded, end='', flush=True)
+ if args.action == 'plan':
+ return 0
+ print('Starting host llama-server; wait for its ready/health response. A printed plan is not successful inference.', file=sys.stderr)
+ # Foreground process: no daemon, enrollment, automatic console deployment,
+ # or insecure public API. Ctrl+C reaches both and stops this session.
+ return run_foreground(placement['argv'])
+ except (FleetError, ModelError, OSError, ValueError) as exc:
+ print(f'ps5lm-fleet: {exc}', file=sys.stderr)
+ return 2
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/fleet/models.py b/fleet/models.py
new file mode 100644
index 0000000..44bea40
--- /dev/null
+++ b/fleet/models.py
@@ -0,0 +1,630 @@
+"""Bounded, metadata-only GGUF v3 inspection and public HTTPS acquisition.
+
+No model code, pickle, tensor execution, or third-party packages are used. Metadata
+identity is deliberately NOT a checksum of model weights. Downloaded files have a
+separate complete-file SHA256. Size layouts follow ggml's GGUF specification and
+src/ggml-common.h; unsupported encodings/architectures fail closed.
+"""
+# Metadata inspection and bounded acquisition; no model or simulation execution.
+# SPDX-License-Identifier: GPL-3.0-or-later
+from __future__ import annotations
+
+import hashlib
+import http.client
+import ipaddress
+import math
+import os
+from pathlib import Path
+import re
+import queue
+import shutil
+import socket
+import ssl
+import stat
+import struct
+import tempfile
+import threading
+import time
+from urllib.parse import parse_qsl, quote, urljoin, urlsplit
+
+
+class ModelError(ValueError):
+ """Invalid model file or unsupported structural encoding."""
+
+
+class DownloadError(ModelError):
+ """Model download failed or violated public-HTTPS/resource policy."""
+
+
+MAX_HEADER_BYTES = 64 * 1024**2
+MAX_STRING_BYTES = 1024**2
+MAX_METADATA = 16_384
+MAX_ARRAY_ELEMENTS = 1_000_000
+MAX_TENSORS = 200_000
+MAX_LAYERS = 4096
+DEFAULT_MAX_BYTES = 16 * 1024**3
+DEFAULT_MAX_CACHE_BYTES = 64 * 1024**3
+DISK_RESERVE_BYTES = 16 * 1024**2
+# GGML type id -> (elements per block, bytes per block). Unknown types must not
+# be estimated from a filename or bits-per-weight label.
+GGML_TYPES = {
+ 0: (1, 4), # F32
+ 1: (1, 2), # F16
+ 2: (32, 18), # Q4_0
+ 3: (32, 20), # Q4_1
+ 6: (32, 22), # Q5_0
+ 7: (32, 24), # Q5_1
+ 8: (32, 34), # Q8_0
+ 9: (32, 36), # Q8_1
+ 10: (256, 84), # Q2_K
+ 11: (256, 110), # Q3_K
+ 12: (256, 144), # Q4_K
+ 13: (256, 176), # Q5_K
+ 14: (256, 210), # Q6_K
+ 15: (256, 292), # Q8_K
+ 30: (1, 2), # BF16
+}
+_SCALARS = {0: 'B', 1: 'b', 2: 'H', 3: 'h', 4: 'I', 5: 'i',
+ 6: 'f', 7: 'B', 10: 'Q', 11: 'q', 12: 'd'}
+_BLOCK = re.compile(r'^blk\.(0|[1-9][0-9]*)\.(.+)$')
+_ARRAY_KEYS = {f'{arch}.attention.{suffix}' for arch in ('llama', 'qwen2')
+ for suffix in ('head_count', 'head_count_kv', 'key_length', 'value_length')}
+_REQUIRED = ('attn_norm.weight', 'attn_q.weight', 'attn_k.weight',
+ 'attn_v.weight', 'attn_output.weight', 'ffn_norm.weight',
+ 'ffn_gate.weight', 'ffn_up.weight', 'ffn_down.weight')
+
+
+def _align(value, alignment):
+ return (value + alignment - 1) // alignment * alignment
+
+
+class _Reader:
+ def __init__(self, stream, file_size):
+ self.stream = stream
+ self.file_size = file_size
+ self.pos = 0
+ self.identity = hashlib.sha256()
+ self.endian = '<'
+
+ def read(self, size):
+ if size < 0 or self.pos + size > min(self.file_size, MAX_HEADER_BYTES):
+ raise ModelError('Truncated GGUF header or header exceeds 64 MiB inspection limit')
+ data = self.stream.read(size)
+ if len(data) != size:
+ raise ModelError('Truncated GGUF header')
+ self.pos += size
+ self.identity.update(data)
+ return data
+
+ def unpack(self, fmt):
+ return struct.unpack(self.endian + fmt, self.read(struct.calcsize(fmt)))[0]
+
+ def string(self, *, limit=MAX_STRING_BYTES):
+ size = self.unpack('Q')
+ if size > limit:
+ raise ModelError(f'GGUF string exceeds {limit} byte limit')
+ try:
+ return self.read(size).decode('utf-8')
+ except UnicodeDecodeError as exc:
+ raise ModelError('Invalid UTF-8 in GGUF header') from exc
+
+ def value(self, kind, *, retain=True):
+ if kind in _SCALARS:
+ result = self.unpack(_SCALARS[kind])
+ if kind == 7:
+ if result not in (0, 1):
+ raise ModelError('Invalid GGUF boolean')
+ return bool(result)
+ if isinstance(result, float) and not math.isfinite(result):
+ raise ModelError('Non-finite GGUF metadata')
+ return result
+ if kind == 8:
+ return self.string()
+ if kind != 9:
+ raise ModelError(f'Unknown GGUF metadata value type {kind}')
+ item_type = self.unpack('I')
+ count = self.unpack('Q')
+ if count > MAX_ARRAY_ELEMENTS:
+ raise ModelError('GGUF metadata array exceeds element limit')
+ if item_type == 9 or item_type not in {*_SCALARS, 8}:
+ raise ModelError('Nested/unknown GGUF metadata arrays are unsupported')
+ # Tokenizer vocabularies can be large; validate and hash their contents
+ # without retaining a million Python objects. Relevant numeric arrays
+ # are bounded by MAX_LAYERS and are needed for per-layer GQA.
+ keep = retain and count <= MAX_LAYERS
+ values = [] if keep else None
+ for _ in range(count):
+ item = self.value(item_type, retain=False)
+ if keep:
+ values.append(item)
+ return values if keep else {'array_length': count, 'array_type': item_type}
+
+
+def _positive_int(value, name, maximum=2**31 - 1):
+ if type(value) is not int or value <= 0 or value > maximum:
+ raise ModelError(f'{name} must be a positive bounded integer')
+ return value
+
+
+def _per_layer(metadata, key, layers, default=None):
+ value = metadata.get(key, default)
+ values = value if isinstance(value, list) else [value] * layers
+ if len(values) != layers:
+ raise ModelError(f'{key} must have exactly {layers} layer entries')
+ return [_positive_int(v, key) for v in values]
+
+
+def inspect_file(path) -> dict:
+ """Inspect a regular GGUF v3 file without reading tensor payloads.
+
+ Invalid structure raises ModelError. Unsupported, well-formed models return
+ supported=False and explanatory unsupported_reasons; never plan those models.
+ layer_bytes/input_bytes/output_bytes include actual tensor storage spans and
+ padding. Tied embeddings are additionally charged to the output stage. The
+ file header is reported separately, not presented as resident tensor memory.
+ """
+ path = Path(path)
+ try:
+ with os.fdopen(os.open(path, os.O_RDONLY | getattr(os, 'O_NONBLOCK', 0)), 'rb') as stream:
+ info = os.fstat(stream.fileno())
+ if not stat.S_ISREG(info.st_mode):
+ raise ModelError('GGUF input must be a regular file')
+ size = info.st_size
+ reader = _Reader(stream, size)
+ if reader.read(4) != b'GGUF':
+ raise ModelError('Not a GGUF file (expected GGUF magic)')
+ version_bytes = reader.read(4)
+ if version_bytes == struct.pack('>I', 3):
+ raise ModelError('Big-endian GGUF is not supported; use little-endian GGUF v3')
+ if struct.unpack('<I', version_bytes)[0] != 3:
+ raise ModelError('Only GGUF version 3 is supported')
+ tensor_count = reader.unpack('Q')
+ metadata_count = reader.unpack('Q')
+ if not 0 < tensor_count <= MAX_TENSORS:
+ raise ModelError('GGUF tensor count is zero or exceeds inspection limit')
+ if metadata_count > MAX_METADATA:
+ raise ModelError('GGUF metadata count exceeds inspection limit')
+ metadata = {}
+ for _ in range(metadata_count):
+ key = reader.string(limit=1024)
+ if not key or key in metadata:
+ raise ModelError('Empty or duplicate GGUF metadata key')
+ kind = reader.unpack('I')
+ metadata[key] = reader.value(kind, retain=key in _ARRAY_KEYS)
+ alignment = metadata.get('general.alignment', 32)
+ if type(alignment) is not int or alignment < 1 or alignment > 1024**2 or alignment & (alignment - 1):
+ raise ModelError('GGUF alignment must be a bounded power of two')
+ tensors = []
+ names = set()
+ unsupported = []
+ unknown_types = set()
+ for _ in range(tensor_count):
+ name = reader.string(limit=1024)
+ if not name or name in names:
+ raise ModelError('Empty or duplicate GGUF tensor name')
+ names.add(name)
+ dimensions = reader.unpack('I')
+ if not 1 <= dimensions <= 4:
+ raise ModelError('GGUF tensors must have one to four dimensions')
+ shape = [_positive_int(reader.unpack('Q'), 'tensor dimension') for _ in range(dimensions)]
+ elements = math.prod(shape)
+ if elements > 2**63 - 1:
+ raise ModelError('GGUF tensor element count exceeds signed 64-bit bound')
+ dtype = reader.unpack('I')
+ offset = reader.unpack('Q')
+ if offset % alignment:
+ raise ModelError(f'Tensor {name} has an unaligned offset')
+ nbytes = None
+ if dtype in GGML_TYPES:
+ block, block_size = GGML_TYPES[dtype]
+ if shape[0] % block:
+ raise ModelError(f'Tensor {name} row is not a whole quantization block')
+ nbytes = elements // block * block_size
+ else:
+ unknown_types.add(dtype)
+ tensors.append({'name': name, 'shape': shape, 'type': dtype,
+ 'offset': offset, 'nbytes': nbytes})
+ data_offset = _align(reader.pos, alignment)
+ if data_offset >= size:
+ raise ModelError('GGUF file has no tensor data')
+ header_hash = reader.identity.hexdigest()
+ except OSError as exc:
+ raise ModelError(f'Could not read GGUF file: {exc.strerror or type(exc).__name__}') from exc
+
+ tensors.sort(key=lambda t: t['offset'])
+ for index, tensor in enumerate(tensors):
+ start = tensor['offset']
+ end = tensors[index + 1]['offset'] if index + 1 < len(tensors) else size - data_offset
+ if start >= end or data_offset + end > size:
+ raise ModelError('GGUF tensor offsets overlap or lie outside the file')
+ if tensor['nbytes'] is not None and tensor['nbytes'] > end - start:
+ raise ModelError(f'Tensor {tensor["name"]} is truncated or overlaps its successor')
+ # Assign every payload byte, including file padding/gaps, exactly once.
+ tensor['span_bytes'] = end - start
+ if unknown_types:
+ unsupported.append('Unsupported GGML tensor type IDs: ' + ', '.join(map(str, sorted(unknown_types))))
+ architecture = metadata.get('general.architecture', '')
+ if not isinstance(architecture, str) or not architecture:
+ raise ModelError('Missing general.architecture string')
+ if architecture not in ('llama', 'qwen2'):
+ unsupported.append(f'Unsupported architecture {architecture!r}; only standard dense llama/qwen2 are supported. Hybrid/recurrent KV layouts are not inferred.')
+ if any(key.startswith('split.') for key in metadata) or re.search(r'-\d{5}-of-\d{5}\.gguf$', path.name):
+ unsupported.append('Split GGUF files are unsupported; supply a complete merged single-file model')
+ if metadata.get('general.type', 'model') != 'model':
+ unsupported.append('Only complete model GGUF files are supported (not adapters or vocabularies)')
+ layers = _positive_int(metadata.get(f'{architecture}.block_count'), 'block_count', MAX_LAYERS)
+ hidden = _positive_int(metadata.get(f'{architecture}.embedding_length'), 'embedding_length')
+ for suffix in ('expert_count', 'expert_used_count'):
+ if metadata.get(f'{architecture}.{suffix}', 0) != 0:
+ unsupported.append('Mixture-of-experts models are unsupported')
+ break
+ if any('.ssm.' in k or '.recurrent.' in k for k in metadata):
+ unsupported.append('Hybrid/recurrent model state is unsupported')
+ layer_bytes = [0] * layers
+ input_bytes = tensors[0]['offset']
+ output_bytes = 0
+ block_names = [set() for _ in range(layers)]
+ by_name = {t['name']: t for t in tensors}
+ shared = []
+ for tensor in tensors:
+ name = tensor['name']
+ match = _BLOCK.fullmatch(name)
+ if match:
+ layer = int(match.group(1))
+ if layer >= layers:
+ raise ModelError('Tensor block index exceeds declared block_count')
+ layer_bytes[layer] += tensor['span_bytes']
+ block_names[layer].add(match.group(2))
+ if any(marker in name for marker in ('_exps.', '_shexp.', 'ssm_', 'recurrent')):
+ unsupported.append('Expert/hybrid tensor layout is unsupported')
+ elif name.startswith('blk.'):
+ raise ModelError(f'Malformed block tensor name {name}')
+ elif name.startswith(('output.', 'output_norm.')):
+ output_bytes += tensor['span_bytes']
+ else:
+ input_bytes += tensor['span_bytes']
+ shared.append(name)
+ # Unknown shared tensors still consume memory. They also prevent declaring
+ # an unfamiliar graph to be a supported dense transformer.
+ # The pinned llama loader may duplicate RoPE weight tensors across devices.
+ # Refuse those layouts until replication is modeled, rather than charge a
+ # single host copy and undercount each remote stage.
+ if any('rope_freqs' in name or 'rope_factors' in name for name in by_name):
+ unsupported.append('RoPE weight-tensor replication across RPC devices is not yet modeled')
+ known_shared = {'token_embd.weight'}
+ unfamiliar = sorted(set(shared) - known_shared)
+ if unfamiliar:
+ unsupported.append('Unrecognized shared tensors: ' + ', '.join(unfamiliar[:8]))
+ for required in ('token_embd.weight', 'output_norm.weight'):
+ if required not in by_name:
+ unsupported.append(f'Missing required shared tensor {required}')
+ allowed_block = set(_REQUIRED) | {name.replace('.weight', '.bias') for name in _REQUIRED}
+ allowed_block |= {'rope_freqs.weight'}
+ for layer, available in enumerate(block_names):
+ unfamiliar_block = available - allowed_block
+ if unfamiliar_block:
+ unsupported.append(f'Block {layer} has unrecognized tensors: ' + ', '.join(sorted(unfamiliar_block)[:8]))
+ missing = set(_REQUIRED) - available
+ if missing:
+ unsupported.append(f'Block {layer} is incomplete: missing ' + ', '.join(sorted(missing)))
+ tied = 'output.weight' not in by_name and 'token_embd.weight' in by_name
+ replicated = by_name['token_embd.weight']['span_bytes'] if tied else 0
+ output_bytes += replicated
+ kv = []
+ # Only compute KV for a supported architecture with a complete known graph.
+ if not unsupported:
+ heads = _per_layer(metadata, f'{architecture}.attention.head_count', layers)
+ kv_heads = _per_layer(metadata, f'{architecture}.attention.head_count_kv', layers, heads)
+ key_lengths = metadata.get(f'{architecture}.attention.key_length')
+ value_lengths = metadata.get(f'{architecture}.attention.value_length')
+ for layer in range(layers):
+ if heads[layer] % kv_heads[layer]:
+ raise ModelError('attention.head_count must be divisible by head_count_kv')
+ if hidden % heads[layer] and (key_lengths is None or value_lengths is None):
+ raise ModelError('embedding_length must be divisible by head_count for implicit head sizes')
+ default_dims = [hidden // count for count in heads]
+ key_dims = _per_layer(metadata, f'{architecture}.attention.key_length', layers, default_dims)
+ value_dims = _per_layer(metadata, f'{architecture}.attention.value_length', layers, default_dims)
+ embedding = by_name['token_embd.weight']['shape']
+ if len(embedding) != 2 or embedding[0] != hidden:
+ raise ModelError('token_embd.weight shape disagrees with embedding_length')
+ if by_name['output_norm.weight']['shape'] != [hidden]:
+ raise ModelError('output_norm.weight shape disagrees with embedding_length')
+ if not tied and by_name['output.weight']['shape'] != embedding:
+ raise ModelError('output.weight shape disagrees with token embedding')
+ for layer in range(layers):
+ prefix = f'blk.{layer}.'
+ expected = {'attn_norm.weight': [hidden], 'ffn_norm.weight': [hidden],
+ 'attn_q.weight': [hidden, heads[layer] * key_dims[layer]],
+ 'attn_k.weight': [hidden, kv_heads[layer] * key_dims[layer]],
+ 'attn_v.weight': [hidden, kv_heads[layer] * value_dims[layer]],
+ 'attn_output.weight': [heads[layer] * value_dims[layer], hidden]}
+ for suffix, shape in expected.items():
+ if by_name[prefix + suffix]['shape'] != shape:
+ raise ModelError(f'{prefix + suffix} shape disagrees with attention metadata')
+ gate = by_name[prefix + 'ffn_gate.weight']['shape']
+ if len(gate) != 2 or gate[0] != hidden or by_name[prefix + 'ffn_up.weight']['shape'] != gate or by_name[prefix + 'ffn_down.weight']['shape'] != [gate[1], hidden]:
+ raise ModelError(f'Block {layer} feed-forward shapes are inconsistent')
+ kv.append(kv_heads[layer] * (key_dims[layer] + value_dims[layer]) * 2)
+ unsupported = list(dict.fromkeys(unsupported))
+ identity = hashlib.sha256((header_hash + ':' + str(size)).encode('ascii')).hexdigest()
+ return {
+ 'model_id': 'gguf-meta-sha256:' + identity,
+ 'identity_kind': 'metadata-only-sha256',
+ 'format': 'gguf', 'gguf_version': 3, 'architecture': architecture,
+ 'name': metadata.get('general.name', path.name),
+ 'supported': not unsupported, 'unsupported_reasons': unsupported,
+ 'layer_count': layers, 'layer_bytes': layer_bytes,
+ 'input_bytes': input_bytes, 'output_bytes': output_bytes,
+ 'kv_bytes_per_layer_per_token': kv, 'kv_cache_dtype': 'fp16' if kv else None,
+ 'kv_element_bytes': 2 if kv else None,
+ 'kv_elements_per_layer_per_token': [value // 2 for value in kv],
+ 'context_length': _positive_int(metadata[f'{architecture}.context_length'], 'context_length') if f'{architecture}.context_length' in metadata else None,
+ 'hidden_size': hidden, 'file_size_bytes': size, 'tensor_count': len(tensors),
+ 'header_bytes': data_offset, 'tensor_storage_bytes': size - data_offset,
+ 'tied_embeddings': tied, 'replicated_output_bytes': replicated,
+ 'alignment_bytes': alignment,
+ }
+
+
+_CREDENTIAL_KEYS = {'token', 'access_token', 'auth', 'authorization', 'api_key',
+ 'apikey', 'password', 'secret', 'bearer'}
+_TRANSITION_RANGES = (ipaddress.ip_network('64:ff9b::/96'),
+ ipaddress.ip_network('64:ff9b:1::/48'),
+ ipaddress.ip_network('2002::/16'),
+ ipaddress.ip_network('2001::/32'))
+
+
+def _public_ip(value):
+ try:
+ address = ipaddress.ip_address(value)
+ except ValueError:
+ return False
+ if not address.is_global or address.is_multicast or address.is_unspecified or address.is_reserved:
+ return False
+ if isinstance(address, ipaddress.IPv6Address):
+ if address.ipv4_mapped and not _public_ip(str(address.ipv4_mapped)):
+ return False
+ if any(address in network for network in _TRANSITION_RANGES):
+ return False
+ return True
+
+
+def _validate_url(url):
+ if not isinstance(url, str) or len(url) > 8192 or any(ord(c) < 33 or ord(c) == 127 for c in url):
+ raise DownloadError('URL must be a bounded HTTPS URL without whitespace/control characters')
+ try:
+ parsed = urlsplit(url)
+ if parsed.scheme != 'https' or not parsed.hostname or parsed.port not in (None, 443):
+ raise DownloadError('Only public HTTPS URLs on port 443 are allowed')
+ if parsed.username is not None or parsed.password is not None:
+ raise DownloadError('Embedded URL credentials are not allowed')
+ if parsed.fragment or '\\' in url or '%' in parsed.hostname:
+ raise DownloadError('URL fragments, backslashes, and encoded hostnames are not allowed')
+ if any(key.lower() in _CREDENTIAL_KEYS for key, _ in parse_qsl(parsed.query, max_num_fields=128)):
+ raise DownloadError('Bearer tokens and authentication secrets in model URLs are not allowed')
+ hostname = parsed.hostname.encode('idna').decode('ascii').rstrip('.')
+ if not hostname or len(hostname) > 253:
+ raise DownloadError('Invalid URL hostname')
+ target = quote(parsed.path or '/', safe="/%:@!$&'()*+,;=-._~")
+ if parsed.query:
+ target += '?' + quote(parsed.query, safe="%/?@!$&'()*+,;=:-._~")
+ return hostname, target
+ except (ValueError, UnicodeError) as exc:
+ raise DownloadError('Invalid public HTTPS URL') from exc
+
+
+def _resolve_public(host, timeout=30):
+ # getaddrinfo has no native timeout. A daemon resolver bounds the caller's
+ # wait; at most four lookups occur for a download. No address is used before
+ # this result has passed every public-address check.
+ result = queue.Queue(maxsize=1)
+ def resolve():
+ try:
+ result.put(socket.getaddrinfo(host, 443, type=socket.SOCK_STREAM))
+ except Exception as exc:
+ result.put(exc)
+ threading.Thread(target=resolve, daemon=True).start()
+ try:
+ addresses = result.get(timeout=timeout)
+ except queue.Empty as exc:
+ raise DownloadError('Model DNS resolution exceeded time limit') from exc
+ if isinstance(addresses, Exception):
+ raise DownloadError('Model host could not be resolved') from addresses
+ if not addresses or len(addresses) > 64:
+ raise DownloadError('Host has no usable addresses or too many DNS results')
+ pins = []
+ for family, socktype, protocol, _canonical, sockaddr in addresses:
+ if family not in (socket.AF_INET, socket.AF_INET6) or not _public_ip(sockaddr[0]):
+ raise DownloadError('Model host resolves to a non-public address; download blocked')
+ if family == socket.AF_INET6 and (sockaddr[2] or sockaddr[3]):
+ raise DownloadError('Scoped IPv6 addresses are not allowed')
+ pin = (family, socktype, protocol, sockaddr)
+ if pin not in pins:
+ pins.append(pin)
+ return pins
+
+
+class _PinnedHTTPSConnection(http.client.HTTPSConnection):
+ """TCP connects to checked numeric IP; TLS SNI/cert checks use original host.
+
+ No second DNS lookup, proxy environment, cookies, auth headers, or connection
+ reuse across redirects. Checking getpeername adds a post-connect invariant.
+ """
+ def __init__(self, host, pin, timeout):
+ super().__init__(host, port=443, timeout=timeout, context=ssl.create_default_context())
+ self.pin = pin
+ self.transport = None
+
+ def abort(self):
+ transport = self.transport
+ if transport is not None:
+ try:
+ transport.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ transport.close()
+
+ def connect(self):
+ family, socktype, protocol, sockaddr = self.pin
+ raw = socket.socket(family, socktype, protocol)
+ self.transport = raw
+ try:
+ raw.settimeout(self.timeout)
+ raw.connect(sockaddr)
+ if ipaddress.ip_address(raw.getpeername()[0]) != ipaddress.ip_address(sockaddr[0]):
+ raise DownloadError('Connected model server does not match the validated IP')
+ self.sock = self._context.wrap_socket(raw, server_hostname=self.host, do_handshake_on_connect=False)
+ self.transport = self.sock
+ self.sock.do_handshake()
+ except BaseException:
+ raw.close()
+ raise
+
+
+def _cache_usage(directory):
+ total = 0
+ for index, entry in enumerate(directory.iterdir()):
+ if index >= 10_000:
+ raise DownloadError('Model cache has too many files')
+ info = entry.lstat()
+ if not stat.S_ISREG(info.st_mode):
+ raise DownloadError('Model cache must contain only regular files')
+ total += info.st_size
+ return total
+
+
+def fetch_model(url, cache_dir, max_bytes=DEFAULT_MAX_BYTES, *, timeout=30,
+ max_seconds=600, max_cache_bytes=DEFAULT_MAX_CACHE_BYTES):
+ """Download bounded public HTTPS bytes into a content-addressed cache.
+
+ Returns (Path, full_file_sha256). At most three redirects, revalidated and
+ numerically pinned at every hop. Does not load/extract/execute model code.
+ Call inspect_file on the result before admitting it for model planning.
+ """
+ if type(max_bytes) is not int or max_bytes < 1 or max_bytes > 2**63 - 1:
+ raise DownloadError('max_bytes must be a positive signed 64-bit integer')
+ if type(max_cache_bytes) is not int or max_cache_bytes < 1:
+ raise DownloadError('max_cache_bytes must be a positive integer')
+ if not isinstance(timeout, (int, float)) or not 0 < timeout <= 120 or not isinstance(max_seconds, (int, float)) or not 0 < max_seconds <= 3600:
+ raise DownloadError('timeout must be 0..120 seconds and max_seconds 0..3600 seconds')
+ _validate_url(url)
+ directory = Path(cache_dir)
+ partial = None
+ connection = None
+ timer = None
+ deadline = time.monotonic() + max_seconds
+ try:
+ directory.mkdir(parents=True, exist_ok=True)
+ if directory.is_symlink() or not directory.is_dir():
+ raise DownloadError('Model cache must be a real directory')
+ used = _cache_usage(directory)
+ current = url
+ for redirects in range(4):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise DownloadError('Model download exceeded total time limit')
+ host, target = _validate_url(current)
+ pins = _resolve_public(host, min(timeout, remaining))
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise DownloadError('Model download exceeded total time limit')
+ # Deterministic first validated endpoint; no unbounded connection retries.
+ connection = _PinnedHTTPSConnection(host, pins[0], min(timeout, remaining))
+ # Interrupt a slow-drip header/body or TLS peer at the absolute
+ # deadline, rather than merely applying an idle socket timeout.
+ timer = threading.Timer(remaining, connection.abort)
+ timer.daemon = True
+ timer.start()
+ connection.request('GET', target, headers={'Accept': 'application/octet-stream',
+ 'Accept-Encoding': 'identity', 'User-Agent': 'ps5fleet/0.1',
+ 'Connection': 'close'})
+ response = connection.getresponse()
+ if response.status in (301, 302, 303, 307, 308):
+ location = response.getheader('Location')
+ timer.cancel()
+ connection.close()
+ connection = None
+ if not location or redirects == 3:
+ raise DownloadError('Model download redirect limit exceeded or missing Location')
+ current = urljoin(current, location)
+ continue
+ if response.status != 200:
+ raise DownloadError(f'Model server returned HTTP {response.status}')
+ if response.getheader('Content-Encoding', 'identity').lower() not in ('identity', ''):
+ raise DownloadError('Compressed HTTP transfer content is unsupported')
+ lengths = response.headers.get_all('Content-Length', [])
+ if len(lengths) > 1:
+ raise DownloadError('Ambiguous Content-Length headers')
+ advertised = None
+ if lengths:
+ if not re.fullmatch(r'[0-9]+', lengths[0]) or len(lengths[0]) > 20:
+ raise DownloadError('Invalid Content-Length header')
+ advertised = int(lengths[0])
+ if advertised > max_bytes:
+ raise DownloadError('Model exceeds download byte limit')
+ transfer = response.getheader('Transfer-Encoding', '').lower()
+ if transfer and (transfer != 'chunked' or lengths):
+ raise DownloadError('Ambiguous or unsupported HTTP transfer encoding')
+ allowance = min(max_bytes, max_cache_bytes - used)
+ if allowance <= 0 or (advertised is not None and advertised > allowance):
+ raise DownloadError('Model cache disk budget would be exceeded')
+ if shutil.disk_usage(directory).free < (advertised or 1) + DISK_RESERVE_BYTES:
+ raise DownloadError('Insufficient free disk space for model')
+ descriptor, temporary = tempfile.mkstemp(prefix='.download-', suffix='.part', dir=directory)
+ partial = Path(temporary)
+ digest = hashlib.sha256()
+ received = 0
+ with os.fdopen(descriptor, 'wb') as output:
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise DownloadError('Model download exceeded total time limit')
+ if connection.sock is not None:
+ connection.sock.settimeout(min(timeout, remaining))
+ chunk = response.read1(min(1024**2, allowance - received + 1))
+ if not chunk:
+ break
+ received += len(chunk)
+ if received > allowance:
+ raise DownloadError('Model exceeds download byte or cache disk budget')
+ if shutil.disk_usage(directory).free < len(chunk) + DISK_RESERVE_BYTES:
+ raise DownloadError('Insufficient free disk space for model')
+ digest.update(chunk)
+ output.write(chunk)
+ output.flush()
+ os.fsync(output.fileno())
+ if received == 0 or (advertised is not None and received != advertised):
+ raise DownloadError('Empty or truncated model download')
+ # Enforce framing completion even when HTTPResponse.read1 returned
+ # EOF quietly for a truncated chunked stream (normally it raises).
+ if response.length not in (None, 0):
+ raise DownloadError('Truncated model download')
+ checksum = digest.hexdigest()
+ final = directory / (checksum + '.gguf')
+ os.replace(partial, final)
+ partial = None
+ return final, checksum
+ raise DownloadError('Model download redirect limit exceeded')
+ except DownloadError:
+ raise
+ except (OSError, http.client.HTTPException) as exc:
+ raise DownloadError(f'Model download failed: {type(exc).__name__}') from exc
+ finally:
+ if timer is not None:
+ timer.cancel()
+ if connection is not None:
+ connection.close()
+ if partial is not None:
+ try:
+ partial.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def inspect_url(url, cache_dir, max_bytes=DEFAULT_MAX_BYTES, **download_options):
+ """Convenience wrapper adding full file checksum and cached path."""
+ path, digest = fetch_model(url, cache_dir, max_bytes, **download_options)
+ result = inspect_file(path)
+ result.update({'sha256': digest, 'path': str(path)})
+ return result
diff --git a/fleet/nodes.example.json b/fleet/nodes.example.json
new file mode 100644
index 0000000..15d4b9a
--- /dev/null
+++ b/fleet/nodes.example.json
@@ -0,0 +1,8 @@
+{
+ "host_memory_mib": 8192,
+ "host_reserve_mib": 2048,
+ "nodes": [
+ {"id": "ps5-a", "endpoint": "192.168.50.21:30052", "memory_mib": 10240, "reserve_mib": 2048},
+ {"id": "ps5-b", "endpoint": "192.168.50.22:30052", "memory_mib": 10240, "reserve_mib": 2048}
+ ]
+}
diff --git a/fleet/planner.py b/fleet/planner.py
new file mode 100644
index 0000000..1ed6ef7
--- /dev/null
+++ b/fleet/planner.py
@@ -0,0 +1,158 @@
+"""Contiguous layer placement for the pinned llama.cpp RPC layer split.
+
+This is a capacity estimate, not a reservation or a throughput prediction. The
+host retains input/shared tensors; the last remote gets the output projection.
+SPDX-License-Identifier: GPL-3.0-or-later
+"""
+from __future__ import annotations
+
+import ipaddress
+import math
+import re
+
+MIB = 1024**2
+PRIVATE = tuple(ipaddress.ip_network(c) for c in ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/8'))
+
+
+class FleetError(ValueError):
+ pass
+
+
+def integer(value, label, low=1, high=2**53):
+ if type(value) is not int or not low <= value <= high:
+ raise FleetError(f'{label} must be an integer in {low}..{high}')
+ return value
+
+
+def endpoint(value):
+ if not isinstance(value, str) or not re.fullmatch(r'[0-9.]+:[0-9]{1,5}', value):
+ raise FleetError('Node endpoint must be numeric private IPv4:port (no DNS, URL or IPv6)')
+ host, port = value.split(':')
+ try:
+ ip = ipaddress.IPv4Address(host)
+ except ipaddress.AddressValueError as exc:
+ raise FleetError('Invalid IPv4 node endpoint') from exc
+ if not any(ip in net for net in PRIVATE) or ip == ipaddress.IPv4Address('127.0.0.0'):
+ raise FleetError('RPC is unauthenticated: only explicit RFC1918 or loopback addresses are allowed')
+ integer(int(port), 'RPC port', 1, 65535)
+ return f'{ip}:{int(port)}'
+
+
+def inventory(raw):
+ if not isinstance(raw, dict):
+ raise FleetError('Inventory must be a JSON object')
+ integer(raw.get('host_memory_mib'), 'host_memory_mib')
+ integer(raw.get('host_reserve_mib'), 'host_reserve_mib', 1)
+ nodes = raw.get('nodes')
+ if not isinstance(nodes, list) or not 2 <= len(nodes) <= 15:
+ raise FleetError('A fleet needs 2..15 selected nodes; every node receives at least one layer')
+ result, ids, endpoints = [], set(), set()
+ for node in nodes:
+ if not isinstance(node, dict):
+ raise FleetError('Every node must be an object')
+ name = node.get('id')
+ if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,64}', name) or name in ids:
+ raise FleetError('Node IDs must be unique simple names, at most 64 characters')
+ address = endpoint(node.get('endpoint'))
+ if address in endpoints:
+ raise FleetError('Duplicate RPC endpoint')
+ memory = integer(node.get('memory_mib'), f'{name}.memory_mib')
+ reserve = integer(node.get('reserve_mib'), f'{name}.reserve_mib', 1)
+ if reserve >= memory:
+ raise FleetError(f'{name}: reserve must be below memory budget')
+ result.append(dict(id=name, endpoint=address, memory_mib=memory, reserve_mib=reserve))
+ ids.add(name)
+ endpoints.add(address)
+ return dict(host_memory_mib=raw['host_memory_mib'], host_reserve_mib=raw['host_reserve_mib'], nodes=result)
+
+
+def plan(model, config, context=4096):
+ config = inventory(config)
+ context = integer(context, 'context', 32, 1048576)
+ if model.get('supported') is not True:
+ raise FleetError('Unsupported model: ' + '; '.join(model.get('unsupported_reasons', [])))
+ if model.get('architecture') not in ('llama', 'qwen2'):
+ raise FleetError('Only dense llama and qwen2 are admitted by the fleet estimator')
+ limit = integer(model.get('context_length'), 'model context_length')
+ if context > limit:
+ raise FleetError(f'Requested context {context} exceeds model training context {limit}')
+ count = integer(model.get('layer_count'), 'layer_count', 2, 512)
+ nodes = config['nodes']
+ if len(nodes) > count:
+ raise FleetError('More nodes than repeating layers')
+ weights = model.get('layer_bytes')
+ kv = model.get('kv_bytes_per_layer_per_token')
+ if not isinstance(weights, list) or not isinstance(kv, list) or len(weights) != count or len(kv) != count:
+ raise FleetError('Missing complete layer and KV memory accounting')
+ if model.get('kv_cache_dtype') != 'fp16' or model.get('kv_element_bytes') != 2:
+ raise FleetError('Fleet currently supports only FP16 KV cache')
+ for value in weights + kv:
+ integer(value, 'layer weight/KV bytes')
+ # Round up conservatively for backend padding. One sequence only, no sliding
+ # window/recurrent state, no quantized cache, no flash-attention assumptions.
+ padded_context = (context + 255) // 256 * 256
+ resident = [w + k * padded_context for w, k in zip(weights, kv)]
+ output = integer(model.get('output_bytes'), 'output_bytes')
+ input_bytes = integer(model.get('input_bytes'), 'input_bytes')
+ # The entire file stays on host disk. Only the input weights are retained on
+ # host for compute; reserve covers model I/O staging, tokenizer and buffers.
+ host_bytes = input_bytes + config['host_reserve_mib'] * MIB
+ if host_bytes > config['host_memory_mib'] * MIB:
+ raise FleetError('Host input/shared tensors plus reserve exceed host memory budget')
+ prefix = [0]
+ for value in resident:
+ prefix.append(prefix[-1] + value)
+ # Exact minimax *memory utilisation* for the chosen node order, not fastest
+ # inference. All weights in a block stay together. Ties are deterministic.
+ previous = {0: 0.0}
+ parents = []
+ for i, node in enumerate(nodes):
+ current, parent = {}, {}
+ capacity, reserve = node['memory_mib'] * MIB, node['reserve_mib'] * MIB
+ for end in range(i + 1, count - (len(nodes) - i - 1) + 1):
+ for start, score in previous.items():
+ if start >= end:
+ continue
+ memory = prefix[end] - prefix[start] + reserve + (output if i == len(nodes) - 1 else 0)
+ if memory > capacity:
+ continue
+ candidate = max(score, memory / capacity)
+ if candidate < current.get(end, math.inf):
+ current[end], parent[end] = candidate, start
+ previous = current
+ parents.append(parent)
+ if count not in previous:
+ raise FleetError('No contiguous layer split fits every selected node including FP16 KV, output and reserves')
+ spans, end = [], count
+ for i in range(len(nodes) - 1, -1, -1):
+ start = parents[i][end]
+ spans.append((start, end))
+ end = start
+ spans.reverse()
+ # llama.cpp assigns slot i using upper_bound(cumulative splits, i/(L+1)).
+ # Boundaries halfway between slots avoid rounding a layer onto the wrong
+ # device. The output is the extra slot L, assigned to the last worker.
+ cumulative = [2 * end - 1 for _, end in spans[:-1]] + [2 * (count + 1)]
+ ratios = [a - b for a, b in zip(cumulative, [0] + cumulative[:-1])]
+ assignments = []
+ for i, (node, (start, end)) in enumerate(zip(nodes, spans)):
+ weights_bytes = sum(weights[start:end]) + (output if i == len(nodes) - 1 else 0)
+ kv_bytes = sum(kv[start:end]) * padded_context
+ reserve = node['reserve_mib'] * MIB
+ assignments.append(dict(**node, device=f'RPC{i}', layer_start=start,
+ layer_end=end, output_layer=i == len(nodes) - 1,
+ weights_bytes=weights_bytes, kv_bytes=kv_bytes,
+ reserve_bytes=reserve, estimated_bytes=weights_bytes + kv_bytes + reserve))
+ return dict(schema_version=1, status='estimated_not_reserved', architecture=model['architecture'],
+ layer_count=count, context_tokens=context, padded_context_tokens=padded_context,
+ parallel_sequences=1, cache_dtype='f16', tensor_split=ratios, nodes=assignments,
+ host_estimated_bytes=host_bytes, host_model_disk_bytes=model['file_size_bytes'],
+ max_estimated_memory_utilisation=previous[count],
+ warnings=[
+ 'Experimental unauthenticated RPC: isolated trusted network only, no public/guest LAN exposure.',
+ 'Memory estimates are not reservations; backend allocation/compute buffers can exceed the configured reserves.',
+ 'Input/shared tensors and model file stay on the controller; only layer/output tensors are distributed by RPC.',
+ 'Every node is required for each request. No failover, pipeline throughput or PS5 performance is claimed.',
+ 'Only dense llama/qwen2 single-file GGUF and one sequence with FP16 KV are admitted; hybrids/MoE are refused.',
+ 'A successful host test does not validate PS5 title linkage, RADV kernels, network behaviour or memory stability.',
+ ])
diff --git a/patches/fleet/0001-ps5-rpc-sockets.patch b/patches/fleet/0001-ps5-rpc-sockets.patch
new file mode 100644
index 0000000..86d7abe
--- /dev/null
+++ b/patches/fleet/0001-ps5-rpc-sockets.patch
@@ -0,0 +1,58 @@
+diff --git a/ggml/src/ggml-rpc/transport.cpp b/ggml/src/ggml-rpc/transport.cpp
+index 0d53438..31b8450 100644
+--- a/ggml/src/ggml-rpc/transport.cpp
++++ b/ggml/src/ggml-rpc/transport.cpp
+@@ -545,8 +545,15 @@ bool socket_t::impl::send_data(const void * data, size_t size) {
+ size_t bytes_sent = 0;
+ while (bytes_sent < size) {
+ size_t size_to_send = std::min(size - bytes_sent, MAX_CHUNK_SIZE);
+- ssize_t n = send(fd, (const char *)data + bytes_sent, size_to_send, 0);
+- if (n < 0) {
++ // PS5LM: a disconnected controller must not kill the title with
++ // SIGPIPE. BSDs without MSG_NOSIGNAL use SO_NOSIGPIPE below.
++#ifdef MSG_NOSIGNAL
++ const int flags = MSG_NOSIGNAL;
++#else
++ const int flags = 0;
++#endif
++ ssize_t n = send(fd, (const char *)data + bytes_sent, size_to_send, flags);
++ if (n <= 0) {
+ LOG_ERROR("send failed (bytes_sent=%zu, size_to_send=%zu)\n",
+ bytes_sent, size_to_send);
+ return false;
+@@ -698,5 +705,10 @@ static bool is_valid_fd(sockfd_t sockfd) {
+ static bool set_no_delay(sockfd_t sockfd) {
+ int flag = 1;
++#if !defined(MSG_NOSIGNAL) && defined(SO_NOSIGPIPE)
++ if (setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (char *)&flag, sizeof(int)) != 0) {
++ return false;
++ }
++#endif
+ // set TCP_NODELAY to disable Nagle's algorithm
+ int ret = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
+ return ret == 0;
+@@ -734,7 +746,11 @@ socket_ptr socket_t::create_server(const char * host, int port) {
+ LOG_ERROR("Invalid host address: %s\n", host);
+ return nullptr;
+ }
+- struct sockaddr_in serv_addr;
++ struct sockaddr_in serv_addr = {};
++#if defined(__FreeBSD__) || defined(__APPLE__)
++ // The PS5's BSD socket ABI includes this byte before sin_family.
++ serv_addr.sin_len = sizeof(serv_addr);
++#endif
+ serv_addr.sin_family = AF_INET;
+ serv_addr.sin_addr.s_addr = inet_addr(host);
+ serv_addr.sin_port = htons(port);
+@@ -758,7 +774,10 @@ socket_ptr socket_t::connect(const char * host, int port) {
+ LOG_ERROR("Failed to set TCP_NODELAY\n");
+ return nullptr;
+ }
+- struct sockaddr_in addr;
++ struct sockaddr_in addr = {};
++#if defined(__FreeBSD__) || defined(__APPLE__)
++ addr.sin_len = sizeof(addr);
++#endif
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(port);
+ struct hostent * server = gethostbyname(host);
diff --git a/patches/fleet/0002-rpc-disable-extra-listeners.patch b/patches/fleet/0002-rpc-disable-extra-listeners.patch
new file mode 100644
index 0000000..32e90b8
--- /dev/null
+++ b/patches/fleet/0002-rpc-disable-extra-listeners.patch
@@ -0,0 +1,17 @@
+diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp
+index 45fa8a4..a832f6f 100644
+--- a/ggml/src/ggml-rpc/ggml-rpc.cpp
++++ b/ggml/src/ggml-rpc/ggml-rpc.cpp
+@@ -2189,6 +2189,12 @@ void rpc_server::sync_all_backends() {
+ // so it gets the same transport upgrades (e.g. RDMA).
+ bool rpc_server::comm_init(const rpc_msg_comm_init_req & request, rpc_msg_comm_init_rsp & response) {
+ response.ok = 0;
++ // PS5LM layer fleets do not use pairwise allreduce. Enforce this on the
++ // server as well as the client: COMM_INIT otherwise opens an extra wildcard
++ // listener or connects to a peer chosen by the RPC caller.
++ if (std::getenv("GGML_RPC_NO_COMM") != nullptr) {
++ return true;
++ }
+ if (request.device >= backends.size() || request.world != 2 || request.rank >= request.world) {
+ return true;
+ }
diff --git a/patches/fleet/0003-rpc-portable-bounded-peer-host.patch b/patches/fleet/0003-rpc-portable-bounded-peer-host.patch
new file mode 100644
index 0000000..24678da
--- /dev/null
+++ b/patches/fleet/0003-rpc-portable-bounded-peer-host.patch
@@ -0,0 +1,19 @@
+Subject: [PATCH] rpc: avoid strnlen hidden by PS5 XOPEN feature macros
+
+The native CMake build uses _XOPEN_SOURCE=600, which hides strnlen in the
+PS5 SDK headers. Use a bounded C++ scan with the same semantics instead.
+This does not enable peer communications; NO_COMM still rejects them.
+
+diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp
+--- a/ggml/src/ggml-rpc/ggml-rpc.cpp
++++ b/ggml/src/ggml-rpc/ggml-rpc.cpp
+@@ -2226,7 +2226,8 @@
+ }
+ state.peer->update_caps(remote_caps);
+ } else {
+- const std::string host(request.host, strnlen(request.host, sizeof(request.host)));
++ const char * host_end = std::find(request.host, request.host + sizeof(request.host), '\0');
++ const std::string host(request.host, host_end);
+ // rank 0 may not be listening yet, retry for a few seconds
+ for (int i = 0; i < 100 && state.peer == nullptr; i++) {
+ state.peer = socket_t::connect(host.c_str(), request.port);
diff --git a/patches/fleet/0004-rpc-log-server-socket-errors.patch b/patches/fleet/0004-rpc-log-server-socket-errors.patch
new file mode 100644
index 0000000..9686e3e
--- /dev/null
+++ b/patches/fleet/0004-rpc-log-server-socket-errors.patch
@@ -0,0 +1,28 @@
+Subject: [PATCH] rpc: say why the server socket could not be created
+
+Upstream returns nullptr from socket, bind and listen without errno, so a
+worker that cannot listen only prints "Failed to create server socket".
+
+diff --git a/ggml/src/ggml-rpc/transport.cpp b/ggml/src/ggml-rpc/transport.cpp
+--- a/ggml/src/ggml-rpc/transport.cpp
++++ b/ggml/src/ggml-rpc/transport.cpp
+@@ -736,6 +736,7 @@
+ socket_ptr socket_t::create_server(const char * host, int port) {
+ auto sockfd = socket(AF_INET, SOCK_STREAM, 0);
+ if (!is_valid_fd(sockfd)) {
++ LOG_ERROR("Failed to open a socket: %s\n", strerror(errno));
+ return nullptr;
+ }
+ if (!set_reuse_addr(sockfd)) {
+@@ -756,9 +757,11 @@
+ serv_addr.sin_port = htons(port);
+
+ if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
++ LOG_ERROR("Failed to bind %s:%d: %s\n", host, port, strerror(errno));
+ return nullptr;
+ }
+ if (listen(sockfd, 1) < 0) {
++ LOG_ERROR("Failed to listen on %s:%d: %s\n", host, port, strerror(errno));
+ return nullptr;
+ }
+ LOG_DBG("[%s] listening on %s:%d\n", __func__, host, port);
diff --git a/ps5/app/fleet_worker.cpp b/ps5/app/fleet_worker.cpp
new file mode 100644
index 0000000..9b5ae09
--- /dev/null
+++ b/ps5/app/fleet_worker.cpp
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "fleet_worker.hpp"
+
+#include "ggml-backend.h"
+#include "ggml-rpc.h"
+
+#include <cerrno>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <exception>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+namespace ps5lm {
+
+FleetWorkerConfig read_fleet_worker_config(const char * path) {
+ // No lstat: a PS5 title gets EPERM from it (seen on a console). Opening with
+ // O_NOFOLLOW refuses a link (ELOOP), O_NONBLOCK keeps a FIFO from hanging the
+ // title before the status/quit loop starts, and fstat checks the opened file.
+ int flags = O_RDONLY | O_NONBLOCK;
+#ifdef O_NOFOLLOW
+ flags |= O_NOFOLLOW;
+#endif
+ const int fd = open(path, flags);
+ if (fd < 0) {
+ if (errno == ENOENT) {
+ return {}; // Ordinary PS5LM until explicitly opted in.
+ }
+ if (errno == ELOOP) {
+ return { FleetWorkerConfig::invalid, "", "fleet-worker.txt must be a regular file, not a link or device" };
+ }
+ return { FleetWorkerConfig::invalid, "", std::string("Cannot open fleet-worker.txt: ") + std::strerror(errno) };
+ }
+ struct stat info = {};
+ if (fstat(fd, &info) != 0 || !S_ISREG(info.st_mode)) {
+ close(fd);
+ return { FleetWorkerConfig::invalid, "", "fleet-worker.txt changed or is not a regular file" };
+ }
+ char data[1025];
+ size_t size = 0;
+ bool failed = false;
+ while (size < sizeof(data)) {
+ const ssize_t n = read(fd, data + size, sizeof(data) - size);
+ if (n < 0 && errno == EINTR) {
+ continue;
+ }
+ if (n <= 0) {
+ failed = n < 0;
+ break;
+ }
+ size += static_cast<size_t>(n);
+ }
+ close(fd);
+ if (failed || size == sizeof(data)) {
+ return { FleetWorkerConfig::invalid, "", "fleet-worker.txt is unreadable or exceeds 1024 bytes" };
+ }
+ return parse_fleet_worker_config(std::string(data, size));
+}
+
+std::string run_fleet_worker(const FleetWorkerConfig & config) {
+ // Revalidate at the listener boundary, even if a caller bypassed the file reader.
+ if (config.state != FleetWorkerConfig::enabled ||
+ parse_fleet_worker_config(config.endpoint + "\nI_UNDERSTAND_RPC_IS_UNAUTHENTICATED\n").state != FleetWorkerConfig::enabled) {
+ return "Refusing invalid fleet worker configuration";
+ }
+ try {
+ // Layer splitting does not need peer collectives. The matching server
+ // patch rejects COMM_INIT, which would otherwise open another wildcard
+ // listener at a port chosen by the controller. Override env.txt too.
+ if (setenv("GGML_RPC_NO_COMM", "1", 1) != 0) {
+ return "Cannot disable extra RPC listeners; refusing to start";
+ }
+ // The title's stderr does not reach app.log; ggml's log (RPC and Vulkan
+ // errors included) goes to stdout, which does.
+ ggml_log_set([](ggml_log_level, const char * text, void *) { std::fputs(text, stdout); }, nullptr);
+ ggml_backend_load_all();
+ ggml_backend_reg_t vulkan = ggml_backend_reg_by_name("Vulkan");
+ if (!vulkan) {
+ return "No Vulkan backend; refusing CPU fallback";
+ }
+ ggml_backend_dev_t device = nullptr;
+ for (size_t i = 0; i < ggml_backend_reg_dev_count(vulkan); ++i) {
+ auto candidate = ggml_backend_reg_dev_get(vulkan, i);
+ const auto type = ggml_backend_dev_type(candidate);
+ if (type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU) {
+ if (device) {
+ return "Expected exactly one PS5 Vulkan device";
+ }
+ device = candidate;
+ }
+ }
+ if (!device) {
+ return "No Vulkan GPU device; refusing CPU fallback";
+ }
+ std::fprintf(stdout,
+ "ps5lm-fleet: WARNING: unauthenticated, unencrypted RPC v%d.%d.%d on %s\n"
+ "ps5lm-fleet: trusted isolated LAN ONLY; no public forwarding; one controller at a time\n"
+ "ps5lm-fleet: exporting only %s; local model server/downloads are disabled\n",
+ RPC_PROTO_MAJOR_VERSION, RPC_PROTO_MINOR_VERSION, RPC_PROTO_PATCH_VERSION,
+ config.endpoint.c_str(), ggml_backend_dev_name(device));
+ // No cache: avoids unbounded disk growth and HOME dependence. TCP only
+ // (GGML_RPC_RDMA=OFF). The host sends the assigned weights over this socket.
+ ggml_backend_rpc_start_server(config.endpoint.c_str(), nullptr, 6, 1, &device);
+ return "RPC stopped or failed to bind; inspect /data/PS5LM/app.log and restart the title";
+ } catch (const std::exception & ex) {
+ return std::string("RPC worker failed: ") + ex.what();
+ } catch (...) {
+ return "RPC worker failed with an unknown exception";
+ }
+}
+
+} // namespace ps5lm
diff --git a/ps5/app/fleet_worker.hpp b/ps5/app/fleet_worker.hpp
new file mode 100644
index 0000000..99fc880
--- /dev/null
+++ b/ps5/app/fleet_worker.hpp
@@ -0,0 +1,96 @@
+// Experimental, opt-in fleet worker. RPC has no authentication or encryption.
+// Never enable it on an untrusted network. SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <string>
+#include <vector>
+
+namespace ps5lm {
+
+struct FleetWorkerConfig {
+ enum State { disabled, enabled, invalid } state = disabled;
+ std::string endpoint;
+ std::string error;
+};
+
+// Deliberately tiny, dependency-free parser so the safety gate is host-testable.
+// Exactly two nonempty lines: the console's private IPv4:port and the acknowledgement.
+// Do not accept hostnames, wildcard addresses, public addresses, or extra options.
+inline FleetWorkerConfig parse_fleet_worker_config(const std::string & text) {
+ FleetWorkerConfig config;
+ config.state = FleetWorkerConfig::invalid;
+ config.error = "Expected private IPv4:port and I_UNDERSTAND_RPC_IS_UNAUTHENTICATED on two lines";
+ if (text.size() > 1024 || text.find('\0') != std::string::npos) {
+ return config;
+ }
+ std::vector<std::string> lines;
+ for (size_t pos = 0; pos < text.size();) {
+ const size_t end = text.find('\n', pos);
+ std::string line = text.substr(pos, end == std::string::npos ? end : end - pos);
+ if (!line.empty() && line.back() == '\r') {
+ line.pop_back();
+ }
+ lines.push_back(line);
+ if (end == std::string::npos) {
+ break;
+ }
+ pos = end + 1;
+ }
+ if (lines.size() != 2 || lines[1] != "I_UNDERSTAND_RPC_IS_UNAUTHENTICATED") {
+ return config;
+ }
+ const std::string & endpoint = lines[0];
+ const size_t colon = endpoint.find(':');
+ if (colon == std::string::npos || colon == 0 || colon + 1 == endpoint.size()) {
+ return config;
+ }
+ auto number = [](const std::string & s, unsigned limit, unsigned & out) {
+ if (s.empty() || s.size() > 5 || (s.size() > 1 && s[0] == '0')) {
+ return false;
+ }
+ out = 0;
+ for (char c : s) {
+ if (c < '0' || c > '9') {
+ return false;
+ }
+ out = out * 10 + static_cast<unsigned>(c - '0');
+ if (out > limit) {
+ return false;
+ }
+ }
+ return true;
+ };
+ const std::string host = endpoint.substr(0, colon);
+ unsigned octets[4] = {}, port = 0;
+ size_t pos = 0;
+ for (size_t i = 0; i < 4; ++i) {
+ const size_t dot = host.find('.', pos);
+ if ((i < 3) != (dot != std::string::npos) ||
+ !number(host.substr(pos, dot == std::string::npos ? dot : dot - pos), 255, octets[i])) {
+ return config;
+ }
+ pos = dot == std::string::npos ? host.size() : dot + 1;
+ }
+ const bool private_ip = octets[0] == 10 ||
+ (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31) ||
+ (octets[0] == 192 && octets[1] == 168);
+ const bool loopback = host == "127.0.0.1";
+ if ((!private_ip && !loopback) || octets[3] == 0 || octets[3] == 255 ||
+ !number(endpoint.substr(colon + 1), 39999, port) || port < 1024) {
+ // A PS5 title gets EACCES binding port 40000 and up (39999 binds; measured).
+ config.error = "Bind only a private console IPv4 (or 127.0.0.1), port 1024..39999; never 0.0.0.0";
+ return config;
+ }
+ config.state = FleetWorkerConfig::enabled;
+ config.endpoint = endpoint;
+ config.error.clear();
+ return config;
+}
+
+FleetWorkerConfig read_fleet_worker_config(const char * path);
+
+// Blocks in upstream RPC until it fails; returns the reason, never silently
+// falls back to CPU. The title must be closed/restarted to stop this worker.
+std::string run_fleet_worker(const FleetWorkerConfig & config);
+
+} // namespace ps5lm
diff --git a/ps5/app/main.cpp b/ps5/app/main.cpp
index 6bf8097..5f2fe19 100644
--- a/ps5/app/main.cpp
+++ b/ps5/app/main.cpp
@@ -41,6 +41,9 @@
#include "dashboard.hpp"
#include "fetch.hpp"
+#if PS5LM_FLEET // the fleet build only: PS5LM_FLEET=1 scripts/build-app.sh
+#include "fleet_worker.hpp"
+#endif
#include "market.hpp"
#include "display.hpp"
#include "ggml-backend.h"
@@ -107,6 +110,9 @@ constexpr const char * kEnv = "/data/PS5LM/env.txt"; // driver and ggml
constexpr const char * kTextOnly = "/data/PS5LM/text-only"; // the last load's projector failed: load without it once
constexpr const char * kQuit = "/data/PS5LM/quit";
constexpr const char * kSettings = "/data/PS5LM/settings.json";
+#if PS5LM_FLEET
+constexpr const char * kFleetWorker = "/data/PS5LM/fleet-worker.txt";
+#endif
constexpr const char * kScratch = "/data/PS5LM/scratch";
// The file tools only: a title cannot start processes (no shell command).
constexpr const char * kTools = "read_file,write_file,edit_file,file_glob_search,grep_search,get_info";
@@ -707,6 +713,72 @@ int main(int, char **) {
}
sceSystemServiceHideSplashScreen();
+#if PS5LM_FLEET
+ // Fleet is a mutually exclusive startup mode, not another local model.
+ // In particular, do not start StatsCollector (its HTTP probes), model
+ // auto-load, downloads, or controller/file commands that could restart or
+ // allocate memory behind the remote controller's back. Malformed config
+ // stays here, with no listener and no fallback into normal model mode.
+ const FleetWorkerConfig fleet = read_fleet_worker_config(kFleetWorker);
+ if (fleet.state != FleetWorkerConfig::disabled) {
+ std::atomic<bool> stopped{ false };
+ std::string worker_error = fleet.error;
+ std::function<void()> worker = [&] {
+ worker_error = run_fleet_worker(fleet);
+ std::printf("ps5lm-fleet: %s\n", worker_error.c_str());
+ stopped.store(true, std::memory_order_release);
+ };
+ if (fleet.state == FleetWorkerConfig::enabled) {
+ pthread_attr_t attr;
+ int rc = pthread_attr_init(&attr);
+ if (rc == 0) {
+ rc = pthread_attr_setstacksize(&attr, 16u << 20);
+ pthread_t thread{};
+ if (rc == 0) {
+ rc = pthread_create(&thread, &attr, [](void * p) -> void * {
+ (*static_cast<std::function<void()> *>(p))();
+ return nullptr;
+ }, &worker);
+ if (rc == 0) {
+ pthread_detach(thread); // Lifetime is the title, not a model load.
+ }
+ }
+ pthread_attr_destroy(&attr);
+ }
+ if (rc != 0) {
+ worker_error = std::string("Cannot start RPC thread: ") + std::strerror(rc);
+ stopped = true;
+ }
+ notify("PS5LM fleet: experimental unauthenticated RPC. Trusted isolated LAN only.");
+ } else {
+ std::printf("ps5lm-fleet: %s\n", worker_error.c_str());
+ stopped = true;
+ }
+ hui::ui::Feedback quiet;
+ // Upstream's blocking API has no readiness callback: do not label this
+ // as Ready. The host's successful RPC handshake verifies availability.
+ for (uint64_t n = 0;; ++n) {
+ const bool failed = stopped.load(std::memory_order_acquire);
+ dash.set_busy(failed ? "Fleet worker stopped" : "Experimental fleet RPC worker",
+ failed ? worker_error : fleet.endpoint + " - no authentication; isolated LAN only");
+ quiet.clear();
+ dash.update(hui::InputFrame{}, 1.0f / 60.0f, quiet);
+ if (ui_ok) {
+ render();
+ if (n % 60 == 45 && !take_request_file("/data/PS5LM/screenshot").empty()) {
+ save_screen("/data/PS5LM/screen.bmp", display.width(), display.height());
+ }
+ display.swap();
+ } else {
+ sceKernelUsleep(16667);
+ }
+ if (n % 60 == 0) {
+ quit_if_asked(); // Existing safe title-close path; not cancellation in a GPU call.
+ }
+ }
+ }
+#endif
+
StatsCollector stats;
stats.start(kPort);
set_activity_sink(&stats); // llama-server's request hooks (patches/0007) report here
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
index cb9fecb..0a16059 100755
--- a/scripts/build-app.sh
+++ b/scripts/build-app.sh
@@ -10,6 +10,8 @@
#
# scripts/build-app.sh configure, build and package
# PS5LM_PREBUILT_UI=OFF ... omit the optional downloaded browser UI
+# PS5LM_FLEET=1 ... the fleet build: adds ggml's RPC backend,
+# patches/fleet and the RPC worker (docs/FLEET.md)
# CMAKE_BUILD_PARALLEL_LEVEL also bounds the native dashboard compilers.
set -euo pipefail
@@ -27,6 +29,8 @@ headers="$root/.deps/ps5-vk-headers"
glsdk=${PS5_OPENGL_SDK:-$(bash "$root/third_party/ps5-homebrew-ui/tools/fetch-opengl-sdk.sh")}
sce_sys="$root/ps5/app/sce_sys"
param="$sce_sys/param.json"
+fleet=${PS5LM_FLEET:-0}
+[[ $fleet == 0 || $fleet == 1 ]] || { echo "build-app: PS5LM_FLEET must be 0 or 1" >&2; exit 2; }
for f in "$archive" "$tool" "$vk/runtime/libc.prx" "$sdk/bin/prospero-lld" "$glsdk/lib/libPS5OpenGL.a"; do
[ -e "$f" ] || { echo "build-app: missing $f" >&2; exit 2; }
@@ -59,9 +63,23 @@ EOF
fi
# The PS5 changes to llama.cpp (patches/), as scripts/build-llama.sh applies them.
+# patches/fleet goes on top only for a fleet build; a default build after a fleet
+# one takes it back out first, last patch first.
+fleet_patches=("$root"/patches/fleet/*.patch)
+if [[ $fleet == 0 ]]; then
+ for (( i = ${#fleet_patches[@]} - 1; i >= 0; i-- )); do
+ p=${fleet_patches[i]}
+ if git -C "$llama" apply --reverse --check "$p" 2>/dev/null; then git -C "$llama" apply --reverse "$p"; fi
+ done
+fi
for p in "$root"/patches/*.patch; do
git -C "$llama" apply --reverse --check "$p" 2>/dev/null || git -C "$llama" apply "$p"
done
+if [[ $fleet == 1 ]]; then
+ for p in "${fleet_patches[@]}"; do
+ git -C "$llama" apply --reverse --check "$p" 2>/dev/null || git -C "$llama" apply "$p"
+ done
+fi
# ftpsrv (drakmor's 1.16-ng-stable), PS5LM's copy: a payload the app sends to
# elfldr when no ftpsrv answers (connect_ftp_writer in ps5/app/ftp_writer.hpp).
@@ -74,6 +92,7 @@ mkdir -p "$out/ftpsrv"
make -C "$ftpsrv" -f Makefile.ps5 PS5_PAYLOAD_SDK="$sdk" ELF="$out/ftpsrv/ps5lm-ftpsrv.elf" > "$out/ftpsrv.build.log" 2>&1 ||
{ tail -30 "$out/ftpsrv.build.log" >&2; exit 1; }
+# CI may omit the optional browser UI download; the console dashboard is unaffected.
flags="-DSUBPROCESS_HAVE_CWD=0 -I$headers/include"
# llama.cpp throws, catches and uses dynamic_cast; the PS5 target turns
# exceptions and RTTI off by default.
@@ -85,7 +104,7 @@ cmake -S "$llama" -B "$out/llama" -G Ninja \
-DCMAKE_C_FLAGS="$flags" -DCMAKE_CXX_FLAGS="$cxxflags" \
-DBUILD_SHARED_LIBS=OFF -DGGML_BACKEND_DL=OFF -DGGML_NATIVE=OFF -DGGML_CPU_ALL_VARIANTS=OFF \
-DGGML_AVX=ON -DGGML_AVX2=ON -DGGML_FMA=ON -DGGML_F16C=ON -DGGML_BMI2=ON -DGGML_AVX512=OFF \
- -DGGML_OPENMP=OFF -DGGML_CCACHE=OFF -DGGML_VULKAN=ON \
+ -DGGML_OPENMP=OFF -DGGML_CCACHE=OFF -DGGML_VULKAN=ON -DGGML_RPC="$([[ $fleet == 1 ]] && echo ON || echo OFF)" -DGGML_RPC_RDMA=OFF \
-DVulkan_INCLUDE_DIR="$headers/include" -DVulkan_LIBRARY="$archive" \
-DVulkan_GLSLC_EXECUTABLE="$(command -v glslc)" -DSPIRV-Headers_DIR="$headers/cmake" \
-DMATH_LIBRARY=SceLibcInternal \
@@ -101,9 +120,15 @@ obj="$out/obj"
mkdir -p "$obj" "$out/stubs"
cxx() { "$root/ps5/app/ps5cxx" -std=c++17 -O2 -ffunction-sections -fdata-sections "$@"; }
cxx -std=c++20 -fexceptions -fcxx-exceptions -frtti -I "$headers/include" -I "$llama/ggml/include" -I "$root/third_party/ps5-homebrew-ui/src" \
- -I "$glsdk/include" -DGL_GLEXT_PROTOTYPES=1 \
+ -I "$glsdk/include" -DGL_GLEXT_PROTOTYPES=1 -DPS5LM_FLEET="$fleet" \
-c "$root/ps5/app/main.cpp" -o "$obj/main.o"
cxx -fexceptions -fcxx-exceptions -c "$root/ps5/app/model_plan.cpp" -o "$obj/model_plan.o"
+fleet_objects=()
+if [[ $fleet == 1 ]]; then
+ cxx -fexceptions -fcxx-exceptions -I "$llama/ggml/include" \
+ -c "$root/ps5/app/fleet_worker.cpp" -o "$obj/fleet_worker.o"
+ fleet_objects=("$obj/fleet_worker.o")
+fi
cxx -std=c++20 -fexceptions -fcxx-exceptions -I "$llama/vendor" -c "$root/ps5/app/settings.cpp" -o "$obj/settings.o"
cxx -std=c++20 -fexceptions -fcxx-exceptions -c "$root/ps5/app/fetch.cpp" -o "$obj/fetch.o"
cxx -std=c++20 -fexceptions -fcxx-exceptions -I "$llama/vendor" -c "$root/ps5/app/market.cpp" -o "$obj/market.o"
@@ -207,7 +232,7 @@ mapfile -t libs < <(find "$out/llama" -name '*.a' | sort)
"$sdk/bin/prospero-lld" "${radv_linker_script[@]}" --eh-frame-hdr "${radv_link_flags[@]}" \
--version-script "$vk/tooling/native/app-symbols.map" --exclude-libs=ALL \
-e _start -o "$out/llvm-pie.elf" \
- "$obj/app_crt.o" "$obj/app_cpp_runtime.o" "$obj/main.o" "$obj/display.o" "$obj/model_plan.o" "$obj/settings.o" "$obj/fetch.o" "$obj/market.o" "$obj/ftp_writer.o" "$obj/activity.o" "$obj/sha256.o" "$obj/dashboard.o" "$obj/stats.o" \
+ "$obj/app_crt.o" "$obj/app_cpp_runtime.o" "$obj/main.o" "$obj/display.o" "$obj/model_plan.o" "${fleet_objects[@]}" "$obj/settings.o" "$obj/fetch.o" "$obj/market.o" "$obj/ftp_writer.o" "$obj/activity.o" "$obj/sha256.o" "$obj/dashboard.o" "$obj/stats.o" \
--start-group "${libs[@]}" "$obj/libps5lm_kit.a" "$obj/libps5app_compat.a" "$out/gl/libps5lm_gl.a" --end-group \
"$out/stubs/libSceAgc.so" "$out/stubs/libSceAgcDriver.so" \
"${radv_link_inputs[@]}" \
@@ -267,4 +292,6 @@ printf '%s\n' "ftpsrv by John Törnblom and drakmor, GPL-3.0-or-later: https://g
"with PS5LM's patches/ftpsrv/0001-loopback-only-for-ps5lm.patch: 127.0.0.1:2123 only, as ps5lm-ftpsrv." \
> "$app/payloads/ps5lm-ftpsrv-NOTICE.txt"
"$tool" self --inspect --file "$app/eboot.bin" > /dev/null
-echo "build-app: $app ($(stat -c %s "$app/eboot.bin") bytes)"
+# release-app.sh names the zip after the variant this build made.
+if [[ $fleet == 1 ]]; then echo fleet; else echo default; fi > "$out/variant"
+echo "build-app: $app ($(stat -c %s "$app/eboot.bin") bytes, $(cat "$out/variant"))"
diff --git a/scripts/build-fleet-host.sh b/scripts/build-fleet-host.sh
new file mode 100755
index 0000000..7d8b4e5
--- /dev/null
+++ b/scripts/build-fleet-host.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# Build the CPU-only host/controller and localhost RPC test workers.
+set -euo pipefail
+root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
+llama="$root/third_party/llama.cpp"
+out="${PS5LM_FLEET_BUILD:-$root/build/fleet-host}"
+cmake_bin="${CMAKE:-cmake}"
+ninja_bin="${NINJA:-ninja}"
+for tool in "$cmake_bin" "$ninja_bin" python3 git; do
+ command -v "$tool" >/dev/null || { echo "build-fleet-host: missing $tool" >&2; exit 2; }
+done
+if [ ! -f "$llama/CMakeLists.txt" ]; then
+ echo 'build-fleet-host: run git submodule update --init third_party/llama.cpp' >&2
+ exit 2
+fi
+expected=$(git -C "$root" ls-tree HEAD third_party/llama.cpp | awk '{print $3}')
+actual=$(git -C "$llama" rev-parse HEAD)
+if [ "$actual" != "$expected" ]; then
+ echo "build-fleet-host: llama.cpp revision $actual differs from pinned $expected" >&2
+ exit 2
+fi
+# Keep the same patch set on the controller and the fleet title (PS5LM_FLEET=1
+# scripts/build-app.sh), with no protocol fork.
+for patch in "$root"/patches/*.patch "$root"/patches/fleet/*.patch; do
+ git -C "$llama" apply --reverse --check "$patch" 2>/dev/null || git -C "$llama" apply "$patch"
+done
+# patches/0007's request hooks are weak and only the PS5 title defines them; ELF
+# linkers leave them null, Apple's ld must be told they may stay undefined.
+link_flags=()
+if [ "$(uname -s)" = Darwin ]; then
+ link_flags=("-DCMAKE_EXE_LINKER_FLAGS=-Wl,-U,_ps5lm_activity_begin -Wl,-U,_ps5lm_activity_data -Wl,-U,_ps5lm_activity_end")
+fi
+"$cmake_bin" -S "$llama" -B "$out" -G Ninja "${link_flags[@]}" \
+ -DCMAKE_MAKE_PROGRAM="$(command -v "$ninja_bin")" \
+ -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF \
+ -DGGML_RPC=ON -DGGML_RPC_RDMA=OFF -DGGML_BACKEND_DL=OFF \
+ -DGGML_NATIVE=OFF -DGGML_CPU_ALL_VARIANTS=OFF \
+ -DGGML_CUDA=OFF -DGGML_VULKAN=OFF -DGGML_METAL=OFF \
+ -DGGML_OPENMP=OFF -DGGML_CCACHE=OFF \
+ -DLLAMA_OPENSSL=OFF -DLLAMA_BUILD_COMMON=ON -DLLAMA_BUILD_TESTS=ON \
+ -DLLAMA_BUILD_EXAMPLES=OFF -DLLAMA_BUILD_TOOLS=ON -DLLAMA_BUILD_SERVER=ON \
+ -DLLAMA_BUILD_APP=OFF -DLLAMA_BUILD_UI=OFF -DLLAMA_USE_PREBUILT_UI=OFF
+"$cmake_bin" --build "$out" --parallel "${CMAKE_BUILD_PARALLEL_LEVEL:-2}" \
+ --target llama-server llama-cli ggml-rpc-server test-rpc-multi-server
+python3 - "$out" "$actual" "$(git -C "$root" rev-parse HEAD)" "$root" <<'PY_MANIFEST'
+import hashlib
+import json
+from pathlib import Path
+import sys
+out = Path(sys.argv[1]).resolve()
+(out / "fleet-build.json").write_text(json.dumps({
+ "llama_revision": sys.argv[2],
+ "ps5lm_revision": sys.argv[3],
+ "binary": str(out / "bin/llama-server"),
+ "server_sha256": hashlib.sha256((out / "bin/llama-server").read_bytes()).hexdigest(),
+ "rpc_binary": str(out / "bin/ggml-rpc-server"),
+ "backends": ["CPU", "RPC"],
+ "applied_patches": {str(p.relative_to(Path(sys.argv[4]) / "patches")): hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in sorted((Path(sys.argv[4]) / "patches").glob("*.patch"))
+ + sorted((Path(sys.argv[4]) / "patches/fleet").glob("*.patch"))},
+}, indent=2) + "\n")
+PY_MANIFEST
+printf 'build-fleet-host: %s (llama.cpp %s)\n' "$out/bin" "$actual"
diff --git a/scripts/release-app.sh b/scripts/release-app.sh
index a92979a..7709de5 100755
--- a/scripts/release-app.sh
+++ b/scripts/release-app.sh
@@ -1,9 +1,11 @@
#!/usr/bin/env bash
# Packages the built app for a release: build/release/ps5lm-app-v<version>.zip
# holding the app's title folder (PPSA99575), plus its sha256. The version comes from
-# ps5/app/version.hpp; the git tag is v<version>.
+# ps5/app/version.hpp; the git tag is v<version>. After a fleet build the zip is
+# ps5lm-app-fleet-v<version>.zip (docs/FLEET.md).
#
# scripts/build-app.sh && scripts/release-app.sh
+# PS5LM_FLEET=1 scripts/build-app.sh && scripts/release-app.sh
#
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
@@ -13,7 +15,12 @@ version=$(sed -n 's/^#define PS5LM_VERSION "\(.*\)"$/\1/p' "$root/ps5/app/versio
title=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["titleId"])' "$root/ps5/app/sce_sys/param.json")
app="$root/build/app-ps5/title/$title"
out="$root/build/release"
-zip="$out/ps5lm-app-v$version.zip"
+variant=$(cat "$root/build/app-ps5/variant" 2>/dev/null || echo default)
+case $variant in
+ default) zip="$out/ps5lm-app-v$version.zip" ;;
+ fleet) zip="$out/ps5lm-app-fleet-v$version.zip" ;;
+ *) echo "release-app: unknown build variant '$variant'" >&2; exit 1 ;;
+esac
[ -f "$app/eboot.bin" ] || { echo "release-app: build it first (scripts/build-app.sh)" >&2; exit 1; }
grep -q "^## \[$version\]" "$root/CHANGELOG.md" || { echo "release-app: CHANGELOG.md has no [$version] entry" >&2; exit 1; }
diff --git a/scripts/test-fleet.sh b/scripts/test-fleet.sh
new file mode 100755
index 0000000..5e091e3
--- /dev/null
+++ b/scripts/test-fleet.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+# Fast offline checks by default; --rpc also builds and runs real CPU RPC inference.
+set -euo pipefail
+root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "$root"
+mkdir -p build/fleet-tests
+python3 -m unittest discover -s tests -p 'test_fleet_*.py' -v
+cxx=${CXX:-c++}
+"$cxx" -std=c++17 -Wall -Wextra -Werror -I ps5/app \
+ tests/fleet_worker_config_test.cpp -o build/fleet-tests/worker-config
+build/fleet-tests/worker-config
+"$cxx" -std=c++17 -Wall -Wextra -Werror -I ps5/app -I third_party/llama.cpp/ggml/include \
+ tests/fleet_worker_runtime_test.cpp ps5/app/fleet_worker.cpp -o build/fleet-tests/worker-runtime
+build/fleet-tests/worker-runtime
+"$cxx" -std=c++17 -O1 ps5/app/model_plan_test.cpp ps5/app/model_plan.cpp -o build/fleet-tests/existing-model-plan
+build/fleet-tests/existing-model-plan
+bash -n scripts/build-fleet-host.sh scripts/build-app.sh scripts/test-fleet.sh
+if [[ ${1:-} == --rpc ]]; then
+ # Fail fast on a clean runner, before the C++ build, if fixture imports
+ # are missing. This uses the pinned submodule, never a separately installed gguf.
+ PYTHONPATH="$root/third_party/llama.cpp/gguf-py${PYTHONPATH:+:$PYTHONPATH}" \
+ python3 -c 'import numpy, yaml, gguf'
+ scripts/build-fleet-host.sh
+ out="${PS5LM_FLEET_BUILD:-$root/build/fleet-host}"
+ "${CMAKE:-cmake}" -E env CTEST_OUTPUT_ON_FAILURE=1 \
+ "$(dirname "$(command -v "${CMAKE:-cmake}")")/ctest" --test-dir "$out" -R '^test-rpc-multi-server$'
+ python3 tests/fleet_rpc_no_comm_test.py --binary "$out/bin/ggml-rpc-server"
+ python3 tests/fleet_rpc_smoke.py --build "$out"
+elif [[ $# != 0 ]]; then
+ echo 'usage: scripts/test-fleet.sh [--rpc]' >&2
+ exit 2
+fi
diff --git a/tests/fleet_rpc_no_comm_test.py b/tests/fleet_rpc_no_comm_test.py
new file mode 100644
index 0000000..9645ef6
--- /dev/null
+++ b/tests/fleet_rpc_no_comm_test.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+"""Regression for the pinned v8 RPC server's server-side NO_COMM gate.
+
+Starts one loopback CPU worker. Sends only valid HELLO/COMM_INIT/DEVICE_COUNT
+frames, never model data. The requested extra port is already reserved, so even
+an unpatched worker cannot open a wildcard listener there; rank 1 only targets
+loopback. This is a narrow wire regression, not a general RPC implementation.
+"""
+import argparse
+from contextlib import ExitStack
+import os
+from pathlib import Path
+import socket
+import struct
+import subprocess
+import time
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def receive(sock, length):
+ result = bytearray()
+ while len(result) < length:
+ chunk = sock.recv(length-len(result))
+ if not chunk:
+ raise AssertionError('RPC closed before the response completed')
+ result.extend(chunk)
+ return bytes(result)
+
+
+def request(sock, command, payload, expected_size):
+ sock.sendall(struct.pack('<BQ', command, len(payload)) + payload)
+ size, = struct.unpack('<Q', receive(sock, 8))
+ assert size == expected_size, (size, expected_size)
+ return receive(sock, size)
+
+
+def run(binary):
+ with ExitStack() as stack:
+ # Reserve a separate port for the rejected COMM_INIT. A bound loopback
+ # socket (no SO_REUSEADDR) excludes wildcard bind on that same port.
+ reserved = stack.enter_context(socket.socket())
+ reserved.bind(('127.0.0.1', 0))
+ comm_port = reserved.getsockname()[1]
+ chooser = socket.socket()
+ chooser.bind(('127.0.0.1', 0))
+ port = chooser.getsockname()[1]
+ chooser.close()
+ log_path = ROOT / 'build/fleet-smoke/no-comm.log'
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+ log = stack.enter_context(log_path.open('w'))
+ worker = subprocess.Popen([str(binary), '--host', '127.0.0.1', '--port', str(port),
+ '--device', 'CPU', '--threads', '1'],
+ stdout=log, stderr=subprocess.STDOUT,
+ env=dict(os.environ, GGML_RPC_NO_COMM='1', GGML_RPC_NO_RDMA='1'))
+ try:
+ deadline = time.monotonic()+20
+ while True:
+ if worker.poll() is not None:
+ raise AssertionError(f'worker exited {worker.returncode}; see {log_path}')
+ try:
+ sock = stack.enter_context(socket.create_connection(('127.0.0.1', port), timeout=0.1))
+ break
+ except OSError:
+ if time.monotonic() >= deadline:
+ raise TimeoutError('worker did not bind its loopback port')
+ time.sleep(0.05)
+ sock.settimeout(1)
+ hello = request(sock, 14, bytes(24), 28)
+ assert hello[:3] == bytes([8, 0, 0]), hello[:3]
+ for rank in (0, 1):
+ body = struct.pack('<IIII64s', 0, rank, 2, comm_port, b'127.0.0.1')
+ assert request(sock, 20, body, 1) == b'\0', f'rank {rank} was not refused'
+ # The refusal must leave this connection and normal RPC intact.
+ assert request(sock, 15, b'', 4) == struct.pack('<I', 1)
+ assert worker.poll() is None
+ print('RPC NO_COMM: rank 0 and rank 1 refused; ordinary RPC remains usable; no extra listeners')
+ finally:
+ # Closing the connection before terminating avoids a blocked read.
+ if 'sock' in locals():
+ sock.close()
+ if worker.poll() is None:
+ worker.terminate()
+ try:
+ worker.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ worker.kill()
+ worker.wait()
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--binary', type=Path, default=ROOT/'build/fleet-host/bin/ggml-rpc-server')
+ run(parser.parse_args().binary.resolve())
diff --git a/tests/fleet_rpc_smoke.py b/tests/fleet_rpc_smoke.py
new file mode 100644
index 0000000..a367840
--- /dev/null
+++ b/tests/fleet_rpc_smoke.py
@@ -0,0 +1,208 @@
+#!/usr/bin/env python3
+"""Real CPU RPC smoke: one tiny model, two localhost workers, one API host.
+
+This proves host TCP RPC graph execution, not PS5 hardware or Vulkan support.
+Run after scripts/build-fleet-host.sh. Logs/results remain in build/fleet-smoke.
+"""
+from contextlib import ExitStack
+from pathlib import Path
+import argparse
+import json
+import math
+import os
+import re
+import signal
+import sys
+import socket
+import subprocess
+import time
+import urllib.error
+import urllib.request
+
+from make_fleet_fixture import ROOT, make_fixture
+
+
+def free_ports(count):
+ # Hold all sockets until we have distinct ports. Workers take them next.
+ with ExitStack() as stack:
+ sockets = [stack.enter_context(socket.socket()) for _ in range(count)]
+ for sock in sockets:
+ sock.bind(("127.0.0.1", 0))
+ return [sock.getsockname()[1] for sock in sockets]
+
+
+def stop(process):
+ # Own a new process group so the CLI and its llama-server child are reaped.
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ if process.poll() is None:
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+
+
+def spawn(stack, command, logfile, env):
+ stream = stack.enter_context(logfile.open("w"))
+ process = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT, env=env, start_new_session=True)
+ stack.callback(stop, process)
+ return process
+
+
+def wait_ready(process, port, http=False):
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ if process.poll() is not None:
+ raise RuntimeError(f"process exited with {process.returncode} before port {port} was ready")
+ try:
+ if http:
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=1) as response:
+ if response.status == 200:
+ return
+ else:
+ with socket.create_connection(("127.0.0.1", port), timeout=1):
+ return
+ except (OSError, urllib.error.URLError):
+ time.sleep(0.05)
+ raise TimeoutError(f"port {port} was not ready in 60 seconds")
+
+
+def complete(port):
+ payload = {"prompt": [1, 259, 260, 261], "n_predict": 8, "temperature": 0,
+ "seed": 42, "ignore_eos": True, "return_tokens": True,
+ "n_probs": 5, "cache_prompt": False}
+ request = urllib.request.Request(f"http://127.0.0.1:{port}/completion",
+ data=json.dumps(payload).encode(),
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(request, timeout=60) as response:
+ result = json.load(response)
+ assert len(result.get("tokens", [])) == 8, result
+ return result
+
+
+def compare_logprobs(expected, actual):
+ left = expected["completion_probabilities"]
+ right = actual["completion_probabilities"]
+ assert len(left) == len(right) == 8
+ differences = []
+ for a, b in zip(left, right):
+ assert len(a["top_logprobs"]) == len(b["top_logprobs"]) == 5
+ for x, y in zip(a["top_logprobs"], b["top_logprobs"]):
+ assert x["id"] == y["id"], (x, y)
+ difference = abs(x["logprob"] - y["logprob"])
+ assert math.isfinite(difference) and difference <= 1e-5, difference
+ differences.append(difference)
+ return max(differences)
+
+
+def run(build, output):
+ output.mkdir(parents=True, exist_ok=True)
+ fixture = make_fixture(output / "tiny-llama.gguf")
+ rpc_server = build / "bin/ggml-rpc-server"
+ server = build / "bin/llama-server"
+ for binary in (rpc_server, server):
+ if not binary.is_file():
+ raise FileNotFoundError(f"{binary}; first run scripts/build-fleet-host.sh")
+ rpc_a, rpc_b, api = free_ports(3)
+ endpoints = [f"127.0.0.1:{port}" for port in (rpc_a, rpc_b)]
+ devices = ["RPC0", "RPC1"]
+ env = dict(os.environ, GGML_RPC_DEBUG="1", GGML_RPC_NO_RDMA="1", GGML_RPC_NO_COMM="1")
+ common = [str(server), "--model", str(fixture), "--host", "127.0.0.1", "--port", str(api),
+ "--ctx-size", "128", "--parallel", "1", "--threads", "2", "--threads-batch", "2",
+ "--batch-size", "128", "--ubatch-size", "128", "--cache-type-k", "f16",
+ "--cache-type-v", "f16", "--flash-attn", "off", "--fit", "off", "--no-warmup",
+ "--load-mode", "mmap", "--lazy-mode", "off", "--no-op-offload", "--log-verbosity", "5"]
+ commands = []
+ with ExitStack() as local_stack:
+ local_command = common + ["--device", "none", "--gpu-layers", "0"]
+ commands.append(local_command)
+ local = spawn(local_stack, local_command, output / "local.log", env)
+ wait_ready(local, api, http=True)
+ expected = complete(api)
+ with ExitStack() as stack:
+ for suffix, port in (("a", rpc_a), ("b", rpc_b)):
+ command = [str(rpc_server), "--host", "127.0.0.1", "--port", str(port),
+ "--device", "CPU", "--threads", "2"]
+ commands.append(command)
+ worker = spawn(stack, command, output / f"worker-{suffix}.log", env)
+ wait_ready(worker, port)
+ # Five offloadable units: block 0-3 plus output. Midpoint 3/10 puts
+ # blocks 0-1 on A and blocks 2-3 plus output on B, away from boundaries.
+ command = common + ["--rpc", ",".join(endpoints), "--device", ",".join(devices),
+ "--gpu-layers", "all", "--split-mode", "layer", "--tensor-split", "3,7"]
+ commands.append(command)
+ remote = spawn(stack, command, output / "controller.log", env)
+ wait_ready(remote, api, http=True)
+ actual = complete(api)
+ assert expected["tokens"] == actual["tokens"], (expected["tokens"], actual["tokens"])
+ rpc_logprob_error = compare_logprobs(expected, actual)
+ controller_log = (output / "controller.log").read_text(errors="replace")
+ placements = {}
+ for layer, device in re.findall(r"load_tensors: layer\s+(\d+) assigned to device ([^\s,]+)", controller_log):
+ placements[int(layer)] = device
+ assert placements == {0: devices[0], 1: devices[0], 2: devices[1], 3: devices[1], 4: devices[1]}, placements
+ worker_evidence = {}
+ for suffix in ("a", "b"):
+ log = (output / f"worker-{suffix}.log").read_text(errors="replace")
+ allocations = len(re.findall(r"\[alloc_buffer\].*remote_size: [1-9]", log))
+ computes = len(re.findall(r"\[graph_(?:re)?compute\]", log))
+ assert allocations > 0 and computes > 0, (suffix, allocations, computes)
+ assert "invalid data ptr" not in log, suffix
+ worker_evidence[suffix] = {"allocations": allocations, "compute_calls": computes}
+ # Exercise the actual user-facing CLI after restarting both workers.
+ cli_a, cli_b, cli_api = free_ports(3)
+ cli_endpoints = [f"127.0.0.1:{port}" for port in (cli_a, cli_b)]
+ inventory = {"host_memory_mib": 128, "host_reserve_mib": 16,
+ "nodes": [{"id": f"worker-{i}", "endpoint": endpoint,
+ "memory_mib": 128, "reserve_mib": 16}
+ for i, endpoint in enumerate(cli_endpoints)]}
+ inventory_path = output / "nodes.json"
+ inventory_path.write_text(json.dumps(inventory, indent=2) + "\n")
+ cli_plan = output / "cli-plan.json"
+ with ExitStack() as stack:
+ for suffix, port in (("a", cli_a), ("b", cli_b)):
+ command = [str(rpc_server), "--host", "127.0.0.1", "--port", str(port),
+ "--device", "CPU", "--threads", "2"]
+ commands.append(command)
+ worker = spawn(stack, command, output / f"cli-worker-{suffix}.log", env)
+ wait_ready(worker, port)
+ command = [sys.executable, "-m", "fleet", "serve", "--model", str(fixture),
+ "--nodes", str(inventory_path), "--context", "128", "--binary", str(server),
+ "--port", str(cli_api), "--plan-out", str(cli_plan), "--ack-insecure-rpc"]
+ commands.append(command)
+ cli_env = dict(env, PYTHONPATH=str(ROOT))
+ controller = spawn(stack, command, output / "cli-controller.log", cli_env)
+ wait_ready(controller, cli_api, http=True)
+ cli_response = complete(cli_api)
+ assert cli_response["tokens"] == expected["tokens"], cli_response
+ cli_logprob_error = compare_logprobs(expected, cli_response)
+ checked_plan = json.loads(cli_plan.read_text(errors="replace"))
+ assert checked_plan["memory_source"] == "min(operator_budget,live_RPC_snapshot)", checked_plan
+ assert checked_plan["tensor_split"] == [3, 7], checked_plan
+ for suffix in ("a", "b"):
+ log = (output / f"cli-worker-{suffix}.log").read_text(errors="replace")
+ assert re.search(r"\[alloc_buffer\].*remote_size: [1-9]", log), suffix
+ assert "[graph_compute]" in log, suffix
+ (output / "cli-response.json").write_text(json.dumps(cli_response, indent=2) + "\n")
+ result = {"status": "passed", "scope": "Linux CPU TCP RPC only; no PS5 or Vulkan validation",
+ "model": str(fixture), "model_bytes": fixture.stat().st_size,
+ "tokens": actual["tokens"], "local_tokens": expected["tokens"],
+ "fleet_cli_tokens": cli_response["tokens"], "fleet_cli_preflight": "passed",
+ "top5_logprobs_compared_per_run": 40,
+ "rpc_max_logprob_error": rpc_logprob_error, "cli_max_logprob_error": cli_logprob_error,
+ "placements": placements, "workers": worker_evidence, "commands": commands}
+ (output / "result.json").write_text(json.dumps(result, indent=2) + "\n")
+ (output / "local-response.json").write_text(json.dumps(expected, indent=2) + "\n")
+ (output / "rpc-response.json").write_text(json.dumps(actual, indent=2) + "\n")
+ print(json.dumps({key: value for key, value in result.items() if key != "commands"}, indent=2))
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--build", type=Path, default=ROOT / "build/fleet-host")
+ parser.add_argument("--output", type=Path, default=ROOT / "build/fleet-smoke")
+ args = parser.parse_args()
+ run(args.build.resolve(), args.output.resolve())
diff --git a/tests/fleet_worker_config_test.cpp b/tests/fleet_worker_config_test.cpp
new file mode 100644
index 0000000..de27b6a
--- /dev/null
+++ b/tests/fleet_worker_config_test.cpp
@@ -0,0 +1,43 @@
+// Portable safety-gate checks; no PS5 SDK, network, or ggml runtime required.
+// c++ -std=c++17 -Wall -Wextra -Werror -I ps5/app tests/fleet_worker_config_test.cpp -o build/fleet-worker-config-test
+#include "fleet_worker.hpp"
+
+#include <cstdlib>
+#include <iostream>
+
+int main() {
+ using ps5lm::FleetWorkerConfig;
+ using ps5lm::parse_fleet_worker_config;
+ const std::string ack = "\nI_UNDERSTAND_RPC_IS_UNAUTHENTICATED\n";
+ int checks = 0;
+ auto check = [&](bool ok, const std::string & label) {
+ ++checks;
+ if (!ok) {
+ std::cerr << "FAIL: " << label << '\n';
+ std::exit(1);
+ }
+ };
+ for (const std::string endpoint : { "10.0.0.1:30052", "172.16.0.1:1024", "172.31.255.254:39999",
+ "192.168.1.2:30052", "127.0.0.1:30052" }) {
+ const auto config = parse_fleet_worker_config(endpoint + ack);
+ check(config.state == FleetWorkerConfig::enabled && config.endpoint == endpoint && config.error.empty(), endpoint);
+ }
+ for (const std::string endpoint : { "", "0.0.0.0:30052", "8.8.8.8:30052", "172.15.0.1:30052",
+ "172.32.0.1:30052", "192.169.0.1:30052", "localhost:30052", "ps5:30052",
+ "10.0.0.1", "10.0.0.1:", "10.0.0.1:0", "10.0.0.1:1023", "10.0.0.1:65536",
+ "10.0.0.1:-1", "10.0.0.1:+30052", "10.0.0.1:030052", "10.0.0.1:30052junk",
+ "010.0.0.1:30052", "10.0.0.256:30052", "10.0.1:30052", "10.0.0.1.2:30052",
+ "10.0.0.1:30052:50053", "10.0.0.0:30052", "10.0.0.255:30052", "[::1]:30052",
+ " 10.0.0.1:30052", "10.0.0.1:30052 ", "10.0.0.1:40000", "10.0.0.1:65535", "127.0.0.2:30052", "169.254.0.1:30052" }) {
+ const auto config = parse_fleet_worker_config(endpoint + ack);
+ check(config.state == FleetWorkerConfig::invalid && config.endpoint.empty() && !config.error.empty(), endpoint);
+ }
+ for (const std::string & text : std::vector<std::string>{ "", "10.0.0.1:30052\n", "10.0.0.1:30052\nYES\n",
+ "10.0.0.1:30052" + ack + "extra\n", "10.0.0.1:30052" + ack + "\n",
+ std::string(1025, 'x'), std::string("10.0.0.1:30052\0", 16) + ack }) {
+ check(parse_fleet_worker_config(text).state == FleetWorkerConfig::invalid, "invalid contents");
+ }
+ check(parse_fleet_worker_config("192.168.1.2:30052\r\nI_UNDERSTAND_RPC_IS_UNAUTHENTICATED\r\n").state == FleetWorkerConfig::enabled, "CRLF");
+ check(parse_fleet_worker_config("192.168.1.2:30052\nI_UNDERSTAND_RPC_IS_UNAUTHENTICATED").state == FleetWorkerConfig::enabled, "no final newline");
+ std::cout << "PASS: " << checks << " fleet worker config checks\n";
+}
diff --git a/tests/fleet_worker_runtime_test.cpp b/tests/fleet_worker_runtime_test.cpp
new file mode 100644
index 0000000..31e1a30
--- /dev/null
+++ b/tests/fleet_worker_runtime_test.cpp
@@ -0,0 +1,101 @@
+// Unit tests with a deliberately fake backend. No GPU or socket is opened.
+// Build with fleet_worker.cpp and include ps5/app plus third_party/llama.cpp/ggml/include.
+#include "fleet_worker.hpp"
+#include "ggml-backend.h"
+#include "ggml-rpc.h"
+
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fstream>
+#include <iostream>
+#include <stdexcept>
+#include <sys/stat.h>
+#include <unistd.h>
+
+struct ggml_backend_reg { int unused; };
+struct ggml_backend_device { enum ggml_backend_dev_type type; };
+static ggml_backend_reg registry{};
+static ggml_backend_device gpu{GGML_BACKEND_DEVICE_TYPE_IGPU};
+static bool have_vulkan = true, throw_from_rpc = false;
+static size_t device_count = 1;
+static int rpc_calls = 0;
+static std::string last_endpoint;
+
+extern "C" {
+void ggml_backend_load_all() {}
+void ggml_log_set(ggml_log_callback, void *) {}
+ggml_backend_reg_t ggml_backend_reg_by_name(const char * name) {
+ return have_vulkan && std::strcmp(name, "Vulkan") == 0 ? &registry : nullptr;
+}
+size_t ggml_backend_reg_dev_count(ggml_backend_reg_t) { return device_count; }
+ggml_backend_dev_t ggml_backend_reg_dev_get(ggml_backend_reg_t, size_t) { return &gpu; }
+enum ggml_backend_dev_type ggml_backend_dev_type(ggml_backend_dev_t device) { return device->type; }
+const char * ggml_backend_dev_name(ggml_backend_dev_t) { return "FakeVulkan0"; }
+void ggml_backend_rpc_start_server(const char * endpoint, const char * cache, size_t threads,
+ size_t count, ggml_backend_dev_t * devices) {
+ const char * no_comm = std::getenv("GGML_RPC_NO_COMM");
+ if (cache || threads != 6 || count != 1 || devices[0] != &gpu || !no_comm || std::strcmp(no_comm, "1") != 0) {
+ std::abort();
+ }
+ ++rpc_calls;
+ last_endpoint = endpoint;
+ if (throw_from_rpc) {
+ throw std::runtime_error("test failure");
+ }
+}
+}
+
+int main() {
+ using namespace ps5lm;
+ int checks = 0;
+ auto check = [&](bool ok, const char * label) {
+ ++checks;
+ if (!ok) {
+ std::cerr << "FAIL: " << label << '\n';
+ std::exit(1);
+ }
+ };
+ const std::string text = "192.168.1.2:30052\nI_UNDERSTAND_RPC_IS_UNAUTHENTICATED\n";
+ const auto valid = parse_fleet_worker_config(text);
+ check(!run_fleet_worker({}).empty() && rpc_calls == 0, "disabled cannot open listener");
+ check(!run_fleet_worker({FleetWorkerConfig::enabled, "0.0.0.0:30052", ""}).empty() && rpc_calls == 0,
+ "forged wildcard config revalidated");
+ have_vulkan = false;
+ check(run_fleet_worker(valid).find("No Vulkan") != std::string::npos && rpc_calls == 0, "no Vulkan");
+ have_vulkan = true;
+ device_count = 0;
+ check(run_fleet_worker(valid).find("No Vulkan GPU") != std::string::npos && rpc_calls == 0, "empty backend");
+ device_count = 2;
+ check(run_fleet_worker(valid).find("exactly one") != std::string::npos && rpc_calls == 0, "ambiguous devices");
+ device_count = 1;
+ gpu.type = GGML_BACKEND_DEVICE_TYPE_CPU;
+ check(run_fleet_worker(valid).find("No Vulkan GPU") != std::string::npos && rpc_calls == 0, "no CPU fallback");
+ gpu.type = GGML_BACKEND_DEVICE_TYPE_IGPU;
+ setenv("GGML_RPC_NO_COMM", "0", 1); // Worker must override any app env setting.
+ check(run_fleet_worker(valid).find("stopped") != std::string::npos && rpc_calls == 1 &&
+ last_endpoint == valid.endpoint, "one Vulkan device, return is failure not success");
+ check(std::string(std::getenv("GGML_RPC_NO_COMM")) == "1", "worker disables extra listeners");
+ throw_from_rpc = true;
+ check(run_fleet_worker(valid).find("test failure") != std::string::npos && rpc_calls == 2, "exception reported");
+
+ char path[] = "/tmp/ps5lm-fleet-config-XXXXXX";
+ int fd = mkstemp(path);
+ check(fd >= 0, "temporary config file");
+ close(fd);
+ check(read_fleet_worker_config(path).state == FleetWorkerConfig::invalid, "empty file fails closed");
+ std::ofstream(path) << text;
+ check(read_fleet_worker_config(path).state == FleetWorkerConfig::enabled, "file enabled");
+ std::ofstream(path) << std::string(1025, 'x');
+ check(read_fleet_worker_config(path).state == FleetWorkerConfig::invalid, "oversized file fails closed");
+ unlink(path);
+ check(read_fleet_worker_config(path).state == FleetWorkerConfig::disabled, "missing file disabled");
+ check(read_fleet_worker_config("/tmp").state == FleetWorkerConfig::invalid, "directory fails closed");
+ check(mkfifo(path, 0600) == 0, "temporary FIFO");
+ check(read_fleet_worker_config(path).state == FleetWorkerConfig::invalid, "FIFO fails without blocking");
+ unlink(path);
+ check(symlink("/not-a-file-ps5lm-fleet", path) == 0, "temporary dangling symlink");
+ check(read_fleet_worker_config(path).state == FleetWorkerConfig::invalid, "dangling link does not disable fleet mode");
+ unlink(path);
+ std::cout << "PASS: " << checks << " fleet worker runtime/file checks (fake backend, no network)\n";
+}
diff --git a/tests/make_fleet_fixture.py b/tests/make_fleet_fixture.py
new file mode 100644
index 0000000..85ae048
--- /dev/null
+++ b/tests/make_fleet_fixture.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+"""Create a deterministic, untrained 4-block GGUF for RPC correctness tests.
+
+Uses the pinned llama.cpp GGUF writer and NumPy. This is not a useful language
+model and its output is intentionally meaningless. No weights are downloaded.
+"""
+from pathlib import Path
+import argparse
+import sys
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "third_party/llama.cpp/gguf-py"))
+
+
+def make_fixture(path: Path) -> Path:
+ import numpy as np
+ import gguf
+
+ path.parent.mkdir(parents=True, exist_ok=True)
+ writer = gguf.GGUFWriter(path, "llama")
+ writer.add_name("PS5LM deterministic fleet test fixture; untrained")
+ writer.add_context_length(256)
+ writer.add_embedding_length(32)
+ writer.add_block_count(4)
+ writer.add_feed_forward_length(64)
+ writer.add_head_count(4)
+ writer.add_head_count_kv(2)
+ writer.add_layer_norm_rms_eps(1e-5)
+ writer.add_rope_dimension_count(8)
+ writer.add_rope_freq_base(10000.0)
+ writer.add_tokenizer_model("llama")
+ tokens = ["<unk>", "<s>", "</s>"] + [f"<0x{i:02X}>" for i in range(256)]
+ tokens += [chr(i) for i in range(97, 123)] + ["\u2581"]
+ writer.add_token_list(tokens)
+ writer.add_token_scores([0.0] * len(tokens))
+ writer.add_token_types([2, 3, 3] + [6] * 256 + [1] * 27)
+ writer.add_bos_token_id(1)
+ writer.add_eos_token_id(2)
+ writer.add_unk_token_id(0)
+ writer.add_add_bos_token(True)
+ rng = np.random.default_rng(20261021)
+
+ def weight(name, shape):
+ writer.add_tensor(name, (rng.standard_normal(shape) * 0.08).astype(np.float32))
+
+ weight("token_embd.weight", (len(tokens), 32))
+ writer.add_tensor("output_norm.weight", np.ones(32, dtype=np.float32))
+ weight("output.weight", (len(tokens), 32))
+ for layer in range(4):
+ prefix = f"blk.{layer}."
+ writer.add_tensor(prefix + "attn_norm.weight", np.ones(32, dtype=np.float32))
+ writer.add_tensor(prefix + "ffn_norm.weight", np.ones(32, dtype=np.float32))
+ for name, shape in (
+ ("attn_q.weight", (32, 32)),
+ ("attn_k.weight", (16, 32)),
+ ("attn_v.weight", (16, 32)),
+ ("attn_output.weight", (32, 32)),
+ ("ffn_gate.weight", (64, 32)),
+ ("ffn_down.weight", (32, 64)),
+ ("ffn_up.weight", (64, 32)),
+ ):
+ weight(prefix + name, shape)
+ writer.write_header_to_file()
+ writer.write_kv_data_to_file()
+ writer.write_tensors_to_file()
+ writer.close()
+ return path
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("output", nargs="?", type=Path,
+ default=ROOT / "build/fleet-smoke/tiny-llama.gguf")
+ args = parser.parse_args()
+ result = make_fixture(args.output)
+ print(f"{result}: {result.stat().st_size} bytes (untrained)")
diff --git a/tests/requirements-fleet.txt b/tests/requirements-fleet.txt
new file mode 100644
index 0000000..c5d7500
--- /dev/null
+++ b/tests/requirements-fleet.txt
@@ -0,0 +1,3 @@
+# Fixture-only dependencies; GGUF writer comes from the pinned llama.cpp submodule.
+numpy==2.2.6
+PyYAML==6.0.2
diff --git a/tests/test_fleet_controller.py b/tests/test_fleet_controller.py
new file mode 100644
index 0000000..134d5a5
--- /dev/null
+++ b/tests/test_fleet_controller.py
@@ -0,0 +1,210 @@
+import bisect
+import itertools
+import json
+import os
+from pathlib import Path
+import struct
+import signal
+import time
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+from fleet import controller, models, planner
+from test_fleet_models import write_gguf
+
+
+def inventory(count=2, memory=32, reserve=1):
+ return dict(host_memory_mib=64, host_reserve_mib=1,
+ nodes=[dict(id=f'n{i}', endpoint=f'127.0.0.1:{50052+i}', memory_mib=memory, reserve_mib=reserve)
+ for i in range(count)])
+
+
+def model(count=6):
+ return dict(supported=True, architecture='llama', context_length=4096, layer_count=count,
+ layer_bytes=[2*planner.MIB]*count, kv_bytes_per_layer_per_token=[64]*count,
+ kv_cache_dtype='fp16', kv_element_bytes=2, input_bytes=planner.MIB,
+ output_bytes=3*planner.MIB, file_size_bytes=(count*2+4)*planner.MIB)
+
+
+class PlannerTests(unittest.TestCase):
+ def test_complete_coverage_and_kv(self):
+ result = planner.plan(model(), inventory(), 300)
+ self.assertEqual(result['padded_context_tokens'], 512)
+ self.assertEqual(sum(n['layer_end']-n['layer_start'] for n in result['nodes']), 6)
+ self.assertEqual(result['nodes'][0]['layer_start'], 0)
+ self.assertEqual(result['nodes'][-1]['layer_end'], 6)
+ self.assertFalse(result['nodes'][0]['output_layer'])
+ self.assertTrue(result['nodes'][-1]['output_layer'])
+ self.assertEqual(sum(n['kv_bytes'] for n in result['nodes']), 6*64*512)
+
+ def test_midpoint_ratios_match_llama_float32_upper_bound(self):
+ f32 = lambda v: struct.unpack('f', struct.pack('f', v))[0]
+ for count in range(2, 40):
+ for workers in range(2, min(count, 8)+1):
+ result = planner.plan(model(count), inventory(workers, memory=200), 32)
+ cumulative = list(itertools.accumulate(result['tensor_split']))
+ splits = [f32(v/cumulative[-1]) for v in cumulative]
+ for i, node in enumerate(result['nodes']):
+ for layer in range(node['layer_start'], node['layer_end']):
+ self.assertEqual(bisect.bisect_right(splits, f32(layer/(count+1))), i)
+ self.assertEqual(bisect.bisect_right(splits, f32(count/(count+1))), workers-1)
+
+ def test_unequal_layers_choose_feasible_partition(self):
+ info = model(4)
+ info['layer_bytes'] = [8*planner.MIB, 2*planner.MIB, planner.MIB, planner.MIB]
+ conf = inventory(memory=12)
+ conf['nodes'][1]['memory_mib'] = 8
+ result = planner.plan(info, conf, 32)
+ self.assertEqual(result['nodes'][0]['layer_end'], 2)
+ for node in result['nodes']:
+ self.assertLessEqual(node['estimated_bytes'], node['memory_mib'] * planner.MIB)
+
+ def test_infeasible_not_silently_cpu_spill(self):
+ with self.assertRaisesRegex(planner.FleetError, 'No contiguous'):
+ planner.plan(model(), inventory(memory=5), 4096)
+
+ def test_maximum_15_nodes_executes_cli_limit(self):
+ result = planner.plan(model(16), inventory(15, memory=64), 32)
+ self.assertEqual(len(result['tensor_split']), 15)
+
+ def test_host_budget(self):
+ conf = inventory()
+ conf['host_memory_mib'] = 1
+ with self.assertRaisesRegex(planner.FleetError, 'Host'):
+ planner.plan(model(), conf)
+
+ def test_unsupported_and_long_context(self):
+ for change in [dict(supported=False, unsupported_reasons=['hybrid']), dict(architecture='qwen35'),
+ dict(kv_cache_dtype='q8_0'), dict(kv_bytes_per_layer_per_token=[]), dict(layer_count=513)]:
+ with self.subTest(change=change), self.assertRaises(planner.FleetError):
+ planner.plan(dict(model(), **change), inventory())
+ with self.assertRaisesRegex(planner.FleetError, 'training context'):
+ planner.plan(model(), inventory(), 8192)
+
+ def test_endpoint_validation(self):
+ for value in ('0.0.0.0:50052', '8.8.8.8:50052', '100.64.0.1:1', '169.254.1.2:1',
+ 'ps5:50052', 'http://127.0.0.1:1', '[::1]:50', '127.0.0.1:0', '127.0.0.1:65536',
+ '127.0.0.1:1,--host', '192.168.001.1:50', None):
+ with self.subTest(value=value), self.assertRaises(planner.FleetError):
+ planner.endpoint(value)
+ for value in ('192.168.1.21:50052', '10.1.1.1:50052', '172.31.1.1:1', '127.0.0.1:50052'):
+ self.assertEqual(planner.endpoint(value), value)
+
+ def test_inventory_invalid(self):
+ for conf in ({}, dict(inventory(), nodes=[]), inventory(1), inventory(16), inventory(17), inventory(reserve=32)):
+ with self.subTest(config=conf), self.assertRaises(planner.FleetError):
+ planner.inventory(conf)
+ conf = inventory()
+ conf['nodes'][1]['endpoint'] = conf['nodes'][0]['endpoint']
+ with self.assertRaisesRegex(planner.FleetError, 'Duplicate'):
+ planner.inventory(conf)
+ conf = inventory()
+ conf['nodes'][0]['memory_mib'] = True
+ with self.assertRaises(planner.FleetError):
+ planner.inventory(conf)
+
+
+class ControllerTests(unittest.TestCase):
+ def test_generated_command_pins_devices_and_runtime(self):
+ result = planner.plan(model(), inventory())
+ args = controller.command('/tmp/server', '/tmp/a model.gguf', result)
+ self.assertEqual(args[args.index('--device')+1], 'RPC0,RPC1')
+ self.assertEqual(args[args.index('--host')+1], '127.0.0.1')
+ self.assertEqual(args[args.index('--fit')+1], 'off')
+ self.assertEqual(args[args.index('--model')+1], str(Path('/tmp/a model.gguf').resolve()))
+ self.assertEqual(args[args.index('--parallel')+1], '1')
+
+ def test_environment_cannot_override_plan(self):
+ with patch.dict(os.environ, {'LLAMA_ARG_MODEL': 'bad', 'LLAMA_ARG_RPC': '8.8.8.8:1'}):
+ env = controller.child_environment()
+ self.assertNotIn('LLAMA_ARG_MODEL', env)
+ self.assertNotIn('LLAMA_ARG_RPC', env)
+ self.assertEqual(env['GGML_RPC_NO_RDMA'], '1')
+
+ def test_preflight_caps_declared_budget(self):
+ text = ('Available devices:\n RPC0: 127.0.0.1:50052 (64 MiB, 24 MiB free)\n'
+ ' RPC1: 127.0.0.1:50053 (64 MiB, 48 MiB free)\n')
+ with patch.object(subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, text, '')):
+ conf = controller.probe('/tmp/server', inventory())
+ self.assertEqual([n['memory_mib'] for n in conf['nodes']], [24, 32])
+
+ def test_preflight_fail_closed(self):
+ texts = ['', 'Available devices:\n (none)\n',
+ 'RPC0: 127.0.0.1:50052 (32 MiB, 0 MiB free)\n',
+ 'RPC0: 127.0.0.1:50052 (32 MiB, 40 MiB free)\n',
+ 'RPC0: 127.0.0.1:50052 (32 MiB, 20 MiB free)\nRPC1: 127.0.0.1:50052 (32 MiB, 20 MiB free)\n']
+ for text in texts:
+ with self.subTest(text=text), patch.object(subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, text, '')):
+ with self.assertRaises(planner.FleetError):
+ controller.probe('/tmp/server', inventory())
+ with patch.object(subprocess, 'run', side_effect=subprocess.TimeoutExpired('server', 1)):
+ with self.assertRaisesRegex(planner.FleetError, 'no model server'):
+ controller.probe('/tmp/server', inventory())
+
+ def test_cli_plan_real_gguf(self):
+ with tempfile.TemporaryDirectory() as directory:
+ d = Path(directory)
+ path = write_gguf(d/'tiny.gguf', layers=4)
+ config = d/'nodes.json'
+ config.write_text(json.dumps(inventory()))
+ output = d/'plan.json'
+ result = subprocess.run([os.sys.executable, '-m', 'fleet', 'plan', '--model', str(path),
+ '--nodes', str(config), '--context', '256', '--plan-out', str(output)],
+ capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ decoded = json.loads(output.read_text())
+ self.assertEqual(decoded['model_sha256'], controller.checksum(path))
+ self.assertEqual(decoded['status'], 'estimated_not_reserved')
+ self.assertEqual(decoded['memory_source'], 'operator_budgets_only')
+ for action in ('serve', 'plan'):
+ argv = [action, '--model', str(path), '--nodes', str(config)]
+ if action == 'plan':
+ argv += ['--sha256', '0'*64]
+ self.assertEqual(controller.main(argv), 2)
+
+ @unittest.skipUnless(os.name == 'posix', 'POSIX wrapper signal ownership')
+ def test_wrapper_sigterm_reaps_server(self):
+ with tempfile.TemporaryDirectory() as directory:
+ pidfile = Path(directory)/'server.pid'
+ child_code = ("import os,time; from pathlib import Path; "
+ f"Path({str(pidfile)!r}).write_text(str(os.getpid())); time.sleep(120)")
+ wrapper_code = ("from fleet.controller import run_foreground; import sys; "
+ f"sys.exit(run_foreground({[os.sys.executable, '-c', child_code]!r}))")
+ wrapper = subprocess.Popen([os.sys.executable, '-c', wrapper_code])
+ try:
+ deadline = time.monotonic()+5
+ while not pidfile.exists() and time.monotonic() < deadline:
+ time.sleep(0.02)
+ self.assertTrue(pidfile.exists())
+ child_pid = int(pidfile.read_text())
+ wrapper.send_signal(signal.SIGTERM)
+ self.assertEqual(wrapper.wait(timeout=5), 143)
+ with self.assertRaises(ProcessLookupError):
+ os.kill(child_pid, 0)
+ finally:
+ if wrapper.poll() is None:
+ wrapper.kill()
+ wrapper.wait()
+
+ def test_manifest_hash_and_revision(self):
+ with tempfile.TemporaryDirectory() as directory:
+ d = Path(directory)
+ (d/'bin').mkdir()
+ binary = d/'bin/llama-server'
+ binary.write_text('#!/bin/sh\nexit 0\n')
+ binary.chmod(0o700)
+ with self.assertRaisesRegex(planner.FleetError, 'Missing build manifest'):
+ controller.verify_binary(binary)
+ manifest = d/'fleet-build.json'
+ data = dict(llama_revision=controller.LLAMA_REVISION, server_sha256=controller.checksum(binary))
+ manifest.write_text(json.dumps(data))
+ controller.verify_binary(binary)
+ binary.write_text('#!/bin/sh\nexit 1\n')
+ with self.assertRaisesRegex(planner.FleetError, 'checksum'):
+ controller.verify_binary(binary)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_fleet_models.py b/tests/test_fleet_models.py
new file mode 100644
index 0000000..464d2a0
--- /dev/null
+++ b/tests/test_fleet_models.py
@@ -0,0 +1,427 @@
+"""Synthetic GGUF fixtures and offline download policy/security tests."""
+import hashlib
+from http.client import IncompleteRead
+from email.message import Message
+from pathlib import Path
+import socket
+import struct
+import tempfile
+import threading
+import unittest
+from unittest.mock import patch
+
+from fleet import models
+
+
+def _string(value):
+ encoded = value.encode('utf-8')
+ return struct.pack('<Q', len(encoded)) + encoded
+
+
+def _value(value):
+ if isinstance(value, str):
+ return struct.pack('<I', 8) + _string(value)
+ if isinstance(value, list):
+ return struct.pack('<IIQ', 9, 4, len(value)) + b''.join(struct.pack('<I', item) for item in value)
+ return struct.pack('<II', 4, value)
+
+
+def write_gguf(path, layers=2, arch='llama', tied=True, *, metadata=None,
+ omit=(), extra=(), offsets=None, dtype=0, hidden=4,
+ heads=2, kv_heads=1, fill=0):
+ """Write a complete tiny, structurally valid dense transformer GGUF."""
+ meta = {'general.architecture': arch, 'general.name': 'Tiny offline fixture',
+ f'{arch}.block_count': layers, f'{arch}.embedding_length': hidden,
+ f'{arch}.context_length': 4096,
+ f'{arch}.attention.head_count': heads,
+ f'{arch}.attention.head_count_kv': kv_heads}
+ meta.update(metadata or {})
+ specs = [('token_embd.weight', [hidden, 8], dtype)]
+ key_dims = meta.get(f'{arch}.attention.key_length', hidden // heads)
+ value_dims = meta.get(f'{arch}.attention.value_length', hidden // heads)
+ for layer in range(layers):
+ layer_kv = kv_heads[layer] if isinstance(kv_heads, list) else kv_heads
+ layer_key = key_dims[layer] if isinstance(key_dims, list) else key_dims
+ layer_value = value_dims[layer] if isinstance(value_dims, list) else value_dims
+ parts = [('attn_norm.weight', [hidden]),
+ ('attn_q.weight', [hidden, heads * layer_key]),
+ ('attn_k.weight', [hidden, layer_kv * layer_key]),
+ ('attn_v.weight', [hidden, layer_kv * layer_value]),
+ ('attn_output.weight', [heads * layer_value, hidden]),
+ ('ffn_norm.weight', [hidden]),
+ ('ffn_gate.weight', [hidden, 8]),
+ ('ffn_up.weight', [hidden, 8]),
+ ('ffn_down.weight', [8, hidden])]
+ specs += [(f'blk.{layer}.{name}', shape, 0) for name, shape in parts]
+ specs += [('output_norm.weight', [hidden], 0)]
+ if not tied:
+ specs += [('output.weight', [hidden, 8], dtype)]
+ specs += list(extra)
+ specs = [item for item in specs if item[0] not in omit]
+ header = b'GGUF' + struct.pack('<IQQ', 3, len(specs), len(meta))
+ for key, value in meta.items():
+ header += _string(key) + _value(value)
+ data = bytearray()
+ for index, (name, shape, encoding) in enumerate(specs):
+ elements = 1
+ for dimension in shape:
+ elements *= dimension
+ block, block_size = models.GGML_TYPES.get(encoding, (1, 4))
+ nbytes = elements // block * block_size
+ offset = offsets[index] if offsets is not None else len(data)
+ header += _string(name) + struct.pack('<I', len(shape))
+ header += b''.join(struct.pack('<Q', dim) for dim in shape)
+ header += struct.pack('<IQ', encoding, offset)
+ data.extend(bytes([fill]) * models._align(nbytes, 32))
+ header += bytes(models._align(len(header), 32) - len(header))
+ Path(path).write_bytes(header + data)
+ return Path(path)
+
+
+class InspectionTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.path = Path(self.tmp.name) / 'tiny.gguf'
+
+ def test_dense_llama_gqa_exact_accounting(self):
+ model = models.inspect_file(write_gguf(self.path))
+ self.assertTrue(model['supported'], model['unsupported_reasons'])
+ self.assertEqual(model['layer_bytes'], [640, 640])
+ self.assertEqual(model['input_bytes'], 128)
+ self.assertEqual(model['output_bytes'], 160)
+ self.assertEqual(model['kv_bytes_per_layer_per_token'], [8, 8])
+ self.assertEqual(model['kv_cache_dtype'], 'fp16')
+ self.assertEqual(model['kv_element_bytes'], 2)
+ self.assertEqual(model['context_length'], 4096)
+ self.assertEqual(model['file_size_bytes'], self.path.stat().st_size)
+ self.assertEqual(sum(model['layer_bytes']) + model['input_bytes'] + model['output_bytes'],
+ model['tensor_storage_bytes'] + model['replicated_output_bytes'])
+
+ def test_rope_replication_fails_closed(self):
+ model = models.inspect_file(write_gguf(self.path, extra=[('rope_freqs.weight', [2], 0)]))
+ self.assertFalse(model['supported'])
+ self.assertTrue(any('replication' in reason for reason in model['unsupported_reasons']))
+
+ def test_qwen2_untied_output(self):
+ model = models.inspect_file(write_gguf(self.path, arch='qwen2', tied=False))
+ self.assertTrue(model['supported'])
+ self.assertFalse(model['tied_embeddings'])
+ self.assertEqual(model['replicated_output_bytes'], 0)
+ self.assertEqual(model['output_bytes'], 160)
+
+ def test_per_layer_gqa_and_head_size(self):
+ model = models.inspect_file(write_gguf(self.path, kv_heads=[1, 2], metadata={
+ 'llama.attention.key_length': 3, 'llama.attention.value_length': 2}))
+ self.assertEqual(model['kv_bytes_per_layer_per_token'], [10, 20])
+ self.assertEqual(model['kv_elements_per_layer_per_token'], [5, 10])
+
+ def test_identity_is_explicitly_not_full_weight_hash(self):
+ write_gguf(self.path, fill=1)
+ first = models.inspect_file(self.path)
+ sha1 = hashlib.sha256(self.path.read_bytes()).hexdigest()
+ write_gguf(self.path, fill=2)
+ second = models.inspect_file(self.path)
+ sha2 = hashlib.sha256(self.path.read_bytes()).hexdigest()
+ self.assertEqual(first['model_id'], second['model_id'])
+ self.assertNotEqual(sha1, sha2)
+ self.assertEqual(first['identity_kind'], 'metadata-only-sha256')
+
+ def test_hybrid_architecture_no_fake_kv(self):
+ model = models.inspect_file(write_gguf(self.path, arch='qwen35'))
+ self.assertFalse(model['supported'])
+ self.assertEqual(model['kv_bytes_per_layer_per_token'], [])
+ self.assertIn('Hybrid/recurrent', ' '.join(model['unsupported_reasons']))
+
+ def test_missing_tensor_not_supported(self):
+ model = models.inspect_file(write_gguf(self.path, omit=['blk.1.attn_k.weight']))
+ self.assertFalse(model['supported'])
+ self.assertIn('Block 1 is incomplete', ' '.join(model['unsupported_reasons']))
+
+ def test_shared_unknown_tensor_is_counted_and_rejected(self):
+ baseline = models.inspect_file(write_gguf(self.path))
+ model = models.inspect_file(write_gguf(self.path, extra=[('surprise.weight', [4], 0)]))
+ self.assertFalse(model['supported'])
+ self.assertEqual(model['input_bytes'], baseline['input_bytes'] + 32)
+
+ def test_split_metadata_is_not_supported(self):
+ model = models.inspect_file(write_gguf(self.path, metadata={'split.count': 2}))
+ self.assertFalse(model['supported'])
+ self.assertIn('Split GGUF', ' '.join(model['unsupported_reasons']))
+
+ def test_split_filename_is_not_supported(self):
+ path = self.path.with_name('tiny-00001-of-00002.gguf')
+ self.assertFalse(models.inspect_file(write_gguf(path))['supported'])
+
+ def test_unknown_type_is_explicitly_unsupported(self):
+ model = models.inspect_file(write_gguf(self.path, dtype=999))
+ self.assertFalse(model['supported'])
+ self.assertIn('999', ' '.join(model['unsupported_reasons']))
+
+ def test_unknown_block_tensor_is_counted_and_rejected(self):
+ model = models.inspect_file(write_gguf(self.path, extra=[('blk.0.unrecognized.weight', [4], 0)]))
+ self.assertFalse(model['supported'])
+ self.assertEqual(model['layer_bytes'][0], 672)
+
+ def test_directory_and_fifo_are_rejected_without_blocking(self):
+ with self.assertRaises(models.ModelError):
+ models.inspect_file(self.tmp.name)
+ if hasattr(models.os, 'mkfifo'):
+ fifo = Path(self.tmp.name) / 'named-pipe'
+ models.os.mkfifo(fifo)
+ with self.assertRaisesRegex(models.ModelError, 'regular file'):
+ models.inspect_file(fifo)
+
+ def test_q4_block_bytes(self):
+ model = models.inspect_file(write_gguf(self.path, hidden=32, dtype=2))
+ self.assertTrue(model['supported'])
+ self.assertEqual(model['input_bytes'], 160) # 8*18 bytes rounded to 32
+
+ def test_quantized_row_must_have_complete_blocks(self):
+ write_gguf(self.path, hidden=4, dtype=2)
+ with self.assertRaisesRegex(models.ModelError, 'quantization block'):
+ models.inspect_file(self.path)
+
+ def test_truncated_tensor(self):
+ write_gguf(self.path)
+ self.path.write_bytes(self.path.read_bytes()[:-20])
+ with self.assertRaisesRegex(models.ModelError, 'truncated'):
+ models.inspect_file(self.path)
+
+ def test_overlapping_tensor_offsets(self):
+ write_gguf(self.path, offsets=[0] * 20)
+ with self.assertRaisesRegex(models.ModelError, 'overlap'):
+ models.inspect_file(self.path)
+
+ def test_offsets_outside_file(self):
+ write_gguf(self.path, offsets=[2**50 + n * 1024 for n in range(20)])
+ with self.assertRaisesRegex(models.ModelError, 'outside'):
+ models.inspect_file(self.path)
+
+ def test_metadata_shape_mismatch(self):
+ write_gguf(self.path, metadata={'llama.embedding_length': 8})
+ with self.assertRaisesRegex(models.ModelError, 'shape disagrees'):
+ models.inspect_file(self.path)
+
+ def test_invalid_magic_version_alignment(self):
+ for content in (b'nope' + bytes(32), b'GGUF' + struct.pack('<IQQ', 2, 1, 0)):
+ self.path.write_bytes(content)
+ with self.assertRaises(models.ModelError):
+ models.inspect_file(self.path)
+ write_gguf(self.path, metadata={'general.alignment': 3})
+ with self.assertRaisesRegex(models.ModelError, 'power of two'):
+ models.inspect_file(self.path)
+
+ def test_oversized_string_and_array_are_bounded(self):
+ base = b'GGUF' + struct.pack('<IQQ', 3, 1, 1)
+ self.path.write_bytes(base + struct.pack('<Q', 2**63))
+ with self.assertRaisesRegex(models.ModelError, 'string exceeds'):
+ models.inspect_file(self.path)
+ self.path.write_bytes(base + _string('tokenizer.ggml.tokens') + struct.pack('<IIQ', 9, 8, 2**63))
+ with self.assertRaisesRegex(models.ModelError, 'array exceeds'):
+ models.inspect_file(self.path)
+
+ def test_huge_tensor_and_metadata_count(self):
+ for tensor_count, metadata_count in ((2**63, 0), (1, 2**63)):
+ self.path.write_bytes(b'GGUF' + struct.pack('<IQQ', 3, tensor_count, metadata_count))
+ with self.assertRaises(models.ModelError):
+ models.inspect_file(self.path)
+
+
+class FakeResponse:
+ def __init__(self, body=b'GGUF-example', status=200, headers=None, fail=False):
+ self.status = status
+ self.body = body
+ self.headers = Message()
+ for key, value in (headers or {}).items():
+ self.headers[key] = str(value)
+ self.length = None
+ self.fail = fail
+
+ def getheader(self, name, default=None):
+ return self.headers.get(name, default)
+
+ def read1(self, amount):
+ if self.fail:
+ raise IncompleteRead(b'partial')
+ part, self.body = self.body[:amount], self.body[amount:]
+ return part
+
+
+class DownloadTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.cache = Path(self.tmp.name) / 'cache'
+ self.connections = []
+ self.responses = []
+ owner = self
+
+ class FakeConnection:
+ def __init__(self, host, pin, timeout):
+ self.host, self.pin = host, pin
+ self.sock = None
+ owner.connections.append(self)
+ def request(self, method, target, headers):
+ self.method, self.target, self.headers = method, target, headers
+ def getresponse(self):
+ return owner.responses.pop(0)
+ def close(self):
+ pass
+ def abort(self):
+ pass
+
+ self.connection = patch.object(models, '_PinnedHTTPSConnection', FakeConnection)
+ self.connection.start()
+ self.addCleanup(self.connection.stop)
+ self.dns = patch.object(models.socket, 'getaddrinfo', return_value=[
+ (socket.AF_INET, socket.SOCK_STREAM, 6, '', ('93.184.216.34', 443))])
+ self.dns_mock = self.dns.start()
+ self.addCleanup(self.dns.stop)
+
+ def fetch(self, **kwargs):
+ return models.fetch_model('https://example.org/model.gguf', self.cache, **kwargs)
+
+ def test_stream_hash_atomic_name(self):
+ body = b'GGUF-tiny-model'
+ self.responses = [FakeResponse(body, headers={'Content-Length': len(body)})]
+ path, digest = self.fetch(max_bytes=100)
+ self.assertEqual(path.name, hashlib.sha256(body).hexdigest() + '.gguf')
+ self.assertEqual(path.read_bytes(), body)
+ self.assertEqual(digest, hashlib.sha256(body).hexdigest())
+ self.assertEqual(len(list(self.cache.iterdir())), 1)
+ self.assertNotIn('Authorization', self.connections[0].headers)
+ self.assertEqual(self.connections[0].pin[3], ('93.184.216.34', 443))
+
+ def test_forbidden_url_forms(self):
+ invalid = ['http://example.org/m', 'https://name:[email protected]/m',
+ 'https://example.org:8080/m', 'file:///etc/passwd',
+ 'https://example.org/m?access_token=secret',
+ 'https://example.org/m#fragment', 'https://example.org/\nX:1',
+ 'https://%31%32%37.0.0.1/m', 'https://example.org\\@localhost/m']
+ for url in invalid:
+ with self.subTest(url=url), self.assertRaises(models.DownloadError):
+ models.fetch_model(url, self.cache)
+ self.assertEqual(self.connections, [])
+
+ def test_private_and_mixed_dns_blocked(self):
+ for address in ('127.0.0.1', '10.0.0.1', '169.254.169.254', '192.168.1.1',
+ '100.64.0.1', '0.0.0.0', '224.0.0.1'):
+ self.dns_mock.return_value = [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (address, 443))]
+ with self.subTest(address=address), self.assertRaisesRegex(models.DownloadError, 'non-public'):
+ self.fetch()
+ self.dns_mock.return_value += [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('93.184.216.34', 443))]
+ with self.assertRaises(models.DownloadError):
+ self.fetch()
+ self.assertEqual(self.connections, [])
+
+ def test_ipv6_mapped_private_and_transition_blocked(self):
+ for address in ('::1', 'fe80::1', 'fc00::1', '::ffff:127.0.0.1',
+ '64:ff9b::7f00:1', '2002:7f00:1::', 'ff02::1'):
+ self.assertFalse(models._public_ip(address), address)
+ self.assertTrue(models._public_ip('2606:4700:4700::1111'))
+
+ def test_redirect_validated_no_private_connection(self):
+ self.responses = [FakeResponse(status=302, headers={'Location': 'https://localhost/model'})]
+ self.dns_mock.side_effect = [
+ [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('93.184.216.34', 443))],
+ [(socket.AF_INET, socket.SOCK_STREAM, 6, '', ('127.0.0.1', 443))]]
+ with self.assertRaisesRegex(models.DownloadError, 'non-public'):
+ self.fetch()
+ self.assertEqual(len(self.connections), 1)
+
+ def test_relative_redirect_and_cross_origin_no_auth(self):
+ self.responses = [FakeResponse(status=302, headers={'Location': '/next'}),
+ FakeResponse(status=307, headers={'Location': 'https://cdn.example.net/m'}),
+ FakeResponse(b'ok')]
+ path, _ = self.fetch()
+ self.assertEqual(path.read_bytes(), b'ok')
+ self.assertEqual([c.target for c in self.connections], ['/model.gguf', '/next', '/m'])
+ self.assertEqual(self.dns_mock.call_count, 3)
+ self.assertTrue(all(not {'Authorization', 'Cookie'} & set(c.headers) for c in self.connections))
+
+ def test_dns_resolution_deadline(self):
+ release = threading.Event()
+ completed = threading.Event()
+ def blocked_lookup(*args, **kwargs):
+ release.wait(timeout=5)
+ completed.set()
+ return []
+ self.dns_mock.side_effect = blocked_lookup
+ try:
+ with self.assertRaisesRegex(models.DownloadError, 'DNS resolution'):
+ models._resolve_public('example.org', timeout=0.01)
+ # A deadline must return while DNS is still blocked. Avoid a tight
+ # wall-clock speed assertion that flakes on busy hosted runners.
+ self.assertFalse(completed.is_set())
+ finally:
+ release.set()
+ completed.wait(timeout=5)
+
+ def test_numeric_ip_connect_uses_pin_and_original_tls_sni(self):
+ # Use the real connection class beneath the mock layer to verify there
+ # is no second DNS lookup, and that certificate/SNI hostname is retained.
+ self.connection.stop()
+ pin = (socket.AF_INET, socket.SOCK_STREAM, 6, ('93.184.216.34', 443))
+ with patch.object(models.socket, 'socket') as socket_factory, patch.object(models.ssl, 'create_default_context') as context:
+ raw = socket_factory.return_value
+ raw.getpeername.return_value = ('93.184.216.34', 443)
+ connection = models._PinnedHTTPSConnection('example.org', pin, 1)
+ connection.connect()
+ raw.connect.assert_called_once_with(('93.184.216.34', 443))
+ context.return_value.wrap_socket.assert_called_once_with(raw, server_hostname='example.org', do_handshake_on_connect=False)
+ context.return_value.wrap_socket.return_value.do_handshake.assert_called_once()
+ self.dns_mock.assert_not_called()
+
+ def test_redirect_limit(self):
+ self.responses = [FakeResponse(status=302, headers={'Location': '/next'}) for _ in range(4)]
+ with self.assertRaisesRegex(models.DownloadError, 'redirect limit'):
+ self.fetch()
+ self.assertEqual(len(self.connections), 4)
+
+ def test_known_and_unknown_lengths_bounded_and_cleaned(self):
+ for headers in ({'Content-Length': 10}, {}):
+ self.responses = [FakeResponse(b'0123456789', headers=headers)]
+ with self.assertRaisesRegex(models.DownloadError, 'limit|budget'):
+ self.fetch(max_bytes=4)
+ self.assertEqual(list(self.cache.iterdir()), [])
+
+ def test_truncation_and_network_error_cleaned(self):
+ for response in (FakeResponse(b'ab', headers={'Content-Length': 4}), FakeResponse(fail=True)):
+ self.responses = [response]
+ with self.assertRaises(models.DownloadError):
+ self.fetch()
+ self.assertEqual(list(self.cache.iterdir()), [])
+
+ def test_bad_status_and_encoding(self):
+ for response in (FakeResponse(status=404), FakeResponse(headers={'Content-Encoding': 'gzip'}),
+ FakeResponse(headers={'Transfer-Encoding': 'chunked', 'Content-Length': 12})):
+ self.responses = [response]
+ with self.assertRaises(models.DownloadError):
+ self.fetch()
+
+ def test_cache_budget_and_space(self):
+ self.cache.mkdir()
+ (self.cache / 'old.gguf').write_bytes(b'old')
+ self.responses = [FakeResponse(b'abc')]
+ with self.assertRaisesRegex(models.DownloadError, 'budget'):
+ self.fetch(max_cache_bytes=4)
+ self.responses = [FakeResponse(b'abc')]
+ with patch.object(models.shutil, 'disk_usage') as disk:
+ disk.return_value.free = 0
+ with self.assertRaisesRegex(models.DownloadError, 'disk space'):
+ self.fetch()
+ self.assertEqual([p.name for p in self.cache.iterdir()], ['old.gguf'])
+
+ def test_inspect_url_includes_full_hash(self):
+ file = Path(self.tmp.name) / 'fixture.gguf'
+ write_gguf(file)
+ self.responses = [FakeResponse(file.read_bytes())]
+ result = models.inspect_url('https://example.org/tiny', self.cache)
+ self.assertTrue(result['supported'])
+ self.assertEqual(result['sha256'], hashlib.sha256(file.read_bytes()).hexdigest())
+ self.assertTrue(Path(result['path']).exists())
+
+
+if __name__ == '__main__':
+ unittest.main()