Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ exclude =
scripts/tune
# The speech engines keep the Python conventions of their former repository
engines/speech
engines/diffusion
# max-complexity = 10

# The XDNA NPU kernel generators are standalone build scripts: they are run by
Expand Down
37 changes: 37 additions & 0 deletions .github/workflows/diffusion-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Diffusion engine
on:
pull_request:
paths:
- '.github/workflows/diffusion-ci.yml'
- 'engines/diffusion/**'
- 'ggml/**'
- 'CMakeLists.txt'
push:
branches: [temp-12429]
paths:
- '.github/workflows/diffusion-ci.yml'
- 'engines/diffusion/**'
- 'ggml/**'
- 'CMakeLists.txt'
workflow_dispatch:

permissions:
contents: read

jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-24.04
options: -DGGML_BLAS=OFF
- os: macos-15
options: -DGGML_METAL=ON -DSD_COREML=ON
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v6
- name: Configure diffusion against Fabric GGML
run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DFABRIC_BUILD_DIFFUSION=ON -DBUILD_LLAMA=OFF -DSD_BUILD_TESTS=ON ${{ matrix.options }}
- run: cmake --build build --config Release --parallel 3
- run: ctest --test-dir build/engines/diffusion -C Release --output-on-failure
9 changes: 9 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[submodule "engines/diffusion/examples/server/frontend"]
path = engines/diffusion/examples/server/frontend
url = https://github.com/leejet/sdcpp-webui.git
[submodule "engines/diffusion/thirdparty/libwebm"]
path = engines/diffusion/thirdparty/libwebm
url = https://github.com/webmproject/libwebm.git
[submodule "engines/diffusion/thirdparty/libwebp"]
path = engines/diffusion/thirdparty/libwebp
url = https://github.com/webmproject/libwebp.git
14 changes: 14 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ endif()

option(LLAMA_USE_SYSTEM_GGML "Use system libggml" OFF)
option(BUILD_LLAMA "Build, install LLAMA package artifacts as well." ON)
option(FABRIC_BUILD_DIFFUSION "fabric: build the diffusion engine against Fabric ggml" OFF)
option(FABRIC_BUILD_SPEECH "fabric: build the speech engines (engines/speech/) against the in-tree ggml" OFF)
set(FABRIC_SPEECH_COREML_OPTIONS WHISPER_COREML PARAKEET_COREML TTS_CPP_COREML AUDIOGEN_COREML AUDIOGEN_MINIMAX_COREML)

Expand All @@ -84,6 +85,9 @@ macro(fabric_enable_objc_before_ggml_for_speech_coreml)
endmacro()

fabric_enable_objc_before_ggml_for_speech_coreml()
if (APPLE AND FABRIC_BUILD_DIFFUSION AND SD_COREML)
enable_language(OBJC OBJCXX)
endif()

option(LLAMA_WASM_MEM64 "llama: use 64-bit memory in WASM builds" ON)

Expand Down Expand Up @@ -262,10 +266,20 @@ endif()
if (NOT TARGET ggml AND NOT LLAMA_USE_SYSTEM_GGML)
set(GGML_BUILD_NUMBER ${LLAMA_BUILD_NUMBER})
set(GGML_BUILD_COMMIT ${LLAMA_BUILD_COMMIT})
if (FABRIC_BUILD_DIFFUSION AND NOT DEFINED GGML_MAX_NAME)
set(GGML_MAX_NAME 160)
endif()
add_subdirectory(ggml)
# ... otherwise assume ggml is added by a parent CMakeLists.txt
endif()

if (FABRIC_BUILD_DIFFUSION)
if (SD_BUILD_TESTS)
enable_testing()
endif()
add_subdirectory(engines/diffusion)
endif()

if (FABRIC_BUILD_SPEECH)
if (SPEECH_BUILD_TESTS)
enable_testing()
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,18 @@ Run VisionPsy Nano and Flash vision-language models through the multimodal subsy
- **Image sizing**: `--image-no-upscale on` enables the Flash preprocessing rule, rounding image sizes to the slice grid without always stretching smaller images to the maximum size. Use it for Flash projectors that do not declare this rule in GGUF metadata.
- **Memory-aware vision attention**: automatic flash-attention selection accounts for image size and device memory on backends without efficient cooperative-matrix flash attention.

### Diffusion Engine

The engine in `engines/diffusion/` comes from `tetherto/qvac-ext-stable-diffusion.cpp` at `08a5801475eb6d6adf08c5f214027492b394ffd1` (branch `2026-11-01`). Build the library and its model-free tests with the in-tree GGML:

```bash
cmake -S . -B build -DFABRIC_BUILD_DIFFUSION=ON -DBUILD_LLAMA=OFF -DSD_BUILD_TESTS=ON
cmake --build build --config Release
ctest --test-dir build/engines/diffusion -C Release --output-on-failure
```

Diffusion requires at least 160 bytes for GGML tensor names. When enabling diffusion, build GGML and all of its consumers together with the same `GGML_MAX_NAME` setting. For a standalone engine build against an installed compatible GGML, configure `engines/diffusion` with `-DSD_USE_SYSTEM_GGML=ON`.

### Speech and Audio Engines

The [`engines/speech/`](engines/speech/README.md) tree holds the speech and audio engines formerly developed in `qvac-fabric-speech.cpp`: Whisper, Parakeet, TTS and audio generation. They build against the in-tree `ggml/`:
Expand Down
12 changes: 12 additions & 0 deletions engines/diffusion/.clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
BasedOnStyle: Chromium
UseTab: Never
IndentWidth: 4
TabWidth: 4
AllowShortIfStatementsOnASingleLine: false
ColumnLimit: 0
AccessModifierOffset: -4
NamespaceIndentation: All
FixNamespaceComments: false
AlignAfterOpenBracket: true
AlignConsecutiveAssignments: true
IndentCaseLabels: true
10 changes: 10 additions & 0 deletions engines/diffusion/.clang-tidy
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Checks: >
modernize-make-shared,
modernize-use-nullptr,
modernize-use-override,
modernize-pass-by-value,
modernize-return-braced-init-list,
modernize-deprecated-headers,
HeaderFilterRegex: '^$'
WarningsAsErrors: ''
FormatStyle: none
8 changes: 8 additions & 0 deletions engines/diffusion/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
build*/
docs/
test/
tests/

.cache/
*.swp
models/
3 changes: 3 additions & 0 deletions engines/diffusion/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/start-server.sh text eol=lf
/start-server.bat text eol=crlf
/examples/server/frontend-video-cache-default.patch text eol=lf
29 changes: 29 additions & 0 deletions engines/diffusion/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
build*/
cmake-build-*/
test/
tests/
logs/
.vscode/
.idea/
.cache/
*.swp
*.bat
!/start-server.bat
/start-server.local.sh
/start-server.local.bat
/start-server.local.ps1
*.bin
*.exe
*.gguf
output*.png
models*
*.log
preview.png
.claude/
CLAUDE.local.md
.agents/
.codex/

.venv*/
bench-results/
__pycache__/
186 changes: 186 additions & 0 deletions engines/diffusion/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
# Instructions for stable-diffusion.cpp

This document is for AI coding agents working in this repository. It should
describe agent-specific workflow, repository routing, editing boundaries, and
project-specific pitfalls.

For general contribution rules, including PR scope, commit conventions, code
style, dependency updates, security hygiene, and AI-assisted contribution policy,
see `CONTRIBUTING.md`.

---

## Agent Operating Rules

Before analyzing or modifying the repository:

1. Read this file.
2. Use `rg` / `rg --files` or directory listing commands to confirm the current
tree before relying on a path.
3. Start from `src/` and relevant `docs/` for runtime behavior.
4. Read the relevant code before editing.
5. Prefer the smallest change that fits the existing architecture.
6. Report focused verification and mention any tests not run.

Agents must not:

* Run `git push`, create PRs, or submit issue/PR comments on the user's behalf.
* Create commits unless the user explicitly requests that specific commit.
* Modify `ggml/`, `thirdparty/`, or `examples/server/frontend/` unless
explicitly requested and necessary.
* Read large local model files or tokenizer vocabulary files.
* Rewrite unrelated code for style-only reasons.
* Add secrets, model weights, generated binaries, local absolute paths, or
machine-specific output.

When a change is large, architectural, or likely to affect public behavior,
pause and present a short plan before editing.

---

## Repository Map and Editing Boundaries

This is a routing map for agents, not a full architecture document. The layout
can change, so verify paths before using them. Do not inspect excluded
large-data directories while checking the tree.

### Primary Project Code

Core implementation lives under `src/`.

Current source layout includes:

* `src/core/` - shared tensor, ggml integration, backend, graph, RNG, and utility
code.
* `src/model/` - model families and model components.
* `src/model_io/` - model file loading, GGUF, safetensors, pickle, and related
serialization helpers.
* `src/runtime/` - sampling, denoising, guidance, caching, preprocessing, and
runtime execution helpers.
* `src/tokenizers/` - tokenizer implementations.
* `src/conditioning/` - conditioning and prompt-related implementation.
* `src/extensions/` - optional feature extensions.
* top-level `src/*.cpp` and `src/*.h` files - public implementation entry
points, model loading, conversion, versioning, and shared managers.

`src/tokenizers/vocab/` contains large tokenizer vocabulary data. Do not read or
parse files in this directory; reference the path only when necessary.

### Public API

`include/` contains the C API exposed by the project. Currently the primary
public header is `include/stable-diffusion.h`.

Treat public headers as stable API. Avoid breaking compatibility unless the user
explicitly requests it. If public behavior changes, update relevant examples or
documentation.

### Examples

`examples/` contains programs demonstrating library usage.

* `examples/cli/` - command line program for running models, testing features,
and debugging.
* `examples/common/` - shared example support code.
* `examples/server/` - server application built on top of the library.
Before modifying built-in recipes, read and follow
[the built-in recipe policy](examples/server/recipes/README.md).
* `examples/server/frontend/` - git submodule containing independent frontend
code. Avoid modifying it unless explicitly requested.

### Documentation and Tooling

* `docs/` - documentation for supported models, build options, behavior, and
workflows.
* `scripts/` - development, model processing, build automation, formatting, and
tooling scripts.
* `cmake/` - CMake support modules.
* `docker/` - Docker-related project files.
* `assets/` - documentation assets; not runtime code.

### External, Local, and Generated State

* `ggml/` - git submodule for the ggml dependency.
* `thirdparty/` - vendored third-party dependencies.
* `models/` - local model storage. Ignore this directory and do not read model
files.
* `test/` - local testing scripts. Use only when relevant to the task.
* `build/`, `build_*`, and similar directories - generated build outputs.
Inspect them only when debugging a build result.

---

## Agent Workflow for Code Changes

1. Identify the relevant modules under `src/`.
2. Check whether the change touches the public API in `include/`.
3. Consult relevant `docs/` and examples before changing user-facing behavior.
4. Follow existing local patterns before adding new abstractions.
5. Keep edits scoped to the requested behavior.
6. Run the narrowest useful build, test, or inspection command available.

Follow `CONTRIBUTING.md` for formatting, naming, PR expectations, dependency
update policy, and security rules. For tokenizer additions, follow its embedded-data
allowlist and default to an external `tokenizer.json`.

---

## Code Comments

Keep comments rare and useful.

Do not add comments that only describe what the code does. Add comments only
when the code cannot fully express the logic, the logic is unusually complex, or
there are historical reasons, invariants, constraints, compatibility concerns,
or known pitfalls that future maintainers need to understand.

Do not add task-specific comments that will be meaningless after review.

Examples from the current codebase:

```cpp
// GOOD: explains a safety constraint that is not obvious from the assignment.
// From src/model_io/pickle_io.cpp.
// Non-tensor checkpoint metadata can use REDUCE for arbitrary
// Python objects. Do not execute it; keep stack shape only.
stack.push_back(make_none_value());

// BAD: describes only what the next line does.
// Set the token count to zero.
token_count = 0;
```

---

## Text File Encoding

When reading or editing repository text files:

* Prefer UTF-8 with LF for Markdown, frontend source, JSON, and other text-first
project files unless the file already clearly uses a different encoding.
* Do not assume terminal output encoding matches file encoding on Windows.
* A file that looks garbled in PowerShell output may still be valid UTF-8.
* When inspecting UTF-8 files in PowerShell, prefer explicit UTF-8 reads such as:
* `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8`
* `Get-Content -Encoding utf8 <path>`
* Avoid rewriting a file purely because console output looked garbled; verify
the actual file encoding first.

---

## Tensor and Layout Notes

Additional tensor/layout rules for this codebase:

* `sd::Tensor` shape order is not PyTorch/NumPy-style. `shape()[0]` is the
lowest and most contiguous dimension, and higher indices are higher
dimensions.
* Broadcasting for `sd::Tensor` must align dimensions from low to high dimension
indices. If one tensor has fewer dimensions, append implicit `1`s at the
higher-dimension end.
* `ggml_n_dims` / `ggml_n_dims(tensor)` can drop trailing singleton high
dimensions. Do not assume a logical trailing dimension of `1` will still be
counted in ggml metadata.
* Internal tensor-returning interfaces use an empty `sd::Tensor` to represent
null, absent, or failure states. Do not add `std::optional<sd::Tensor<...>>`
for internal APIs unless a distinct semantic state is truly required.
11 changes: 11 additions & 0 deletions engines/diffusion/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
@AGENTS.md

## Claude Code

Follow `AGENTS.md` as the shared repository instructions.

Do not duplicate contribution, style, PR, dependency, or security policy here;
use `CONTRIBUTING.md` as the canonical source for those rules.

Keep Claude-specific project notes in this file only when they do not apply to
other coding agents.
Loading
Loading