diff --git a/.engineering/security-exceptions.json b/.engineering/security-exceptions.json index 642d4928..91882949 100644 --- a/.engineering/security-exceptions.json +++ b/.engineering/security-exceptions.json @@ -3,19 +3,22 @@ "exceptions": [ { "id": "PYSEC-2026-2447", - "aliases": ["CVE-2025-69872", "GHSA-w8v5-vhqr-4h9v"], + "aliases": [ + "CVE-2025-69872", + "GHSA-w8v5-vhqr-4h9v" + ], "package": "diskcache", "affected_version": "5.6.3", "owner": "repository engineering", - "review_by": "2026-09-30", - "expires_on": "2026-11-15", - "reason": "diskcache is a transitive llama-cpp-python dependency and no fixed upstream release is currently available", - "reachability": "Local LLM Server does not instantiate llama-cpp-python disk-cache APIs or enable disk prompt caching; repository search has no LlamaDiskCache/set_cache/cache_type wiring", + "review_by": "2026-11-19", + "expires_on": "2026-11-26", + "reason": "Time-boxed exception for unfixed diskcache 5.6.3 (CVE-2025-69872 / PYSEC-2026-2447), transitive through llama-cpp-python. Re-reviewed 2026-11-19 against GitHub/OSV and PyPI: upstream still has no fixed release; active security audit and 7-day expiry retained. Do not extend again without repository security review.", + "reachability": "Repository code search 2026-11-19 found zero LlamaDiskCache / set_cache( usages, zero direct diskcache import usages; only the security exception file mentions diskcache. llama_server cache_type settings are llama.cpp KV cache flags, not python-diskcache. Vulnerability requires attacker-controlled cache files followed by unsafe unpickling; this product does not expose diskcache reading.", "compensating_controls": [ - "model/runtime state remains local-only by default", - "no product API enables llama-cpp-python disk cache", - "security audit remains scheduled weekly so an upstream fixed release is detected", - "exception expires automatically through repository validation" + "No LlamaDiskCache / set_cache( or direct diskcache APIs exposed in repository runtime code (GitHub code search verified 2026-11-19)", + "Korgis local-first runtime does not expose a disk cache directory for untrusted write access", + "Dependency security audit is preserved with exactly this named exception, never disabled", + "Exception expires within seven days (2026-11-26); remove on upstream fix or on new reachable usage" ], "remediation": "remove the exception and update the lock as soon as a fixed diskcache release or a llama-cpp-python release without the vulnerable dependency is available" } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 83658ca8..16b9ff65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -187,7 +187,8 @@ jobs: name: Playwright E2E needs: [scope, guards, reuse] if: always() && needs.guards.result == 'success' && contains(needs.scope.outputs.required_gates, 'browser-e2e') && needs.reuse.outputs.reused != 'true' - runs-on: ubuntu-latest + # Playwright's pinned Chromium supports Ubuntu 24.04; ubuntu-latest moved to 26.04. + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 with: {ref: "${{ needs.scope.outputs.head_sha }}"} diff --git a/README.md b/README.md index e99fdbca..59a372c3 100644 --- a/README.md +++ b/README.md @@ -257,3 +257,4 @@ Contributors work from `dev` and follow [`AGENTS.md`](AGENTS.md). Canonical setu See [`LICENSE`](LICENSE). Built by [Daniele Moltisanti](https://daniele21.github.io/) as the reusable execution layer of a broader Local AI effort: control the runtime, measure the result, then decide Local, Hybrid or Cloud. +See also [FLUX.3 Image Klein local GGUF setup](docs/flux3-image-klein-q5km.md) and [Qwen Turbo reference editing](docs/qwen-21-turbo-image-edit.md). diff --git a/docs/current-state.md b/docs/current-state.md index 3ee07ac0..5b7232d7 100644 --- a/docs/current-state.md +++ b/docs/current-state.md @@ -1,7 +1,7 @@ # Current State Status: active -Last reviewed: 2026-09-28 +Last reviewed: 2026-11-19 Local LLM Server is a local-first multi-backend **runtime control plane for local AI applications**, with Local LLM Studio as its browser control plane. Hosted CI proves deterministic software contracts; hardware- and human-dependent claims require matching real evidence. @@ -12,7 +12,7 @@ Local LLM Server is a local-first multi-backend **runtime control plane for loca - Repository-side L2 acceptance: `d528b6c5b676e705e7ccf24800929da6d5534203`. - Representative Apple Silicon evidence is accepted for TH-E1, EV-3, HE-2, RES-2 and RRG-5. - Bounded manual accessibility and representative-user usability evidence is accepted for tested source `a29e77c1ce4e65294440cfe4fc47e33c92173096`. -- Full L2 evidence is complete; the current action is final FULL publication preflight and promotion to `main`. +- The August L2 evidence covers its reviewed source; it must not be extended to newly integrated November image-generation engines without matching test and representative-device evidence. ## Accepted deterministic surface @@ -55,6 +55,13 @@ All required checks/journeys are acceptance-ready with no blocking finding. No r thermal and reclamation remain unproven. See `docs/workstreams/qwen-image-2-1.md`. +## November 2026 image runtime reconciliation + +- The dedicated main-compatibility integration is tracked in [PR #290](https://github.com/daniele21/korgis/pull/290), including separate Qwen Image 2.1 Turbo and FLUX.3 Image Klein Q5_K_M native model profiles. The Experiments Playground implementation is on main via [PR #136](https://github.com/daniele21/experiments/pull/136). +- FLUX reuses the Q5_K_M transformer directly from the local LM Studio directory. Its Qwen3-VL-4B encoder and FLUX.2 VAE are independent required artifacts. Native image generation on representative macOS hardware is **not yet verified**. +- Qwen Turbo edit mode remains opt-in. Memory estimates for both profiles are provisional; a first real 512px smoke, latency and unified-memory/swap evidence are required before production acceptance. No automatic memory-protection bypass is introduced. +- CI and source checks are ongoing on the integration branch. A historical green test does not prove FLUX model startup, image quality, image editing or commercial suitability; checksum/license review remain open. + ## Durable references - `docs/architecture.md` diff --git a/docs/flux3-image-klein-q5km.md b/docs/flux3-image-klein-q5km.md new file mode 100644 index 00000000..1e87cd08 --- /dev/null +++ b/docs/flux3-image-klein-q5km.md @@ -0,0 +1,118 @@ +# FLUX.3 Image Klein Q5_K_M · LM Studio integration (experimental) + +**Status:** native Korgis registry/loader integrated. Unit tests do not prove +the user's actual Mac binary can generate FLUX.3 images; first image E2E and +resource calibration are mandatory before marking production-ready. + +## Components (distilled, 16-step, CFG 1.0) + +FLUX.3 **Image** Klein is not FLUX.2 Klein or FLUX.3 Klein **Base**. +The Q5_K_M GGUF is the **diffusion transformer only**, not a complete +standalone model. [Unsloth](https://huggingface.co/unsloth/flux-3-image-klein-GGUF) +and [stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp/blob/master/docs/models/flux3.md) +specify a separate **Qwen3-VL-4B-Instruct text encoder** and **FLUX.2 VAE**. + +1. Diffusion GGUF: **existing**, no copy or automatic download: + `$HOME/.lmstudio/models/unsloth/flux-3-image-klein-GGUF/flux-3-image-klein-Q5_K_M.gguf` + (Unsloth Q5_K_M; approximately 4.22 decimal GB). +2. Text encoder: `unsloth/Qwen3-VL-4B-Instruct-GGUF`, + `Qwen3-VL-4B-Instruct-Q4_K_M.gguf`, managed target + `~/.local-llm/models/flux-3-image-klein-gguf-q5km/text_encoder/Qwen3-VL-4B-Instruct-Q4_K_M.gguf`. + Registry revision `cc8371d67a57fc6ae05fc5a9c2df763914928539`. +3. VAE: `unsloth/flux-3-image-klein`, `ae.safetensors`, managed target + `~/.local-llm/models/flux-3-image-klein-gguf-q5km/vae/ae.safetensors`. + **Its upstream SHA256/revision are not yet locked**, so do not treat this + provisional source entry as immutable-provenance evidence. + +Both auxiliary components must be present to start image inference. The +registry path is resolved relative to **the current user's home**, not a +hard-coded Mac account. If the LM Studio GGUF is absent, Korgis rejects it +without downloading it somewhere else. The original GGUF is validated for +regular file, a plausible minimum byte size, and the `GGUF` header, but +this is *not yet full artifact integrity verification*. + +## Start on a Mac with LM Studio weights already installed + +```bash +cd ~/Projects/experiments/korgis +git fetch origin +git switch feat/flux3-klein-q5km-lmstudio-20261119 +git pull --ff-only + +# Check the local transformer is present; no model inference runs here. +ls -lh "$HOME/.lmstudio/models/unsloth/flux-3-image-klein-GGUF/flux-3-image-klein-Q5_K_M.gguf" + +# First run: Korgis may download the separate 4B encoder and VAE to its +# own managed bundle. It never re-downloads the existing LM Studio GGUF. +uv run --frozen local-llm serve \ + --model flux-3-image-klein-gguf-q5km \ + --host 127.0.0.1 --port 1235 \ + --sd-server-bin "$HOME/.local-llm/tools/sdcpp-b43af40461cc64c89cac3b621019f8914f50dd9c/build/bin/sd-server" +``` + +For a strictly offline run *after* the two auxiliary artifacts exist, add +`--no-download` to the command. If they are not installed, the error will +show the exact missing managed path. Source repository downloads could be +gated or unavailable; use an approved Hugging Face client to fetch those two +files explicitly if Korgis cannot obtain them. The pinned native +stable-diffusion.cpp build must include FLUX.3 (upstream support introduced +October 2026). A filename or revision alone does not establish binary support. + +Check `curl -fsS http://127.0.0.1:1235/v1/models` for +`flux-3-image-klein-gguf-q5km`. Then run one **small** generation: + +```bash +curl -fsS http://127.0.0.1:1235/v1/images/generations \ + -H 'Content-Type: application/json' \ + -d '{"model":"flux-3-image-klein-gguf-q5km", + "prompt":"A single emerald-green mug on a white desk, morning window light", + "size":"512x512","n":1,"seed":43,"num_inference_steps":16, + "output_format":"png","guidance_scale":1.0}' \ + > flux3-response.json + +python3 - <<'PY' +import base64, json +from pathlib import Path +data = json.loads(Path("flux3-response.json").read_text()) +Path("flux3-test.png").write_bytes(base64.b64decode(data["data"][0]["b64_json"])) +print("Saved flux3-test.png") +PY +open flux3-test.png +``` + +Check that the output is coherent, the backend actually uses the GGUF and +**Qwen3-VL-4B + FLUX.2 VAE** rather than Qwen Image weights, and record +elapsed time, process RSS/unified-memory pressure and swap I/O. The +configured `disk_backed_image` estimate is **9 GiB provisional**; it is +not a benchmarked peak or a license to turn off host protections. + +## Experiments comparison + +Check out Experiments branch +`feat/imagegen-flux3-klein-q5km-20261119`. In the Image Generation +Playground select **FLUX.3 Image Klein GGUF Q5_K_M**, or pick it as an +additional arm in **Compare models**. To generate a FLUX vs Gemini vs GPT +comparison, start FLUX in Korgis and configure server-side cloud API keys. +You can also compare FLUX with Qwen if *both* are loaded and host memory +permits. The default `serve --model` starts only one local runtime; +`--models` can start multiple but may exceed available RAM on a 32 GiB Mac. +Avoid automatically forcing simultaneous residency. + +The existing benchmark `smoke`, `budget`, and `robust` suites can +compare the new model using the catalog key. The FLUX Kommunity License +has noncommercial/commercial-output conditions; review it before customer +use. No auto-download of the 9B prompt upsampler is attempted. Unlike the +BFL reference pipeline, Korgis feeds the **literal prompt as entered**, +so prompt-upsampled BFL service examples are not identical to this setup. + +### Acceptance checklist + +- [x] Registered distinct model and 16-step preset, without altering Qwen +- [x] Deterministic path resolution and local-only GGUF startup checks +- [x] Separate encoder/VAE dependencies, per-model metadata and benchmark arm +- [ ] CI test verification and complete native Mac startup +- [ ] 512px generation at seed 43 with correct 16-step sampling +- [ ] Measured RSS, unified-memory pressure, swap and runtime latency +- [ ] Validate outputs at 768/1024 before quality comparisons +- [ ] Lock the upstream VAE revision/checksum and local GGUF digest +- [ ] Validate native image editing separately; it is not enabled by this PR diff --git a/docs/qwen-21-turbo-image-edit.md b/docs/qwen-21-turbo-image-edit.md new file mode 100644 index 00000000..4e508832 --- /dev/null +++ b/docs/qwen-21-turbo-image-edit.md @@ -0,0 +1,147 @@ +# Qwen Image 2.1 Turbo: resource-safe reference editing (draft) + +**Status: integration foundation implemented, native edit with vision projector not yet proven E2E.** Keep this separate from existing text-to-image and from Experiments benchmarks. Do not merge based on API unit tests alone. + +## Why this design + +The pinned `stable-diffusion.cpp` commit +[`b43af40461cc64c89cac3b621019f8914f50dd9c`](https://github.com/leejet/stable-diffusion.cpp/tree/b43af40461cc64c89cac3b621019f8914f50dd9c) +already supports reference images through its asynchronous `/sdcpp/v1/img_gen` +(`ref_images` field). It also has `/v1/images/edits` and SDAPI `img2img`, +but using the already integrated native async-job API reuses the current +submission, polling, timeout and cancellation machinery and avoids a second +inference engine. This first release does not expose arbitrary native options, +init-image strength or masks before validating their behavior with Qwen Turbo. + +Qwen Image 2.1 + a GGUF Qwen3-VL-8B text encoder **requires the matching +vision projector**. The [upstream model guide](https://github.com/leejet/stable-diffusion.cpp/blob/b43af40461cc64c89cac3b621019f8914f50dd9c/docs/qwen_image_2.1.md) +specifies `--llm_vision` for reference editing. + +Other designs studied: +- **InvokeAI:** model cache has RAM/VRAM limits, lock-based access, and controlled + model offload/eviction; Korgis retains its own central ResourceManager and + serializes inference through the existing runtime lease. +- **Diffusers:** CPU, group and disk offloading all trade memory for latency. + For this Mac/Metal GGUF use case Korgis retains `diffusion=disk,te=cpu,vae=cpu`, + `--disable-prefetch` and tiled VAE rather than adding a PyTorch runtime. +- **ComfyUI:** flexible image workflows are useful as a quality/reference oracle, + but do not justify adding a DAG runtime or second weights manager to Korgis. + +## Opt-in model and resource contract + +The original three local files remain the text-to-image bundle: diffusion, +text encoder and VAE. A fourth **optional** artifact is registered separately: + +- Repo: `unsloth/Qwen3-VL-8B-Instruct-GGUF` +- Immutable revision: `174e4a339d8aceef41c87fda9f732c042d49e50b` +- Filename: `mmproj-BF16.gguf` (~1.16 GB on disk) +- SHA256: `6516bb64bae1503a0fcd7ec9fa39655f8c481580be0a0a066397941d9761c9f4` +- Local target: `~/.local-llm/models/qwen-image-2.1-turbo-gguf-q4km/text_encoder/mmproj-BF16.gguf` + +Projector metadata is not part of the text-to-image completeness gate. Without +the explicit editing flag the projector is not opened, verified or downloaded. +With the flag, Korgis verifies the full SHA256 and launches its existing native +server with `--llm_vision`. `--no-download` fails if the projector is missing; +the app does not silently download model assets in offline mode. + +Existing Turbo T2I uses an **8 GiB provisional** resident estimate. Edit mode +adds **2 GiB provisional** for projector and vision activations, yielding a +**10 GiB effective resident estimate** on the same memory ledger. The existing +disk-backed profile uses a 1.25× reserve factor and up to 3 GiB OS reserve: +for a 32 GiB Mac an editing startup therefore needs roughly **15.5 GiB +reclaimable memory**, before optional concurrent load. This bound is *not* +proven adequate until a real edit is profiled. Existing swap usage is never +added to available RAM. The API rejects new editing work when host pressure +is elevated or unknown, both before and after acquisition of the runtime lease. + +## First API slice + +`POST /v1/images/edits`, multipart form: +- `image`: exactly one PNG file (max 8 MiB, up to 1 megapixel source pixels). +- `prompt`: text editing instruction. +- `model`: resident model key, optional. +- `size`: `WIDTHxHEIGHT`, optional; default source dimensions. +- `seed`, `num_inference_steps`: optional, validated against 8-step Turbo cap. +- `n`: must be 1. + +First-release image output is capped at 1 megapixel and dimensions must be +multiples of 32. Input data is validated using PNG signature, IHDR, +dimensions and IHDR checksum before encoding to base64 and sending `ref_images` +to the private native server. No remote image URL, arbitrary filesystem path, +multiple reference images, mask, or unvalidated native parameters are accepted. +Korgis does not intentionally persist the uploaded image (the multipart +library may spool larger bodies to temporary local files); raw images are not +logged. Output is OpenAI-shaped `data[0].b64_json`; metadata includes source +SHA256, original dimensions, generation and local runtime evidence. + +**This is not a network-hardened multi-user upload service.** Use loopback +binding, avoid untrusted remote clients, and do not publish the API publicly +without transport-level size limits/authentication and further input fuzzing. + +## Manual test when projector is installed + +First verify free disk space, the file and SHA256. Explicit download is needed +only for this editing variant, not for normal text-to-image: + +```bash +mkdir -p "$HOME/.local-llm/models/qwen-image-2.1-turbo-gguf-q4km/text_encoder" +# Download from the pinned Hugging Face revision above using an approved +# network-enabled tool, then verify its SHA256: +shasum -a 256 "$HOME/.local-llm/models/qwen-image-2.1-turbo-gguf-q4km/text_encoder/mmproj-BF16.gguf" +``` + +Run the *edit foundation branch* of Korgis (not the stable T2I branch): +```bash +uv run --frozen local-llm serve \ + --model qwen-image-2.1-turbo-gguf-q4km \ + --image-editing-enabled \ + --host 127.0.0.1 --port 1235 \ + --sd-server-bin "$HOME/.local-llm/tools/sdcpp-b43af40461cc64c89cac3b621019f8914f50dd9c/build/bin/sd-server" \ + --no-download +``` + +When resident startup and memory admission succeed, submit a local 512x512 PNG: + +```bash +curl -fsS http://127.0.0.1:1235/v1/images/edits \ + -F "model=qwen-image-2.1-turbo-gguf-q4km" \ + -F "prompt=Change the ceramic mug from red to blue; keep the rest identical" \ + -F "image=@/absolute/path/to/reference-512.png;type=image/png" \ + -F "size=512x512" -F "seed=42" -F "num_inference_steps=8" \ + > edited-response.json +python3 - <<'PY' +import base64 +import json +from pathlib import Path +result = json.loads(Path("edited-response.json").read_text()) +Path("edited-image.png").write_bytes( + base64.b64decode(result["data"][0]["b64_json"]) +) +print(result["korgis"]["latency_ms"]) +PY +``` + +Do **not** run production image-editing workloads on the previous T2I 8 GiB +estimate, or bypass `LOCAL_LLM_HOST_MEMORY_GUARD` after a refusal. + +## Acceptance plan, in order + +1. Static and isolated API/engine tests: text-to-image unchanged; opt-in + capabilities, checksum and path, command `--llm_vision`, malformed image + rejection, exact one native `ref_images` field, no input pixels logged. +2. On the Mac, check if the projector is present; if absent, do not simulate + editing success. Download and checksum it in a controlled separate step. +3. Native `sd-server` small 512px edit with exact seed and prompt. Verify + that the pinned build actually supports Qwen Turbo reference conditioning. +4. Full Korgis E2E edit on host: initial and final memory pressure, RSS, + swap-in/out, wall time, image fidelity and source/image hashes. +5. Repeat at 768 and 1024, with at least three prompts: object color change, + preserve composition, and legible text replacement. Include negative + source checks (invalid PNG, too large, missing projector, low memory). +6. Only after E2E and manual review: JPEG/WebP ingestion, multiple references, + masks, queued jobs/cancellation and separate Experiments evaluation suite. + +Do not interpret a valid output PNG as successful editing: image-to-image +requires **measurable adherence to the source and instruction**, not just +successful inference. Keep the benchmark and visual review in +`daniele21/experiments`. diff --git a/docs/workstreams/README.md b/docs/workstreams/README.md index 48913a15..64ce611a 100644 --- a/docs/workstreams/README.md +++ b/docs/workstreams/README.md @@ -15,3 +15,4 @@ Do not create separate plan/progress/status files for the same workstream. Git h ## Active - [Qwen Image 2.1 Local Generation](qwen-image-2-1.md) — first-class local image-generation capability, Diffusers runtime, API integration and validation. +- [Qwen Image 2.1 Turbo GGUF](qwen-image-2-1-turbo.md) — pinned Turbo bundle, exact native sigma schedule, Korgis E2E validation. diff --git a/docs/workstreams/qwen-image-2-1-turbo.md b/docs/workstreams/qwen-image-2-1-turbo.md new file mode 100644 index 00000000..f866fa7d --- /dev/null +++ b/docs/workstreams/qwen-image-2-1-turbo.md @@ -0,0 +1,90 @@ +# Qwen Image 2.1 Turbo — Korgis + +Status: active +Last reviewed: 2026-11-08 +Owner: Korgis local image-generation runtime +Read when: implementing, validating or reviewing Qwen Turbo GGUF inference + +## Outcome + +Run `qwen-image-2.1-turbo-gguf-q4km` through existing Korgis download, residency, +scheduler and `POST /v1/images/generations` contracts, with an exact eight-step +Turbo schedule. Standard Qwen Image 2.1 remains a different selectable model. +No local inference service is owned by Experiments. + +## Invariants + +- The new runtime is local only: no cloud fallback, new scheduler or ad-hoc child process. +- Three Unsloth artifacts have published SHA-256 digests: Turbo Q4_K_M + diffusion GGUF, Qwen3-VL Q4_K_XL text encoder GGUF and BF16 VAE. + Each source revision is pinned to a verified full Git commit; local files + still need SHA-256 verification before claiming device readiness. +- Native `sd-server` receives exact `sample_params.custom_sigmas` for 8 steps, + Euler and CFG 1; incompatible overrides fail before native submission. +- Korgis keeps the subprocess lease, request limits, safe path-free provenance + and owned teardown. Artifact size is not claimed as memory use. +- Model license is Qwen Research License (research/evaluation). +- Fake-server tests are not evidence of Apple Silicon generation performance. + +## Delivery state + +| Slice | State | Evidence / next gate | +| --- | --- | --- | +| K0 — reconcile required GGUF parts from main into dev | DONE | PR #258, hosted CI and Repository Health passed | +| K1 — pinned separate Turbo artifact bundle | DONE | PR #259 deterministic registry tests included in green CI | +| K2 — model-specific exact Turbo sigma preset | DONE | PR #259 native fake-job/override tests included in green CI | +| K3 — config, API and lifecycle integration | DONE | PR #259 config + API contract tests included in green CI | +| K4 — representative Mac proof | ACTIVE | User has placed three local files; SHA-256, compatible sd-server, real PNG and memory evidence remain unverified | +| K5 — Q8 or MLX variants | READY | Only after K4 + benchmark evidence | + +Independent source streams K1 and K2 were developed on separate branches, +combined into feature PR [#259](https://github.com/daniele21/korgis/pull/259). +The original design is recorded in planning PR [#257](https://github.com/daniele21/korgis/pull/257). + +## Native reference & configuration + +- Checkpoint: `unsloth/Qwen-Image-2.1-Turbo-GGUF`, text encoder: + `unsloth/Qwen3-VL-8B-Instruct-GGUF`, VAE: + `unsloth/Qwen-Image-2.1-FP8`. All three source digests are in the registry. +- Runtime: `stable_diffusion_cpp_image`; model key + `qwen-image-2.1-turbo-gguf-q4km`. +- Initial request: 1024×1024, PNG, seed 42. Model defaults: eight steps, + Euler, CFG 1, `qwen-image-2.1-turbo-v1` custom sigma schedule. +- File root: `~/.local-llm/models/qwen-image-2.1-turbo-gguf-q4km/`. + Built-in startup uses disk-backed diffusion, CPU encoder and tiled VAE as + conservative starting settings, not a proven memory target. + +## Validation + +Deterministic commands: + +```bash +uv run --frozen pytest \ + tests/test_registry_validation.py \ + tests/test_config_multimodal.py \ + tests/test_stable_diffusion_cpp_compat.py \ + tests/test_stable_diffusion_cpp_image_engine.py \ + tests/test_qwen_image_21_turbo_registry.py \ + tests/test_qwen_image_21_turbo_sampling.py \ + tests/test_qwen_image_21_turbo_integration.py \ + tests/test_image_generation_api.py -q +uv run --frozen ruff check src/ tests/ --select E9,F63,F7,F82 +``` + +CI / Repository Health on PR #259 passed at commit `138b0a9ffce19b3877a9ce01c02efec4896d5869`: 916 Python tests, lint and guards green. After the revised Unsloth configuration passes CI, Mac validation must verify a real PNG output from one resident +Korgis model, correct runtime/config/seed/sigma provenance, cold/warm timings, +bounded resource observation, no unexpected downloads, and clean process teardown. +Do not interpret unit tests as Mac memory-fit, production readiness or visual +quality proof. An unverified/unsupported native `custom_sigmas` path must fail, +not silently revert to a generic scheduler. + +## Consumer handoff + +Experiments adds a separate Qwen Turbo arm to its existing image-generation +benchmark. It must call the Korgis endpoint, record actual seed/provenance and +keep prompt suites, evaluation, artifacts and dashboard in Experiments. +OpenAI/Gemini routing through Korgis is a later distinct capability. + +Sources: +- https://huggingface.co/unsloth/Qwen-Image-2.1-Turbo-GGUF +- https://github.com/leejet/stable-diffusion.cpp/blob/master/examples/server/api.md diff --git a/src/local_llm_server/cli.py b/src/local_llm_server/cli.py index 8b908ac7..5f0cf4a8 100644 --- a/src/local_llm_server/cli.py +++ b/src/local_llm_server/cli.py @@ -105,6 +105,7 @@ def main() -> None: p_serve.add_argument("--image-scheduler", default=None, dest="image_scheduler") p_serve.add_argument("--image-diffusion-flash-attention", action=argparse.BooleanOptionalAction, default=None, dest="image_diffusion_flash_attention") p_serve.add_argument("--image-offload-to-cpu", action=argparse.BooleanOptionalAction, default=None, dest="image_offload_to_cpu") + p_serve.add_argument("--image-editing-enabled", action=argparse.BooleanOptionalAction, default=None, dest="image_editing_enabled", help="Opt into reference image editing; requires matching vision projector and additional memory") p_serve.add_argument("--image-vae-tiling", action=argparse.BooleanOptionalAction, default=None, dest="image_vae_tiling") p_serve.add_argument("--image-vae-tile-size", default=None, dest="image_vae_tile_size") p_serve.add_argument("--startup-timeout", type=int, default=None, dest="startup_timeout") diff --git a/src/local_llm_server/config.py b/src/local_llm_server/config.py index 1c848ddd..0ac15452 100644 --- a/src/local_llm_server/config.py +++ b/src/local_llm_server/config.py @@ -41,6 +41,7 @@ "default_min_p": 0.0, "default_repeat_penalty": 1.0, "backend": "llama_cpp", + "resource_admission_profile": "standard", "mmproj_path": None, "llama_server_port": 8091, "llama_server_bin": None, @@ -77,8 +78,13 @@ "image_output_format": "png", "image_sampling_method": "euler", "image_scheduler": None, + # Registry-owned schedule; deliberately no public arbitrary sigma-list input. + "image_sigma_schedule": None, + "image_verify_existing_artifacts": False, "image_diffusion_flash_attention": True, "image_offload_to_cpu": True, + "image_editing_enabled": False, + "image_editing_extra_resident_bytes": 0, "image_vae_tiling": False, "image_vae_tile_size": None, "multimodal": False, @@ -143,6 +149,7 @@ "image_scheduler": "LOCAL_LLM_IMAGE_SCHEDULER", "image_diffusion_flash_attention": "LOCAL_LLM_IMAGE_DIFFUSION_FLASH_ATTENTION", "image_offload_to_cpu": "LOCAL_LLM_IMAGE_OFFLOAD_TO_CPU", + "image_editing_enabled": "LOCAL_LLM_IMAGE_EDITING_ENABLED", "image_vae_tiling": "LOCAL_LLM_IMAGE_VAE_TILING", "image_vae_tile_size": "LOCAL_LLM_IMAGE_VAE_TILE_SIZE", "startup_timeout": "LOCAL_LLM_STARTUP_TIMEOUT", @@ -163,6 +170,7 @@ "llama_server_allow_unvalidated", "llama_server_cont_batching", "llama_server_kv_unified", "llama_server_fit", "image_diffusion_flash_attention", "image_offload_to_cpu", + "image_editing_enabled", "sd_server_mmap", "sd_server_disable_prefetch", "image_vae_tiling", } _INT_ENV = { @@ -170,6 +178,7 @@ "llama_server_port", "mlx_vlm_server_port", "sd_server_port", "startup_timeout", "default_top_k", "image_width", "image_height", "image_num_inference_steps", "image_quantization_bits", "image_max_inference_steps", "image_max_pixels", + "image_editing_extra_resident_bytes", "max_concurrent_requests", "max_kv_size", "llama_server_min_build", "llama_server_fit_target_mib", "llama_server_fit_ctx", "llama_server_cache_ram_mib", @@ -293,6 +302,7 @@ def build_config( cfg["mmproj_url"] = entry.get("mmproj_url", "") cfg["lmstudio_path"] = entry.get("lmstudio_path") cfg["size_gb"] = entry.get("size_gb") + cfg["license"] = entry.get("license") # Immutable identity metadata is optional. Absence means the runtime can # still execute, but automatic evidence-grade identity is intentionally not # claimed. Explicit kwargs allow controlled direct-path deployments to pin @@ -344,6 +354,44 @@ def build_config( ) cfg["artifact_specs"] = dict(entry.get("artifacts") or {}) + # Editing is an opt-in extension of the same image runtime. Keep projector + # metadata out of the required T2I bundle so existing installs stay valid. + projector_spec = entry.get("image_editing_projector") + if projector_spec is not None: + if not isinstance(projector_spec, dict): + raise ValueError("image_editing_projector must be a mapping") + raw_relative = projector_spec.get("local_path") + if not isinstance(raw_relative, str) or not raw_relative: + raise ValueError("image_editing_projector requires a relative local_path") + root = (models_dir / model).resolve() + projector_path = (root / raw_relative).resolve() + if projector_path == root or root not in projector_path.parents: + raise ValueError("image_editing_projector path escapes model bundle") + cfg["image_editing_projector_path"] = str(projector_path) + cfg["image_editing_projector_spec"] = dict(projector_spec) + else: + cfg["image_editing_projector_path"] = None + cfg["image_editing_projector_spec"] = None + + if cfg["image_editing_enabled"]: + if backend != "stable_diffusion_cpp_image" or projector_spec is None: + raise ValueError( + "image editing is only available for an explicitly configured " + "stable-diffusion.cpp model with a vision projector" + ) + if cfg["image_editing_extra_resident_bytes"] <= 0: + raise ValueError("image editing requires a positive extra resident budget") + base_estimate = cfg.get("resource_estimate_bytes") + if not isinstance(base_estimate, int) or isinstance(base_estimate, bool) or base_estimate <= 0: + raise ValueError("image editing requires a calibrated baseline resident estimate") + # The resource envelope, admission policy and status must agree. + cfg["resource_estimate_bytes"] = ( + base_estimate + cfg["image_editing_extra_resident_bytes"] + ) + # Per-runtime descriptor, not a claim about all GGUF models. + inputs = list(entry.get("input_modalities") or ["text"]) + cfg["input_modalities"] = sorted(set(inputs + ["image"])) + if not cfg.get("mmproj_path") and entry.get("mmproj_filename"): cfg["mmproj_path"] = str( resolved_source.mmproj_path @@ -360,6 +408,9 @@ def build_config( if capability_key in entry and capability_key not in explicit: cfg[capability_key] = list(entry.get(capability_key) or []) + if cfg["image_editing_enabled"]: + cfg["input_modalities"] = sorted(set(cfg.get("input_modalities") or ["text"]) | {"image"}) + return cfg diff --git a/src/local_llm_server/image_editing_api.py b/src/local_llm_server/image_editing_api.py new file mode 100644 index 00000000..25ccadfa --- /dev/null +++ b/src/local_llm_server/image_editing_api.py @@ -0,0 +1,202 @@ +"""Opt-in, bounded image editing through the existing native sd-server. + +No remote image URLs, paths, masks or arbitrary native arguments enter this API. +The first supported format is one PNG reference; all bytes stay local and are +discarded at request end. Full imaging support follows measured Mac E2E tests. +""" +from __future__ import annotations + +import base64 +import hashlib +import struct +import time +import zlib +from dataclasses import replace + +from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile, status +from starlette.concurrency import run_in_threadpool + +from .core.contracts import InferenceError +from .image_generation_request import ImageGenerationRequest, prepare_image_generation_request +from .request_pipeline import public_error_detail +from .task_policy import enforce_request_capabilities + +MAX_UPLOAD_BYTES = 8 * 1024 * 1024 +MAX_SOURCE_PIXELS = 1_048_576 # first release: <=1 megapixel, to bound vision activations +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" + + +def validate_png_reference(data: bytes, *, max_pixels: int = MAX_SOURCE_PIXELS) -> tuple[int, int]: + """Inspect fixed PNG signature/IHDR without expanding untrusted compressed pixels.""" + if len(data) < 33 or len(data) > MAX_UPLOAD_BYTES: + raise ValueError("PNG reference must be between 33 bytes and 8 MiB") + if not data.startswith(PNG_SIGNATURE) or data[12:16] != b"IHDR": + raise ValueError("Only PNG reference images are supported") + if struct.unpack(">I", data[8:12])[0] != 13: + raise ValueError("Invalid PNG IHDR") + crc = struct.unpack(">I", data[29:33])[0] + if zlib.crc32(data[12:29]) & 0xFFFFFFFF != crc: + raise ValueError("Corrupt PNG IHDR") + width, height = struct.unpack(">II", data[16:24]) + if not (32 <= width <= 2048 and 32 <= height <= 2048): + raise ValueError("Reference dimensions must be between 32 and 2048 pixels") + if width * height > max_pixels: + raise ValueError("Reference image exceeds configured pixel budget") + return width, height + + +def install_image_editing_api(application: FastAPI) -> FastAPI: + if getattr(application.state, "image_editing_api_installed", False): + return application + application.state.image_editing_api_installed = True + + @application.post("/v1/images/edits", tags=["Images"]) + async def edit_image( + request: Request, + image: UploadFile = File(...), + prompt: str = Form(...), + model: str | None = Form(None), + size: str | None = Form(None), + seed: int | None = Form(None), + num_inference_steps: int | None = Form(None), + n: int = Form(1), + ): + manager = getattr(request.app.state, "runtime_manager", None) + if manager is None: + raise HTTPException(status_code=503, detail={ + "code": "runtime_unavailable", "message": "Runtime manager unavailable", + }) + try: + runtime = manager.resolve(model) + except LookupError as exc: + raise HTTPException(status_code=404, detail={ + "code": "model_not_resident", "message": str(exc), + }) from exc + + if not runtime.cfg.get("image_editing_enabled"): + raise HTTPException(status_code=400, detail={ + "code": "unsupported_task", + "message": "Start this model with --image-editing-enabled to use image edits.", + }) + + if n != 1: + raise HTTPException(status_code=400, detail={ + "code": "invalid_request", "message": "Only one output is supported", + }) + if image.content_type != "image/png": + raise HTTPException(status_code=415, detail={ + "code": "unsupported_media_type", "message": "Upload one PNG image", + }) + + try: + source = await image.read(MAX_UPLOAD_BYTES + 1) + finally: + await image.close() + + try: + width, height = validate_png_reference( + source, + max_pixels=min( + MAX_SOURCE_PIXELS, + int(runtime.cfg.get("image_max_pixels") or MAX_SOURCE_PIXELS), + ), + ) + image_request = ImageGenerationRequest( + model=runtime.key, + prompt=prompt, + n=n, + size=size or f"{width}x{height}", + seed=seed, + num_inference_steps=num_inference_steps, + ) + prepared = prepare_image_generation_request( + image_request, + runtime_key=runtime.key, + runtime_config=runtime.cfg, + ) + if prepared.width % 32 or prepared.height % 32: + raise ValueError("Edited output dimensions must be multiples of 32") + if prepared.width * prepared.height > MAX_SOURCE_PIXELS: + raise ValueError("Edited output exceeds the first-release 1MP safety limit") + # Describe the presence of an image without inserting raw image + # bytes into the public canonical request or policy logs. + canonical = replace( + prepared.canonical, + messages=({"role": "user", "content": [{"type": "input_image"}]},), + ) + enforce_request_capabilities(canonical, runtime_config=runtime.cfg) + except ValueError as exc: + raise HTTPException(status_code=400, detail={ + "code": "invalid_request", "message": str(exc), + }) from exc + except InferenceError as exc: + raise HTTPException( + status_code=400, detail=public_error_detail(exc), + ) from exc + + # Editing has higher transient memory requirements than text-to-image. + # Refuse a new request under elevated pressure; swap used is not RAM. + resource_manager = manager.resource_manager + if resource_manager is not None and resource_manager.host_protection_enabled: + observation = resource_manager.host_memory_status() + if observation is None or observation.get("pressure") != "normal": + raise HTTPException(status_code=503, detail={ + "code": "resource_exhausted", + "message": "Host memory pressure is not normal; edit was not started", + "retryable": True, + }) + + generate = getattr(runtime.engine, "generate_image", None) + if not callable(generate): + raise HTTPException(status_code=400, detail={ + "code": "unsupported_task", + "message": "Image editing backend is unavailable", + }) + params = dict(prepared.backend_payload) + params["ref_images"] = [ + "data:image/png;base64," + base64.b64encode(source).decode("ascii") + ] + source_digest = hashlib.sha256(source).hexdigest() + started = time.perf_counter() + + def run_native_edit(): + # Native submission and polling are synchronous I/O. Keeping the + # lease in this worker prevents blocking FastAPI's event loop for + # the minutes an image job may take. + with manager.lease_runtime(runtime): + if resource_manager is not None and resource_manager.host_protection_enabled: + latest = resource_manager.host_memory_status() + if latest is None or latest.get("pressure") != "normal": + raise HTTPException(status_code=503, detail={ + "code": "resource_exhausted", + "message": "Host memory pressure increased while edit was queued", + "retryable": True, + }) + return generate(params) + + try: + result = await run_in_threadpool(run_native_edit) + except (RuntimeError, ValueError, TimeoutError) as exc: + raise HTTPException(status_code=500, detail={ + "code": "backend_error", "message": str(exc), + }) from exc + return { + "created": int(time.time()), + "model": runtime.model_id, + "data": [{"b64_json": base64.b64encode(result.data).decode("ascii")}], + "korgis": { + "runtime_key": runtime.key, + "backend": getattr(runtime.engine, "backend", "unknown"), + "mime_type": result.mime_type, + "width": result.width, + "height": result.height, + "seed": result.seed, + "latency_ms": (time.perf_counter() - started) * 1000, + "source_sha256": source_digest, + "source_width": width, + "source_height": height, + "generation": result.metadata, + }, + } + + return application diff --git a/src/local_llm_server/image_generation_api.py b/src/local_llm_server/image_generation_api.py index 984deade..441f3f42 100644 --- a/src/local_llm_server/image_generation_api.py +++ b/src/local_llm_server/image_generation_api.py @@ -7,6 +7,7 @@ from fastapi import FastAPI, HTTPException, Request, status from .core.contracts import InferenceError +from .image_editing_api import install_image_editing_api from .image_generation_request import ( ImageGenerationRequest, prepare_image_generation_request, @@ -118,4 +119,4 @@ def generate_image(payload: ImageGenerationRequest, request: Request): }, } - return application + return install_image_editing_api(application) diff --git a/src/local_llm_server/image_sampling_presets.py b/src/local_llm_server/image_sampling_presets.py new file mode 100644 index 00000000..cd817b2c --- /dev/null +++ b/src/local_llm_server/image_sampling_presets.py @@ -0,0 +1,60 @@ +"""Pinned model-specific sampler presets for the native image backend. + +Never silently substitute an ordinary eight-step schedule for Turbo's +manually specified denoising sigmas. +""" +from __future__ import annotations + +import hashlib +import json +import math + +QWEN_IMAGE_21_TURBO_V1 = ( + 1.0, 0.978453, 0.95418, 0.926626, 0.89508, + 0.845148, 0.704534, 0.414568, 0.0, +) +_PRESETS = {"qwen-image-2.1-turbo-v1": QWEN_IMAGE_21_TURBO_V1} + + +def resolve_image_sigma_schedule( + preset: str | None, + *, + steps: int, + guidance_scale: float, + sampling_method: str, + scheduler: str | None, +) -> tuple[float, ...] | None: + """Resolve a validated profile, rejecting incompatible request overrides.""" + if not preset: + return None + try: + sigmas = _PRESETS[preset] + except KeyError as exc: + raise ValueError(f"Unknown image sigma schedule: {preset}") from exc + + if not 2 <= len(sigmas) <= 1001: + raise ValueError("custom sigmas must contain 2–1001 values") + if any( + not math.isfinite(value) or value < 0 + for value in sigmas + ): + raise ValueError("custom sigmas must be nonnegative and finite") + if any(a <= b for a, b in zip(sigmas, sigmas[1:])) or sigmas[-1] != 0: + raise ValueError("custom sigmas must descend strictly and end at zero") + if steps != len(sigmas) - 1: + raise ValueError( + f"{preset} requires exactly {len(sigmas) - 1} denoising steps, got {steps}" + ) + if guidance_scale != 1.0: + raise ValueError(f"{preset} requires guidance_scale=1.0") + if sampling_method != "euler": + raise ValueError(f"{preset} requires sampling_method=euler") + if scheduler is not None: + raise ValueError(f"{preset} does not accept a scheduler override") + return sigmas + + +def image_sigma_digest(sigmas: tuple[float, ...]) -> str: + """SHA-256 of the effective ordered list, for shareable evidence.""" + serialized = json.dumps(list(sigmas), separators=(",", ":"), allow_nan=False) + return hashlib.sha256(serialized.encode("ascii")).hexdigest() diff --git a/src/local_llm_server/model_sources.py b/src/local_llm_server/model_sources.py index cbd25a38..57b883b2 100644 --- a/src/local_llm_server/model_sources.py +++ b/src/local_llm_server/model_sources.py @@ -206,6 +206,24 @@ def resolve_bundle_artifacts( raise ValueError( f"Model '{key}' artifact '{name}' escapes its bundle directory" ) + # Artifact-specific LM Studio reuse is opt-in and limited to the + # current user's LM Studio model tree. Never copy or re-download the + # transformer when its exact GGUF already exists there. + lmstudio_relative = raw_spec.get("lmstudio_relative_path") + if lmstudio_relative is not None: + if not isinstance(lmstudio_relative, str) or not lmstudio_relative.strip(): + raise ValueError(f"Model '{key}' artifact '{name}' has invalid LM Studio path") + relative_lm = Path(lmstudio_relative) + if relative_lm.is_absolute() or ".." in relative_lm.parts: + raise ValueError(f"Model '{key}' artifact '{name}' LM Studio path must be relative") + lmstudio_root = (Path.home() / ".lmstudio" / "models").resolve() + candidate = (lmstudio_root / relative_lm).resolve() + if candidate == lmstudio_root or lmstudio_root not in candidate.parents: + raise ValueError(f"Model '{key}' artifact '{name}' LM Studio path escapes model tree") + if explicit_root is None and ( + candidate.is_file() or bool(raw_spec.get("lmstudio_required", False)) + ): + destination = candidate resolved[str(name)] = destination return resolved @@ -329,7 +347,13 @@ def resolve_registry_model( return ResolvedModel( model_path=str(root), local_path=root, - source_type="explicit" if explicit_path is not None else "managed", + source_type=( + "explicit" if explicit_path is not None else + "lmstudio" if any( + (Path.home() / ".lmstudio" / "models").resolve() in path.parents + for path in artifacts.values() + ) else "managed" + ), downloaded=is_complete_sdcpp_image_bundle(artifacts), artifacts=artifacts, ) diff --git a/src/local_llm_server/models_registry.yaml b/src/local_llm_server/models_registry.yaml index 4bb7995e..a30db0a7 100644 --- a/src/local_llm_server/models_registry.yaml +++ b/src/local_llm_server/models_registry.yaml @@ -334,6 +334,132 @@ models: startup_timeout: 600 tags: [image-generation, qwen, local, gguf, q4-k-m, stable-diffusion-cpp] + # Qwen Image 2.1 Turbo; keep separate from the full Qwen Image 2.1 profile. + # Qwen Research License: research/evaluation, not general commercial use. + # Turbo GGUF bundle aligned to local Unsloth GGUF+GGUF+VAE layout. + # Each SHA256 is published by its Hugging Face file page. The source + # revisions and bytes are pinned; existing files are re-verified by SHA256. + qwen-image-2.1-turbo-gguf-q4km: + model_id: "unsloth/Qwen-Image-2.1-Turbo-GGUF" + backend: stable_diffusion_cpp_image + quantization: "Q4_K_M" + size_gb: 10.03 # combined artifact sizes (decimal GB), not RAM/VRAM + license: "qwen-research" + thinking_mode: none + tasks: [image_generation] + input_modalities: [text] + output_modalities: [image] + artifacts: + diffusion_model: + repo: "unsloth/Qwen-Image-2.1-Turbo-GGUF" + revision: "5d1f9f759ea877ae556cda88dbec958b62ad3809" + filename: "qwen-image-2.1-turbo-Q4_K_M.gguf" + local_path: "diffusion/qwen-image-2.1-turbo-Q4_K_M.gguf" + sha256: "8940e8b522af886e0c0f5afddf720e82dd223cb9a43580b5f61c4d740452ac20" + text_encoder: + repo: "unsloth/Qwen3-VL-8B-Instruct-GGUF" + revision: "174e4a339d8aceef41c87fda9f732c042d49e50b" + filename: "Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf" + local_path: "text_encoder/Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf" + sha256: "e3d1a6e87c5cb31e054f2c3bc0dd82ffde052f613de5eef3665b7bd33c9b703e" + vae: + repo: "unsloth/Qwen-Image-2.1-FP8" + revision: "db2bfe9028a3c1f486833be12f3a928e5f4a1286" + filename: "vae/qwen_image_2.1_vae_bf16.safetensors" + local_path: "vae/qwen_image_2.1_vae_bf16.safetensors" + sha256: "71879ffd5321e6d10c3c87513e2b474b1252efa7f3dec2969214a9bf06a6dd5c" + # Optional, only loaded when --image-editing-enabled is explicitly set. + # The text-to-image bundle stays valid with the original three files. + image_editing_projector: + repo: "unsloth/Qwen3-VL-8B-Instruct-GGUF" + revision: "174e4a339d8aceef41c87fda9f732c042d49e50b" + filename: "mmproj-BF16.gguf" + local_path: "text_encoder/mmproj-BF16.gguf" + sha256: "6516bb64bae1503a0fcd7ec9fa39655f8c481580be0a0a066397941d9761c9f4" + params: + # Experimental measured-RSS-informed envelope, NOT measured unified peak. + # Must be recalibrated with memory/swap evidence on representative Macs. + resource_admission_profile: disk_backed_image + resource_estimate_bytes: 8589934592 # 8 GiB initial resident budget + # Extra safety allowance for projector + vision activations (provisional). + image_editing_extra_resident_bytes: 2147483648 # +2 GiB only in edit mode + sd_server_port: 8093 + image_width: 1024 + image_height: 1024 + image_num_inference_steps: 8 + image_max_inference_steps: 8 + image_max_pixels: 4194304 + image_guidance_scale: 1.0 + image_sampling_method: euler + image_sigma_schedule: "qwen-image-2.1-turbo-v1" + image_verify_existing_artifacts: true + image_diffusion_flash_attention: true + image_offload_to_cpu: true + sd_server_params_backend: "diffusion=disk,te=cpu,vae=cpu" + sd_server_max_vram: "-2" + sd_server_model_args: "qwen_image_2_1_prefix_cache=false" + sd_server_disable_prefetch: true + image_vae_tiling: true + image_vae_tile_size: "256x256" + image_output_format: png + max_concurrent_requests: 1 + startup_timeout: 600 + tags: [image-generation, qwen, turbo, local, gguf, q4-k-m, stable-diffusion-cpp] + + # FLUX.3 Image Klein distilled, Q5_K_M transformer reused directly from LM Studio. + # The Qwen3-VL-4B text encoder and the FLUX.2 VAE are separate required files. + # No extra downloads/copies of the 4.22 GB GGUF are ever performed. + flux-3-image-klein-gguf-q5km: + model_id: "unsloth/flux-3-image-klein-GGUF" + backend: stable_diffusion_cpp_image + quantization: "Q5_K_M" + size_gb: 7.2 # approximate combined weights on disk; NOT a RAM measurement + license: "flux-kommunity-license" + thinking_mode: none + tasks: [image_generation] + input_modalities: [text] + output_modalities: [image] + artifacts: + diffusion_model: + repo: "unsloth/flux-3-image-klein-GGUF" + revision: main # source provenance only; transformer is LM Studio local-only + filename: "flux-3-image-klein-Q5_K_M.gguf" + local_path: "diffusion/flux-3-image-klein-Q5_K_M.gguf" + lmstudio_relative_path: "unsloth/flux-3-image-klein-GGUF/flux-3-image-klein-Q5_K_M.gguf" + lmstudio_required: true + text_encoder: + repo: "unsloth/Qwen3-VL-4B-Instruct-GGUF" + revision: "cc8371d67a57fc6ae05fc5a9c2df763914928539" + filename: "Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + local_path: "text_encoder/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vae: + repo: "unsloth/flux-3-image-klein" + revision: main # lock to a verified commit/checksum before general release + filename: "ae.safetensors" + local_path: "vae/ae.safetensors" + params: + # Provisional disk-backed envelope; requires real macOS RSS/unified + # memory and swap evidence before this estimate can be calibrated. + resource_admission_profile: disk_backed_image + resource_estimate_bytes: 9663676416 # 9 GiB provisional resident budget + sd_server_port: 8093 + image_width: 1024 + image_height: 1024 + image_num_inference_steps: 16 + image_max_inference_steps: 16 + image_max_pixels: 1048576 + image_guidance_scale: 1.0 + image_sampling_method: euler + image_output_format: png + image_diffusion_flash_attention: true + image_offload_to_cpu: true + sd_server_params_backend: "diffusion=disk,te=cpu,vae=cpu" + sd_server_max_vram: "-2" + sd_server_disable_prefetch: true + max_concurrent_requests: 1 + startup_timeout: 600 + tags: [image-generation, flux3, klein, distilled, local, gguf, q5-k-m, stable-diffusion-cpp] + # voxtral-mini-3b: # filename: "mistralai_Voxtral-Mini-3B-2507-Q4_K_M.gguf" # mmproj_filename: "mmproj-mistralai_Voxtral-Mini-3B-2507-f16.gguf" diff --git a/src/local_llm_server/resource_manager.py b/src/local_llm_server/resource_manager.py index 21d67bae..99ebd5a1 100644 --- a/src/local_llm_server/resource_manager.py +++ b/src/local_llm_server/resource_manager.py @@ -10,8 +10,13 @@ import threading from dataclasses import dataclass from enum import Enum +from math import ceil +from typing import TYPE_CHECKING -from .resources import ResourceBudget +from .resources import ResourceBudget, ResourcePressure, ResourceValueSource, classify_memory_pressure + +if TYPE_CHECKING: + from .resources import ResourceObserver class AdmissionDecision(str, Enum): @@ -20,6 +25,13 @@ class AdmissionDecision(str, Enum): UNKNOWN = "unknown" +class HostAdmissionProfile(str, Enum): + """The disk-backed policy is limited to explicitly configured image runtimes.""" + + STANDARD = "standard" + DISK_BACKED_IMAGE = "disk_backed_image" + + class ReservationState(str, Enum): RESERVED = "reserved" COMMITTED = "committed" @@ -37,6 +49,7 @@ class ResourceReservation: accounted_bytes: int state: ReservationState kind: ReservationKind = ReservationKind.RESIDENT + admission_profile: HostAdmissionProfile = HostAdmissionProfile.STANDARD @dataclass(frozen=True, slots=True) @@ -52,10 +65,128 @@ class AdmissionResult: class ResourceManager: """Thread-safe configured-budget ledger shared by all memory owners.""" - def __init__(self, budget: ResourceBudget) -> None: + def __init__( + self, + budget: ResourceBudget, + *, + host_observer: ResourceObserver | None = None, + ) -> None: self._budget = budget + self._host_observer = host_observer self._reservations: dict[str, ResourceReservation] = {} self._lock = threading.RLock() + # Last event from a live, supervised macOS Dispatch source (if opted in). + # A value of None is unknown, not normal. + self._native_pressure: ResourcePressure | None = None + + @property + def host_protection_enabled(self) -> bool: + return self._host_observer is not None + + def update_native_pressure(self, pressure: ResourcePressure | None) -> None: + """Accept a verified event only while the native source is alive. + + Clearing on helper exit is required: a stale normal event must not + suppress a later measured host-pressure warning. + """ + if pressure is not None and pressure is ResourcePressure.UNKNOWN: + raise ValueError("unknown is not a native pressure transition") + if pressure is not None and not isinstance(pressure, ResourcePressure): + raise TypeError("native pressure must be ResourcePressure or None") + with self._lock: + self._native_pressure = pressure + + def _effective_pressure(self, derived: ResourcePressure) -> ResourcePressure: + with self._lock: + native = self._native_pressure + if native is None: + return derived + # A native NORMAL *transition* is not evidence that a missing + # vm_stat measurement is safe. Preserve unknown unless the event + # carries a warning/critical signal that should block new work. + if derived is ResourcePressure.UNKNOWN and native is ResourcePressure.NORMAL: + return ResourcePressure.UNKNOWN + rank = {ResourcePressure.UNKNOWN: -1, ResourcePressure.NORMAL: 0, + ResourcePressure.ELEVATED: 1, ResourcePressure.CRITICAL: 2} + return native if rank[native] > rank[derived] else derived + + def host_memory_status(self) -> dict[str, object] | None: + """Public-safe observed host status; read-only, never an eviction command. + + The pressure classification is a heuristic derived from reclaimable + host pages, NOT a native macOS memory-pressure notification. + """ + observer = self._host_observer + if observer is None: + return None + try: + snapshot = observer.snapshot() + except Exception: + snapshot = None + + if snapshot is None: + with self._lock: + native = self._native_pressure + pressure = self._effective_pressure(ResourcePressure.UNKNOWN) + status = { + "pressure": pressure.value, + "source": ( + "native_dispatch_event" if native is not None + and pressure is native else "unavailable" + ), + "available_bytes": None, + "total_bytes": None, + "swap_used_bytes": None, + "alert": _host_pressure_alert(pressure), + "automatic_pressure_eviction_enabled": False, + } + if native is not None: + status["native_last_event"] = native.value + return status + + def measured(value: object) -> int | None: + if getattr(value, "source", None) is not ResourceValueSource.MEASURED: + return None + number = getattr(value, "value", None) + return number if isinstance(number, int) and not isinstance(number, bool) and number >= 0 else None + + pressure = ( + classify_memory_pressure(snapshot) + if measured(snapshot.available_memory_bytes) is not None + and measured(snapshot.total_memory_bytes) is not None + else ResourcePressure.UNKNOWN + ) + with self._lock: + native = self._native_pressure + effective = self._effective_pressure(pressure) + status = { + "pressure": effective.value, + "source": ( + "native_dispatch_event" if native is not None + and effective is native + and (pressure is ResourcePressure.UNKNOWN or effective is not pressure) + else "derived_available_fraction" if pressure is not ResourcePressure.UNKNOWN + else "unavailable" + ), + "available_bytes": measured(snapshot.available_memory_bytes), + "total_bytes": measured(snapshot.total_memory_bytes), + "swap_used_bytes": measured(getattr(snapshot, "swap_used_bytes", None)), + "alert": _host_pressure_alert(effective), + "automatic_pressure_eviction_enabled": False, + } + if native is not None: + status["native_last_event"] = native.value + status["derived_pressure"] = pressure.value + return status + + def reject_unestimated_load(self) -> AdmissionResult: + """A missing size cannot silently bypass host admission on macOS.""" + with self._lock: + return self._result( + AdmissionDecision.REJECT, + requested_bytes=0, + reason="resident memory estimate unavailable under host memory guard", + ) @property def budget(self) -> ResourceBudget: @@ -78,7 +209,12 @@ def reserve( requested_bytes: int, *, kind: ReservationKind = ReservationKind.RESIDENT, + admission_profile: HostAdmissionProfile = HostAdmissionProfile.STANDARD, ) -> AdmissionResult: + if not isinstance(admission_profile, HostAdmissionProfile): + raise ValueError("unknown host admission profile") + if kind is not ReservationKind.RESIDENT and admission_profile is not HostAdmissionProfile.STANDARD: + raise ValueError("disk-backed host admission applies only to resident models") if not reservation_id.strip(): raise ValueError("reservation_id must be non-empty") if requested_bytes < 0: @@ -87,7 +223,7 @@ def reserve( with self._lock: if reservation_id in self._reservations: raise ValueError(f"reservation already exists: {reservation_id}") - decision = self._decision_for(requested_bytes) + decision = self._decision_for(requested_bytes, admission_profile=admission_profile) if decision.decision is AdmissionDecision.ADMIT: self._reservations[reservation_id] = ResourceReservation( reservation_id=reservation_id, @@ -95,6 +231,7 @@ def reserve( accounted_bytes=requested_bytes, state=ReservationState.RESERVED, kind=kind, + admission_profile=admission_profile, ) return decision @@ -116,15 +253,27 @@ def commit(self, reservation_id: str, *, observed_bytes: int | None = None) -> A requested_bytes=accounted, reason="observed footprint exceeds configured usable budget", ) + # The new backend now occupies real host memory. Check that the + # system still has headroom before publishing the resident runtime. + host = self._check_host_available( + 0, + exclude_reservation_id=reservation_id, + admission_profile=current.admission_profile, + ) + if host is not None and host.decision is AdmissionDecision.REJECT: + return host self._reservations[reservation_id] = ResourceReservation( reservation_id=reservation_id, requested_bytes=current.requested_bytes, accounted_bytes=accounted, state=ReservationState.COMMITTED, kind=current.kind, + admission_profile=current.admission_profile, ) return self._result( - AdmissionDecision.ADMIT if usable is not None else AdmissionDecision.UNKNOWN, + AdmissionDecision.ADMIT + if usable is not None or self.host_protection_enabled + else AdmissionDecision.UNKNOWN, requested_bytes=accounted, reason=( "committed within configured budget" @@ -140,25 +289,113 @@ def release(self, reservation_id: str) -> bool: def rollback(self, reservation_id: str) -> bool: return self.release(reservation_id) - def _decision_for(self, requested_bytes: int) -> AdmissionResult: + def _decision_for( + self, + requested_bytes: int, + *, + admission_profile: HostAdmissionProfile = HostAdmissionProfile.STANDARD, + ) -> AdmissionResult: usable = self._budget.usable_bytes - if usable is None: + accounted = sum(item.accounted_bytes for item in self._reservations.values()) + if usable is not None and accounted + requested_bytes > usable: + return self._result( + AdmissionDecision.REJECT, + requested_bytes=requested_bytes, + reason="configured usable budget would be exceeded", + ) + host = self._check_host_available( + requested_bytes, admission_profile=admission_profile, + ) + if host is not None and host.decision is AdmissionDecision.REJECT: + return host + if usable is None and host is None: return self._result( AdmissionDecision.UNKNOWN, requested_bytes=requested_bytes, reason="no configured resource limit", ) - accounted = sum(item.accounted_bytes for item in self._reservations.values()) - if accounted + requested_bytes > usable: + return self._result( + AdmissionDecision.ADMIT, + requested_bytes=requested_bytes, + reason=( + "host headroom and configured budget admit reservation" + if usable is not None and host is not None + else "host headroom admits reservation" + if host is not None + else "reservation fits configured usable budget" + ), + ) + + def _check_host_available( + self, requested_bytes: int, *, exclude_reservation_id: str | None = None, + admission_profile: HostAdmissionProfile = HostAdmissionProfile.STANDARD, + ) -> AdmissionResult | None: + """Live admission, separate from the configured per-Korgis ledger. + + Already COMMITTED processes are reflected in the host's measured + available memory. Count only still-pending reservations to avoid + double charging resident models. The 1.5x load allowance is a policy + safety estimate, not a proven native/GPU peak memory bound. + """ + observer = self._host_observer + if observer is None: + return None + snapshot = None + try: + snapshot = observer.snapshot() + total = snapshot.total_memory_bytes.value + available = snapshot.available_memory_bytes.value + except Exception: + total = available = None + if ( + snapshot is None + or not isinstance(total, int) or not isinstance(available, int) + or snapshot.total_memory_bytes.source is not ResourceValueSource.MEASURED + or snapshot.available_memory_bytes.source is not ResourceValueSource.MEASURED + or total <= 0 or available < 0 + ): return self._result( AdmissionDecision.REJECT, requested_bytes=requested_bytes, - reason="configured usable budget would be exceeded", + reason="host memory observation unavailable", + ) + # The conservative OS reserve alone is not enough when the measured + # host is already under pressure (especially with a small new load). + # No resident runtime is unloaded here; admission only rejects. + pressure = self._effective_pressure(classify_memory_pressure(snapshot)) + if pressure in {ResourcePressure.ELEVATED, ResourcePressure.CRITICAL}: + return self._result( + AdmissionDecision.REJECT, + requested_bytes=requested_bytes, + reason=f"host available memory unsafe: host memory pressure is {pressure.value}; rejecting new allocation", + ) + # Disk-backed image engines stream model weights from disk. Their full + # file size is not a resident-memory estimate. A specific calibrated + # working-set estimate is required at the caller, with a smaller but + # non-zero OS reserve. Swap is NEVER added to available physical RAM. + # All measurement, pressure and post-load checks still apply. + if admission_profile is HostAdmissionProfile.DISK_BACKED_IMAGE: + reserve = max(2 * 1024**3, min(3 * 1024**3, ceil(total * 0.09375))) + growth_factor = 1.25 + else: + reserve = max(2 * 1024**3, min(6 * 1024**3, ceil(total * 0.1875))) + growth_factor = 1.5 + pending = sum( + entry.accounted_bytes + for key, entry in self._reservations.items() + if key != exclude_reservation_id and entry.state is ReservationState.RESERVED + ) + projected = ceil((requested_bytes + pending) * growth_factor) + if available - projected < reserve: + return self._result( + AdmissionDecision.REJECT, + requested_bytes=requested_bytes, + reason="host available memory cannot cover estimated growth and OS reserve", ) return self._result( AdmissionDecision.ADMIT, requested_bytes=requested_bytes, - reason="reservation fits configured usable budget", + reason="host available memory above conservative admission floor", ) def _result( @@ -192,3 +429,12 @@ def _require(self, reservation_id: str) -> ResourceReservation: return self._reservations[reservation_id] except KeyError as exc: raise KeyError(f"unknown reservation: {reservation_id}") from exc + +def _host_pressure_alert(pressure: ResourcePressure) -> str: + if pressure is ResourcePressure.CRITICAL: + return "critical" + if pressure is ResourcePressure.ELEVATED: + return "warning" + if pressure is ResourcePressure.NORMAL: + return "none" + return "unknown" diff --git a/src/local_llm_server/resources.py b/src/local_llm_server/resources.py index 0a6b8078..6e708435 100644 --- a/src/local_llm_server/resources.py +++ b/src/local_llm_server/resources.py @@ -58,6 +58,7 @@ class SystemResourceSnapshot: process_rss_bytes: ResourceValue = field(default_factory=lambda: ResourceValue.unavailable("bytes")) accelerator_memory_bytes: ResourceValue = field(default_factory=lambda: ResourceValue.unavailable("bytes")) thermal_pressure: ResourceValue = field(default_factory=lambda: ResourceValue.unavailable("level")) + swap_used_bytes: ResourceValue = field(default_factory=lambda: ResourceValue.unavailable("bytes")) @dataclass(frozen=True, slots=True) diff --git a/src/local_llm_server/runtime.py b/src/local_llm_server/runtime.py index 74eb0efd..0aae349e 100644 --- a/src/local_llm_server/runtime.py +++ b/src/local_llm_server/runtime.py @@ -10,7 +10,7 @@ from enum import Enum from typing import Any -from .resource_manager import AdmissionDecision, AdmissionResult, ResourceManager +from .resource_manager import AdmissionDecision, AdmissionResult, HostAdmissionProfile, ResourceManager from .runtime_admission import admission_metadata, estimated_runtime_load_bytes @@ -640,15 +640,48 @@ def _next_ready_runtime_key_unlocked(self) -> str | None: ) def _reserve_runtime_load(self, runtime_key: str, cfg: dict[str, Any]) -> str | None: + profile_name = str(cfg.get("resource_admission_profile") or "standard") + try: + profile = HostAdmissionProfile(profile_name) + except ValueError as exc: + raise ValueError(f"unknown resource admission profile: {profile_name!r}") from exc + if profile is HostAdmissionProfile.DISK_BACKED_IMAGE: + # Never extend the reduced footprint allowance to an arbitrary + # model. Only native image inference with disk-mapped diffusion + # and an explicit working-set estimate may use this profile. + backend = cfg.get("backend") + backend_params = str(cfg.get("sd_server_params_backend") or "") + tokens = { + pair.strip() + for pair in backend_params.split(",") + if pair.strip() + } + if ( + backend != "stable_diffusion_cpp_image" + or "diffusion=disk" not in tokens + or cfg.get("resource_estimate_bytes") is None + or cfg.get("image_offload_to_cpu") is not True + ): + raise ValueError( + "disk_backed_image admission requires native image backend, " + "diffusion=disk, CPU offload and explicit working-set estimate" + ) estimate = estimated_runtime_load_bytes(cfg) + # build_config has already combined base model and vision projector + # budgets for an opted-in edit runtime. Do not charge twice. manager = self._resource_manager + if manager is not None and manager.host_protection_enabled and estimate is None: + raise ResourceAdmissionError(manager.reject_unestimated_load()) if manager is None or estimate is None: cfg["resource_admission"] = admission_metadata(None, estimate_bytes=estimate) return None reservation_id = self._next_reservation_id(runtime_key) - result = manager.reserve(reservation_id, estimate) + result = manager.reserve( + reservation_id, estimate, admission_profile=profile, + ) cfg["resource_admission"] = admission_metadata(result, estimate_bytes=estimate) + cfg["resource_admission"]["profile"] = profile.value if result.decision is AdmissionDecision.REJECT: raise ResourceAdmissionError(result) if result.decision is AdmissionDecision.UNKNOWN: diff --git a/src/local_llm_server/server.py b/src/local_llm_server/server.py index 4be6f9ca..97eaedcf 100644 --- a/src/local_llm_server/server.py +++ b/src/local_llm_server/server.py @@ -489,6 +489,7 @@ def get_models(request: Request): "path": runtime.cfg["model_path"], "backend": getattr(runtime.engine, "backend", runtime.cfg.get("backend")), "default": runtime.key == manager.default_model, + "image_editing_enabled": bool(runtime.cfg.get("image_editing_enabled", False)), } for runtime in manager.list() ], diff --git a/src/local_llm_server/stable_diffusion_cpp_compat.py b/src/local_llm_server/stable_diffusion_cpp_compat.py index a276d1fa..b0b2240f 100644 --- a/src/local_llm_server/stable_diffusion_cpp_compat.py +++ b/src/local_llm_server/stable_diffusion_cpp_compat.py @@ -93,6 +93,15 @@ def build_sd_server_command( "--listen-port", str(_positive_int(port, "sd_server_port")), ] + if cfg.get("image_editing_enabled"): + projector = cfg.get("image_editing_projector_path") + if not projector or not Path(str(projector)).is_file(): + raise FileNotFoundError( + "Qwen image editing requires the matching Qwen3-VL vision projector; " + "download it first or start without --image-editing-enabled" + ) + cmd.extend(["--llm_vision", str(projector)]) + if bool(cfg.get("image_diffusion_flash_attention", True)): cmd.append("--diffusion-fa") if bool(cfg.get("image_offload_to_cpu", True)): diff --git a/src/local_llm_server/stable_diffusion_cpp_image_engine.py b/src/local_llm_server/stable_diffusion_cpp_image_engine.py index 7c8be25e..1222a7af 100644 --- a/src/local_llm_server/stable_diffusion_cpp_image_engine.py +++ b/src/local_llm_server/stable_diffusion_cpp_image_engine.py @@ -14,6 +14,7 @@ from .downloader import ensure_model from .image_generation_common import GeneratedImage +from .image_sampling_presets import image_sigma_digest, resolve_image_sigma_schedule from .model_sources import artifact_download_url from .process import ManagedProcess from .stable_diffusion_cpp_compat import ( @@ -92,6 +93,16 @@ def _build_artifact_provenance( if value is not None and str(value).strip(): item[field] = str(value) provenance[name] = item + if self.cfg.get("image_editing_enabled"): + spec = self.cfg.get("image_editing_projector_spec") + path = self.cfg.get("image_editing_projector_path") + if isinstance(spec, Mapping) and isinstance(path, str): + item = {"filename": Path(path).name} + for field in ("repo", "revision", "sha256"): + value = spec.get(field) + if value is not None and str(value).strip(): + item[field] = str(value) + provenance["vision_projector"] = item return provenance def _ensure_artifacts(self, specs: Mapping[str, Any]) -> None: @@ -102,15 +113,45 @@ def _ensure_artifacts(self, specs: Mapping[str, Any]) -> None: raise ValueError( f"stable-diffusion.cpp bundle is missing artifact '{name}'" ) + if spec.get("lmstudio_required"): + # Do not silently download or duplicate a model explicitly + # owned by LM Studio. Validate it is a plausible complete GGUF + # before spawning the native backend. + if not path.is_file(): + raise FileNotFoundError( + f"LM Studio transformer missing: {path}. " + "Install the exact GGUF in LM Studio or use the matching model path." + ) + if path.stat().st_size < 3_500_000_000: + raise ValueError( + f"LM Studio GGUF looks incomplete (<3.5 GB): {path}" + ) + with path.open("rb") as handle: + if handle.read(4) != b"GGUF": + raise ValueError(f"LM Studio file does not have a GGUF header: {path}") ensure_model( url=artifact_download_url(dict(spec)), dest=path, - no_download=bool(self.cfg.get("no_download", False)), + no_download=bool(self.cfg.get("no_download", False)) or bool(spec.get("lmstudio_required")), expected_sha256=( str(spec["sha256"]) if spec.get("sha256") is not None else None ), + verify_existing=bool(self.cfg.get("image_verify_existing_artifacts", False)), + ) + + if self.cfg.get("image_editing_enabled"): + spec = self.cfg.get("image_editing_projector_spec") + path = self.cfg.get("image_editing_projector_path") + if not isinstance(spec, Mapping) or not isinstance(path, str): + raise ValueError("image editing needs a pinned vision projector") + ensure_model( + url=artifact_download_url(dict(spec)), + dest=Path(path), + no_download=bool(self.cfg.get("no_download", False)), + expected_sha256=str(spec["sha256"]), + verify_existing=True, ) def _start(self) -> None: @@ -193,18 +234,47 @@ def generate_image(self, payload: dict[str, Any]) -> GeneratedImage: if scheduler: sample_params["scheduler"] = str(scheduler) + sigma_preset = self.cfg.get("image_sigma_schedule") + effective_sigmas = resolve_image_sigma_schedule( + str(sigma_preset) if sigma_preset else None, + steps=steps, + guidance_scale=guidance, + sampling_method=sample_method, + scheduler=str(scheduler) if scheduler is not None else None, + ) + if effective_sigmas is not None: + sample_params["custom_sigmas"] = list(effective_sigmas) + + # The same async native image job path handles text-only generation + # and Qwen reference-image editing. Input pixels are not logged or + # persisted by Korgis; only output bytes and bounded metadata return. + reference_images = payload.get("ref_images") + if reference_images is not None: + if not self.cfg.get("image_editing_enabled"): + raise ValueError("reference editing is disabled for this runtime") + if not isinstance(reference_images, list) or len(reference_images) != 1: + raise ValueError("first editing release supports one reference image") + if not isinstance(reference_images[0], str) or not reference_images[0].startswith( + "data:image/png;base64," + ): + raise ValueError("editing reference must be a validated PNG data URL") + + native_payload: dict[str, Any] = { + "prompt": prompt, + "width": width, + "height": height, + "seed": seed, + "batch_count": 1, + "sample_params": sample_params, + "output_format": output_format, + } + if reference_images is not None: + native_payload["ref_images"] = reference_images + submission = self._json_request( "POST", "/sdcpp/v1/img_gen", - payload={ - "prompt": prompt, - "width": width, - "height": height, - "seed": seed, - "batch_count": 1, - "sample_params": sample_params, - "output_format": output_format, - }, + payload=native_payload, ) job_id = str(submission.get("id") or "").strip() poll_url = str( @@ -267,8 +337,14 @@ def generate_image(self, payload: dict[str, Any]) -> GeneratedImage: "vae_tiling": bool(self.cfg.get("image_vae_tiling", False)), "vae_tile_size": self.cfg.get("image_vae_tile_size"), }, + "image_editing": reference_images is not None, "sampling_method": sample_method, "scheduler": scheduler, + "sigma_schedule": str(sigma_preset) if sigma_preset else None, + "custom_sigmas": list(effective_sigmas) if effective_sigmas else None, + "sigma_schedule_sha256": ( + image_sigma_digest(effective_sigmas) if effective_sigmas else None + ), "num_inference_steps": steps, "guidance_scale": guidance, "generation_time_seconds": generation_seconds, diff --git a/tests/test_disk_backed_image_admission.py b/tests/test_disk_backed_image_admission.py new file mode 100644 index 00000000..b6c51b52 --- /dev/null +++ b/tests/test_disk_backed_image_admission.py @@ -0,0 +1,150 @@ +"""Regression tests for bounded disk-backed image admission. + +The stored swap amount is observation only. No host RAM allowance is +derived from swap usage, and the ordinary model policy is unchanged. +""" +from __future__ import annotations + +from dataclasses import dataclass + +import pytest + +from local_llm_server.resource_manager import ( + AdmissionDecision, HostAdmissionProfile, ResourceManager, ReservationKind, +) +from local_llm_server.resources import ( + ResourceBudget, ResourceValue, ResourceValueSource, SystemResourceSnapshot, +) +from local_llm_server.runtime import ModelRuntimeManager + +GIB = 1024**3 + + +@dataclass +class Host: + available: int = 14 * GIB + total: int = 32 * GIB + swap: int = 14 * GIB + + def snapshot(self) -> SystemResourceSnapshot: + measured = ResourceValueSource.MEASURED + return SystemResourceSnapshot( + captured_at_monotonic=1.0, + platform="darwin", + total_memory_bytes=ResourceValue(self.total, measured, "bytes"), + available_memory_bytes=ResourceValue(self.available, measured, "bytes"), + swap_used_bytes=ResourceValue(self.swap, measured, "bytes"), + ) + + +def manager(host: Host) -> ResourceManager: + return ResourceManager(ResourceBudget(limit_bytes=None), host_observer=host) + + +def test_opt_in_disk_backed_admits_estimated_8g_when_normal_memory() -> None: + host = Host() + standard = manager(host).reserve("std", 8 * GIB) + assert standard.decision is AdmissionDecision.REJECT + guarded = manager(host) + admitted = guarded.reserve( + "turbo", 8 * GIB, + admission_profile=HostAdmissionProfile.DISK_BACKED_IMAGE, + ) + assert admitted.decision is AdmissionDecision.ADMIT + assert guarded.snapshot()[0].admission_profile is HostAdmissionProfile.DISK_BACKED_IMAGE + host.available = 7 * GIB + assert guarded.commit("turbo").decision is AdmissionDecision.ADMIT + assert guarded.release("turbo") + assert guarded.snapshot() == () + + +def test_swap_amount_never_adds_to_physical_available() -> None: + host = Host(available=4 * GIB, swap=100 * GIB) + result = manager(host).reserve( + "turbo", 8 * GIB, + admission_profile=HostAdmissionProfile.DISK_BACKED_IMAGE, + ) + assert result.decision is AdmissionDecision.REJECT + assert host.swap > host.available + + +@pytest.mark.parametrize("available", [0, 2 * GIB, 6 * GIB]) +def test_disk_backed_rejects_pressure_or_insufficient_headroom(available: int) -> None: + host = Host(available=available) + result = manager(host).reserve( + "turbo", 8 * GIB, + admission_profile=HostAdmissionProfile.DISK_BACKED_IMAGE, + ) + assert result.decision is AdmissionDecision.REJECT + + +def test_disk_backed_commit_still_rejects_post_load_pressure() -> None: + host = Host() + resources = manager(host) + assert resources.reserve( + "turbo", 8 * GIB, + admission_profile=HostAdmissionProfile.DISK_BACKED_IMAGE, + ).decision is AdmissionDecision.ADMIT + host.available = 5 * GIB + failed = resources.commit("turbo") + assert failed.decision is AdmissionDecision.REJECT + resources.rollback("turbo") + assert resources.snapshot() == () + + +def test_nonresident_reservations_cannot_request_disk_backed() -> None: + with pytest.raises(ValueError, match="resident models"): + manager(Host()).reserve( + "request", 100, + kind=ReservationKind.TRANSIENT, + admission_profile=HostAdmissionProfile.DISK_BACKED_IMAGE, + ) + + +@pytest.mark.parametrize( + "override", + [ + {"backend": "llama_server"}, + {"sd_server_params_backend": "diffusion=ram,te=cpu,vae=cpu"}, + {"image_offload_to_cpu": False}, + {"resource_estimate_bytes": None}, + {"resource_admission_profile": "not_a_profile"}, + ], +) +def test_runtime_rejects_invalid_profile_before_engine(monkeypatch, override: dict) -> None: + cfg = { + "model": "turbo", + "model_id": "turbo", + "backend": "stable_diffusion_cpp_image", + "sd_server_params_backend": "diffusion=disk,te=cpu,vae=cpu", + "image_offload_to_cpu": True, + "resource_estimate_bytes": 8 * GIB, + "resource_admission_profile": "disk_backed_image", + } + cfg.update(override) + loaded = [] + monkeypatch.setattr( + "local_llm_server.config.build_config", + lambda **_kwargs: dict(cfg), + ) + monkeypatch.setattr( + "local_llm_server.engine.load_llm", + lambda _cfg: loaded.append(_cfg), + ) + runtime = ModelRuntimeManager(resource_manager=manager(Host())) + with pytest.raises(ValueError, match="admission|disk_backed"): + runtime.load("turbo") + assert loaded == [] + +def test_turbo_registry_uses_bounded_profile_not_a_global_guard_bypass() -> None: + from local_llm_server.config import build_config + + turbo = build_config("qwen-image-2.1-turbo-gguf-q4km") + assert turbo["resource_admission_profile"] == "disk_backed_image" + assert turbo["resource_estimate_bytes"] == 8 * GIB + assert turbo["sd_server_params_backend"].startswith("diffusion=disk") + assert turbo["image_offload_to_cpu"] is True + + standard = build_config("qwen-image-2.1-gguf-q4km") + assert standard["resource_admission_profile"] == "standard" + assert standard["resource_estimate_bytes"] is None diff --git a/tests/test_flux3_klein_local_bundle.py b/tests/test_flux3_klein_local_bundle.py new file mode 100644 index 00000000..b7698b6e --- /dev/null +++ b/tests/test_flux3_klein_local_bundle.py @@ -0,0 +1,129 @@ +"""FLUX.3 Klein integration: local-only transformer, separate VAE/text encoder.""" +from __future__ import annotations + +from pathlib import Path + +import pytest + +from local_llm_server.config import build_config +from local_llm_server.model_sources import resolve_bundle_artifacts +from local_llm_server.stable_diffusion_cpp_compat import build_sd_server_command +from local_llm_server.stable_diffusion_cpp_image_engine import StableDiffusionCppImageEngine + +FLUX = "flux-3-image-klein-gguf-q5km" +GIB = 1024**3 + + +def _local_gguf(home: Path, *, valid: bool = True) -> Path: + gguf = ( + home / ".lmstudio" / "models" / "unsloth" + / "flux-3-image-klein-GGUF" + / "flux-3-image-klein-Q5_K_M.gguf" + ) + gguf.parent.mkdir(parents=True) + with gguf.open("wb") as handle: + handle.write(b"GGUF" if valid else b"NOPE") + handle.truncate(3_550_000_000) + return gguf + + +def test_flux3_registry_reuses_local_gguf_without_copy_or_download( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(Path, "home", lambda: tmp_path) + local = _local_gguf(tmp_path) + cfg = build_config(FLUX, no_download=True) + assert cfg["backend"] == "stable_diffusion_cpp_image" + assert cfg["model_source"] == "lmstudio" + assert Path(cfg["model_artifacts"]["diffusion_model"]) == local.resolve() + assert cfg["model_artifacts"]["text_encoder"].endswith( + "text_encoder/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + ) + assert cfg["model_artifacts"]["vae"].endswith("vae/ae.safetensors") + assert cfg["model_downloaded"] is False # two auxiliary files are missing + assert cfg["image_num_inference_steps"] == 16 + assert cfg["image_max_inference_steps"] == 16 + assert cfg["image_guidance_scale"] == 1.0 + assert cfg["image_sigma_schedule"] is None # never reuse Qwen Turbo sigmas + assert cfg["resource_admission_profile"] == "disk_backed_image" + assert cfg["resource_estimate_bytes"] == 9 * GIB + assert cfg["license"] == "flux-kommunity-license" + + +def test_flux3_missing_lmstudio_transformer_is_not_silently_downloaded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(Path, "home", lambda: tmp_path) + cfg = build_config(FLUX, no_download=False) + assert cfg["model_source"] == "lmstudio" + engine = object.__new__(StableDiffusionCppImageEngine) + engine.cfg = cfg + engine.artifacts = { + name: Path(value) + for name, value in cfg["model_artifacts"].items() + } + with pytest.raises(FileNotFoundError, match="LM Studio transformer missing"): + engine._ensure_artifacts(cfg["artifact_specs"]) + + +def test_flux3_refuses_truncated_or_wrong_gguf( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(Path, "home", lambda: tmp_path) + local = _local_gguf(tmp_path, valid=False) + cfg = build_config(FLUX, no_download=True) + engine = object.__new__(StableDiffusionCppImageEngine) + engine.cfg = cfg + engine.artifacts = { + name: Path(value) + for name, value in cfg["model_artifacts"].items() + } + with pytest.raises(ValueError, match="GGUF header"): + engine._ensure_artifacts(cfg["artifact_specs"]) + with local.open("wb") as handle: + handle.write(b"GGUF") + with pytest.raises(ValueError, match="incomplete"): + engine._ensure_artifacts(cfg["artifact_specs"]) + + +def test_flux3_native_command_has_three_matching_components_and_no_qwen_projector( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(Path, "home", lambda: tmp_path) + _local_gguf(tmp_path) + cfg = build_config(FLUX, no_download=True) + command = build_sd_server_command( + binary=tmp_path / "sd-server", + artifacts=cfg["model_artifacts"], + host="127.0.0.1", port=8093, cfg=cfg, + ) + assert command[command.index("--diffusion-model") + 1].endswith( + "flux-3-image-klein-Q5_K_M.gguf" + ) + assert command[command.index("--llm") + 1].endswith( + "Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + ) + assert command[command.index("--vae") + 1].endswith("ae.safetensors") + assert "--llm_vision" not in command + assert "--disable-prefetch" in command + assert "diffusion=disk,te=cpu,vae=cpu" in command + + +def test_bundle_lmstudio_path_cannot_escape_user_model_root( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(Path, "home", lambda: tmp_path) + spec = { + "artifacts": { + "diffusion_model": { + "local_path": "diffusion/model.gguf", + "lmstudio_relative_path": "../../outside.gguf", + "lmstudio_required": True, + }, + }, + } + with pytest.raises(ValueError, match="must be relative"): + resolve_bundle_artifacts("unsafe", spec, tmp_path / "managed") + spec["artifacts"]["diffusion_model"]["lmstudio_relative_path"] = "/etc/passwd" + with pytest.raises(ValueError, match="must be relative"): + resolve_bundle_artifacts("unsafe", spec, tmp_path / "managed") diff --git a/tests/test_image_editing_api.py b/tests/test_image_editing_api.py new file mode 100644 index 00000000..d7555f0f --- /dev/null +++ b/tests/test_image_editing_api.py @@ -0,0 +1,270 @@ +"""Security, route compatibility and opt-in integration for one-image edits.""" +from __future__ import annotations + +import base64 +import hashlib +import struct +import zlib + +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from local_llm_server.config import build_config +from local_llm_server.image_editing_api import validate_png_reference +from local_llm_server.image_generation_api import install_image_generation_api +from local_llm_server.image_generation_common import GeneratedImage +from local_llm_server.runtime import ModelRuntimeManager +from local_llm_server.stable_diffusion_cpp_compat import build_sd_server_command + +MODEL = "qwen-image-2.1-turbo-gguf-q4km" + + +def make_png(width: int = 512, height: int = 512) -> bytes: + def chunk(name: bytes, payload: bytes) -> bytes: + return ( + struct.pack(">I", len(payload)) + name + payload + + struct.pack(">I", zlib.crc32(name + payload) & 0xFFFFFFFF) + ) + ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IEND", b"") + + +class FakeImageEngine: + backend = "stable_diffusion_cpp_image" + + def __init__(self) -> None: + self.calls = [] + + def generate_image(self, payload): + self.calls.append(payload) + return GeneratedImage( + data=make_png(512, 512), + mime_type="image/png", + width=512, + height=512, + seed=payload.get("seed"), + metadata={"native_job": "fake"}, + ) + + def close(self): + pass + + +def app_with_engine(*, enabled: bool = True): + cfg = build_config(MODEL, image_editing_enabled=enabled) + manager = ModelRuntimeManager(default_model=MODEL) + engine = FakeImageEngine() + manager.add(cfg, engine) + app = FastAPI() + app.state.runtime_manager = manager + install_image_generation_api(app) + return TestClient(app), engine + + +def test_editing_off_does_not_claim_image_input_or_load_projector(): + cfg = build_config(MODEL) + assert cfg["image_editing_enabled"] is False + assert cfg["input_modalities"] == ["text"] + assert cfg["resource_estimate_bytes"] == 8 * 1024**3 + assert cfg["image_editing_projector_path"].endswith("text_encoder/mmproj-BF16.gguf") + + +def test_opt_in_uses_pinned_projector_and_extra_2g_budget(): + cfg = build_config(MODEL, image_editing_enabled=True) + assert cfg["input_modalities"] == ["image", "text"] + assert cfg["image_editing_extra_resident_bytes"] == 2 * 1024**3 + assert cfg["resource_estimate_bytes"] == 10 * 1024**3 + spec = cfg["image_editing_projector_spec"] + assert spec["revision"] == "174e4a339d8aceef41c87fda9f732c042d49e50b" + assert spec["sha256"] == "6516bb64bae1503a0fcd7ec9fa39655f8c481580be0a0a066397941d9761c9f4" + + +def test_projector_required_for_edit_opt_in_but_not_for_text_to_image(tmp_path): + binary = tmp_path / "sd-server" + artifacts = { + "diffusion_model": tmp_path / "diffusion.gguf", + "text_encoder": tmp_path / "encoder.gguf", + "vae": tmp_path / "vae.safetensors", + } + base = {"image_editing_enabled": False} + command = build_sd_server_command( + binary=binary, artifacts=artifacts, host="127.0.0.1", port=8093, cfg=base, + ) + assert "--llm_vision" not in command + projector = tmp_path / "mmproj.gguf" + config = {**base, "image_editing_enabled": True, + "image_editing_projector_path": str(projector)} + import pytest + with pytest.raises(FileNotFoundError, match="vision projector"): + build_sd_server_command( + binary=binary, artifacts=artifacts, host="127.0.0.1", port=8093, + cfg=config, + ) + projector.write_bytes(b"test vision projector fixture") + edited = build_sd_server_command( + binary=binary, artifacts=artifacts, host="127.0.0.1", port=8093, + cfg=config, + ) + assert edited[edited.index("--llm_vision") + 1] == str(projector) + + +def test_one_png_edit_reuses_existing_engine_and_returns_only_generated_image(): + client, engine = app_with_engine() + source = make_png() + response = client.post( + "/v1/images/edits", + data={"model": MODEL, "prompt": "Change the wall color", "seed": "42", + "num_inference_steps": "8"}, + files={"image": ("room.png", source, "image/png")}, + ) + assert response.status_code == 200, response.text + result = response.json() + assert base64.b64decode(result["data"][0]["b64_json"]) == source + assert result["korgis"]["source_sha256"] == hashlib.sha256(source).hexdigest() + assert result["korgis"]["source_width"] == 512 + assert len(engine.calls) == 1 + payload = engine.calls[0] + assert payload["seed"] == 42 + assert payload["num_inference_steps"] == 8 + assert payload["width"] == 512 and payload["height"] == 512 + assert payload["ref_images"] == [ + "data:image/png;base64," + base64.b64encode(source).decode("ascii") + ] + assert "ref_images" not in str(result) + + +def test_disabled_edit_returns_typed_failure_before_backend(): + client, engine = app_with_engine(enabled=False) + response = client.post( + "/v1/images/edits", data={"prompt": "Edit"}, + files={"image": ("a.png", make_png(), "image/png")}, + ) + assert response.status_code == 400 + assert response.json()["detail"]["code"] == "unsupported_task" + assert engine.calls == [] + + +def test_untrusted_input_checks_before_inference(): + client, engine = app_with_engine() + cases = [ + (make_png(4096, 512), "image/png", 400), + (make_png(512, 512) + b"x" * (8 * 1024 * 1024), "image/png", 400), + (b"not really png", "image/png", 400), + (make_png(), "image/jpeg", 415), + ] + for data, mime, code in cases: + response = client.post( + "/v1/images/edits", data={"prompt": "Modify"}, + files={"image": ("source.png", data, mime)}, + ) + assert response.status_code == code, response.text + assert engine.calls == [] + + +def test_size_step_and_n_limits_match_generation_policy(): + client, engine = app_with_engine() + for params in ( + {"size": "4000x4000"}, + {"num_inference_steps": "9"}, + {"n": "2"}, + ): + response = client.post( + "/v1/images/edits", data={"prompt": "Edit", **params}, + files={"image": ("a.png", make_png(), "image/png")}, + ) + assert response.status_code == 400, response.text + assert engine.calls == [] + + +def test_png_header_validation_does_not_decode_untrusted_pixels(): + import pytest + data = make_png(1024, 512) + assert validate_png_reference(data) == (1024, 512) + with pytest.raises(ValueError, match="Corrupt PNG"): + validate_png_reference(data[:29] + b"AAAA" + data[33:]) + with pytest.raises(ValueError, match="pixel budget"): + validate_png_reference(make_png(2048, 2048), max_pixels=512 * 512) + +def test_editing_output_over_1mp_is_rejected_before_native_submission(): + client, engine = app_with_engine() + response = client.post( + "/v1/images/edits", + data={"prompt": "Edit", "size": "2048x1024"}, + files={"image": ("a.png", make_png(), "image/png")}, + ) + assert response.status_code == 400 + assert engine.calls == [] + + +def test_unaligned_output_is_rejected_before_native_submission(): + client, engine = app_with_engine() + response = client.post( + "/v1/images/edits", + data={"prompt": "Edit", "size": "1000x1000"}, + files={"image": ("a.png", make_png(), "image/png")}, + ) + assert response.status_code == 400 + assert engine.calls == [] + + +def test_long_edit_does_not_block_fastapi_health_requests(): + """A waiting native image job must not freeze the ASGI event loop.""" + from threading import Event, Thread + + from fastapi import FastAPI + from fastapi.testclient import TestClient + + cfg = build_config(MODEL, image_editing_enabled=True) + manager = ModelRuntimeManager(default_model=MODEL) + engine = FakeImageEngine() + started = Event() + release = Event() + probe_done = Event() + original_generate = engine.generate_image + + def held_generate(payload): + started.set() + if not release.wait(timeout=8): + raise TimeoutError("test image engine did not get released") + return original_generate(payload) + + engine.generate_image = held_generate + manager.add(cfg, engine) + app = FastAPI() + app.state.runtime_manager = manager + install_image_generation_api(app) + + @app.get("/probe") + async def probe(): + return {"responsive": True} + + result = {} + with TestClient(app) as client: + def do_edit(): + result["edit"] = client.post( + "/v1/images/edits", + data={"prompt": "Change background"}, + files={"image": ("source.png", make_png(), "image/png")}, + ) + + def do_probe(): + result["probe"] = client.get("/probe") + probe_done.set() + + edit_thread = Thread(target=do_edit, daemon=True) + ping_thread = Thread(target=do_probe, daemon=True) + edit_thread.start() + try: + assert started.wait(timeout=4), "native edit was not submitted" + ping_thread.start() + # With synchronous generate() on the event loop, this would time + # out even though the native engine has its own worker/process. + assert probe_done.wait(timeout=2), "event loop blocked during native image edit" + assert result["probe"].json() == {"responsive": True} + finally: + release.set() + edit_thread.join(timeout=8) + if ping_thread.ident is not None: + ping_thread.join(timeout=4) + assert not edit_thread.is_alive() + assert result["edit"].status_code == 200 diff --git a/tests/test_image_editing_memory_admission.py b/tests/test_image_editing_memory_admission.py new file mode 100644 index 00000000..0efb6c08 --- /dev/null +++ b/tests/test_image_editing_memory_admission.py @@ -0,0 +1,75 @@ +"""Editing must reserve more host memory than the proven text-to-image path.""" +from __future__ import annotations + +from dataclasses import dataclass + +import pytest + +from local_llm_server.config import build_config +from local_llm_server.resource_manager import ResourceManager +from local_llm_server.resources import ( + ResourceBudget, ResourceValue, ResourceValueSource, SystemResourceSnapshot, +) +from local_llm_server.runtime import ModelRuntimeManager, ResourceAdmissionError + +GIB = 1024**3 +TURBO = "qwen-image-2.1-turbo-gguf-q4km" + + +@dataclass +class Mac: + available: int + swap: int = 14 * GIB + + def snapshot(self) -> SystemResourceSnapshot: + measured = ResourceValueSource.MEASURED + return SystemResourceSnapshot( + captured_at_monotonic=1, + platform="darwin", + total_memory_bytes=ResourceValue(32 * GIB, measured, "bytes"), + available_memory_bytes=ResourceValue(self.available, measured, "bytes"), + swap_used_bytes=ResourceValue(self.swap, measured, "bytes"), + ) + + +def runtime(host: Mac) -> ModelRuntimeManager: + return ModelRuntimeManager(resource_manager=ResourceManager( + ResourceBudget(limit_bytes=None), host_observer=host, + )) + + +def test_editing_rejects_14g_headroom_while_text_to_image_still_admits(): + mac = Mac(available=14 * GIB) + manager = runtime(mac) + txt = build_config(TURBO) + editing = build_config(TURBO, image_editing_enabled=True) + assert txt["resource_estimate_bytes"] == 8 * GIB + assert editing["resource_estimate_bytes"] == 10 * GIB + + resident = manager._reserve_runtime_load(TURBO, txt) + assert resident is not None + manager.resource_manager.release(resident) + + with pytest.raises(ResourceAdmissionError, match="host available memory"): + manager._reserve_runtime_load(TURBO, editing) + assert manager.resource_manager.snapshot() == () + + +def test_opt_in_editing_can_admit_safely_with_16g_reclaimable_and_releases(): + mac = Mac(available=16 * GIB, swap=100 * GIB) + manager = runtime(mac) + cfg = build_config(TURBO, image_editing_enabled=True) + resident = manager._reserve_runtime_load(TURBO, cfg) + assert resident is not None + assert cfg["resource_admission"]["estimate_bytes"] == 10 * GIB + assert cfg["resource_admission"]["profile"] == "disk_backed_image" + assert manager.resource_manager.snapshot()[0].accounted_bytes == 10 * GIB + manager.resource_manager.release(resident) + assert manager.resource_manager.snapshot() == () + + +def test_swap_cannot_rescue_editing_when_actual_available_memory_is_low(): + manager = runtime(Mac(available=4 * GIB, swap=200 * GIB)) + with pytest.raises(ResourceAdmissionError): + manager._reserve_runtime_load(TURBO, build_config(TURBO, image_editing_enabled=True)) + assert manager.resource_manager.snapshot() == () diff --git a/tests/test_image_editing_native_job.py b/tests/test_image_editing_native_job.py new file mode 100644 index 00000000..66c6db19 --- /dev/null +++ b/tests/test_image_editing_native_job.py @@ -0,0 +1,156 @@ +"""One input reference must use the existing pinned async native job path.""" +from __future__ import annotations + +import base64 +import hashlib +import json +from pathlib import Path +from urllib.parse import urlparse + +import pytest + +from local_llm_server.stable_diffusion_cpp_image_engine import StableDiffusionCppImageEngine + + +class Response: + def __init__(self, obj): + self.obj = obj + + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def read(self): + return json.dumps(self.obj).encode("utf-8") + + +class FakeProcess: + instances = [] + + def __init__(self, command, *, name, logger): + self.command = command + self.started = False + self.closed = False + self.__class__.instances.append(self) + + def start(self): + self.started = True + + def wait_ready(self, readiness, *, timeout): + assert readiness() + + def close(self): + self.closed = True + + +def fixture_config(tmp_path: Path, *, projector_present: bool = True): + artifacts = {} + for name, basename in ( + ("diffusion_model", "diff.gguf"), + ("text_encoder", "text.gguf"), + ("vae", "vae.safetensors"), + ): + p = tmp_path / name / basename + p.parent.mkdir(parents=True) + p.write_bytes(b"weights") + artifacts[name] = str(p) + projector = tmp_path / "text_encoder" / "mmproj-BF16.gguf" + content = b"vision-test-weights" + if projector_present: + projector.write_bytes(content) + binary = tmp_path / "sd-server" + binary.write_bytes(b"#!/bin/sh\n") + binary.chmod(0o755) + return { + "model_artifacts": artifacts, + "artifact_specs": { + role: {"url": "https://example.invalid/" + role} + for role in artifacts + }, + "image_editing_enabled": True, + "image_editing_projector_path": str(projector), + "image_editing_projector_spec": { + "repo": "unsloth/Qwen3-VL-8B-Instruct-GGUF", + "revision": "174e4a339d8aceef41c87fda9f732c042d49e50b", + "filename": "mmproj-BF16.gguf", + "sha256": hashlib.sha256(content).hexdigest(), + }, + "sd_server_bin": str(binary), + "startup_timeout": 600, + "no_download": True, + "image_num_inference_steps": 8, + "image_guidance_scale": 1.0, + "image_sampling_method": "euler", + "image_sigma_schedule": "qwen-image-2.1-turbo-v1", + } + + +def test_pinned_async_native_edit_receives_only_one_reference(tmp_path): + cfg = fixture_config(tmp_path) + requests = [] + image_data = b"image-placeholder" + image_b64 = base64.b64encode(image_data).decode("ascii") + + def urlopen(request, *, timeout): + path = urlparse(request.full_url).path + body = json.loads(request.data) if request.data else None + requests.append((path, body)) + if path == "/sdcpp/v1/capabilities": + return Response({"supported_modes": ["img_gen"]}) + if path == "/sdcpp/v1/img_gen": + return Response({"id": "edit-1", "poll_url": "/sdcpp/v1/jobs/edit-1"}) + if path == "/sdcpp/v1/jobs/edit-1": + return Response({ + "status": "completed", "started": 1, "completed": 3, + "result": {"images": [{"b64_json": image_b64}], "output_format": "png"}, + }) + raise AssertionError(path) + + engine = StableDiffusionCppImageEngine( + cfg, process_factory=FakeProcess, urlopen=urlopen, + ) + assert "--llm_vision" in engine.process.command + assert "vision_projector" in engine.artifact_provenance + source = "data:image/png;base64," + base64.b64encode(b"source").decode() + result = engine.generate_image({ + "prompt": "Change mug color", "width": 512, "height": 512, + "seed": 42, "num_inference_steps": 8, "ref_images": [source], + }) + assert result.data == image_data + assert result.metadata["image_editing"] is True + assert "source" not in json.dumps(result.metadata) + payload = next(body for path, body in requests if path == "/sdcpp/v1/img_gen") + assert payload["ref_images"] == [source] + assert len(payload["sample_params"]["custom_sigmas"]) == 9 + assert payload["sample_params"]["sample_steps"] == 8 + assert payload["sample_params"]["guidance"]["txt_cfg"] == 1.0 + engine.close() + + +def test_missing_projector_is_detected_before_native_process_starts(tmp_path): + cfg = fixture_config(tmp_path, projector_present=False) + FakeProcess.instances.clear() + with pytest.raises((FileNotFoundError, RuntimeError)): + StableDiffusionCppImageEngine(cfg, process_factory=FakeProcess) + assert FakeProcess.instances == [] + + +def test_reference_is_not_accepted_by_text_only_runtime(tmp_path): + cfg = fixture_config(tmp_path) + cfg["image_editing_enabled"] = False + cfg["image_editing_projector_spec"] = None + cfg["image_editing_projector_path"] = None + def urlopen(request, *, timeout): + if urlparse(request.full_url).path == "/sdcpp/v1/capabilities": + return Response({"supported_modes": ["img_gen"]}) + raise AssertionError("no native edit should be submitted") + engine = StableDiffusionCppImageEngine( + cfg, process_factory=FakeProcess, urlopen=urlopen, + ) + with pytest.raises(ValueError, match="disabled"): + engine.generate_image({ + "prompt": "Edit", "ref_images": ["data:image/png;base64,c291cmNl"] + }) + engine.close() diff --git a/tests/test_qwen_image_21_turbo_integration.py b/tests/test_qwen_image_21_turbo_integration.py new file mode 100644 index 00000000..8cfebedb --- /dev/null +++ b/tests/test_qwen_image_21_turbo_integration.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import pytest + +from local_llm_server.config import build_config +from local_llm_server.image_generation_request import ( + ImageGenerationRequest, + prepare_image_generation_request, +) + +TURBO = "qwen-image-2.1-turbo-gguf-q4km" + + +def test_turbo_resolves_pinned_backend_and_sampling_profile_without_download(): + cfg = build_config(TURBO) + assert cfg["model"] == TURBO + assert cfg["backend"] == "stable_diffusion_cpp_image" + assert cfg["model_id"] == "unsloth/Qwen-Image-2.1-Turbo-GGUF" + assert cfg["image_sigma_schedule"] == "qwen-image-2.1-turbo-v1" + assert cfg["image_num_inference_steps"] == 8 + assert cfg["image_guidance_scale"] == 1.0 + assert cfg["image_verify_existing_artifacts"] is True + assert cfg["image_offload_to_cpu"] is True + assert cfg["sd_server_params_backend"] == "diffusion=disk,te=cpu,vae=cpu" + assert set(cfg["model_artifacts"]) == { + "diffusion_model", "text_encoder", "vae", + } + + +def test_turbo_http_preflight_rejects_steps_above_runtime_cap(): + cfg = build_config(TURBO) + prepared = prepare_image_generation_request( + ImageGenerationRequest( + model=TURBO, + prompt="Small red cube", + size="1024x1024", + seed=42, + num_inference_steps=8, + ), + runtime_key=TURBO, + runtime_config=cfg, + ) + assert prepared.backend_payload["seed"] == 42 + assert prepared.backend_payload["width"] == 1024 + assert prepared.backend_payload["height"] == 1024 + with pytest.raises(ValueError, match="maximum 8"): + prepare_image_generation_request( + ImageGenerationRequest( + model=TURBO, + prompt="Small red cube", + num_inference_steps=9, + ), + runtime_key=TURBO, + runtime_config=cfg, + ) + + +def test_standard_qwen_image_profile_has_no_turbo_sigma_schedule(): + cfg = build_config("qwen-image-2.1-gguf-q4km") + assert cfg["image_sigma_schedule"] is None + assert cfg["image_num_inference_steps"] == 20 diff --git a/tests/test_qwen_image_21_turbo_registry.py b/tests/test_qwen_image_21_turbo_registry.py new file mode 100644 index 00000000..ea8322cd --- /dev/null +++ b/tests/test_qwen_image_21_turbo_registry.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from pathlib import Path + +from local_llm_server.model_sources import artifact_download_url, resolve_bundle_artifacts +from local_llm_server.registry import load_registry, validate_registry + +TURBO = "qwen-image-2.1-turbo-gguf-q4km" +# Published by Hugging Face file pages (LFS/Xet SHA256, not Xet hash). +UNSLOTH_ARTIFACTS = { + "diffusion_model": { + "repo": "unsloth/Qwen-Image-2.1-Turbo-GGUF", + "revision": "5d1f9f759ea877ae556cda88dbec958b62ad3809", + "filename": "qwen-image-2.1-turbo-Q4_K_M.gguf", + "local_path": "diffusion/qwen-image-2.1-turbo-Q4_K_M.gguf", + "sha256": "8940e8b522af886e0c0f5afddf720e82dd223cb9a43580b5f61c4d740452ac20", + }, + "text_encoder": { + "repo": "unsloth/Qwen3-VL-8B-Instruct-GGUF", + "revision": "174e4a339d8aceef41c87fda9f732c042d49e50b", + "filename": "Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf", + "local_path": "text_encoder/Qwen3-VL-8B-Instruct-UD-Q4_K_XL.gguf", + "sha256": "e3d1a6e87c5cb31e054f2c3bc0dd82ffde052f613de5eef3665b7bd33c9b703e", + }, + "vae": { + "repo": "unsloth/Qwen-Image-2.1-FP8", + "revision": "db2bfe9028a3c1f486833be12f3a928e5f4a1286", + "filename": "vae/qwen_image_2.1_vae_bf16.safetensors", + "local_path": "vae/qwen_image_2.1_vae_bf16.safetensors", + "sha256": "71879ffd5321e6d10c3c87513e2b474b1252efa7f3dec2969214a9bf06a6dd5c", + }, +} + + +def test_turbo_is_distinct_three_source_registry_profile() -> None: + registry = load_registry() + validate_registry(registry) + entry = registry["models"][TURBO] + standard = registry["models"]["qwen-image-2.1-gguf-q4km"] + assert entry["model_id"] == "unsloth/Qwen-Image-2.1-Turbo-GGUF" + assert entry["model_id"] != standard["model_id"] + assert entry["backend"] == "stable_diffusion_cpp_image" + assert entry["license"] == "qwen-research" + assert entry["params"]["image_num_inference_steps"] == 8 + assert entry["params"]["image_sigma_schedule"] == "qwen-image-2.1-turbo-v1" + assert entry["params"]["image_verify_existing_artifacts"] is True + assert set(entry["artifacts"]) == set(UNSLOTH_ARTIFACTS) + + for role, expected in UNSLOTH_ARTIFACTS.items(): + artifact = entry["artifacts"][role] + assert artifact["repo"] == expected["repo"] + assert artifact["revision"] == expected["revision"] + assert artifact["filename"] == expected["filename"] + assert artifact["local_path"] == expected["local_path"] + assert artifact["sha256"] == expected["sha256"] + assert artifact_download_url(artifact) == ( + f"https://huggingface.co/{expected['repo']}/resolve/" + f"{expected['revision']}/" + f"{expected['filename']}?download=true" + ) + + +def test_turbo_bundle_paths_match_users_three_directories( + tmp_path: Path, +) -> None: + registry = load_registry() + turbo = resolve_bundle_artifacts( + TURBO, registry["models"][TURBO], tmp_path + ) + standard = resolve_bundle_artifacts( + "qwen-image-2.1-gguf-q4km", + registry["models"]["qwen-image-2.1-gguf-q4km"], + tmp_path, + ) + assert set(turbo) == set(UNSLOTH_ARTIFACTS) + assert all(path.is_relative_to(tmp_path / TURBO) for path in turbo.values()) + assert turbo["text_encoder"].suffix == ".gguf" + assert not set(turbo.values()) & set(standard.values()) + + +def test_local_bundle_is_detected_without_download(tmp_path: Path) -> None: + from local_llm_server.model_sources import ( + is_complete_sdcpp_image_bundle, + ) + + registry = load_registry() + paths = resolve_bundle_artifacts(TURBO, registry["models"][TURBO], tmp_path) + assert not is_complete_sdcpp_image_bundle(paths) + for path in paths.values(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"tiny fixture") + assert is_complete_sdcpp_image_bundle(paths) diff --git a/tests/test_qwen_image_21_turbo_sampling.py b/tests/test_qwen_image_21_turbo_sampling.py new file mode 100644 index 00000000..28a937cb --- /dev/null +++ b/tests/test_qwen_image_21_turbo_sampling.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +import base64 +import hashlib +import json +from pathlib import Path +from urllib.parse import urlparse + +import pytest + +from local_llm_server.image_sampling_presets import ( + QWEN_IMAGE_21_TURBO_V1, + image_sigma_digest, + resolve_image_sigma_schedule, +) +from local_llm_server.stable_diffusion_cpp_image_engine import ( + StableDiffusionCppImageEngine, +) + + +def _resolve(**overrides): + params = { + "steps": 8, + "guidance_scale": 1.0, + "sampling_method": "euler", + "scheduler": None, + } + params.update(overrides) + return resolve_image_sigma_schedule("qwen-image-2.1-turbo-v1", **params) + + +def test_turbo_preset_has_exact_eight_steps_and_stable_digest(): + assert _resolve() == QWEN_IMAGE_21_TURBO_V1 + assert len(QWEN_IMAGE_21_TURBO_V1) == 9 + assert QWEN_IMAGE_21_TURBO_V1[-1] == 0.0 + assert len(image_sigma_digest(QWEN_IMAGE_21_TURBO_V1)) == 64 + assert resolve_image_sigma_schedule( + None, steps=20, guidance_scale=6.0, + sampling_method="euler", scheduler="discrete" + ) is None + + +@pytest.mark.parametrize( + "overrides", + [ + {"steps": 7}, + {"steps": 9}, + {"guidance_scale": 0.0}, + {"guidance_scale": 6.0}, + {"sampling_method": "euler_a"}, + {"scheduler": "discrete"}, + ], +) +def test_turbo_rejects_noncanonical_generation(overrides): + with pytest.raises(ValueError, match="requires|override"): + _resolve(**overrides) + + +def test_turbo_rejects_unknown_preset(): + with pytest.raises(ValueError, match="Unknown image sigma schedule"): + resolve_image_sigma_schedule( + "unexpected", steps=8, guidance_scale=1, + sampling_method="euler", scheduler=None, + ) + + +class FakeResponse: + def __init__(self, body): + self.body = body + + def __enter__(self): + return self + + def __exit__(self, *_args): + return False + + def read(self): + return json.dumps(self.body).encode("utf-8") + + +class FakeProcess: + def __init__(self, command, *, name, logger): + self.command = command + self.closed = False + + def start(self): + pass + + def wait_ready(self, check_ready, *, timeout): + assert check_ready() + + def close(self): + self.closed = True + + +def _engine(tmp_path, calls, *, verify=False, tamper_hash=False): + paths = { + "diffusion_model": tmp_path / "diffusion" / "diffusion.gguf", + "text_encoder": tmp_path / "encoder" / "encoder.safetensors", + "vae": tmp_path / "vae" / "vae.safetensors", + } + for path in paths.values(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"tiny-test-weight") + sha = hashlib.sha256(b"tiny-test-weight").hexdigest() + specs = { + name: { + "url": "https://example.invalid/no-download", + "sha256": "0" * 64 if tamper_hash else sha, + } + for name in paths + } + binary = tmp_path / "sd-server" + binary.write_text("#!/bin/sh\nprintf 'stable-diffusion.cpp version: 1.2.3'\n") + binary.chmod(0o755) + + def urlopen(request, *, timeout): + path = urlparse(request.full_url).path + body = json.loads(request.data) if request.data is not None else {} + calls.append((request.method, path, body)) + if path == "/sdcpp/v1/capabilities": + return FakeResponse({"supported_modes": ["img_gen"]}) + if path == "/sdcpp/v1/img_gen": + return FakeResponse({ + "id": "t1", "status": "queued", + "poll_url": "/sdcpp/v1/jobs/t1", + }) + if path == "/sdcpp/v1/jobs/t1": + return FakeResponse({ + "id": "t1", "status": "completed", + "result": { + "output_format": "png", + "images": [{"b64_json": base64.b64encode(b"png").decode()}], + }, + }) + raise AssertionError(path) + + cfg = { + "model_artifacts": {key: str(p) for key, p in paths.items()}, + "artifact_specs": specs, + "sd_server_bin": str(binary), + "no_download": True, + "startup_timeout": 60, + "image_sigma_schedule": "qwen-image-2.1-turbo-v1", + "image_verify_existing_artifacts": verify, + "image_num_inference_steps": 8, + "image_guidance_scale": 1.0, + "image_sampling_method": "euler", + } + return StableDiffusionCppImageEngine( + cfg, process_factory=FakeProcess, + urlopen=urlopen, sleeper=lambda _: None, + ) + + +def test_sd_server_receives_exact_turbo_sigmas_and_reports_effective_params(tmp_path): + calls = [] + engine = _engine(tmp_path, calls, verify=True) + try: + result = engine.generate_image({ + "prompt": "A red cube on white", + "width": 1024, + "height": 1024, + "seed": 42, + }) + native = next(body for _, path, body in calls if path == "/sdcpp/v1/img_gen") + assert native["sample_params"] == { + "sample_method": "euler", + "sample_steps": 8, + "guidance": {"txt_cfg": 1.0}, + "custom_sigmas": list(QWEN_IMAGE_21_TURBO_V1), + } + assert result.data == b"png" + assert result.seed == 42 + assert result.metadata["custom_sigmas"] == list(QWEN_IMAGE_21_TURBO_V1) + assert result.metadata["sigma_schedule"] == "qwen-image-2.1-turbo-v1" + assert result.metadata["sigma_schedule_sha256"] == image_sigma_digest( + QWEN_IMAGE_21_TURBO_V1 + ) + finally: + engine.close() + assert engine.process.closed + + +def test_invalid_turbo_override_fails_before_native_submission(tmp_path): + calls = [] + engine = _engine(tmp_path, calls) + try: + with pytest.raises(ValueError, match="exactly 8"): + engine.generate_image({"prompt": "cat", "num_inference_steps": 9}) + assert not any(path == "/sdcpp/v1/img_gen" for _, path, _ in calls) + finally: + engine.close() + + +def test_existing_turbo_file_hash_mismatch_fails_before_start(tmp_path): + with pytest.raises((RuntimeError, ValueError), match="SHA-256|checksum|hash"): + _engine(tmp_path, [], verify=True, tamper_hash=True)