llama.cpp on a jailbroken PS5: run any GGUF model natively on the console, starting with Qwen 3.8
First llama.cpp run on a PS5; safe CPU defaults for the console
Mert Cobanovddd02fd3398a
diff --git a/README.md b/README.mdindex 9039594..09fc1df 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@The first target is **Qwen 3.8** (27B, hybrid Gated DeltaNet attention), the newest open Qwen. No one has run it on a PS5 yet.-> **Status:** `llama-cli`, `llama-server` and `llama-bench` cross-compile and link for the PS5 with no changes to llama.cpp's source. Nothing has run on a console yet: that is next. See [docs/ROADMAP.md](docs/ROADMAP.md).+> **Status:** llama.cpp runs on a PS5. Qwen3.5 0.8B generates 14 tokens/s on two of the console's CPU cores (firmware 13.60, PS5 Slim). Next: the chat UI in the PS5's browser, then bigger models. See [docs/ROADMAP.md](docs/ROADMAP.md) and [docs/CONSOLE.md](docs/CONSOLE.md).## Why llama.cpp@@ -16,7 +16,8 @@ Earlier PS5 LLM work hand-writes GPU kernels for one model at a time. PS5LM port|---|---|| `third_party/llama.cpp` | upstream llama.cpp, pinned as a submodule || `ps5/compat` | the few libc functions the console lacks |-| `probes/memprobe` | Phase 0: measures memory, bandwidth and compute on the console |+| `patches/` | PS5 changes to llama.cpp's source, kept small |+| `probes/` | `memprobe` and `threadprobe`: what a payload gets on the console || `scripts/` | SDK setup, the llama.cpp cross build, sending payloads || `docs/` | [roadmap](docs/ROADMAP.md), [models that fit](docs/MODELS.md), [porting notes](docs/PORTING.md), [research](docs/RESEARCH.md) |diff --git a/docs/CONSOLE.md b/docs/CONSOLE.mdnew file mode 100644index 0000000..4c4109e--- /dev/null+++ b/docs/CONSOLE.md@@ -0,0 +1,51 @@+# Console facts++Measured on the project's test console. Payload numbers come from `probes/memprobe` and `probes/threadprobe`, run through shsrv.++## Setup++- PS5 Slim (CFI-2015), firmware 13.60+- Relapse through WebKit Autoloader v0.5.2 and Payload Manager (PLK)+- Autoload: kstuff-lite 1.11, ShadowMountPlus 1.7beta2, etaHEN 2.5B, ftpsrv 0.21.1, shsrv 0.20, klogsrv 0.9+- FTP upload from a Mac on the same network: about 61 MB/s++The Relapse kernel stage sometimes hangs and the console then shuts down, or sticks on "preparing to turn off" until the power button is held. That is the exploit's race, not anything PS5LM runs.++## Memory, for one payload process++| What | Value |+|---|---|+| Flexible memory configured / free | 8.00 / 7.97 GiB |+| malloc ceiling (256 MiB steps, pages touched) | 6.25 GiB |+| Largest single block (`posix_memalign`) | 6.00 GiB |+| Direct memory | none: size 0, allocation fails with `0x80020023` |++The flexible pool is shared with the system: holding about 6 GiB froze the home screen until the process ended. Plan on 4 to 5 GiB for model, context and buffers in a payload. Bigger models (Qwen 3.8 27B) need a process with direct memory, that is a native app.++## CPU, for one payload process++- AVX, AVX2, FMA, F16C, BMI2; no AVX-512. 16 logical CPUs online.+- **Affinity mask `0xea00`: only CPUs 9, 11, 13, 14 and 15**, shared with system services. Sony priority 700 (normal) for the main thread and new threads.+- 1, 2 and 4 threads busy for a second each: fine.+- Busy-waiting on all five (llama.cpp's defaults: one thread per physical core, `--poll 50`) starved the system: services stopped answering and the console shut down twice. `patches/0001-ps5-safe-cpu-defaults.patch` makes the default thread count the allowed CPUs minus two and turns polling off.++## llama.cpp++First run, Qwen3.5 0.8B Q4_K_M, `-t 2 --poll 0 -lm none`, 512 context:++| | |+|---|---|+| Load | 4.4 s |+| Prompt | 38.5 tok/s |+| Generation | 14.2 tok/s |++`llama-server` loads Granite 4.2 3B (2.1 GiB) with mmap, so mapping a model file works in a payload.++At exit, Sony's libc prints `[SceLibc] A heap error is detected` (SceLibcInternalHeap) after all work is done. Not investigated yet.++## shsrv quirks++- Arguments are split on spaces with no quoting: put prompts in a file (`-f`).+- Programs need an absolute path; a relative one, and very long command lines, end with exit code 3 ("command not found").+- `kill` takes no `-9`; Payload Manager's `/process_kill?pid=N` works.+- `browse <URL>` opens the PS5's web browser.diff --git a/docs/PORTING.md b/docs/PORTING.mdindex 32b2018..62bd99d 100644--- a/docs/PORTING.md+++ b/docs/PORTING.md@@ -6,7 +6,7 @@ What it took to build llama.cpp for the PS5, and why. Upstream is pinned at `b11The SDK compiles with clang's own PS5 target, `x86_64-sie-ps5`, which defines `__PROSPERO__`, `__SCE__` and `__FreeBSD__ 9`. Its CMake toolchain (`prospero-cmake`) presents the console as FreeBSD on x86_64. Programs link dynamically against stubs of Sony's libraries (`libSceLibcInternal`, `libkernel_web`, `libSceNet`, ...) and run as payloads under elfldr.-ggml and libllama build for it as they are: no source changes so far.+ggml and libllama build for it as they are. One source patch so far, for safety on the console rather than for building (below).## Build fixes (all in `scripts/build-llama.sh`)@@ -16,17 +16,16 @@ ggml and libllama build for it as they are: no source changes so far.Build options: AVX, AVX2, FMA, F16C and BMI2 on, AVX-512 off (Zen 2), no OpenMP (ggml's own thread pool), static libraries, no OpenSSL.+## Source patches (`patches/`, applied by `scripts/build-llama.sh`)++1. **`0001-ps5-safe-cpu-defaults.patch`.** A payload may only use 5 of the 16 logical CPUs, and system services share them. llama.cpp's defaults (one thread per physical core, busy-waiting at `--poll 50`) took all five and the console shut down. On `__PROSPERO__` the default thread count becomes the CPUs in the affinity mask (`scePthreadGetaffinity`) minus two, and polling defaults to 0. `-t` and `--poll` still override.+## Output`build/llama-ps5/bin/`: `llama-cli` (20 MB), `llama-server` (20 MB), `llama-bench` (13 MB), position independent FreeBSD ELFs that import from `libSceLibcInternal.sprx`, `libkernel_web.sprx` and `libSceNet.sprx`. The only weak import is `__cxa_thread_atexit_impl`, which libc++abi checks for before use.`llvm-readelf` warns that `PT_DYNAMIC` is larger than `.dynamic`: the SDK's linker script puts `.dynsym`, `.dynstr` and `.rela.dyn` in the same segment, and the SDK's own samples have the same layout.-## Not verified yet--None of this has run on a console. Things to watch in Phase 0 and 1:+## On the console-- whether `mmap` of a multi-GiB model file works in a payload, or llama.cpp needs `--no-mmap`-- whether a single `posix_memalign` of 7 to 9 GiB succeeds-- how many cores the payload process may use, and whether `std::thread::hardware_concurrency()` reports them-- stdout buffering through elfldr's socket+Runs: see [CONSOLE.md](CONSOLE.md). mmap of the model works; one block of 6 GiB is the ceiling; `std::thread::hardware_concurrency()` reports 16 while only 5 CPUs are allowed, hence the patch. Open: the `[SceLibc] A heap error is detected` message at exit.diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex ed63240..cd3f408 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -27,8 +27,8 @@ Decoding is bound by memory bandwidth: tokens per second ≈ effective bandwidth- [x] macOS host toolchain: Homebrew `llvm@21` and `lld` (`scripts/env.sh`)- [x] `probes/memprobe` builds- [x] `scripts/host-relapse.sh` serves the exploit page from macOS or Linux; `scripts/console-setup.sh` sends ftpsrv, klogsrv and shsrv after it-- [ ] Console jailbroken (Relapse, firmware 13.60 or lower), with elfldr (9021), ftpsrv (2121) and klogsrv (3232)-- [ ] `scripts/send.sh probes/memprobe/memprobe.elf`: record the results in `docs/CONSOLE.md`+- [x] Console jailbroken (Relapse, firmware 13.60 or lower), with ftpsrv (2121), shsrv (2323) and klogsrv (3232)+- [x] memprobe and threadprobe on the console: results in [CONSOLE.md](CONSOLE.md)- direct, flexible and malloc ceilings for one payload process- the largest single allocation (llama.cpp's CPU backend puts all weights in one buffer)- read bandwidth with 1 to 8 threads, on malloc and on direct memory@@ -41,7 +41,8 @@ Decoding is bound by memory bandwidth: tokens per second ≈ effective bandwidth- [x] ggml and libllama cross-compile with no source changes- [x] `llama-cli`, `llama-server` and `llama-bench` link ([PORTING.md](PORTING.md) lists the three build fixes)-- [ ] Smoke test with a small model (Qwen3.5 0.8B or SmolLM2) through `scripts/run.sh llama-cli`+- [x] Smoke test: Qwen3.5 0.8B generates text on the PS5 CPU, 14.2 tok/s on two threads+- [x] Safe CPU defaults for the PS5 (`patches/0001`): threads = allowed CPUs minus two, no busy-waiting- [ ] `llama-server` on the console: chat from a laptop or phone with llama.cpp's built-in web UI (port 8081, since websrv takes 8080)- [ ] `llama-bench` numbers for the small model- [ ] **First light: Qwen3.8-27B generates text on the PS5.** UD-Q2_K_XL if Phase 0 says it fits, UD-IQ2_XXS if not. A video of it, posted with the repo.@@ -104,7 +105,7 @@ The route: ggml's Vulkan backend on [Mihawk-99's PS5_Vulkan](https://github.com/| Risk | Plan B ||---|---|-| A payload process gets far less than 7 GiB | Move to the native app shell (Phase 3's) sooner, where direct memory is larger; IQ1_M meanwhile |+| A payload process gets far less than 7 GiB (**confirmed: about 6 GiB, shared with the system**) | Move to the native app shell (Phase 3's) sooner, where direct memory is available; smaller models meanwhile || The CPU is too slow for a 27B | Still first light; Phase 3 is the fix || ggml-vulkan needs a feature the driver lacks | Its feature switches (`GGML_VK_DISABLE_*`), or fix it in the driver with its author || Someone else gets there first | Keep Phase 1 short and publish as soon as it talks |diff --git a/patches/0001-ps5-safe-cpu-defaults.patch b/patches/0001-ps5-safe-cpu-defaults.patchnew file mode 100644index 0000000..0b8320b--- /dev/null+++ b/patches/0001-ps5-safe-cpu-defaults.patch@@ -0,0 +1,49 @@+diff --git a/common/common.cpp b/common/common.cpp+index 401de1d..7e89648 100644+--- a/common/common.cpp++++ b/common/common.cpp+@@ -29,6 +29,11 @@+ #include <unordered_set>+ #include <vector>+++#if defined(__PROSPERO__)++#include <pthread.h>++extern "C" int scePthreadGetaffinity(pthread_t thread, uint64_t * mask);++#endif+++ #if defined(__APPLE__) && defined(__MACH__)+ #include <sys/types.h>+ #include <sys/sysctl.h>+@@ -199,6 +204,16 @@ static int cpu_count_math_cpus(int n_cpu) {+ * Returns number of CPUs on system that are useful for math.+ */+ int32_t common_cpu_get_num_math() {++#if defined(__PROSPERO__)++ // PS5: a payload runs only on the cores its affinity mask allows (5 of 16 on++ // firmware 13.60), and the console's own services share them. Keep two free:++ // using all of them starves those services and the console shuts down.++ uint64_t mask = 0;++ if (scePthreadGetaffinity(pthread_self(), &mask) == 0 && mask != 0) {++ return std::max(1, __builtin_popcountll(mask) - 2);++ }++ return 2;++#endif+ #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)+ int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);+ if (n_cpu < 1) {+diff --git a/common/common.h b/common/common.h+index dcc5ec1..ee1c265 100644+--- a/common/common.h++++ b/common/common.h+@@ -73,7 +73,11 @@ struct common_cpu_params {+ bool mask_valid = false; // Default: any CPU+ enum ggml_sched_priority priority = GGML_SCHED_PRIO_NORMAL; // Scheduling prio : (0 - normal, 1 - medium, 2 - high, 3 - realtime)+ bool strict_cpu = false; // Use strict CPU placement++#if defined(__PROSPERO__)++ uint32_t poll = 0; // PS5: no busy-waiting, the few cores a payload gets are shared with the system++#else+ uint32_t poll = 50; // Polling (busywait) level (0 - no polling, 100 - mostly polling)++#endif+ };++ int32_t common_cpu_get_num_physical_cores();diff --git a/probes/threadprobe/Makefile b/probes/threadprobe/Makefilenew file mode 100644index 0000000..0a38722--- /dev/null+++ b/probes/threadprobe/Makefile@@ -0,0 +1,27 @@+PS5_HOST ?= ps5+PS5_PORT ?= 9021++ifdef PS5_PAYLOAD_SDK+ include $(PS5_PAYLOAD_SDK)/toolchain/prospero.mk+else+ $(error PS5_PAYLOAD_SDK is undefined: source scripts/env.sh)+endif++ELF := threadprobe.elf++# The PS5's CPU is an 8-core Zen 2.+CFLAGS := -Wall -Wextra -Werror -O2 -g -march=znver2+LDLIBS := -lkernel_sys -lpthread++all: $(ELF)++$(ELF): main.c+ $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)++clean:+ rm -f $(ELF)++test: $(ELF)+ $(PS5_DEPLOY) -h $(PS5_HOST) -p $(PS5_PORT) $^++.PHONY: all clean testdiff --git a/probes/threadprobe/main.c b/probes/threadprobe/main.cnew file mode 100644index 0000000..1e86c2f--- /dev/null+++ b/probes/threadprobe/main.c@@ -0,0 +1,100 @@+/* PS5LM threadprobe: what a payload's threads look like to the scheduler.+ *+ * Prints the priority and CPU affinity of the main thread and of a new+ * pthread, then runs short busy bursts on 1, 2 and 4 threads (one second+ * each) and reports how long each took, so a thread setup that starves the+ * system shows up as a short stall, not a dead console. Output goes to stdout+ * and /data/PS5LM/threadprobe.txt.+ *+ * SPDX-License-Identifier: GPL-3.0-or-later+ */+#include <pthread.h>+#include <stdarg.h>+#include <stdint.h>+#include <stdio.h>+#include <sys/resource.h>+#include <sys/stat.h>+#include <time.h>+#include <unistd.h>++int scePthreadGetprio(pthread_t thread, int *prio);+int scePthreadGetaffinity(pthread_t thread, uint64_t *mask);++static FILE *g_log;++static void out(const char *fmt, ...) {+ va_list ap;+ va_start(ap, fmt);+ vprintf(fmt, ap);+ va_end(ap);+ fflush(stdout);+ if (g_log) {+ va_start(ap, fmt);+ vfprintf(g_log, fmt, ap);+ va_end(ap);+ fflush(g_log);+ fsync(fileno(g_log));+ }+}++static double now_s(void) {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;+}++static void describe(const char *who) {+ int prio = -1;+ uint64_t mask = 0;+ const int rp = scePthreadGetprio(pthread_self(), &prio);+ const int ra = scePthreadGetaffinity(pthread_self(), &mask);+ out("%-8s sce prio %d (rc 0x%x), affinity 0x%04llx (rc 0x%x), nice %d\n", who, prio, rp,+ (unsigned long long)mask, ra, getpriority(PRIO_PROCESS, 0));+}++static void *hello(void *arg) {+ (void)arg;+ describe("thread");+ return NULL;+}++static void *burn(void *arg) {+ const double until = *(const double *)arg;+ volatile uint64_t x = 0;+ while (now_s() < until)+ for (int i = 0; i < 100000; i++)+ x += (uint64_t)i;+ return NULL;+}++int main(void) {+ mkdir("/data/PS5LM", 0777);+ g_log = fopen("/data/PS5LM/threadprobe.txt", "w");++ out("PS5LM threadprobe, pid %d\n", (int)getpid());+ describe("main");++ pthread_t t;+ const int rc = pthread_create(&t, NULL, hello, NULL);+ out("pthread_create rc %d\n", rc);+ if (rc == 0)+ pthread_join(t, NULL);++ const int counts[] = {1, 2, 4};+ for (int k = 0; k < 3; k++) {+ const int n = counts[k];+ pthread_t th[4];+ double until = now_s() + 1.0;+ const double t0 = now_s();+ for (int i = 0; i < n; i++)+ pthread_create(&th[i], NULL, burn, &until);+ for (int i = 0; i < n; i++)+ pthread_join(th[i], NULL);+ out("burst %d threads x 1 s took %.2f s\n", n, now_s() - t0);+ }++ out("done\n");+ if (g_log)+ fclose(g_log);+ return 0;+}diff --git a/scripts/build-llama.sh b/scripts/build-llama.shindex d601880..9a3335d 100755--- a/scripts/build-llama.sh+++ b/scripts/build-llama.sh@@ -11,13 +11,24 @@ source "$root/scripts/env.sh"src="$root/third_party/llama.cpp"out="$root/build/llama-ps5"-targets=("${@:-llama-cli llama-server llama-bench}")+targets=("${@:-llama-cli llama-server llama-bench llama-completion}")if [ ! -f "$src/CMakeLists.txt" ]; thenecho "build-llama: run git submodule update --init first" >&2exit 1fi+# The PS5 changes to llama.cpp live in patches/ and go onto the submodule's+# working tree; a patch that is already applied is skipped.+for p in "$root"/patches/*.patch; do+ [ -e "$p" ] || continue+ if git -C "$src" apply --reverse --check "$p" 2>/dev/null; then+ continue+ fi+ git -C "$src" apply "$p"+ echo "build-llama: applied $(basename "$p")"+done+# The PS5's CPU is a Zen 2: AVX2, FMA, F16C and BMI2, no AVX-512.# No OpenMP in the SDK, so ggml's own thread pool. Static everything: a payload# is one ELF. No HTTPS client (models are copied to the console, not downloaded).