diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7c407139bb..61e05ee97c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,6 +15,7 @@ on: [ ".github/workflows/**", ".dockerignore", + "docs/dgl-builtins.md", "docker/Dockerfile*", "scripts/ci-cuda-cache.sh", "**/CMakeLists.txt", @@ -38,6 +39,7 @@ on: [ ".github/workflows/**", ".dockerignore", + "docs/dgl-builtins.md", "docker/Dockerfile*", "scripts/ci-cuda-cache.sh", "**/CMakeLists.txt", @@ -100,6 +102,7 @@ jobs: cd build cmake .. -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DCMAKE_INSTALL_RPATH='$ORIGIN' cmake --build . --config Release + cmake --build . --config Release --target dgl-check-builtins - name: Get commit hash id: commit @@ -121,6 +124,8 @@ jobs: run: | cp ggml/LICENSE ./build/bin/ggml.txt cp LICENSE ./build/bin/stable-diffusion.cpp.txt + cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt + cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt chmod +x start-server.sh zip -j sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}.zip ./build/bin/* ./start-server.sh ./start-server.bat @@ -186,6 +191,8 @@ jobs: run: | cp ggml/LICENSE ./build/bin/ggml.txt cp LICENSE ./build/bin/stable-diffusion.cpp.txt + cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt + cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt chmod +x start-server.sh zip -j sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}-vulkan.zip ./build/bin/* ./start-server.sh ./start-server.bat @@ -366,6 +373,8 @@ jobs: run: | cp ggml/LICENSE ./build/bin/ggml.txt cp LICENSE ./build/bin/stable-diffusion.cpp.txt + cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt + cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt chmod +x start-server.sh zip -j sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}.zip ./build/bin/* ./start-server.sh ./start-server.bat @@ -474,8 +483,11 @@ jobs: ls .\build\bin throw "Can't find stable-diffusion.dll" } + $binPath = Split-Path -Parent $filePath + Copy-Item thirdparty/libwebm/LICENSE.TXT (Join-Path $binPath 'libwebm.txt') + Copy-Item thirdparty/libwebp/COPYING (Join-Path $binPath 'libwebp.txt') if ("${{ matrix.build }}" -eq "cuda12") { - Copy-Item thirdparty/cutlass/LICENSE.txt (Join-Path (Split-Path -Parent $filePath) 'cutlass.txt') + Copy-Item thirdparty/cutlass/LICENSE.txt (Join-Path $binPath 'cutlass.txt') } 7z a sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-${{ matrix.build }}-x64.zip $filePath .\start-server.sh .\start-server.bat @@ -633,6 +645,8 @@ jobs: - name: Pack artifacts if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) || github.event.inputs.create_release == 'true' }} run: | + Copy-Item thirdparty/libwebm/LICENSE.TXT .\build\bin\libwebm.txt + Copy-Item thirdparty/libwebp/COPYING .\build\bin\libwebp.txt 7z a sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-rocm-${{ env.ROCM_VERSION }}-x64.zip .\build\bin\* .\start-server.sh .\start-server.bat - name: Upload artifacts @@ -796,6 +810,8 @@ jobs: run: | cp ggml/LICENSE ./build/bin/ggml.txt cp LICENSE ./build/bin/stable-diffusion.cpp.txt + cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt + cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt chmod +x start-server.sh zip -y -r sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-Ubuntu-${{ env.UBUNTU_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}-rocm-${{ matrix.ROCM_VERSION }}.zip ./build/bin ./start-server.sh ./start-server.bat @@ -819,7 +835,6 @@ jobs: - ubuntu-latest-cmake - ubuntu-latest-cmake-vulkan - ubuntu-latest-rocm - - build-and-push-docker-images - macOS-latest-cmake - windows-latest-cmake - windows-latest-rocm diff --git a/.gitignore b/.gitignore index 13a77540c6..4fe1a50979 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,11 @@ build*/ cmake-build-*/ test/ tests/ +/dgl/* +!/dgl/.gitkeep logs/ +input/ +output/ .vscode/ .idea/ .cache/ diff --git a/AGENTS.md b/AGENTS.md index ea93c92a7a..89d2eb7d79 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,13 +50,18 @@ Core implementation lives under `src/`. Current source layout includes: +* `src/api/` - C API options, generation requests, and translation to DGL. * `src/core/` - shared tensor, ggml integration, backend, graph, RNG, and utility code. +* `src/dgl/` - DGL compilation, execution, and built-in operations. See the + [DGL architecture guide](docs/development/dgl.md) for layer boundaries. * `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/weights/` - weight residency state and reclaim decisions. See the + [weight residency internals](docs/development/weights.md). * `src/tokenizers/` - tokenizer implementations. * `src/conditioning/` - conditioning and prompt-related implementation. * `src/extensions/` - optional feature extensions. @@ -92,6 +97,7 @@ documentation. * `docs/` - documentation for supported models, build options, behavior, and workflows; start from `docs/README.md`. +* `docs/dgl/` - runnable DGL examples grouped by model. * `docs/models/` - model and component usage guides, including LoRAs, adapters, auxiliary models, and model-specific examples. * `docs/guides/` - shared usage workflows, configuration, and performance guides. @@ -127,6 +133,12 @@ documentation. 6. Keep edits scoped to the requested behavior. 7. Run the narrowest useful build, test, or inspection command available. +Regenerate [the DGL built-in catalog](docs/dgl-builtins.md) whenever a +registered function is added, removed, renamed, or changes its parameters, +defaults, or outputs. Run the `dgl-update-builtins` CMake target to +regenerate the catalog and `dgl-check-builtins` to verify it. Update the +DGL guide or examples when a built-in changes behavior. + 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`. diff --git a/CMakeLists.txt b/CMakeLists.txt index 59107d4f40..c50ae80067 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.12) +cmake_minimum_required(VERSION 3.16) project("stable-diffusion") set(CMAKE_EXPORT_COMPILE_COMMANDS ON) @@ -9,14 +9,8 @@ if (NOT XCODE AND NOT MSVC AND NOT CMAKE_BUILD_TYPE) endif() if (MSVC) - cmake_host_system_information(RESULT SD_LOGICAL_CORES QUERY NUMBER_OF_LOGICAL_CORES) - if (SD_LOGICAL_CORES GREATER 8) - math(EXPR SD_DEFAULT_MSVC_MP_COUNT "${SD_LOGICAL_CORES} - 2") - elseif (SD_LOGICAL_CORES GREATER 2) - math(EXPR SD_DEFAULT_MSVC_MP_COUNT "${SD_LOGICAL_CORES} - 1") - else() - set(SD_DEFAULT_MSVC_MP_COUNT "${SD_LOGICAL_CORES}") - endif() + cmake_host_system_information(RESULT SD_PHYSICAL_CORES QUERY NUMBER_OF_PHYSICAL_CORES) + set(SD_DEFAULT_MSVC_MP_COUNT "${SD_PHYSICAL_CORES}") if (NOT SD_DEFAULT_MSVC_MP_COUNT GREATER 0) set(SD_DEFAULT_MSVC_MP_COUNT 1) endif() @@ -24,6 +18,7 @@ if (MSVC) if (NOT SD_MSVC_MP_COUNT MATCHES "^[1-9][0-9]*$" OR SD_MSVC_MP_COUNT GREATER 65536) message(FATAL_ERROR "SD_MSVC_MP_COUNT must be an integer between 1 and 65536") endif() + message("-- SD_MSVC_MP_COUNT: ${SD_MSVC_MP_COUNT}") add_compile_definitions(_CRT_SECURE_NO_WARNINGS) add_compile_definitions(_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING) # /MP is MSVC-only: icx rejects it outright once offloading is enabled. @@ -96,9 +91,10 @@ endif() # general #option(SD_BUILD_TESTS "sd: build tests" ${SD_STANDALONE}) option(SD_BUILD_EXAMPLES "sd: build examples" ${SD_STANDALONE}) +option(SD_BUILD_PCH "sd: use a C++ precompiled header for the library" ON) option(SD_WEBP "sd: enable WebP image I/O support" ${SD_WEBP_DEFAULT}) option(SD_USE_SYSTEM_WEBP "sd: link against system libwebp" OFF) -option(SD_WEBM "sd: enable WebM video output support" ${SD_WEBM_DEFAULT}) +option(SD_WEBM "sd: enable WebM video I/O support" ${SD_WEBM_DEFAULT}) option(SD_USE_SYSTEM_WEBM "sd: link against system libwebm" OFF) option(SD_CUDA "sd: cuda backend" OFF) option(SD_HIPBLAS "sd: rocm backend" OFF) @@ -127,9 +123,6 @@ endif() if(SD_METAL) if(NOT SD_USE_UPSTREAM_GGML) - if(CMAKE_VERSION VERSION_LESS 3.16) - message(FATAL_ERROR "SD_METAL with SD_USE_UPSTREAM_GGML=OFF requires CMake 3.16 or later for OBJC and OBJCXX support") - endif() enable_language(OBJC OBJCXX) endif() message("-- Use Metal as backend stable-diffusion") @@ -184,13 +177,21 @@ if(SD_WEBP) "Expected WebP::libwebpmux or WebP::webpmux." ) endif() + if(TARGET WebP::webpdemux) + add_library(webpdemux ALIAS WebP::webpdemux) + elseif(TARGET WebP::libwebpdemux) + add_library(webpdemux ALIAS WebP::libwebpdemux) + else() + message(FATAL_ERROR "System WebP package must provide WebP::webpdemux or WebP::libwebpdemux.") + endif() else() find_package(PkgConfig REQUIRED) pkg_check_modules(WebP REQUIRED IMPORTED_TARGET GLOBAL libwebp) pkg_check_modules(WebPMux REQUIRED IMPORTED_TARGET GLOBAL libwebpmux) - link_libraries(PkgConfig::WebP) - link_libraries(PkgConfig::WebPMux) + pkg_check_modules(WebPDemux REQUIRED IMPORTED_TARGET GLOBAL libwebpdemux) + add_library(webp ALIAS PkgConfig::WebP) add_library(libwebpmux ALIAS PkgConfig::WebPMux) + add_library(webpdemux ALIAS PkgConfig::WebPDemux) endif() endif() endif() @@ -210,7 +211,7 @@ if(SD_WEBM) pkg_check_modules(WebM REQUIRED IMPORTED_TARGET GLOBAL libwebm) endif() if(PkgConfig_FOUND AND WebM_FOUND) - link_libraries(PkgConfig::WebM) + add_library(webm ALIAS PkgConfig::WebM) else() find_path(WEBM_INCLUDE_DIR NAMES mkvmuxer/mkvmuxer.h mkvparser/mkvparser.h common/webmids.h @@ -236,6 +237,17 @@ endif () set(SD_LIB stable-diffusion) +file(GLOB SD_API_TEMPLATES CONFIGURE_DEPENDS "src/api/templates/*.dgl") +set(SD_API_TEMPLATE_CONTENT "#ifndef __SD_API_TEMPLATES_H__\n#define __SD_API_TEMPLATES_H__\n#include \n#include \n#include \nnamespace sd::api::templates {\ninline const std::map sources = {\n") +foreach(SD_API_TEMPLATE IN LISTS SD_API_TEMPLATES) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${SD_API_TEMPLATE}") + get_filename_component(SD_API_TEMPLATE_NAME "${SD_API_TEMPLATE}" NAME_WE) + file(READ "${SD_API_TEMPLATE}" SD_API_TEMPLATE_TEXT) + string(APPEND SD_API_TEMPLATE_CONTENT "{\"${SD_API_TEMPLATE_NAME}\", R\"SD_DGL(${SD_API_TEMPLATE_TEXT})SD_DGL\"},\n") +endforeach() +string(APPEND SD_API_TEMPLATE_CONTENT "};\n}\n#endif\n") +file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/generated/api_templates.h" CONTENT "${SD_API_TEMPLATE_CONTENT}") + file(GLOB SD_LIB_SOURCES CONFIGURE_DEPENDS "src/*.h" "src/*.cpp" @@ -255,11 +267,19 @@ file(GLOB SD_LIB_SOURCES CONFIGURE_DEPENDS "src/extensions/*.h" "src/extensions/*.cpp" "src/extensions/*.hpp" + "src/dgl/*.h" + "src/dgl/*.cpp" + "src/dgl/syntax/*.h" + "src/dgl/syntax/*.cpp" + "src/dgl/bindings/*.h" + "src/dgl/bindings/*.cpp" + "src/dgl/models/*.h" + "src/dgl/models/*.cpp" + "src/dgl/ops/*.h" + "src/dgl/ops/*.cpp" "src/model/*/*.h" "src/model/*/*.cpp" "src/model/*/*.hpp" - "src/pipeline/*.h" - "src/pipeline/*.cpp" "src/runtime/*.h" "src/runtime/*.cpp" "src/runtime/*.hpp" @@ -269,8 +289,18 @@ file(GLOB SD_LIB_SOURCES CONFIGURE_DEPENDS "src/tokenizers/*.cpp" "src/tokenizers/vocab/*.h" "src/tokenizers/vocab/*.cpp" + "src/weights/*.h" + "src/weights/*.cpp" ) +if(CMAKE_GENERATOR MATCHES "^Ninja") + # Compile the vocabulary data alongside PCH generation to shorten the build tail. + set(SD_VOCAB_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/tokenizers/vocab/vocab.cpp") + list(REMOVE_ITEM SD_LIB_SOURCES "${SD_VOCAB_SOURCE}") + list(PREPEND SD_LIB_SOURCES "${SD_VOCAB_SOURCE}") + set_source_files_properties("${SD_VOCAB_SOURCE}" PROPERTIES SKIP_PRECOMPILE_HEADERS ON) +endif() + find_program(GIT_EXE NAMES git git.exe NO_CMAKE_FIND_ROOT_PATH) if(GIT_EXE) execute_process(COMMAND ${GIT_EXE} describe --tags --abbrev=7 --dirty=+ @@ -363,6 +393,14 @@ target_link_libraries(${SD_LIB} PUBLIC ggml) find_package(Threads REQUIRED) target_link_libraries(${SD_LIB} PRIVATE Threads::Threads) target_link_libraries(${SD_LIB} PRIVATE onig sd-utf8proc) +if(SD_WEBP) + target_compile_definitions(${SD_LIB} PRIVATE SD_USE_WEBP) + target_link_libraries(${SD_LIB} PRIVATE webp webpdemux) +endif() +if(SD_WEBM) + target_compile_definitions(${SD_LIB} PRIVATE SD_USE_WEBM) + target_link_libraries(${SD_LIB} PRIVATE webm) +endif() if (SD_CUDA) find_package(CUDAToolkit REQUIRED) # Keep the driver stub on downstream link lines when no driver is installed. @@ -430,9 +468,20 @@ if (SD_HIPBLAS) endif() endif() target_include_directories(${SD_LIB} PUBLIC include) -target_include_directories(${SD_LIB} PRIVATE src src/core) +target_include_directories(${SD_LIB} PRIVATE src src/core "${CMAKE_CURRENT_BINARY_DIR}/generated") target_include_directories(${SD_LIB} PUBLIC thirdparty) target_compile_features(${SD_LIB} PUBLIC c_std_11 cxx_std_17) +# oneAPI 2025.x cannot bundle precompiled headers when -fsycl is enabled. +if(SD_BUILD_PCH AND NOT SD_SYCL) + set(SD_PCH_HEADERS ${SD_LIB_SOURCES}) + list(FILTER SD_PCH_HEADERS INCLUDE REGEX "[.]hpp$") + list(FILTER SD_PCH_HEADERS EXCLUDE REGEX "/tokenizers/vocab/") + list(TRANSFORM SD_PCH_HEADERS PREPEND "$<$:") + list(TRANSFORM SD_PCH_HEADERS APPEND ">") + target_precompile_headers(${SD_LIB} PRIVATE + "$<$:>" + ${SD_PCH_HEADERS}) +endif() set_target_properties(${SD_LIB} PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN ON) @@ -444,6 +493,7 @@ endif() + # # install # @@ -459,12 +509,9 @@ set(SD_INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR} CACHE PATH "Location of h set(SD_LIB_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR} CACHE PATH "Location of library files") set(SD_BIN_INSTALL_DIR ${CMAKE_INSTALL_BINDIR} CACHE PATH "Location of binary files") -set(SD_PUBLIC_HEADERS - ${CMAKE_CURRENT_SOURCE_DIR}/include/stable-diffusion.h) - set_target_properties(${SD_LIB} PROPERTIES - PUBLIC_HEADER "${SD_PUBLIC_HEADERS}") + PUBLIC_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/include/stable-diffusion.h") install(TARGETS ${SD_LIB} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1b5cc654d3..ee2b9c33d9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,6 +43,12 @@ Link new documentation from [the documentation index](docs/README.md) or [the model index](docs/models/README.md), as appropriate. Keep supported model entries and their guide links in the project README. +Use **DGL** for the language name in headings, prose, link text, UI labels, +comments, logs, and diagnostics. Preserve literal spellings in commands, files, +paths, and protocol or metadata fields, such as `-M dgl`, `.dgl`, `docs/dgl/`, +and the metadata key `dgl`. Code identifiers follow their existing naming style, +such as `sd_dgl_run`, `sd::dgl`, `SD_DGL_VALUE_TENSOR`, and `DglWorkspace`. + ### Model Documentation Every new model or component integration must include a user guide in @@ -60,7 +66,9 @@ omitting other sections when they have no content: - `Model files`, with component, weights/downloads, CLI option, and requirement columns. Include tokenizers, projectors, connectors, downloads, conversion, and required preprocessing. -- `Usage`, with `Web UI` and `CLI` subsections where applicable. Link to the +- `Usage`, with `Web UI`, `DGL`, and `Legacy CLI` subsections in that order + where applicable. Group DGL scripts in a task table with descriptive links; + put shared run instructions below the table. Link to the server's shared Web UI guide and list compatible recipes/components. Group complete CLI examples by task or variant within this section; do not add a separate `Quick start` or `Examples` section. Keep API usage in its own diff --git a/README.md b/README.md index 6d62d57539..f36a435e8d 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ API and command-line option may change frequently.*** - [Qwen Image 2.1](./docs/models/qwen_image_2.1.md) - [PiD](./docs/models/pid.md) - [LongCat Image](./docs/models/longcat_image.md) - - [Z-Image](./docs/models/z_image.md) + - [Z-Image](./docs/models/z_image.md), including [DGL ControlNet](./docs/models/z_image.md#controlnet) - [Z-Image L2P](./docs/models/z_image_l2p.md) - [MiniT2I](./docs/models/minit2i.md) - [P-H3-Image](./docs/models/p_h3_image.md) @@ -85,6 +85,7 @@ API and command-line option may change frequently.*** - [Mage-Flow-Edit](./docs/models/mage_flow.md#image-editing) - [LLaDA-Image Edit](./docs/models/llada_image.md#image-editing) - [Fibo 2.0 Dev / Edit Turbo](./docs/models/fibo2.md#fibo-20-edit-turbo) + - [MOSS-Image Edit](./docs/models/moss_image.md#moss-image-edit) - Video Models - [Wan2.1/Wan2.2](./docs/models/wan.md) - [MiniMax-H3](./docs/models/minimax_h3.md) @@ -99,6 +100,7 @@ API and command-line option may change frequently.*** - Control Net support with SD 1.5 - [ADetailer](./docs/models/adetailer.md) - LoRA support, same as [stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#lora) + - [Textual inversion embeddings](./docs/embeddings.md) for SD 1.x/2.x/SDXL via `--embd-dir` and `` tags - Latent Consistency Models support (LCM/LCM-LoRA) - Faster and memory efficient latent decoding with [TAESD](./docs/models/taesd.md) - Upscale images generated with [ESRGAN](./docs/models/esrgan.md) @@ -213,6 +215,7 @@ Browse the [documentation index](./docs/README.md) or jump to a topic: - [Getting started: build, Docker, CLI, and server](./docs/README.md#get-started) - [Models and components](./docs/models/README.md) - [Generation and inputs](./docs/README.md#generation-and-inputs) +- [DGL generation scripts](./docs/dgl.md) - [Devices and performance](./docs/README.md#devices-and-performance) - [Weights and quantization](./docs/README.md#weights-and-quantization) - [Troubleshooting](./docs/troubleshooting.md) diff --git a/assets/hidream-o1/dev_example.png b/assets/hidream-o1/dev_example.png index e7ab12bb38..aaac4c11b5 100644 Binary files a/assets/hidream-o1/dev_example.png and b/assets/hidream-o1/dev_example.png differ diff --git a/dgl/.gitkeep b/dgl/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/docs/README.md b/docs/README.md index 5490146b20..891db9177f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,6 +15,8 @@ For the project overview and supported models, see the [project README](../READM ## Generation and inputs +- [DGL generation scripts](dgl.md) +- [DGL model examples](dgl/README.md) - [C API and migration](guides/c_api.md) - [Sampling methods and schedulers](guides/sampling.md) - [Image editing](guides/edit.md) @@ -40,6 +42,8 @@ For the project overview and supported models, see the [project README](../READM ## Development - [C API internals](development/c_api.md) +- [DGL architecture](development/dgl.md) +- [Weight residency internals](development/weights.md) - [Model configuration and integration conventions](development/model_config.md) - [ggml operator extensions](development/ggml_extensions.md) - [Backend performance probes](development/backend_probe.md) diff --git a/docs/build.md b/docs/build.md index 1533cfb2bc..9d65eadcc9 100644 --- a/docs/build.md +++ b/docs/build.md @@ -1,5 +1,7 @@ # Build from scratch +CMake 3.16 or later is required. + ## Get the Code ```shell @@ -59,9 +61,22 @@ including `GGML_MAX_NAME`. For an upstream package, also set `SD_USE_UPSTREAM_GGML=ON` and point `SD_GGML_SOURCE_DIR` to its matching source tree for the compatibility layer's private headers. -## WebP and WebM Support in Examples +## WebP and WebM Support + +WebP and WebM support are enabled by default. The library links `libwebp`, +`libwebpdemux` and `libwebm` so DGL `video::load` works through the C API as +well as CLI and server. WebP input supports static images and animation; +WebM input supports this project's independent VP8 frames and PCM16 audio. +No libvpx dependency is required. See [DGL media I/O](dgl.md) for frame-rate +and codec restrictions. -The example applications (`examples/cli` and `examples/server`) use `libwebp` to support WebP image I/O, and `examples/cli` can also use `libwebm` for `.webm` video output. Both are enabled by default. WebM output currently reuses `libwebp` to encode each frame as VP8 before muxing with `libwebm`. +The CLI and server also use `libwebp` for WebP images. CLI WebM output reuses +`libwebp` to encode each frame as VP8 before muxing with `libwebm`. System WebP +packages must provide the decoder, demuxer and muxer libraries. + +DGL `video::encode` supports silent WebM and AVI with PCM16 audio. Requesting +WebM audio reports an unsupported-encoder error; use `format="avi"` to include +an audio track. If you do not want WebP/WebM support, you can disable them at configure time: @@ -404,6 +419,24 @@ ccache --show-stats Look for cache hits in the statistics. A normal incremental build with no changed files skips compilation and does not produce new cache hits. +If ccache reports `Could not use precompiled header` for C++ compilations, +add `-DSD_BUILD_PCH=OFF` to your configure command and check the cache again. + +### Precompiled header + +By default, the stable-diffusion C++ library precompiles the JSON header +and the project `.hpp` headers in the library source list to speed up +clean builds. Editing a header used by the PCH rebuilds the PCH and the +C++ files that use it. To disable it, add `-DSD_BUILD_PCH=OFF` to your +configure command. SYCL builds skip the PCH because oneAPI 2025.x cannot +bundle it with `-fsycl`. + +To compare uncached clean builds, pass `-DGGML_CCACHE=OFF`, +`-DCMAKE_C_COMPILER_LAUNCHER=`, and `-DCMAKE_CXX_COMPILER_LAUNCHER=` in both +configure commands. For CUDA builds, also pass `-DCMAKE_CUDA_COMPILER_LAUNCHER=`. +The empty values override any compiler launchers saved in a reused build +directory. + ### MSVC compilation parallelism MSVC builds limit parallel C/C++ compilation within each project by default. diff --git a/docs/development/backend_probe.md b/docs/development/backend_probe.md index c420326d4c..f40876d089 100644 --- a/docs/development/backend_probe.md +++ b/docs/development/backend_probe.md @@ -37,10 +37,13 @@ measurement pair; it cannot interrupt an in-flight backend operation. Only use `candidate_faster` when `completed` is true. On incomplete probes, `error` reports why comparison failed and the timing totals may be partial. The caller handles logging, known architecture rules, fallback policy, and -context-lifetime caching. Keep caches separate by operation (or key a shared -cache by both operation and backend); an attention result must not select a -convolution implementation. If shapes or settings vary within one context, -include them in the corresponding cache key as well. +context-lifetime caching. DGL uses one `BackendProbeCache` shared by all models +in an execution context, including LoRA variants and models loaded by later +programs. It caches both enabled and disabled decisions by operation and compute +backend; CPU attention additionally keys the effective thread count. GPU results +survive changes to the context's thread count. The cache serializes first-time +probes and their decision logs. Explicit operator `on` and `off` bypass the cache. +If probe shapes or other relevant settings become variable, add them to the key. Convolution results are cached separately for 2D and 3D, once per compute backend in the context, just like attention results. Each probe logs its backend, decision, diff --git a/docs/development/c_api.md b/docs/development/c_api.md index 58587a6fac..bfa6fd1e52 100644 --- a/docs/development/c_api.md +++ b/docs/development/c_api.md @@ -13,26 +13,30 @@ See the [C API guide](../guides/c_api.md) for keys, value types and ownership ru | `src/core/media.h` | Private raw media views used by inference and codecs. | | `src/api/result.h/.cpp` | Internal result storage, opaque result accessors, metadata attachment and media ownership. | | `src/api/api.h/.cpp` | Context, generation, callback and query entry points, plus thread-local diagnostics and exception-to-status handling. | -| `src/generation_info.h/.cpp` | Construction of generation metadata JSON. | -| `src/pipeline/generation.h` | Internal generation entry declarations. | -| `src/stable-diffusion.cpp` | Internal typed image/video generation and model-specific validation. | +| `src/api/generation.*` | Persistent DGL context, metadata probing, request execution, callbacks and cancellation. | +| `src/api/generation_program.*`, `generation_image.cpp`, `generation_video.cpp`, `generation_h3.cpp`, `generation_prompt.cpp` | Template selection, literal rendering and host input bindings. | +| `src/api/generation_template.*` | Embedded template parsing, variable formatting and conditional rendering. | +| `src/api/templates/` | Complete DGL execution flows and a few shared helpers. | +| `src/api/program_result.cpp` | Adaptation of DGL tensors and dictionaries to C results. | +| `src/api/generation_metadata.cpp` | Image parameter and WebUI infotext extraction through the metadata C API. | +| `src/api/image_metadata.cpp` | Container metadata reading and text/JSON reports through `sd_read_metadata()`. | +| `src/api/media_metadata.cpp`, `metadata.h` | Shared metadata encoding and C access to PNG/JPEG/XMP/AVI chunks. | | `src/core/option_types.h/.cpp` | Internal mode enums, name lookup and parsing. | -Options are validated and converted once at the API boundary. The runtime reads -typed configuration fields. Internal callers such as ADetailer pass typed -configuration directly to the internal generation entry; they do not rebuild -options or call public setters. +Options are validated and converted at the API boundary. The translator renders +a concrete DGL program and binds media through `main` tensor inputs. All retained +inference entries use the same DGL compiler, execution context and model cache. +There is no separate native pipeline. The option map alone records whether a key was supplied. Zero, false, empty strings and explicit automatic choices remain entries until `unset` removes them. Each conversion starts with a fresh `OptConfig`, then overlays supplied values and validates combinations. Reusing the output configuration cannot -retain a previous request's overrides. ADetailer applies its operation-specific -strength default before the overlay. +retain a previous request's overrides. Fixed defaults live in the configuration constructors. Internal automatic policies (such as model-selected sampler/scheduler and automatic eta/flow shift) -are resolved by the pipeline after refreshing the model sources. Their internal +are resolved by the translator after refreshing the model metadata. Their internal sentinel values describe an automatic policy, not the presence of an input key. Do not infer presence by comparing a typed value against its default. @@ -46,18 +50,40 @@ resource policy. Parameter ranges are checked by the public setters used by the option builders; combinations and model applicability are checked when executing. Examples include only public library headers and do not query library defaults. Capability defaults describe configured overrides; null means that the library -selects the value, and result metadata reports effective values. Post-generation -ADetailer clears inherited dimensions and strength before applying pass overrides, -so its operation defaults also come from the library. +selects the value, and the executed DGL records the effective values. Result storage owns tensors and metadata. Tensor handles contain a dtype-specific `sd::Tensor` and an atomic reference count; options retain handles rather than -copying tensor payloads. Raw pipeline output buffers are converted to tensors at -the boundary and released there. Internal producers with an `sd::Tensor` can +copying tensor payloads. DGL outputs are adapted at the result boundary. +Internal producers with an `sd::Tensor` can move it directly into a handle. Video results keep per-frame tensors and assemble a contiguous video tensor only when requested. Cached assembly is synchronized. Preview tensors are independent snapshots and may be retained by callbacks. -Metadata construction is separate from its attachment to a result. +Results retain the exact compiled DGL source. WebUI conversion and media metadata +embedding are separate from inference and never rebuild the execution program. +`src/api/generation_metadata.cpp` parses the source once to produce image +parameters and WebUI infotext together. Examples obtain this JSON through +`sd_get_generation_metadata()` without compiling or calling the DGL parser. +Container reading and metadata chunk generation also use the public C API. +Examples have no private `src` include path and retain generated DGL source +without legacy JSON conversion or LoRA path rewriting. +The translator uses an explicit `llm_path` as the text encoder's main `path`, falling back to +the checkpoint and other configured encoder paths when it is absent. + +Context creation snapshots options without loading weights. Family probing is +lazy and tracks actual file dependencies. The complete request stays busy during +probing, compilation, batch gaps and execution. File permissions are checked +before probing and on every DGL resource access, including cache hits. +Generation templates load their required components as part of execution. +Capability queries read the detected family under the context lock and probe it +on demand. They leave the generation cancellation state untouched. + +C++ validates inputs, resolves model defaults, prepares geometry and binds host +tensors. Templates describe complete execution flows and optional stages; +operations and models retain computation algorithms. Split templates when the +flow changes substantially, and use conditions for smaller variations. Do not +search and patch rendered source to change execution. See the +[template guide](../../src/api/templates/README.md). These headers are private implementation details and are not installed as part of the public C API. diff --git a/docs/development/dgl.md b/docs/development/dgl.md new file mode 100644 index 0000000000..14a5f31289 --- /dev/null +++ b/docs/development/dgl.md @@ -0,0 +1,69 @@ +# DGL architecture + +A DGL program describes a workflow in terms of model and tensor operations. +The CLI can run a handwritten script. The generation C API renders a script +from request parameters and binds input tensors to its entry point. Both paths +use the same compiler and executor. The C API keeps the rendered source in +`generation_info`. See the [language guide](../dgl.md) and +[C API internals](c_api.md). + +## From source to execution + +1. **Compile the script.** The compiler parses the source, resolves calls and + arguments against the built-in registry or user functions, and checks their + types. It records which values each statement needs and when operations + use model weights. For a configuration-dependent `if`, it checks both + branches and records resource uses from the selected branch. This is enough + for `--check` to validate a program without loading model weights. +2. **Plan the run.** With auto-fit enabled, the runtime combines the graph's + weight-use phases with model parameter sizes, weights already resident in + the context, and current RAM and device budgets. It chooses where to keep + weights and respects explicit backend and split settings. Models first + encountered inside an iteration join the plan when their loader executes. +3. **Execute the graph.** The executor evaluates the bound calls in source + order and releases intermediate values after their last use. As execution + advances, the model manager uses the plan's next-use information to reclaim + idle weight buffers under memory pressure. The value returned by `main` + becomes the program result. + +## Built-ins, operations and models + +The registry describes a built-in's script name, parameters, defaults and +return type. The compiler uses that contract to check calls. At execution, +the binding converts script values to typed C++ arguments, calls an operation +or model loader, and wraps its result for the script. The same registry supplies +the [built-in function catalog](../dgl-builtins.md). + +Operations implement work such as sampling, tensor slicing and media decoding. +They take concrete tensors, model objects, options and event interfaces. Models +own their runners, weight registrations and model-specific inference. Operations +can call models. Both use shared tensor, backend and runtime primitives. Script +values, syntax, registry entries and executor state stay on the language side +of the binding. Model code is independent of operations and bindings. + +For example, a sampling run can use a classifier-free guidance (CFG) predictor. + +```dgl +pos = predictor(model, positive) +guided = cfg(pos, predictor(model, negative), scale = 7) +latent = sample(start, sigmas, predict = guided, rng = rng) +``` + +The first two statements describe which model and conditions to evaluate and how +to combine the predictions. They keep the model reachable. The sampling +operation drives the solver and evaluates that predictor at each required +step. The resource plan therefore accounts for diffusion weights during +`sample`. Each sampling call owns its own prediction history and progress state. + +## What the context retains + +A context owns backend settings, memory budgets and the model cache. A +persistent context can reuse a loaded component across scripts when its +normalized loader settings and source dependencies still match. A run-once +context can release it after its last use. Releasing a script binding and +evicting cached weights are therefore separate lifetime decisions. + +One context runs one program at a time. Each run gets a fresh placement plan +and its own progress, preview and cancellation state. Two runs of the same +source can choose different weight placement as cached resources or available +memory change. See [context execution settings](../dgl.md#context-execution-settings). diff --git a/docs/development/ggml_extensions.md b/docs/development/ggml_extensions.md index c643237f56..14894ac5cb 100644 --- a/docs/development/ggml_extensions.md +++ b/docs/development/ggml_extensions.md @@ -109,15 +109,13 @@ and backend `graph_plan_*` interfaces do not dispatch these extensions. ## Backend services -Packed ComfyUI INT4 linear layers use `sd.linear_w4_convrot.v1`, built by -`ggml_ext_mul_mat_w4_convrot`. The operator consumes byte-packed I8 weights and the -explicit output of `sd.quantize_i8_convrot.v1`; F32 callers get a quantization -node during graph construction. Logical output dimensions are stored in the -operator attributes, so backend copies of the packed activation do not need to -retain the producer's op marker. W4A4 uses row scales; W4A8 additionally exposes -the codebook, channel scales, and FP8 relative scales as tensor dependencies. -CPU, CUDA/HIP/MUSA, and Vulkan register kernels through the same extension API -as INT8. No ggml submodule changes are required. +ComfyUI W4A4 linear layers use `sd.linear_w4_convrot.v1`. W4A8 uses the same +`sd.linear_i8.v1` node as W8A8 with packed weights, a codebook, and FP8 relative +scales. The backend decodes that projection's weights into scheduler workspace +before running the shared INT8 GEMM with its channel scales. Both formats consume the explicit output of +`sd.quantize_i8_convrot.v1`. Logical output dimensions are stored in the linear +operator attributes so backend copies of the packed activation can be used +directly. Services are discovered through `ggml_backend_reg_get_proc_address`: @@ -172,6 +170,14 @@ CPU kernels and fusion rules live in `src/core/cpu/`, with registration collecte in `cpu/registration.cpp`. CUDA-style and Vulkan implementations live in their respective backend directories. +`sd.i8_lora_merge.v1` takes an INT8 weight, its F32 scale tensor, and an F32 LoRA +delta. It rotates the delta when the checkpoint uses convrot, adds it in the +stored weight's basis, and packs a status word, the new scales, and the INT8 +weight into one tensor. Graph copy nodes use integer views to write both +ranges into the cached weight buffers and retain only the status word for +finalization. The views use I32 for aligned ranges and I8 for byte copies. +Layouts without native copy support write back during graph finalization. + `src/core/metal/int8.mm` registers Metal INT8 linear and ConvRot kernels. Their Metal source is embedded at build time and compiled for the selected device during registration. The public `ggml-ext-metal.h` services expose borrowed @@ -278,7 +284,7 @@ backend paths have been removed. CPU, CUDA/HIP/MUSA, and Vulkan register kernels and fusion rules through the extension interfaces. For already quantized activations, `ggml_ext_mul_mat_i8_tensorwise` accepts ordinary -I8 weight and activation tensors. Its optional final `input_scale` parameter is a +I8 weight and activation tensors. Its optional `input_scale` parameter is a separate F32 tensor with one value per activation row. Weight scales have one value per output channel; weight scales and bias can be null. Existing calls omit `input_scale` and retain their original argument order. It computes `float(int32_dot(W, X)) * X_scale * W_scale + bias`, in that diff --git a/docs/development/model_config.md b/docs/development/model_config.md index 398211682f..7dba83221f 100644 --- a/docs/development/model_config.md +++ b/docs/development/model_config.md @@ -132,8 +132,9 @@ To add a model: 1. Add its identity to `SDVersion` without renumbering existing values. 2. Implement the network and `*Config::detect_from_weights` following the conventions above, or reuse an existing runner. -3. Add a definition in its integration file, including its component - factory, traits, geometry, and sampling policy. +3. Add a definition in its integration file with its display name, stable + lowercase DGL family ID, component factory, traits, geometry, and sampling + policy. Use underscores between words in the ID. 4. Add the family's explicit registration in `src/model_registry.cpp`. For a new variant of a registered family, add its definition to that family's list. 5. Add version detection signatures and any required weight-name mappings in @@ -175,6 +176,15 @@ and the output runners. Backend checks, optional IP-Adapter setup, scale overrides, and tokenizer usage validation remain in the common builder. A factory returns failure if any required additional backend cannot initialize. +`Context::params` contains `ModelBuildParams`, limited to model construction. +The native pipeline extracts these values from its `ContextConfig` at the +builder boundary. DGL uses its own typed `ModelLoadParams` for common loader +options and separate DiT, text encoder and VAE parameters for specialized +options. It does not store or convert through `ContextConfig`. Threading, +file mapping, caching and memory budgets belong to the DGL execution context. +The placement cache takes `PlacementOptions` rather than an entry point's +context configuration. + LLM architecture selection, tokenizer requirements, prompt preparation, and encoding remain centralized in `src/conditioning/conditioner.hpp`. Integration factories instantiate the conditioner with the model version; models requiring @@ -204,28 +214,35 @@ the values that differ from the struct defaults. `prediction_from_weights` and `flow_shift_from_weights` preserve checkpoint-dependent defaults during automatic prediction selection; `probe_v_prediction` enables SD2's runtime v-prediction probe. Explicit prediction settings take precedence over automatic selection. +In DGL the override belongs to `predictor`, rather than a model loader. A +resolved `Denoising` configuration supplies prediction scalings, time mapping +and noise conventions without changing the model's resource identity. Model +flow-shift defaults are resolved independently of an explicit prediction override. MOSS's default unconditional skip layer stays in the diffusion engine, with active unconditional SLG taking precedence. The resolved `prediction_t` selects the denoiser directly. Flux3, MiniMax H3 AV, and Ming-Image use `FLUX3_FLOW_PRED`, `H3_AV_FLOW_PRED`, and `MING_IMAGE_FLOW_PRED`; their CLI overrides are `flux3_flow`, `h3_av_flow`, and -`ming_image_flow`. Explicit `sd3_flow` always selects `DiscreteFlowDenoiser`, +`ming_image_flow`. Explicit `flow` always selects `DiscreteFlowDenoiser`, and `flux_flow` always selects `FluxFlowDenoiser`, regardless of model version. Automatic selection retains each model's default implementation. New prediction values are appended before `PREDICTION_COUNT`, preserving existing valid values; clients using the automatic-selection sentinel must rebuild with the new header. `ModelGeometry` declares `diffusion_down_factor`, `latent_channels`, and -`image_channels`. `ref_image_preset` defaults to `"default"`; set it only for models -that need another reference-image preset. - -The common pipeline executes these policies; specialized video, multimodal, -cache, and extension algorithms remain in their existing runtime components. -Model-specific diffusion extra parameters are assembled in the diffusion engine. -Video frame conversion and alignment also remain in the diffusion engine. -`get_vae_scale_factor()` retains PiD's pixel-space special case and otherwise -uses the VAE's scale factor. +`image_channels`. Reference-image workflow defaults belong to API program +generation and its DGL templates. Model definitions do not select shared +reference presets. C++ prepares reference sizes, buckets and crop coordinates; +templates express the pixel transformations and encoding calls. The rendered +program explicitly supplies prompt media and predictor reference latents. + +DGL executes the resulting program. Diffusion models consume reference latents, +`ref_index_mode` and `force_ref_timestep_zero`; a separate enable flag is not +needed. Text encoders retain their native patch alignment, normalization and +model-specific image processing. These model operations do not receive API +resizing or routing policies. Specialized video, multimodal, cache and extension +algorithms remain in their typed model and runtime components. Validate migrations against the previous implementation using synthetic metadata, name conversions, prompt preparation, default/override selection, and focused diff --git a/docs/development/pe_cache.md b/docs/development/pe_cache.md index e181959991..bc4a72d039 100644 --- a/docs/development/pe_cache.md +++ b/docs/development/pe_cache.md @@ -1,9 +1,9 @@ # Position embedding cache `sd::PECache` stores CPU-side `sd::Tensor` data. Each model runner owns -its cache and calls the existing `make_input()` on every graph build. Cache -hits skip PE generation; allocation and upload remain ordinary graph-input -operations. `GGMLRunner` has no PE-specific code or resource hooks. +its cache. A cache hit skips PE generation, and `make_input()` submits the CPU +data through ordinary graph-input allocation and upload. `GGMLRunner` has no +PE-specific code or resource hooks. The cache keeps the most recent key and tensor for each named PE input. A matching key returns the existing tensor by reference. Changing its parameters @@ -13,6 +13,12 @@ there is no LRU, device-buffer cache, memory budget, or graph lifecycle callback CPU data lives with the model runner, including across `runner_end()` calls, and is released when its named entry is replaced or the cache is destroyed. +On CUDA, HIP, and MUSA, LTXAV retains large video RoPE tensors in the existing +device runner cache during sampling. It stores each rotation as an FP32 2×2 matrix. +The tensors count against the runner's device memory budget. +The runner clears them when the position key changes or sampling ends. If +allocation fails, it clears the device cache and retries with the CPU inputs. + ## Adding a model Include `core/pe_cache.h` and declare a member: diff --git a/docs/development/pulid.md b/docs/development/pulid.md index b9ed66bee4..1bb876487c 100644 --- a/docs/development/pulid.md +++ b/docs/development/pulid.md @@ -38,9 +38,9 @@ a new combination of model + backend + hardware: | Run | Expected hash relation | |----------------------------------------------|------------------------------------| -| A: no `--pulid-*` flags | baseline | -| B: PuLID flags, `--pulid-id-weight 0.0` | **byte-identical to A** | -| C: PuLID flags, `--pulid-id-weight 1.0` | **different from A,B**, preserves source identity | +| A: DGL condition without `pulid::apply` | baseline | +| B: same script with `pulid::apply(..., strength = 0)` | **byte-identical to A** | +| C: same script with `pulid::apply(..., strength = 1)` | **different from A,B**, preserves source identity | If A and C differ but A and B differ too, the injection is allocating or computing something even at zero weight -- likely a bug. diff --git a/docs/development/weights.md b/docs/development/weights.md new file mode 100644 index 0000000000..24851c629e --- /dev/null +++ b/docs/development/weights.md @@ -0,0 +1,227 @@ +# Weight residency internals + +`src/weights/` holds weight residency logic that does not depend on runner or +graph code. It currently contains the residency snapshot and the reclaim +planner. `ModelManager` (`src/model_manager*.cpp`) still owns the allocations +and executes the planned actions; it is expected to move into this directory +later. For user-facing behavior, see +[weight residency](../guides/backend.md#weight-residency). + +## Responsibilities + +| Responsibility | Owner | +| --- | --- | +| Component placement: compute devices and params backend | `dgl/run_plan` (auto-fit) | +| Weight state: copies, shared aliases, leases, LoRA epochs, adapter weights | `ModelManager` | +| Reclaim decisions | `weights/reclaim_planner` (pure) | +| Reading weights from model files and mapping them | `weights/weight_reader` | +| Merging LoRA adapters: target matching, INT8 scales, merge graphs | `model/adapter/lora_merge` | +| Asynchronous uploads: queues, events, synchronization | `weights/weight_transfer` | +| Capacity of devices from a snapshot | `weights/accounting` (pure) | +| Source rules: which file data a weight reads, which weights share a copy | `weights/sources` (pure) | +| Copying weights into another buffer type | `weights/weight_copy` | +| When to prefetch | `core/segment_weight_pipeline` | +| Capacity sum of weights, workspaces and buffer pools; trimming pools | `core/execution_engine` | + +`ModelManager` knows where every weight copy is and changes copies safely. +Its `weights::WeightStore` (`weights/store`) owns the weight index, shared +aliases and copy bindings, together with the `TensorState` and block types. +`ModelManager` keeps its resources; a weight state holds its resource only as +an opaque identifier, and the store asks the owner through one policy callback +whether a weight's merge lives in a separate compute copy. Every +change to a binding, block membership, lease, merged version or file source goes +through the store; `TensorState` makes its residency transitions private to it. +A new block joins residency when it is handed to the store. Snapshot generation +and the execution of reclaim actions live in `model_manager_reclaim.cpp` and +change copies only through the store. Capacity queries collect a snapshot of each +device and evaluate it with `weights::evaluate_capacity()`, so a query reads no +live state after the snapshot and uses the same reclaimable bytes as execution. The reader, the merger +and the transfer receive destination tensors and never change bindings. The +reader takes read targets (loader, file, sources, destination) and knows +nothing about residency; staging from the model file reads straight into the +compute copy. The merger receives the targets that need separate compute +copies and returns success; `ModelManager` then records the merged epoch on +those copies. Adapter weights stay registered with `ModelManager`. + +`prepare_params()` (`model_manager_prepare.cpp`) runs three phases. Allocation, +reading, leases, merges and rollback share one lifecycle, so the flow and its +intermediate state stay inside `ModelManager`: `ensure_copies()` loads and stages the +weights, the LoRA layer groups the merge candidates by device, pairs INT8 +weights with their scales and merges, and `commit_merged()` records the version +on the copies of finished groups. `ensure_copies()` succeeds only when every +weight passes `ready_for_compute()`; a view is ready when the weight it views is, +and a loading or staging failure reports whether device memory ran out. +`lora_merge_target()` is the one place that decides which weights a resource's +LoRA version merges into; `pending_merges()` groups the targets still missing +the current version into units of a weight and its INT8 scale. The normal merge, +the batched merge and the final check all use these units, and +`merge_candidates()` only checks that each unit's copies are ready. The merge runs with every weight of the +request leased, so its own reclaim keeps them. Each adapter merges its targets +in batches of at most 4 GiB of F32 updates per graph; a batch that runs out of +device memory, which happens before the graph writes anything, is halved and +tried again. A batch writes its targets only after its graph succeeds, and later +batches resume after the targets already written, so no adapter is merged twice. +Capacity failures the merge recovers from are logged as information, not errors. + +If a single target does not fit next to the leased request, the merge first lets +unmodified params copies yield and resumes from its existing progress. If that +still does not fit, `merge_in_batches()` starts the unfinished work again from +the originals with only one batch of targets and their INT8 scales leased at a time. +The rest of the request stays unleased, so the merge can reclaim it. Completed +compute copies that need to leave the device spill to RAM if there is room, and +stage from that copy with their merged version intact. These RAM copies are +protected until the request is ready. Disk-resident weights may use this temporary +space too and drop it before the graph runs. A batch is split in half when its +copies or its merge graph do not fit, down to a single target. +This path needs host room for the merged copies that have to leave the device. +It checks that no copy lost its merge. Weights merged in place are batched too. +A request whose copies do not stage at all fails before entering this path, +since its merged copies are as large and would not fit at the end either. +The leases pass to the caller only when preparation +succeeds. On a failure or an exception, a scope guard releases them and drops +the copies the merge may have written: compute copies are discarded, and +weights merged in place reload from the model file. + +`ExecutionEngine` asks `ModelManager::plan_reclaim()` for actions, executes them +one at a time through `evict_compute_backend_block()`, and checks the real +capacity after each one. It does not rank candidates itself. Each action keeps +its kind (`ReclaimAction::Drop`, `Move` or `Release`) through execution. A move +releases the copy when no lower location has room. + +Whole-graph capacity is summed by the engine. `fits_after_reclaim()` adds the +idle workspaces of other sessions, which `ensure_capacity()` releases last, to +the weights' reclaimable bytes. The segmentation decision uses this sum, so it +counts the same memory that execution can free. The weight planner does not +see workspaces and stays testable on its own. + +## Weight state + +Each `TensorState` records its copies instead of residency flags. The storage +copy points at the `ParamsStorageBlock` holding the original, or a merge +applied to it in place. The compute copy points at the `ComputeStagingBlock` +the graph reads. Each copy carries the LoRA epoch merged into it. +`loaded()`, `staged()` and `applied_epoch()` derive from these bindings. Views +bind to a shared marker because their data lives in the base weight's +allocation. + +The residency fields are private: copy bindings, epochs, file source, +location, leases and the RAM cache of merged weights. They change only through +transitions on `TensorState`: + +| Transition | When | +| --- | --- | +| `bind_storage`, `unbind_storage` | Load, shared reuse, release | +| `bind_compute`, `unbind_compute` | Staging or prefetch activation, release | +| `mark_merged`, `reset_merges` | LoRA merge into the bound copy, LoRA change | +| `read_from_file` | The next compute copy reads the model file | +| `move_to` | The storage copy moves, or the next load target changes | +| `lease`, `release_lease`, `clear_leases` | Graph use | +| `cache_merged`, `drop_merged_cache` | RAM cache of merged weights | + +Debug builds check after loads and `prepare_params()` that every binding +matches block membership. + +## Snapshot + +`ModelManager::residency_snapshot()` describes one tier (a device or RAM) as +`weights::Allocation`s. Each allocation is a real buffer and lists the weight +`Copy`s it holds, so a buffer shared by several components counts once. + +| Kind | Meaning | +| --- | --- | +| `Compute` | Compute copy staged from a lower location or the model file | +| `Storage` | Params storage: an original, or a merge applied in place | +| `MergedCache` | RAM copy of merged LoRA weights | + +A copy records whether it is in use (`leased`), reserved by a prefetch, movable +(file-backed, not split, view or custom-operator), `superseded` by another copy +that serves the weight now, and whether a lower residency location exists. The +model file is the implicit lowest location of every file-backed weight. + +An original is superseded when its merged LoRA copy is separate, or, in RAM, +when a compute copy already holds it. Pins and protection of the weight do not +keep a superseded copy. Originals that need a separate merged copy are +allocated in storage blocks of their own, so a block of superseded originals +never also holds weights the graph reads in place. On the device, the adapter +weights of immediate LoRAs count as superseded while no merge uses them: they +only feed merges, which load them again. + +## Planner + +`weights::plan_reclaim(snapshot, request)` returns ordered actions: + +| Action | Effect | +| --- | --- | +| `Drop` | Free a copy that has another copy or the model file below it | +| `Move` | Copy to the next residency location, then free | +| `Release` | Free the only copy above the model file | + +Each action reports its bytes and the bytes of the request's own weights that +must load again afterwards. Which allocations an action may touch does not +depend on the order, so capacity checks (`weights::reclaimable_bytes()`) sum the +net bytes of the same actions without ordering them, and only execution +(`ModelManager::plan_reclaim()`) sorts them and resolves their weights. Both +use the same `weights::Request` to build the snapshot, so the segmentation +decision and the executed reclaim follow one rule set. Reload bytes use the device allocation size, +including padding and alignment. + +Device order: + +1. Superseded device originals of merged weights. +2. Weights needed later by the current plan. +3. Actions that reload none of the request's weights. +4. Drops and releases before moves. +5. The caller's preferred eviction order, then least recently used. + +RAM order: merged caches oldest first, then weights needed later, then shared +compute copies, then least recently used. + +An evicted merged compute copy is saved to a RAM cache in the compute device's +pinned host memory when it fits. Segment prefetch uploads a current cache +asynchronously, like an offloaded original, and the uploaded copy keeps the +cache's LoRA version. An INT8 weight is prefetched from its cache only together +with its scale; otherwise it stages synchronously. An upload of an original +records the original's merged version when it is queued, and activation drops +the upload when a merge in place changed the original since. + +Request options cover the other callers: + +| Option | Used by | +| --- | --- | +| `required` | Segment weights that may leave and load again | +| `protected_weights` | Weights that must stay, such as the next prefetch | +| `allow_moves = false` | Making room for a move; victims are released | +| `keep_resources`, `keep_next_use` | First loads. Originals of their own component and of components needed sooner stay, against both moves and releases | +| `priority_limit` | RAM room for a demotion; victims must have a lower priority | + +Session cleanup and `assign_compute_backend()` select actions from the same +candidates. Auto-fit's RAM estimate (`available_ram_for_fit()`) sums the RAM +plan. + +## Call direction + +``` +ExecutionEngine --implements--> weights::CapacityProvider <--reserve-- ModelManager +ExecutionEngine --plan_reclaim / evict_compute_backend_block--> ModelManager +ModelManager::prepare_params --merge_candidates--> lora_merge +``` + +Weight allocations reserve device memory through `CapacityProvider`. The +runtime implements it, sums weights, workspaces and buffer pools, and executes +the residency layer's reclaim plan. `ModelManager` does not call the execution +engine otherwise. + +## Execution + +`prepare_params()` loads, stages, and merges weights. A reclaim made for the +request can release the request's own weights when the plan counts their reload +bytes, so loading and staging repeat until a pass leaves every weight in place. +During a merge, only compute copies and in-place targets are pinned. + +## Planned migration + +The remaining `ModelManager` files move into `src/weights/` without behavior +changes, together with `device_residency_manager.h`, +`core/segment_weight_pipeline` and the RAM and GPU budget helpers from +`core/backend_fit`. `ExecutionEngine` then depends only on the residency +interface header. diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md new file mode 100644 index 0000000000..c9a830bc14 --- /dev/null +++ b/docs/dgl-builtins.md @@ -0,0 +1,215 @@ + +# Built-in DGL functions + +Optional parameters are marked with `?`. Default values follow `=`. See [DGL syntax](dgl.md#dgl-syntax) for `fn`, `map` and `fold`. + +| Function | Parameters | Returns | +|---|---|---| +| `add_noise` | `predict: predictor`, `base: tensor`, `noise: tensor`, `sigma: number` | `tensor` | +| `animatediff::apply` | `model: denoiser`, `motion: animatediff` | `denoiser` | +| `animatediff::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `animatediff` | +| `apg` | `positive: predictor`, `negative: predictor`, `scale: number`, `image_only?: predictor`, `image_scale?: number = 1`, `schedule?: list`, `eta?: number = 1`, `momentum?: number = 0`, `norm_threshold?: number = 0`, `norm_threshold_smoothing?: number = 0` | `predictor` | +| `apply_lora` | `model: model`, `lora: lora`, `weight?: number = 1.0`, `mode?: string` | same type as `model` | +| `audio::load` | `path: string` | `dict`
`sample_rate: int`
`samples: tensor` | +| `audio::save` | `path: string`, `audio: dict`, `format?: string = "f32"` | `void` | +| `audio_latent_shape` | `vae: audio_vae`, `frames: int`, `fps: int` | `tensor` | +| `audio_vae_decode` | `vae: audio_vae`, `latent: tensor` | `dict`
`sample_rate: int`
`samples: tensor` | +| `audio_vae_encode` | `vae: audio_vae`, `samples: tensor`, `sample_rate: int` | `tensor` | +| `cache` | `mode?: string = "disabled"`, `reuse_threshold?: number`, `start_percent?: number`, `end_percent?: number`, `error_decay_rate?: number`, `use_relative_threshold?: bool`, `reset_error_on_compute?: bool`, `residual_diff_threshold?: number`, `max_warmup_steps?: int`, `max_cached_steps?: int`, `max_continuous_cached_steps?: int`, `taylorseer_n_derivatives?: int`, `taylorseer_skip_interval?: int`, `scm_mask?: string`, `spectrum_w?: number`, `spectrum_m?: int`, `spectrum_lam?: number`, `spectrum_window_size?: int`, `spectrum_flex_window?: number`, `spectrum_warmup_steps?: int`, `spectrum_stop_percent?: number` | `dict`
`end_percent: number`
`error_decay_rate: number`
`max_cached_steps: int`
`max_continuous_cached_steps: int`
`max_warmup_steps: int`
`mode: string`
`reset_error_on_compute: bool`
`residual_diff_threshold: number`
`reuse_threshold: number`
`scm_mask: string`
`spectrum_flex_window: number`
`spectrum_lam: number`
`spectrum_m: int`
`spectrum_stop_percent: number`
`spectrum_w: number`
`spectrum_warmup_steps: int`
`spectrum_window_size: int`
`start_percent: number`
`taylorseer_n_derivatives: int`
`taylorseer_skip_interval: int`
`use_relative_threshold: bool` | +| `cfg` | `positive: predictor`, `negative: predictor`, `scale: number`, `image_only?: predictor`, `image_scale?: number = 1`, `schedule?: list` | `predictor` | +| `controlnet::apply` | `condition: dict`, `model: control_net`, `hint: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number`, `type?: string = "none"` | same type as `condition`
`controls: control_bindings` | +| `controlnet::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `control_net` | +| `denoiser_scalings` | `predict: predictor`, `sigma: number` | `dict`
`input_scale: number`
`output_scale: number`
`skip_scale: number` | +| `detections::box_masks` | `image: tensor`, `detections: dict` | `list` | +| `detections::detect` | `detector: detector`, `image: tensor`, `input_size?: int = 640`, `confidence?: number = 0.3`, `nms?: number = 0.45`, `max_detections?: int = 100` | `dict`
`class_ids: tensor`
`scores: tensor`
`xyxy: tensor` | +| `detections::filter` | `image: tensor`, `detections: dict`, `top_k?: int = 0`, `top_k_by?: string = "area"`, `min_area_ratio?: number = 0`, `max_area_ratio?: number = 1`, `sort_by?: string = "none"` | `dict`
`class_ids: tensor`
`scores: tensor`
`xyxy: tensor` | +| `detections::to_regions` | `image: tensor`, `detections: dict` | `dict`
`boxes: tensor`
`height: int`
`width: int` | +| `dit_to_vae_latents` | `vae: vae`, `latent: tensor` | `tensor` | +| `encode_audio` | `encoder: audio_encoder`, `samples: tensor`, `sample_rate: int` | `tensor` | +| `encode_prompt` | `encoder: text_encoder`, `text: string`, `width?: int = 512`, `height?: int = 512`, `clip_skip?: int = -1`, `system?: string`, `media?: list`, `image_bindings?: dict`, `raw?: bool = false` | `dict`
`concat: tensor`
`crossattn: tensor`
`extra_crossattn: list`
`image_embed_indices: list`
`image_embeds: list`
`input_ids: tensor`
`position_ids: tensor`
`ref_audios: list`
`ref_images: list`
`reference_blocks: list`
`reference_blocks.audio: int`
`reference_blocks.kind: string`
`reference_blocks.video: int`
`t5_ids: tensor`
`t5_weights: tensor`
`token_types: tensor`
`vector: tensor`
`vinput_mask: tensor` | +| `encode_vision` | `encoder: vision_encoder`, `image: tensor`, `pooled?: bool = false`, `clip_skip?: int = -2`, `zero?: bool = false`, `zero_input?: bool = false` | `tensor` | +| `image::canny` | `image: tensor`, `high_threshold?: number = 0.08`, `low_threshold?: number = 0.04`, `weak?: number = 0.5`, `strong?: number = 1`, `invert?: bool = false` | `tensor` | +| `image::encode` | `image: tensor`, `format?: string = "png"` | `dict`
`data: bytes`
`mime_type: string` | +| `image::load` | `path: string` | `tensor` | +| `image::load_dir` | `path: string`, `max_images?: int = 0` | `list` | +| `image::save` | `path: string`, `image: tensor` | `void` | +| `image::to_f32` | `image: tensor`, `channels?: int = 0` | `tensor` | +| `image::to_u8` | `pixels: tensor` | `tensor` | +| `ip_adapter::apply` | `condition: dict`, `adapter: ip_adapter`, `tokens: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number` | same type as `condition`
`ip_adapters: ip_adapter_bindings` | +| `ip_adapter::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `ip_adapter` | +| `ip_adapter::project` | `adapter: ip_adapter`, `embedding: tensor` | `tensor` | +| `latent_shape` | `vae: vae`, `width: int`, `height: int`, `batch?: int = 1`, `frames?: int` | `tensor` | +| `list::replace` | `items: list`, `index: int`, `value: any` | `list` | +| `load_audio_encoder` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `audio_encoder` | +| `load_audio_vae` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `family_from?: string = ""`, `linear_type?: string = "auto"` | `audio_vae` | +| `load_detector` (resource) | `path: string`, `backend?: string = ""`, `params_backend?: string = ""`, `linear_type?: string = "auto"` | `detector` | +| `load_dit` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"`, `weights_override?: string = ""` | `denoiser` | +| `load_latent_upscaler` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `latent_upscaler` | +| `load_lora` (resource) | `path: string` | `lora` | +| `load_tae` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `family_from?: string = ""`, `decode_only?: bool = false`, `linear_type?: string = "auto"` | `vae` | +| `load_text_encoder` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `family_from?: string = ""`, `tokenizer?: string = ""`, `vision_path?: string = ""`, `projection_path?: string = ""`, `connectors_path?: string = ""`, `t5_path?: string = ""`, `clip_l_path?: string = ""`, `clip_g_path?: string = ""`, `linear_type?: string = "auto"` | `text_encoder` | +| `load_unet` (resource) (alias of `load_dit`) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"`, `weights_override?: string = ""` | `denoiser` | +| `load_upscaler` (resource) | `path: string`, `tile_size?: int = 128`, `backend?: string = ""`, `params_backend?: string = ""`, `direct?: bool = false`, `linear_type?: string = "auto"` | `upscaler` | +| `load_vae` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `family_from?: string = ""`, `vae_format?: string = "auto"`, `linear_type?: string = "auto"` | `vae` | +| `load_vision_encoder` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `vision_encoder` | +| `ltx::video_positions` | `like: tensor`, `keyframe_latent_frames: int`, `keyframe_frame_index: int`, `keyframe_pixel_frames: int`, `fps?: int = 24`, `spatial_scale?: int = 32`, `temporal_scale?: int = 8`, `causal?: bool = true` | `tensor` | +| `make_rng` | `algorithm?: string = "cuda"`, `seed?: int = 0` | `rng` | +| `make_sigmas` | `predict: predictor`, `latent: tensor`, `scheduler?: string = "discrete"`, `steps: int`, `flow_shift?: number = 0`, `sequence_length?: int`, `extra_args?: string = ""` | `tensor` | +| `math::add` | `a: number`, `b: number` | `number` | +| `math::ceil` | `value: number` | `int` | +| `math::ceil_div` | `numerator: int`, `denominator: int` | `int` | +| `math::div` | `a: number`, `b: number` | `number` | +| `math::floor` | `value: number` | `int` | +| `math::min` | `a: int`, `b: int` | `int` | +| `math::mul` | `a: number`, `b: number` | `number` | +| `math::product` | `items: i64 tensor or list` | `int` | +| `math::round` | `value: number` | `int` | +| `math::sub` | `a: number`, `b: number` | `number` | +| `media::save` | `path: string`, `media: dict` | `void` | +| `photomaker::apply` | `condition: dict`, `photomaker: photomaker`, `tokens: tensor`, `mask: tensor` | same type as `condition`
`crossattn: tensor` | +| `photomaker::encode_images` | `photomaker: photomaker`, `images: list`, `id_embedding?: tensor` | `tensor` | +| `photomaker::encode_prompt` | `encoder: text_encoder`, `text: string`, `tokens: tensor`, `width?: int = 1024`, `height?: int = 1024`, `clip_skip?: int = -1` | `dict`
`condition: dict`
`condition.concat: tensor`
`condition.crossattn: tensor`
`condition.extra_crossattn: list`
`condition.image_embed_indices: list`
`condition.image_embeds: list`
`condition.input_ids: tensor`
`condition.position_ids: tensor`
`condition.ref_audios: list`
`condition.ref_images: list`
`condition.reference_blocks: list`
`condition.reference_blocks.audio: int`
`condition.reference_blocks.kind: string`
`condition.reference_blocks.video: int`
`condition.t5_ids: tensor`
`condition.t5_weights: tensor`
`condition.token_types: tensor`
`condition.vector: tensor`
`condition.vinput_mask: tensor`
`mask: tensor`
`plain: dict`
`plain.concat: tensor`
`plain.crossattn: tensor`
`plain.extra_crossattn: list`
`plain.image_embed_indices: list`
`plain.image_embeds: list`
`plain.input_ids: tensor`
`plain.position_ids: tensor`
`plain.ref_audios: list`
`plain.ref_images: list`
`plain.reference_blocks: list`
`plain.reference_blocks.audio: int`
`plain.reference_blocks.kind: string`
`plain.reference_blocks.video: int`
`plain.t5_ids: tensor`
`plain.t5_weights: tensor`
`plain.token_types: tensor`
`plain.vector: tensor`
`plain.vinput_mask: tensor` | +| `photomaker::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `photomaker` | +| `predictor` | `model: denoiser`, `condition: dict`, `prediction?: string = "auto"`, `concat?: tensor`, `ref_latents?: list`, `ref_audios?: list`, `reference_blocks?: list`, `keyframe_indices?: list`, `ref_index_mode?: string = "fixed"`, `force_ref_timestep_zero?: bool = false`, `ref_rope_anchor?: string = "default"`, `guidance?: number = 3.5`, `skip_layers?: list`, `vace_context?: tensor`, `vace_strength?: number = 1`, `audio_embedding?: tensor`, `video_positions?: tensor`, `audio_length?: int = 0`, `fps?: number = 24`, `video_sigma_shift?: number = 12`, `audio_sigma_shift?: number = 3`, `circular_x?: bool = false`, `circular_y?: bool = false`, `transform?: fn`, `transform_args?: dict` | `predictor` | +| `preview` | `decoder?: vae`, `circular_x?: bool = false`, `circular_y?: bool = false` | `sampling_observer` | +| `pulid::apply` | `condition: dict`, `pulid: pulid`, `embedding: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number` | same type as `condition`
`pulid: pulid_bindings` | +| `pulid::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `pulid` | +| `pulid::load_embedding` | `path: string` | `tensor` | +| `regions::crop` | `image: tensor`, `regions: dict` | `list` | +| `regions::from_boxes` | `width: int`, `height: int`, `boxes: any` | `dict`
`boxes: tensor`
`height: int`
`width: int` | +| `regions::paste` | `background: tensor`, `foregrounds: list`, `regions: dict` | `tensor` | +| `regions::plan_mask_crops` | `masks: list`, `aspect?: i64 tensor or list = [1, 1]`, `padding?: int = 32`, `only_masked?: bool = true` | `list`
`box: tensor`
`index: int`
`mask: tensor` | +| `relayvsr::decode` | `flash: vae`, `latent: tensor`, `frames: tensor`, `keyframe_indices: tensor`, `detail?: number = 1` | `tensor` | +| `relayvsr::latent_shape` | `dit: denoiser`, `keyframes: tensor` | `tensor` | +| `relayvsr::positive_embedding` | `dit: denoiser` | `tensor` | +| `sample` | `start: tensor`, `sigmas: tensor`, `predict: predictor`, `rng: rng`, `method?: string = "euler"`, `eta?: number = 1`, `base?: tensor`, `denoise_mask?: tensor`, `mask_input?: bool = false`, `extra_args?: string = ""`, `finish?: bool`, `cache?: dict`, `observer?: sampling_observer` | `tensor` | +| `seedvr2::positive_embedding` | `dit: denoiser` | `tensor` | +| `sefi::make_sigmas` | `steps: int`, `alpha?: number = 1`, `delta?: number = 0.1` | `dict`
`semantic_sigmas: tensor`
`sigmas: tensor` | +| `sefi::sample` | `start: tensor`, `sigmas: tensor`, `semantic_sigmas: tensor`, `predict: predictor`, `rng: rng`, `method?: string = "euler"`, `eta?: number = 1`, `base?: tensor`, `denoise_mask?: tensor`, `mask_input?: bool = false`, `extra_args?: string = ""`, `finish?: bool`, `cache?: dict`, `observer?: sampling_observer` | `tensor` | +| `slg` | `base: predictor`, `positive: predictor`, `skipped: predictor`, `scale: number`, `start_sigma?: number`, `end_sigma?: number`, `start_step_fraction?: number`, `stop_step_fraction?: number` | `predictor` | +| `switch_predictor` | `before: predictor`, `after: predictor`, `after_steps: int` | `predictor` | +| `t_to_sigma` | `predict: predictor`, `t: number`, `flow_shift?: number = 0`, `latent?: tensor`, `sequence_length?: int` | `number` | +| `tensor::add` | `a: any`, `b: any` | `tensor` | +| `tensor::affine` | `input: tensor`, `scale?: number = 1`, `offset?: number = 0` | `tensor` | +| `tensor::arange` | `start: int`, `end: int`, `step?: int = 1` | `tensor` | +| `tensor::broadcast_to` | `input: tensor`, `shape: i64 tensor or list` | `tensor` | +| `tensor::cast` | `input: tensor`, `dtype: string` | `tensor` | +| `tensor::clamp` | `input: tensor`, `min: number`, `max: number` | `tensor` | +| `tensor::concat` | `items: list`, `axis: int` | `tensor` | +| `tensor::count_nonzero` | `input: tensor` | `int` | +| `tensor::crop` | `input: tensor`, `axes: i64 tensor or list`, `start: i64 tensor or list`, `size: i64 tensor or list` | `tensor` | +| `tensor::div` | `a: any`, `b: any` | `tensor` | +| `tensor::full` | `shape: i64 tensor or list`, `value: number`, `dtype?: string = "f32"` | `tensor` | +| `tensor::gaussian_blur` | `input: tensor`, `sigma: number`, `radius: int`, `axes?: i64 tensor or list`, `precision?: string = "auto"` | `tensor` | +| `tensor::grayscale` | `input: tensor`, `axis?: int = 0` | `tensor` | +| `tensor::index` | `input: tensor`, `indices: list` | `any` | +| `tensor::index_fill` | `input: tensor`, `axis: int`, `indices: i64 tensor or list`, `value: number` | `tensor` | +| `tensor::index_select` | `input: tensor`, `axis: int`, `indices: i64 tensor or list` | `tensor` | +| `tensor::interpolate` | `input: tensor`, `size: i64 tensor or list`, `axes?: i64 tensor or list`, `mode?: string = "bilinear"`, `antialias?: bool = false` | `tensor` | +| `tensor::lerp` | `a: any`, `b: any`, `weight: any` | `tensor` | +| `tensor::literal` | `dtype: string`, `shape: i64 tensor or list`, `data: string` | `tensor` | +| `tensor::load` | `path: string` | `tensor` | +| `tensor::max_pool2d` | `input: tensor`, `kernel: i64 tensor or list`, `axes?: i64 tensor or list`, `stride?: i64 tensor or list`, `padding_before?: i64 tensor or list`, `padding_after?: i64 tensor or list`, `pad_value?: number` | `tensor` | +| `tensor::maximum` | `a: tensor`, `b: tensor` | `tensor` | +| `tensor::min_pool2d` | `input: tensor`, `kernel: i64 tensor or list`, `axes?: i64 tensor or list`, `stride?: i64 tensor or list`, `padding_before?: i64 tensor or list`, `padding_after?: i64 tensor or list`, `pad_value?: number` | `tensor` | +| `tensor::mul` | `a: any`, `b: any` | `tensor` | +| `tensor::numel` | `input: tensor` | `int` | +| `tensor::pad` | `input: tensor`, `pad: i64 tensor or list`, `mode?: string = "constant"`, `value?: number = 0` | `tensor` | +| `tensor::permute` | `input: tensor`, `axes: i64 tensor or list` | `tensor` | +| `tensor::randn_like` | `like: tensor`, `rng: rng` | `tensor` | +| `tensor::replace_slice` | `input: tensor`, `value: tensor`, `axis: int`, `start: int` | `tensor` | +| `tensor::reshape` | `input: tensor`, `shape: i64 tensor or list` | `tensor` | +| `tensor::save` | `path: string`, `tensor: tensor` | `void` | +| `tensor::shape` | `input: tensor` | `tensor` | +| `tensor::threshold` | `input: tensor`, `threshold: number`, `low?: number = 0`, `high?: number = 1` | `tensor` | +| `tensor::to_list` | `input: tensor`, `element?: string = "auto"` | `list` | +| `tensor::translate` | `input: tensor`, `axes: i64 tensor or list`, `offset: i64 tensor or list`, `value?: number = 0` | `tensor` | +| `tensor::unsqueeze` | `input: tensor`, `axis: int` | `tensor` | +| `tensor::vector` | `values: list`, `dtype?: string = "f32"` | `tensor` | +| `tensor::zeros` | `shape: i64 tensor or list`, `dtype?: string = "f32"` | `tensor` | +| `tensor::zeros_like` | `like: tensor` | `tensor` | +| `tiling` | `enabled?: bool = true`, `temporal_tiling?: bool = false`, `tile_size_w?: int = 0`, `tile_size_h?: int = 0`, `target_overlap?: number = 0.5`, `rel_size_w?: number = 0`, `rel_size_h?: number = 0`, `extra_args?: string = ""` | `dict`
`enabled: bool`
`extra_args: string`
`rel_size_h: number`
`rel_size_w: number`
`target_overlap: number`
`temporal_tiling: bool`
`tile_size_h: int`
`tile_size_w: int` | +| `unet_to_vae_latents` (alias of `dit_to_vae_latents`) | `vae: vae`, `latent: tensor` | `tensor` | +| `upscale` | `upscaler: upscaler`, `image: tensor`, `factor?: int` | `tensor` | +| `upscale_latent` | `upscaler: latent_upscaler`, `latent: tensor`, `width?: int`, `height?: int` | `tensor` | +| `vae_decode` | `vae: vae`, `latent: tensor`, `tiling?: dict`, `circular_x?: bool = false`, `circular_y?: bool = false`, `dtype?: string = "u8"` | `tensor` | +| `vae_encode` | `vae: vae`, `pixels: tensor`, `rng: rng`, `tiling?: dict`, `circular_x?: bool = false`, `circular_y?: bool = false`, `posterior?: string = "sample"` | `tensor` | +| `vae_to_dit_latents` | `vae: vae`, `latent: tensor` | `tensor` | +| `vae_to_unet_latents` (alias of `vae_to_dit_latents`) | `vae: vae`, `latent: tensor` | `tensor` | +| `video::encode` | `video: dict`, `audio?: dict`, `format?: string = "webm"` | `dict`
`data: bytes`
`mime_type: string` | +| `video::join_windows` | `windows: list`, `overlap?: int = 0` | `tensor` | +| `video::load` | `path: string`, `max_frames?: int = 0`, `fps_num?: int = 0`, `fps_den?: int = 1`, `audio?: bool = true` | `dict`
`audio: dict`
`audio.sample_rate: int`
`audio.samples: tensor`
`video: dict`
`video.fps_den: int`
`video.fps_num: int`
`video.frames: tensor` | +| `video::save` | `path: string`, `video: dict`, `audio?: dict`, `trim_audio?: bool = false`, `codec?: string = "auto"`, `quality?: int = 90`, `audio_format?: string = "f32"` | `void` | +| `video::split_windows` | `frames: tensor`, `size: int`, `overlap?: int = 0` | `list` | +| `wan::s2v_audio_window` | `embedding: tensor`, `latent_frames: int` | `tensor` | +| `zero_out` | `condition: dict`, `fields?: list` | same type as `condition` | + +## Model family IDs + +Pass the ID as the component loader's `family` argument. The default is `"auto"`. + +| ID | Model family | +|---|---| +| `sd1` | SD 1.x | +| `sd1_inpaint` | SD 1.x Inpaint | +| `sd1_pix2pix` | Instruct-Pix2Pix | +| `sd1_tiny_unet` | SD 1.x Tiny UNet | +| `sd2` | SD 2.x | +| `sd2_inpaint` | SD 2.x Inpaint | +| `sd2_tiny_unet` | SD 2.x Tiny UNet | +| `sdxs_512_ds` | SDXS (512-DS) | +| `sdxs_09` | SDXS (09) | +| `sdxl` | SDXL | +| `sdxl_inpaint` | SDXL Inpaint | +| `sdxl_pix2pix` | SDXL Instruct-Pix2Pix | +| `sdxl_vega` | SDXL (Vega) | +| `sdxl_ssd1b` | SDXL (SSD1B) | +| `svd` | SVD | +| `sd3` | SD3.x | +| `flux` | Flux | +| `flux_fill` | Flux Fill | +| `flux_control` | Flux Control | +| `flex2` | Flex.2 | +| `chroma_radiance` | Chroma Radiance | +| `wan2` | Wan 2.x | +| `wan2_2_i2v` | Wan 2.2 I2V | +| `wan2_2_ti2v` | Wan 2.2 TI2V | +| `wan2_2_s2v` | Wan 2.2 S2V | +| `lingbot_video` | LingBot Video | +| `qwen_image` | Qwen Image | +| `qwen_image_layered` | Qwen Image Layered | +| `qwen_image_2_1` | Qwen Image 2.1 | +| `hunyuan_video` | Hunyuan Video | +| `anima` | Anima | +| `flux2` | Flux.2 | +| `flux2_klein` | Flux.2 klein | +| `ltxav` | LTXAV | +| `minimax_h3` | MiniMax-H3 | +| `hidream_o1` | HiDream O1 | +| `z_image` | Z-Image | +| `boogu_image` | Boogu Image | +| `ovis_image` | Ovis Image | +| `ernie_image` | Ernie Image | +| `lens` | Lens | +| `minit2i` | MiniT2I | +| `longcat_image` | Longcat-Image | +| `pid` | PiD | +| `ideogram4` | Ideogram 4 | +| `sefi_image` | SeFi-Image | +| `krea2` | Krea2 | +| `mage_flow` | Mage Flow | +| `sensenova_u1_5` | SenseNova U1.5 | +| `llada_image` | LLaDA-Image | +| `esrgan` | ESRGAN | +| `pixart` | PixArt | +| `ming_image` | Ming-Image | +| `z_image_l2p` | Z-Image L2P | +| `iris_3b` | Iris-3B | +| `flux3_klein` | Flux.3 Image Klein | +| `moss_image` | MOSS-Image | +| `fibo2` | Fibo-2.0 | +| `chroma` | Chroma | +| `p_h3_image` | P-H3-Image | +| `minimax_h3_image` | MiniMax-H3-Image | +| `relayvsr` | RelayVSR | +| `seedvr2` | SeedVR2 | diff --git a/docs/dgl.md b/docs/dgl.md new file mode 100644 index 0000000000..64a5558966 --- /dev/null +++ b/docs/dgl.md @@ -0,0 +1,1949 @@ +# DGL scripting guide + +Use DGL (Diffusion Graph Language) to compose model and tensor operations in a +script. Values can feed several calls, and functions can process lists. A script +can load its own models and media or receive named input tensors from a host. +Applications can generate a complete script from request settings. + +- **Getting started** · [Build and run](#build-and-run) · [Model examples](dgl/README.md) +- **Writing scripts** · [Language syntax](#dgl-syntax) · [Tensor operations and indexing](#tensor-functions) · [Built-in catalog](dgl-builtins.md) +- **Generation** · [Models and sampling](#independent-generation-components) · [Media I/O](#image-and-video-files) · [Regions and masks](#regions-and-masks) · [Worked examples](#advanced-component-programs) +- **Embedding DGL** · [C API](#c-api) · [Architecture](development/dgl.md) + +## Build and run + +```sh +cmake -S . -B build-dgl -DSD_BUILD_EXAMPLES=ON -DSD_WEBP=OFF -DSD_WEBM=OFF +cmake --build build-dgl --config Release --target sd-cli +``` + +Use the normal backend build options, such as `-DSD_CUDA=ON`, when needed. + +Save the following program as `tensor-example.dgl`. It runs without model weights. + +```dgl +# version: 0.0.0 +fn main() { + return tensor::zeros([4, 4]) +} +``` + +```sh +./build-dgl/bin/sd-cli -M dgl --script tensor-example.dgl --tensor result tensor.npy +``` + +For generation, edit the model path, prompt and seed in the [SD 1.5 example](dgl/sd/sd1-5-txt2img.dgl). + +```sh +./build-dgl/bin/sd-cli -M dgl --script docs/dgl/sd/sd1-5-txt2img.dgl --check +./build-dgl/bin/sd-cli -M dgl --script docs/dgl/sd/sd1-5-txt2img.dgl --tensor latent latent.npy +``` + +To repeat a run, execute the same `.dgl` file again with the same input files. + +`--check` checks syntax, function signatures, references and static types without +loading weights. It does not check model-specific tensor compatibility. + +`--tensor NAME FILE.npy` exports a named output, and can be repeated. The result +summary and tensor names appear in the verbose log (`-v`). `image::save(..., pixels)` +writes PNG files during execution. Rerunning the script writes to the same paths. +Paths are relative to the process working directory. + +DGL mode uses the CLI's log levels and prints logs to stderr. The default level +is `info` (`[I]`). Use `-v` or `--verbose` for verbose (`[V]`) logs, and +`--log-level debug` to include debug (`[D]`) logs. +Sampling reports its method and step count at the start, and elapsed time on +completion, at the info level. + +## DGL syntax + +Execution starts at the single `fn main()` declaration. Standalone scripts use +a zero-argument entry point. + +Use an optional `var { ... }` block before the functions to group values +such as model paths, prompts, and seeds. Each entry is a scalar, list, or +dict literal. The names are available directly in `main()` as if their +bindings appeared at the start of its body. + +```dgl +var { + seeds = [41, 42] +} + +fn next_seed(seed) { + return seed + 1 +} + +fn main() { + return map(seeds, process = next_seed) +} +``` + +### Functions and bindings + +- Declare user-defined functions at file scope using the `fn` keyword and + pass values to them as arguments. Put local bindings inside a function. + When constructing a script, encode string values as JSON string literals. +- Bind each name once, and reference values declared earlier in the same scope. + Names in `var` share the entry point's binding scope. + Positional arguments precede named arguments. Unknown or duplicate arguments + are errors. Argument expressions are evaluated left to right as written at the + call site. A `return` statement, when present, must be last. A function may + finish without a return value, or use bare `return;` to finish explicitly. +- Call functions such as `image::save(...)` directly as statements. Saving + functions return `void`; using them in assignments, arguments, containers + or returned expressions is a compile-time error. +- Strings use JSON escaping. Comments start with `#` or `//`, on their own line + or after code. Only `# version: ...` is reserved for the file's version header. + Semicolons are optional. Lists use `[a, b]`. A dictionary (`dict`) groups + named values using `{name = value, ...}`. Access a field with `dict_value.name`. + A prompt condition contains the fields supplied by its encoder. Reading an + absent field reports its name and source location. See how to read the + [built-in return types](#built-in-functions). +- Functions run sequentially. Recursion, cycles and runtime-dependent control + flow are not supported. Intermediate values are released after their last use + unless a function retains them or the program returns them. + +### Lists, map and fold + +- `map(items, process = function, other_parameter = value)` passes each item as + the first function parameter. Additional arguments are shared across calls. +- `fold(items, initial, process = function, other_parameter = value)` passes + the previous result and the current item as the first two parameters. The + function must return the same type and fields as `initial`. An empty typed + list returns `initial`. +- `items[index]` selects a list element; `items[start:end]` selects a list slice. + `tensor::to_list(tensor::arange(seed, seed + count))` supplies consecutive + integer seeds to `map`. The range end is exclusive. +- Lists contain one element type; integer and floating-point literals may be + mixed in numeric lists. With a list of dictionaries, `map`, `fold` and + dynamic indexing expose shared fields and consistent tensor dtype/rank facts. + A known index into a known list keeps the selected item's own information. + `list::replace` requires a replacement compatible with the list's element + type; incompatible types are rejected during compilation. + +### Conditional expressions + +Use `if condition { expression } else { expression }` to choose a value: + +```dgl +result = if enable_refiner { refine(latent) } else { latent } +``` + +The condition must be a boolean known before resource planning, such as a +`var` value or a literal passed to a function. Conditions derived from tensors, +model outputs or runtime function calls are rejected. Both branches are checked +for valid calls and matching result types and dictionary fields, even when one +is disabled. Each branch can contain local bindings and standalone calls, +followed by a final expression that supplies its result. An `if` used as a value +requires `else`. Conditional expressions can be nested, used as arguments, +indexed or returned. +A conditional used as a standalone statement discards its result, including +`void` results. + +```dgl +result = if enable_refiner { + refiner = load_unet(refiner_weights) + enlarged = tensor::interpolate(latent, [128, 128]) + refine(enlarged, refiner) +} else { + latent +} +``` + +Each branch has its own scope and can read outer bindings. Local names are +unavailable outside the branch, and the two branches may use the same local +names. Bind each name once; shadowing an outer binding is rejected. Use the +final expression instead of `return`, which remains a function statement. +An empty block or one ending in a binding has type `void`. Semicolons remain +optional separators and do not change the final expression's result. +Insert `;` before a following list expression when it could otherwise be read +as indexing of the preceding expression. + +A standalone `if` may omit `else` and has type `void`: + +```dgl +if save_latent { + tensor::save("latent.npy", latent) +} +``` + +The selected block executes for its side effects. Assignments, arguments, +containers and returned values still require the two-branch form. + +Only the selected branch contributes model resources and weight-use phases to +the run plan, and only that branch executes. Each statement in the selected +block retains its own planning boundary, including blocks nested in function +calls or argument expressions. Load optional models inside the branch or inside +the function it calls. Loading a model before the conditional +still loads it unconditionally. For example: + +```dgl +# version: 0.0.0 + +var { + enable_refiner = false + refiner_weights = "optional-refiner.safetensors" +} + +fn main() { + model = if enable_refiner { load_unet(refiner_weights) } else { load_unet("base.safetensors") } + return model +} +``` + +Here the disabled refiner file need not exist. Keep optional model loads +inside their selected branch. Use `map` and `fold` for collections of work. Loops whose next step depends on a computed result are +not supported. + +### DGL versions + +The optional version header declares the minimum DGL runtime version required +within one major version. + +```dgl +# version: 0.0.0 +``` + +Write three unsigned 32-bit decimal integers (`MAJOR.MINOR.PATCH`). The header +may appear once, before all code. Blank lines and ordinary comments may precede +it. Omitting it uses the current runtime. Forms such as `1`, `1.2` and `v1.2.0` +are format errors. + +**Development.** The runtime, examples and C API entry templates currently use +`0.0.0`. Development snapshots have no compatibility guarantee. Identify a +snapshot by its repository commit. The first stable release, `1.0.0`, establishes +compatibility for syntax, built-in signatures and documented behavior. +Development and stable versions reject each other. Verify a development script +before updating its declaration. + +**Stable releases.** The runtime must have the same major version and meet or +exceed the declared minimum. Components are compared numerically. A `1.2.0` +script can run on `1.2.3`, `1.3.0` or `1.10.0`. On `1.1.9` or `2.0.0` the +compiler reports the required and supported versions. Compatible scripts use +the current implementation and its available built-ins. + +| Increment | When to use it | +| --- | --- | +| Major | Existing legal scripts need edits, or their documented meaning changes. | +| Minor | A new capability preserves the behavior of existing legal scripts. | +| Patch | A fix restores documented behavior, or an optimization preserves it. | + +Use the highest applicable increment for a release. DGL is versioned independently +of sd.cpp, the C API and its templates. Raise a script's declaration when it +depends on a new capability or fix. Each complete C API entry template declares +its own minimum, which also covers the helpers it includes. The rendered header +is part of the source retained in `generation_info` and embedded in generation +metadata when enabled. + +### Built-in functions + +The [built-in function catalog](dgl-builtins.md) lists registered functions, +parameters, defaults and return types. For `encode_prompt` and the nested +conditions from `photomaker::encode_prompt`, the **Returns** column lists +possible fields across models. For example, a condition contains `ref_audios` +only when the encoder supplies audio references. Run +`sd-cli -M dgl --list-builtins` to inspect the catalog for your executable. + +To regenerate the checked-in catalog after changing a registration, run +`cmake --build build-dgl --config Release --target dgl-update-builtins`. +The `dgl-check-builtins` target verifies that the file matches the registry. + +## Tensor functions + +Tensor types are U8, I32, I64, F32 and F64. Dimensions are stored contiguous-first: + +| Value | Type | Shape | +|---|---|---| +| RGB image | U8 | `[3, width, height]` | +| RGB video | U8 | `[3, width, height, frame_count]` | +| Audio samples | F32 | `[channels, samples]` | +| Diffusion latent | F32 | Model-specific, including four- and five-dimensional layouts | +| Region boxes | I64 | `[4, region_count]` | +| Detection coordinates | F32 | `[4, detection_count]` | +| Detection scores / class IDs | F32 / I64 | `[detection_count]` | +| Conditioning | F32/I32 | Model-specific; inspect each tensor | + +Rank-zero tensors are scalars. Zero-sized dimensions represent empty tensors. + +### Operations and broadcasting + +Qualified function names use `::`. Call a tensor function with +`tensor::reshape(x, [4, 8])` and access a dictionary field with `condition.crossattn`. + +| Function | Arguments and result | +|---|---| +| `tensor::zeros`, `tensor::full` | Take a shape and optional `dtype` (default `f32`). `full` also takes a scalar fill value. | +| `tensor::zeros_like`, `tensor::randn_like` | Use the input shape and dtype. `randn_like` supports floating-point tensors and requires an RNG object. | +| `tensor::shape`, `tensor::numel`, `tensor::reshape` | Read the shape as a rank-one I64 tensor or the element count as a scalar. Reshape preserves element count and dtype. | +| `tensor::unsqueeze` | Insert a length-one axis, preserving dtype and element order. `axis` accepts `[-rank-1, rank]`; output rank is at most 8. | +| `tensor::pad` | Constant padding with `[before0, after0, before1, after1, ...]` in DGL axis order. `mode="constant"` and `value=0` are defaults. | +| `tensor::vector` | Construct a rank-one tensor from numeric values. The default dtype is `f32`. Read elements with bracket indexing. | +| `tensor::to_list` | Convert a rank-one tensor of at most 10,000 elements into `list` or `list`. `element="auto"` infers the element type from a known dtype; `"int"` and `"number"` declare the expected category. | +| `tensor::arange`, `tensor::index_select` | Generate a rank-one I64 range with exclusive end, or gather slices in index order along one axis. | +| `tensor::crop`, `tensor::replace_slice`, `tensor::concat` | Crop takes lists of axes, starts and sizes. Replacement and concatenation require matching dtype and dimensions outside the selected axis. Use bracket syntax for basic slicing. | +| `tensor::cast` | Explicitly convert to a `dtype`. Integer conversion truncates toward zero and rejects out-of-range values. | +| `tensor::broadcast_to` | Broadcast a tensor to an explicit shape and preserve its dtype. | +| `tensor::add`, `tensor::mul` | Accept floating-point tensors of the same dtype and numeric scalars. | +| `tensor::lerp` | Compute `a * (1 - weight) + b * weight`. Two U8 endpoints accept a scalar or floating-point weight tensor, with output rounded and clamped to U8. | +| `tensor::affine`, `tensor::clamp` | Apply `scale` and `offset`, or constrain values to `min` and `max`. Both take a floating-point tensor. | +| `tensor::interpolate` | Resize two axes of a U8 or floating-point tensor using `size=[width, height]`, `axes=[0, 1]` by default, and a `mode` such as `bilinear` or `bicubic`. | +| `tensor::translate`, `tensor::index_fill` | Shift along selected axes with constant fill, or fill entire slices at selected indices along one axis. | +| `tensor::grayscale`, `tensor::threshold` | Convert the channel axis to grayscale or select `low` below the threshold and `high` at or above it. | +| `tensor::maximum` | Take the elementwise maximum of two tensors with the same dtype and broadcastable shapes. | +| `tensor::max_pool2d`, `tensor::min_pool2d` | Pool over two axes with a configurable kernel and stride. `padding_after` defaults to `padding_before`. Set `pad_value` to include a constant outside the tensor. | +| `tensor::gaussian_blur` | Blur two axes with edge replication. `radius` sets the kernel half-width and `sigma` sets the Gaussian spread. | +| `tensor::literal` | Construct a tensor from its `dtype`, `shape` and little-endian Base64 `data`. | + +Broadcasting aligns dimensions from the lowest axis and treats missing higher +dimensions as 1. A numeric scalar broadcasts to all elements. +Shape, axis and size arguments accept rank-one I64 tensors and lists of +integers. List elements can be scalar expressions, including indexed dimensions; +there is no need to create or modify a tensor just to describe a shape: + +```dgl +shape = tensor::shape(latent) +mask_shape = [shape[0], shape[1], shape[2], 4, shape[4]] +mask = tensor::index_fill(tensor::zeros(mask_shape), axis = 2, indices = [0], value = 1) +``` + +`latent_shape(vae, width, height, ...)` and +`audio_latent_shape(audio_vae, frames, fps)` also return I64 shape tensors. +The audio shape uses the loaded audio VAE's model family and the video duration +(`frames / fps`), keeping each family's latent layout and rounding rules. +Both are metadata queries; `audio_latent_shape` does not load device weights +or run the audio VAE. + +```dgl +sound_shape = audio_latent_shape(audio_vae, frames = frames, fps = 24) +sound_base = tensor::zeros(sound_shape) +``` + +`math::product` multiplies dimensions, and `math::ceil_div` +divides nonnegative integers rounding upward. Schedule functions use scalar arithmetic for indices and `math::floor(steps * strength)` +to convert a fraction of steps to a count. + +### Read-only list and tensor indexing + +Use brackets after any list or tensor expression, including a function call: + +```dgl +first_sigma = sigmas[0] +refine_sigmas = full_sigmas[-13:] +width = tensor::shape(pixels)[0] +patch = x[1:3, :, 0] +``` + +Lists accept exactly one integer index or slice. Integer indices may be negative; +out-of-range indices fail. Slices are half-open, accept omitted or negative +endpoints and clip to the list bounds. A slice preserves the input's element type, +even when empty or when a `list` slice happens to contain only integers. +Integer values do not need to be converted to floating point. + +```dgl +first = items[0] +last = items[-1] +batch = items[2:5] +rest = items[1:] +final_steps = items[-3:] +pixel = patches[0][1, 2, 3] +``` + +`list::at` and the global `tail` function have been removed. To select a suffix, +use `items[-count:]`. This clips to the whole list when `count` exceeds its length; +`count=0` gives `items[-0:]`, equivalent to `items[:]`, rather than an empty list. +Use `items[:0]` for an empty slice. Empty `map` results retain the callback's +inferred return type for that call, such as `list` or `list`. +`list::replace` remains the functional update operation; `map` and `fold` +continue to iterate lists only. + +Axes follow DGL shape order: axis 0 is the lowest, contiguous dimension. +Integer indices remove their axis; slices keep it. Omitted trailing axes are +retained. For `x` shaped `[8,6,4,2]`: + +| Expression | Result | +|---|---| +| `x[1:3, :, 0]` | Tensor `[2,6,2]` | +| `x[1:3, :, 0:1]` | Tensor `[2,6,1,2]` | +| `x[-1]` | Tensor `[6,4,2]` | +| `x[1,2,0,0]` | Numeric scalar | +| `x[3:1]` | Empty tensor `[0,6,4,2]` | + +Integer indices and slice endpoints are integer expressions. Negative indices +count backward from an axis's end; out-of-range integer indices fail. Slices +are half-open, support omitted endpoints, and clip endpoints to the axis bounds. +`x[start:]`, `x[:end]` and `x[:]` are supported. Endpoints can contain scalar +arithmetic, for example `sigmas[count - 13:]`. + +An explicit slice always returns a tensor, including empty and length-one +slices. With only integer indices, consuming all axes returns a scalar; otherwise the +result is a tensor. The compiler retains known rank and element types from +tensor constructors, shape queries and schedules, so fully consumed indices +keep their numeric types in lists and user functions. `--check` rejects known +non-integer indices/endpoints and too many indices for a known rank. +File-loaded tensor ranks and other unknown properties remain runtime checks. Integral tensor elements become DGL integers; +floating-point elements become DGL numbers. + +Brackets form an indexing expression. The checker selects list or tensor rules +from the input type, and execution dispatches to the corresponding operation. +Known list elements and indices also select precise model origins during +resource planning; dynamic indices conservatively combine candidate origins. +Step sizes, ellipsis, boolean masks, index tensors and indexed assignment remain +unsupported. + +### Axis insertion and constant padding + +`tensor::unsqueeze(input, axis)` inserts one length-one dimension and returns +a contiguous tensor with the same values and dtype. Negative axes count from +the end of the insertion positions; `axis=-1` appends a dimension. + +`tensor::pad(input, pad, mode="constant", value=0)` takes an even-length list +or rank-one I64 tensor of padding pairs. The first pair is before/after axis 0, +the second is axis 1, and so on. Unspecified higher axes receive no padding. +Only `constant` mode is supported. Lengths must be nonnegative, the number of +pairs must fit the input rank, and padded shapes retain the 256 MiB limit. +The fill value follows the input dtype's scalar-conversion rules. +An empty or all-zero padding list borrows the input without changing it. + +Frame assembly and constant padding use tensor operations directly. +For example, turn one image into a video tensor and append constant frames: + +```dgl +image = image::load("input.png") +first_frame = tensor::unsqueeze(image::to_f32(image), axis = 2) +frames = tensor::pad(first_frame, [0, 0, 0, 0, 0, 32], value = 0.5) +``` + +Image normalization runs before padding, so `value=0.5` means half-intensity F32 +pixels. The frame axis remains explicit even for a single frame. Use +`tensor::concat` to assemble multiple frames and `tensor::pad` for constant +padding. Negative padding lengths fail instead of discarding input frames. + +### Tensor values as lists + +`tensor::to_list(input, element="auto")` explicitly converts a rank-one tensor +into a script list for `map`, `fold` or list functions. U8, I32 and I64 produce +`list`; F32 and F64 produce `list`. Integers are read directly as +int64 values, preserving I64 values above 2^53. NaN and infinity are rejected. +An empty tensor produces an empty list with the same element type. + +```dgl +fn add_seed(total, seed) { + return total + seed +} + +fn main() { + batch_seeds = tensor::to_list(tensor::arange(42, 46)) + empty = tensor::to_list(tensor::arange(42, 42)) + return { + seeds = batch_seeds, + sum = fold(batch_seeds, 0, process = add_seed), + empty_sum = fold(empty, 0, process = add_seed) + } +} +``` + +The seeds are `[42, 43, 44, 45]`, their sum is `174`, and the empty fold +returns its initial value `0`. A map callback can also construct an RNG from +each seed and return an independent noise tensor. + +The compiler must know the list element type before checking the map or fold +function. With `auto`, it uses a known tensor dtype, such as I64 from `arange` +or the declared dtype of `tensor::vector`. If dtype is unknown, including an +unconverted `tensor::load()` result or a host tensor parameter, declare it: + +```dgl +items = tensor::to_list(tensor::load("seeds.npy"), element = "int") +``` + +`element` must be known at compile time. It declares a type category and does +not cast values: F32 with `element="int"` and I64 with `element="number"` are +errors. Use `tensor::cast` before conversion to change dtype explicitly. Known +rank or dtype mismatches fail compilation; runtime validation checks the actual +input as well. Multidimensional tensors require an explicit reshape first. +Each element creates a script value, so the limit is 10,000 items, including +when the input came from a file or the host. + +The former `seeds(seed, count)` function is removed. Use +`tensor::to_list(tensor::arange(seed, seed + count))`, or a plain integer for a +single fixed seed. Integer range bounds do not wrap at the int64 limit. + +### Scalar arithmetic + +Scalars support `+`, `-`, `*` and `/`, parentheses, and unary `+` and `-`. +Multiplication and division bind before addition and subtraction; binary +operators of equal precedence associate left to right. Indexing binds before +unary signs, so `-sigmas[0]` negates the selected scalar. + +Integer `+`, `-` and `*` preserve the integer type and reject int64 overflow. +A floating-point operand produces a floating-point result. `/` always returns +a floating-point value and rejects division by zero. Use `math::floor`, +`math::ceil` or `math::ceil_div` when an integer count is required. + +```dgl +missing = count - 1 +area = width * height +retained = math::floor((steps - 1) * strength) +sigma = sigmas[count - 13] +``` + +Operators accept numeric scalars. Use `tensor::add`, `tensor::mul` and other +explicit tensor functions for tensor arithmetic. Operators lower to the same +`math::add`, `math::sub`, `math::mul` and `math::div` implementations as calls. +The `var` block continues to accept literals, including signed numbers; +write computed expressions in function bodies. + +### Tensor files + +Use `tensor::save` to write a tensor from any step to a NumPy `.npy` file. +The former top-level names `load_tensor` and `save_tensor` have been removed; +use `tensor::load` and `tensor::save`, with the same parameters and behavior. +Saving functions take the output path first, followed by the data to write. +Saving functions have no return value. Call them as standalone statements; +return tensors or media separately when they should appear in the result. +`tensor::load` reads the same format, including files exported by `--tensor`. + +```dgl +# version: 0.0.0 + +fn main() { + latent = tensor::load("latent.npy") + tensor::save("latent-copy.npy", latent) + return latent +} +``` + +`tensor::load` supports `u8`, `i32`, `i64`, `f32` and `f64` tensors up to rank 8 +and 256 MiB. The NumPy shape is the reverse of the DGL shape, so a DGL +image shaped `[3, width, height]` appears as `(height, width, 3)` in NumPy. + +## Independent generation components + +A generation script loads the model components, encodes the prompt, builds a +predictor and a noise schedule, then samples and decodes the latent. See +[model loading](#model-loading-and-reuse), [prompt formatting](#prompt-encoding), +[predictors](#predictors-and-guidance) and [sampling](#noise-schedules-and-sampling). + +### Model loading and reuse + +Use `load_unet` for UNet architectures such as SD 1.x, SD 2.x and SDXL, +and `load_dit` for diffusion transformers. The names resolve to the same loader. +`load_text_encoder` loads the text encoder and `load_vae` loads the VAE. +A single checkpoint can supply all three components, as in +[SD 1.5 text-to-image](dgl/sd/sd1-5-txt2img.dgl). +For standalone weights whose tensor names are shared across model families, +set `family` to a lowercase [model family ID](dgl-builtins.md#model-family-ids) +such as `"sd1"`, `"flux"` or `"qwen_image_2_1"`. With `family = "auto"`, +you can pass a diffusion checkpoint as `family_from` to detect the family from +its metadata. Use `vision_path` when the text encoder's vision weights are in +a separate file. `path` selects the main text encoder weights; use `clip_l_path`, +`clip_g_path` and `t5_path` when those components are in separate files. + +Component loaders accept `backend`, `params_backend`, +`wtype`, `tensor_type_rules`, `split_mode`, `flash_attn_mode`, `conv_direct_mode` +plus `sage_attn`. Pass one setting per loader parameter. +Use `"auto"`, `"on"` or `"off"` for `flash_attn_mode` and `conv_direct_mode`. +These options apply only to the model returned by that loader. For example: + +```dgl +unet = load_unet("sdxl.safetensors", flash_attn_mode = "on", conv_direct_mode = "off") +vae = load_vae("sdxl.safetensors", flash_attn_mode = "off", conv_direct_mode = "on", conv_scale = 0.03125) +``` + +To place two components separately, set `backend = "cpu"` on the text encoder +and `backend = "cuda0"` on the DiT. The DiT and text encoder +also accept device lists such as `"cuda0&cuda1"` for split execution. + +Loader option `conv_scale` overrides Conv2D input scaling, including grouped +Conv2D. Output scaling is compensated after convolution. The default `0` +keeps model defaults. For an SDXL VAE, set `conv_scale = 0.03125` explicitly, +including when loading the VAE from a separate file. Use `conv_scale = 1` for unscaled convolution. +This does not change VAE latent normalization or model weights. + +Model-loading functions accept literals and scalar literal bindings from +`var` or `main()`. +An execution context caches components by their weight sources and loader +options. Programs run in the same context can share a component even if they +give it different variable names. The cache checks each loader's declared +files, including its configured tokenizer slots. Encoded conditions also track any textual inversion embeddings +used by the prompt. Each run calls generation and image-processing +functions with its own inputs and sampling state. A context permits one active run. + +The CLI defaults to `--run-once on`, which releases models after their last use. +Use `--run-once off` to cache models for reuse during the invocation, subject to +the context's memory limits. Freeing the context releases its cache. + +The executor tracks the last use of each binding and dictionary field. A component +stays loaded while another live value, such as a predictor, still uses it. +Repeated loads share a live component. With `--run-once on`, loading the same +component again after its last use reads its weights again. + +### LoRA combinations + +`load_lora` creates a reusable adapter handle. `apply_lora` registers the +adapter's weights and derives a model of the same type with its own ordered +adapter list. Both models can be used independently. +For example, a low-resolution pass can use `draft` and a later pass can add a +second adapter for refinement. + +```dgl +base = load_unet("sd15.safetensors") +style = load_lora("style.safetensors") +detail = load_lora("detail.safetensors") +draft = apply_lora(base, style, weight = 0.8, mode = "immediately") +refine = apply_lora(draft, detail, weight = 0.4) +``` + +The optional `mode` applies to the entire returned combination. Omitting it +inherits the input model's mode. The same adapter handle can be used on any +weighted model when the adapter contains matching parameters for that model. + +`at_runtime` applies adapters in the forward graph. `immediately` builds and +caches merged buffers for the affected parameters on first use. Compatible +combinations share the original parameter buffers and the adapter tensors +across both modes. Changing mode or strength can reuse the original weights +while they remain resident. Persistent contexts retain idle buffers subject +to RAM and VRAM pressure. Run-once contexts can release shared buffers after +their last use. +In both persistent and run-once contexts, `auto` selects `immediately` for +unquantized and [INT8 tensorwise weights](guides/int8_convrot.md) on the compute +backend without row splitting. It selects `at_runtime` for other quantized +formats, offloaded weights, or row-split weights. + +### Prompt encoding + +`encode_prompt` returns named conditioning tensors. `predictor` binds them to a +model. +Wan and LingBot encoders zero UMT5 embeddings at padding positions before +returning the condition, as required by their fixed-length diffusion text input. +Embeddings for actual prompt tokens are unchanged. + +`encode_prompt` uses the text encoder's model default for an omitted or +nonpositive `clip_skip`, including the penultimate CLIP layer for SD2 and SDXL. +Explicit positive values override that default. Requesting a layer whose weights +are absent reports an encoding error. + +LLM-based encoders accept optional `system` and `raw` arguments. This includes +the Qwen/Mistral/GPT-OSS/Gemma paths, Anima, Fibo, Ming-Image, LLaDA-Image, +LTX, HiDream-O1 and SenseNova U1.5. + +- Omit `system` to keep the model's default prompt formatting. +- Set `system="custom instruction"` to replace only the system text, retaining + the encoder's role markers and the rest of its template. Encoders without a + default system segment insert one using their role format. +- Set `system=""` to omit the whole system segment, including its role markers. + An encoder without a default system segment keeps its existing template. +- `raw=false` is the default. With `raw=true`, `text` is the complete tokenizer + input: no chat template, caption rewriting, prompt-weight parsing or inline + image/embedding resolution. Model-required padding, hidden-layer selection, + learned queries and projections still apply. + +Passing `system` together with `raw=true` is an error, even for `system=""`. +Raw text mode also rejects `media` and `image_bindings` arguments; +use normal template mode for multimodal input. System changes update template +crop offsets and prefix-dependent padding, and image token positions are +computed from the resulting prefix. Default formatting remains unchanged. +CLIP and T5-only encoders reject these formatting overrides. + +For an already loaded LLM text encoder: + +```dgl +custom = encode_prompt(text, prompt, system = "Describe the requested image.") +without_system = encode_prompt(text, prompt, system = "") +raw = encode_prompt(text, tokenizer_input, raw = true) +``` + +The former `unconditional` parameter has been removed. SenseNova's legacy +negative format also omits ``, so `system=""` does not reproduce it. +Use the full negative tokenizer input instead: + +```dgl +negative = encode_prompt(text, + "<|im_start|>user\nblurry<|im_end|>\n<|im_start|>assistant\n", + raw = true) +``` + +Native CLI/C API generation constructs that complete negative input automatically, +for empty and nonempty negative prompts. Ordinary CLIP negative prompts use the +same encoding as positive prompts and need neither `system` nor `raw`. + +#### Media inputs + +`media` supplies ordered inputs to the encoder's existing model-specific prompt +template. An image tensor is shorthand for `{image = tensor}`. Image-only +lists can use either form; mixed media lists use dictionaries so every list +element has the same DGL type: + +```dgl +clip = video::load("inputs/clip.webm") +sound = audio::load("inputs/voice.wav") +condition = encode_prompt(text, prompt, media = [ + {image = source_image}, + {video = clip.video, stride = 12}, + {audio = sound} +]) +``` + +Each dictionary has exactly one `image`, `video` or `audio` field. Video uses +`{frames, fps_num, fps_den}`; audio uses `{samples, sample_rate}`. Only video +accepts `stride`, an integer frame interval in `1..65536`, defaulting to `1`. +Sampling retains source-frame timestamps. A video does not implicitly include +its soundtrack: add `{audio = clip.audio}` separately when needed. Unsupported +media types or image counts are errors. MiniMax H3's audio prompt input adds +its audio marker; audio encoding and predictor references remain separate. + +`image_bindings = {subject = tensor}` supplies images referenced by +`` in the text. Explicit bindings take precedence over file +paths. An invalid referenced binding is an error; an absent name uses the +existing path reader and file-access callback. Unreferenced bindings do not +enter conditioning or its cache key. `raw=true` rejects `media` and +`image_bindings`, including explicitly empty containers. + +Multimodal prompt encoding can consume reference-video frames independently: + +```dgl +condition = encode_prompt(text, prompt, media = [{ video = {frames = frames, fps_num = 24, fps_den = 1}, stride = 12 }]) +``` + +A `video` media entry takes the same video dict. Its `frames` can be a +U8 `[3,w,h,t]` or F32 `[w,h,t,3,1]` tensor. `stride` defaults to 1 frame. The encoder receives selected frames with timestamps +`frame_index * fps_den / fps_num`. At 24 FPS, stride 12 selects timestamps +0, 0.5, 1.0 seconds and so on. Only selected frames are converted to the +encoder's float pixel layout. Audio media uses `{audio = sound}`, where +`sound` is the same samples/sample-rate dict used by audio I/O. + +#### Textual inversion + +For textual inversion, use an inline file path with an SD 1.x, SD 2.x or SDXL +CLIP encoder: + +```dgl +text = load_text_encoder(model_path) +negative = encode_prompt(text, ", blurry") +``` + +`` follows the same path and escaping rules as ``. +Paths resolve from the process working directory. An escaped marker is ordinary +text, and a bare filename or former trigger word is also ordinary text. Other +encoders reject embedding markers. The vectors replace token embeddings before +CLIP adds positional embeddings; prompt weights, token chunks and SDXL dual-CLIP +zero-padding still apply. No tokenizer aliases or loader `embeddings` argument +are used. + +Every encoding checks `SD_DGL_FILE_READ_MODEL` permission before inspecting the +files or looking up a cached condition. Cached conditions track canonical paths +and file versions, including referenced shards. Replacing an embedding invalidates +the condition without rebuilding the text encoder. The server's model directory +allowlist also applies to these paths. Native CLI/C API textual inversion is +unchanged. + +#### Conditioning fields + +`zero_out(condition, fields = ["crossattn"])` returns a new +condition dict with only the selected tensor fields cleared. Omit `fields` to +clear every tensor field and every element of tensor lists. Shapes, dtypes and +non-tensor metadata are preserved; the input dict is unchanged. A selected field +must exist and contain a tensor or tensor list. Clearing a condition is a tensor +operation, and does not make it valid unconditional input for every model. +For SDXL, clear text embeddings while preserving size and crop conditioning: + +```dgl +fn sdxl_zero_text(cond) { + zeroed = zero_out(cond, fields = ["crossattn"]) + pooled_zeros = tensor::zeros_like(cond.vector[:1280]) + adm = tensor::replace_slice(cond.vector, pooled_zeros, axis = 0, start = 0) + return {crossattn = zeroed.crossattn, vector = adm} +} +``` + +The first 1280 values of SDXL's `vector` contain pooled text embeddings; its +remaining 1536 values encode size and crop information. This helper clears +`crossattn` and pooled text only. The CLI/C API calls it for an empty negative +prompt with non-EDM-v prediction. The SDXL examples expose `zero_negative` +as an explicit choice: set it to `false` to use the encoded negative prompt, +including nonempty negative text. Both branches return the two SDXL condition +fields, `crossattn` and `vector`, to keep their static dictionary types identical. + +A conditioning dictionary can use tensors in the fields +consumed by `predictor`, including model-specific token and reference metadata. + +### Predictors and guidance + +`predictor` binds a condition to a diffusion network, with optional `concat` and `ref_latents` inputs. The +[Qwen Image 2.1 editing program](dgl/qwen_image_2.1/qwen-image-2-1-edit.dgl) passes the +reference pixels to the text encoder and their VAE latent to the predictor. +[Text-to-image](dgl/qwen_image_2.1/qwen-image-2-1-txt2img.dgl) uses the same +components with text conditions. +Reference images are prepared by the script. DGL does not select reference +presets or apply a reference resize policy based on the model family. +Use `tensor::interpolate` and `tensor::crop` before encoding. Pass prepared +pixels to `encode_prompt` and prepared latents to `predictor` explicitly. +`predictor(ref_index_mode="increase")` selects reference position indexing; +the default is `"fixed"`. Use `"decrease"` for layered references and set +`force_ref_timestep_zero=true` when required by the checkpoint. +For MOSS-Image, `ref_rope_anchor` aligns reference tokens with the start of the +image (`"image_start"`) or text (`"text_start"`) along the RoPE sequence axis. +`"default"` uses the model's alignment. See the +[MOSS-Image editing examples](models/moss_image.md#dgl). + +`prediction` belongs to `predictor`, for example +`pos = predictor(dit, condition, prediction="eps")`. `load_dit` and its +`load_unet` alias load the model without selecting a prediction parameterization. +Omitting `prediction` selects `"auto"`, using the model's declared defaults and, +when needed, its checkpoint detection. The explicit values are `eps`, `v`, +`edm_v`, `flow`, `flux_flow`, `sefi_flow`, `minit2i_flow`, `sensenova_u1_flow`, +`flux3_flow`, `h3_av_flow`, and `ming_image_flow`. + +`predictor(transform=step_fn, transform_args={...})` calls a script function +for each model evaluation. Its two arguments are the step dictionary and +the supplied `transform_args`. The step contains `sigma`, the model's +`timestep`, and `input_scale`, `skip_scale`, and `output_scale`. Return a +dictionary with the timestep or scale fields to override. `denoiser_scalings` +returns the standard coefficients for a supplied sigma. The +[NitroFusion example](dgl/sd/nitrosd-realism-nitrofusion.dgl) defines its timestep +rounding and output scaling in this function. + +`cfg(pos, neg, scale=4.5, schedule=[7, 6, 5])` uses a scale per step and +falls back to `scale` after the list ends. `cfg` and `apg` both accept +`image_only` and `image_scale` for image editing. APG uses the underlying +model outputs and requires matching prediction scalings across its branches. +Each `sample` call starts its own APG momentum. + +SLG takes a base prediction, a complete positive branch, and a skipped branch. +It adds `scale * (positive - skipped)` to the base prediction. Reusing the same +positive predictor in APG or CFG and SLG shares the forward pass within each +model evaluation. + +```dgl +pos = predictor(dit, pos_cond) +neg = predictor(dit, neg_cond) +skipped = predictor(dit, pos_cond, skip_layers = [7, 8, 9]) +guided = apg(pos, neg, scale = 4.5, eta = 0, momentum = -0.5) +pred = slg(guided, pos, skipped, scale = 2.8, end_sigma = t_to_sigma(pos, t = 0.8)) +latent = sample(start, sigmas, predict = pred, rng = rng) +``` + +`start_sigma` and `end_sigma` define an inclusive sigma window for SLG. +To use the step-based window, set `start_step_fraction` and `stop_step_fraction`. +The step window uses the sigma tensor length (including its endpoint) times +each fraction, rounded down. Only step indices strictly inside the window +activate SLG. When both windows are provided, SLG applies within their +intersection. + +Guidance schedules, SLG step windows, and `switch_predictor(after_steps=...)` +use logical steps starting at one. Multiple model evaluations within one solver +step, such as Heun's predictor and corrector, use the same step index. + +CFG++ samplers request the unconditional prediction from the supplied +predictor. SLG and `switch_predictor` can forward this output from a two-branch +CFG or APG predictor. Every reachable switch branch must supply it; single-branch +predictors and CFG/APG with `image_only` are rejected before model execution. + +### Random streams + +`make_rng("cuda", seed = 42)` creates a seeded RNG object. The algorithm +can be `"cuda"` (Philox on every backend), `"cpu"` (MT19937), or +`"std_default"` (also `"std"`). `vae_encode`, `tensor::randn_like` and `sample` +each require an RNG object. Pass the same object to advance one stream in +execution order. Each call to `make_rng` creates an independent stream, +including when a cached execution context runs a script again. +For example, `tensor::randn_like(base, rng = make_rng("cpu", seed = 42))` +uses a separate MT19937 stream. + +For the same RNG sequence as the generation C API, generate the initial noise with +`tensor::randn_like(base, rng = rng)`, pass that tensor to `add_noise`, then pass +the same `rng` to `sample`. For images, start a new stream from the image seed +before initial noise, and start another before the hires pass, including any +hires VAE re-encoding. For video, share the request stream from VAE encoding +through high- and low-noise sampling and hires refinement. + +### Noise schedules and sampling + +The sampler receives a start tensor, a rank-one F32 sigma tensor and a +predictor. `make_sigmas` returns a schedule tensor, and +`tensor::vector([1, 0.5, 0])` builds one from explicit values. +`sigmas[0]` reads the starting sigma. Return a schedule by name +to export it as one `.npy` array. A single zero sigma requests zero sampling +steps for ordinary samplers. `flow_shift` on `make_sigmas` configures that +table. Sampling uses the table's values and the predictor's inputs. + +`make_sigmas`, `add_noise`, `t_to_sigma`, and `denoiser_scalings` take a predictor +as their first `predict` argument. These queries do not evaluate the predictor. +Build the required prompt/condition and predictor before constructing its +schedule or adding noise. Changing prediction does not reload the model or +its LoRA variant. + +`make_sigmas` and `t_to_sigma` accept a composition when its branches share +one `DenoisingParameterization` object. Predictors from the same model with the +same resolved `prediction` share that object, so ordinary CFG can use `guided` +for its schedule, noise addition and sampling: + +```dgl +pos = predictor(unet, pos_cond, prediction = "eps") +neg = predictor(unet, neg_cond, prediction = "eps") +guided = cfg(pos, neg, scale = cfg_scale) +sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) +start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) +latent = sample(start, sigmas, predict = guided, method = "euler_a", rng = rng) +``` + +Different models or different parameterization objects make the schedule source +ambiguous, even when their noise conventions or scaling rules are compatible. +Pass the branch that defines the desired schedule in that case. For example, +Wan 2.2 can use `make_sigmas(lo, ...)` for the low-noise model's schedule and +`add_noise(hi, ...)` before sampling with the high-noise model. +`denoiser_scalings` accepts a composition only when every branch has the same +scaling rules. For example, +a mixture of `eps` and `v` has no common coefficients, even if a queried sigma +happens to give equal values; query the desired leaf instead. `v` and `edm_v` +share scaling rules, but have different time mappings. + +`add_noise` and sampling finish conversion require only a common noise +convention, so sampling still supports CFG or switched predictors with different +parameterizations such as `eps` and `v`. Compatible CFG branches with different +parameterizations execute separately. APG additionally requires matching +raw-output scalings. + +`make_sigmas` defaults to the `"discrete"` scheduler and rejects `"auto"`. +Choose a different scheduler explicitly when the model requires it. Omit +`flow_shift` when no override is needed; its default is zero. + +`sample(method=...)` defaults to `"euler"`. Choose a sampling method explicitly +when another algorithm is needed; `"auto"` is not accepted. `sefi::sample` also +defaults to `"euler"` and only supports that method. + +`t_to_sigma(predict, t, flow_shift=...)` converts a normalized noise time +before the shift to a sigma. `t=1` is the noisy end, and `t=0` is the +low-noise end of the model's time mapping. A model with a discrete training +grid can have a positive minimum sigma. Pass `latent` or `sequence_length` +for time mappings that depend on the latent size. + +In the [Wan 2.2 image-to-video program](dgl/wan/wan2-2-i2v-a14b.dgl), bracket slices +include the same boundary sigma in both sampling segments. The second Euler segment +takes the first segment's noisy output. Its final latent, the handoff and the +decoded pixel tensor can all be returned. The +[Wan 2.1 text-to-video program](dgl/wan/wan2-1-t2v-1-3b.dgl) uses one predictor +and the full schedule. `video::save` accepts a video dict containing decoded RGB +frame tensors and `fps_num`/`fps_den`, and writes AVI. + +### Sampling caches + +Pass `cache(mode="ucache", reuse_threshold=0.8)` to `sample(cache=...)` to +enable a sampling cache. Available modes are `disabled`, `easycache`, `ucache`, +`dbcache`, `taylorseer`, `cache_dit` and `spectrum`. Support depends on the +denoiser and sampler. Spectrum requires one denoiser, one sigma schedule and a +sampler without CFG++. Each sample call owns its cache state. The runtime +prepares each denoiser and active conditioning component on first use in that +call and reuses its execution scope for the remaining steps. With +`switch_predictor`, a later branch enters execution when the solver reaches it. +Spectrum discards its extrapolation history when an active switch changes +branches or an active CFG/APG guidance scale changes. The new configuration +starts with real model evaluations before extrapolation resumes. Guidance +changes inside unused branches do not invalidate the active history. Active SLG +nodes are part of the key even when they share every model leaf with the base +predictor. For CFG++, only the branch that supplies the root unconditional +output is additionally retained; nested guidance does not inherit that demand. +With caching disabled, execution skips the activity-key traversal entirely. + +Condition-level caches (`easycache`, `ucache`, `dbcache`, `taylorseer` and +`cache_dit`) store separate histories for model conditions. Only enabled caches +prevent CFG batching; an unsupported cache request leaves batching available. +When an active condition leaves, its cache is invalidated. If it was the anchor, +the cache selects a new active condition and rebuilds its calibration. + +DGL's `dbcache` reuses whole-model input/output residuals after checking input +change against `residual_diff_threshold`. `taylorseer` extrapolates each +condition's raw model output using `taylorseer_n_derivatives`; after enough real +samples, `taylorseer_skip_interval` bounds the number of extrapolated steps +between real evaluations. `cache_dit` combines that extrapolation with the +residual-difference gate. These are condition-level algorithms, not block-level +DBCache/TaylorSeer. `Fn_compute_blocks`, `Bn_compute_blocks` and +`scm_policy_dynamic` are not DGL options. Model-block caching requires a runner +integration and is not exposed by this path. + +`max_warmup_steps`, `max_cached_steps`, `max_continuous_cached_steps`, and a `1` +in `scm_mask` force real computation as applicable; forced steps still update +history. Negative values for `max_cached_steps` and `max_continuous_cached_steps` +leave the corresponding limit unset. Condition-level reuse only runs on +completed-step evaluations; intermediate solver evaluations execute the model +normally. + +Spectrum owns the composed predictor's output history independently. Its +`spectrum_warmup_steps` counts logical solver steps, and +`spectrum_stop_percent` sets the stopping position on that same timeline. +Heun's predictor and corrector use separate histories at their logical step +indices; neither evaluation advances the other's warmup. Active branch or +guidance changes reset both histories. Real Spectrum evaluations can still use +batched CFG. Logs report reused predictor evaluations, rather than dividing +Heun's evaluation count by the number of sigma intervals. + +### Sampling previews + +Load a tiny autoencoder with `load_tae("tae.safetensors", family = "sd1")`, or use +`family_from` to identify its model family from a diffusion checkpoint. +Pass it to `vae_encode` or `vae_decode` like any other autoencoder. +For preview-only use, set `decode_only = true` on `load_tae` and pass it to +`preview(decoder=...)`. Attach the returned observer to `sample` or +`sefi::sample`. Load the final decoder separately with `load_vae`. + +```dgl +tae = load_tae("tae.safetensors", family = "sd1", decode_only = true) +observer = preview(decoder = tae) +latent = sample(start, sigmas, predict = guided, rng = rng, observer = observer) +``` + +`preview()` needs no decoder for latent projection. The context's preview +callback selects the mode, interval and noisy or denoised previews. A sampling +call without an observer uses a shared projection preview observer. Without a +decoder, preview falls back to projection. An explicit observer is only needed +to supply a decoder or custom preview settings. An observer can be reused +across sampling calls; each call has its own observation state. The observer +retains its decoder, and decoding resources are acquired only for a selected +preview and released afterwards. Without an enabled preview callback, it +performs no preview decoding. + +### Media dimensions + +Model functions adapt pixel inputs to their own spatial requirements. Dimensions +are rounded to the nearest legal multiple, with half-way values rounded up and +at least one multiple retained. Already compatible inputs pass through without +resizing. Automatic resizing uses Lanczos filtering; it does not impose a +resolution or pixel-area budget. Use `tensor::interpolate` or `tensor::crop` +before encoding when you want to choose the geometry yourself. + +`vae_encode` normally aligns to the VAE's spatial compression factor. +`encode_prompt` independently applies its vision encoder's requirements; the +two paths can see different sizes of the same reference. Qwen Image 2.1 has an +additional model constraint: each vision image slot expands into four reference +latent tokens. Its VAE input therefore aligns to 32 pixels, while the spatial +compression factor remains 16. Neither path changes the source tensor. Existing +fixed-size vision preprocessing still performs its required crop and normalization. + +`latent_shape` aligns requested pixel dimensions to the model family's diffusion +and VAE grid before returning a latent shape. Use that shape for the output +canvas; encoded reference latents can have a different shape. Both +`latent_shape` and video `vae_encode` round temporal lengths up to the supported +grid: `1 + 4k` for Wan, LingBot, Hunyuan Video and SeedVR2, `1 + 8k` for LTX, +and `5 + 17k` for H3 video. Encoding repeats the last frame when padding is +needed, preserving every input frame. Single-image encoding remains a single +image. Decoding returns the actual aligned size; there is no automatic crop +back to the original dimensions. For joint audio/video scripts, derive audio +lengths from the aligned video duration. + +`detections::detect` rounds positive `input_size` values to a multiple of 32 +(minimum 32, maximum 4096); detections remain in original-image coordinates. +The H3 latent upscaler similarly aligns positive target dimensions to even +latent units. LTX upscaling still gets its fixed scale from the checkpoint. +Only actual adaptations emit verbose logs. Invalid ranks, channels, nonpositive +dimensions and incompatible conditioning relationships remain errors. + +### VAE latent spaces + +`vae_encode(vae, pixels, rng)` returns a latent in the VAE's own space. +`vae_to_dit_latents(vae, latent)` applies the model's scaling, shift +or normalization before sampling. After sampling, use +`dit_to_vae_latents(vae, latent)` before `vae_decode(vae, latent)`. +Both spaces use float tensors. A saved tensor needs the matching conversion +for its space and VAE weights. +`vae_to_unet_latents` is an alias of `vae_to_dit_latents`, and +`unet_to_vae_latents` is an alias of `dit_to_vae_latents`; each alias resolves +to the same function and uses the same VAE-specific conversion. +Use the UNet names with UNet models and the DiT names with diffusion transformers. + +`vae_encode` defaults to `posterior="sample"`. Set `posterior="mode"` to +take the posterior mode, as InstructPix2Pix does for its reference image. +The mode leaves the RNG state untouched. The two options give the same result +for deterministic encoders. + +```dgl +rng = make_rng("cuda", seed = seed) +reference = vae_encode(vae, pixels, rng = rng, posterior = "mode") +predict = predictor(unet, condition, concat = reference) +latent = sample(start, sigmas, predict = predict, rng = rng) +image = vae_decode(vae, unet_to_vae_latents(vae, latent)) +``` + +`vae_encode` and `vae_decode` accept `tiling=tiling(tile_size_w=32, +tile_size_h=32)`. Use `temporal_tiling=true` for supported video VAEs. +`predictor(circular_x=true, circular_y=true)` enables circular convolution +padding for that prediction branch and its active ControlNets. Branches can +share a model while using different settings; each forward call restores the +previous settings afterwards. Model weights are reused. + +Set the same arguments independently on `vae_encode`, `vae_decode`, or +`preview(decoder=..., circular_x=true, circular_y=true)` for VAE operations +and preview decoding. Latent projection does not use convolution padding. +Configure predictor, VAE and preview padding consistently for seamless +generation. `sample` and `sefi::sample` do not accept circular padding options. + +Load an F32 latent with `tensor::load` and use the matching latent space for the +receiving function. + +Use `vae_decode(..., dtype = "f32")` to postprocess normalized float pixels in +`[width, height, channels, batch]` or `[width, height, time, channels, batch]` +layout. The default `"u8"` returns packed pixels. + +## Image and video files + +Media I/O uses `image::load` / `image::save`, `video::load` / `video::save` +and `audio::load` / `audio::save`. The former global names and the aliases +`read_image`, `read_video`, `read_audio` and `save` have been removed. +Model loading, inference and latent operations keep their current names. +`image::to_f32` and `image::to_u8` convert pixel representations for both images +and video frames; ordinary tensor dtype changes use `tensor::cast`. + +### Image files + +`image::load(path)` decodes PNG, JPEG, BMP and other formats supported by +stb_image into a U8 tensor shaped `[channels, width, height]`. Grayscale with +alpha is decoded as RGBA. `image::save(path, pixels)` writes a U8 pixel tensor +to PNG and returns no value. A write failure interrupts execution. + +```dgl +# version: 0.0.0 +fn main() { + pixels = image::load("input.png") + patch = tensor::crop(pixels, axes = [1, 2], start = [16, 32], size = [256, 256]) + output = tensor::interpolate(patch, axes = [1, 2], size = [512, 512]) + image::save("output.png", output) + return output +} +``` + +Use `mode="nearest_exact"` for half-pixel nearest-neighbor sampling. +`mode="nearest_max"` uses nearest-neighbor sampling when enlarging and the +maximum of each source region when shrinking, preserving active mask pixels. + +### Pixel formats + +`image::to_f32(image)` converts image/video pixels to the F32 +representation used by VAE and conditioning functions: + +| Input | Output | Values | +|---|---|---| +| U8 image `[c, w, h]` | F32 `[w, h, c, 1]` | Divided by 255 | +| U8 video `[c, w, h, t]` | F32 `[w, h, t, c, 1]` | Divided by 255 | +| F32 pixels in either output layout | Same F32 layout | Preserved without rescaling | + +The default preserves the input channel count, including masks and alpha. +Set `channels=3` to request RGB or `channels=4` for RGBA. `channels=0` explicitly +selects the default preservation behavior. Supported channel conversions +are grayscale to RGB/RGBA, RGB to RGBA (opaque alpha), and RGBA to RGB (drop +alpha). One- or two-channel data can be preserved, but RGB-to-grayscale and +grayscale-with-alpha conversion are not provided by this function. F32 input +with preserved or matching channels is borrowed without copying. For example, +`image::to_f32(mask)` keeps a single-channel mask, while a ControlNet RGB hint +can use `image::to_f32(hint, channels=3)`. + +`image::to_u8(pixels)` reverses the layout conversion. It clamps normalized F32 +pixels to `[0, 1]`, scales by 255 and rounds to U8, producing `[c, w, h]` for an +image or `[c, w, h, t]` for a video. It also accepts U8 pixels. For example, +`image::save("output.png", image::to_u8(pixels))` saves a processed F32 image. +Both functions return tensors; they introduce no separate image value type. + +### Encoded media and bytes + +`image::encode(image, format="png")` encodes a U8 pixel tensor in memory. +`video::encode(video, audio?, format="webm")` encodes a complete video using +the video dict's `fps_num` / `fps_den`. An optional audio dict is supported +with `format="avi"`. Both return an ordinary `{data: bytes, mime_type: string}` dict. + +`bytes` is an immutable binary value, including embedded zero bytes. Assignments, +arguments and return values share its buffer. It is distinct from strings and +U8 tensors and is not converted to a flat tensor result. + +```dgl +cover = image::encode(pixels) +clip = video::encode(video) +media::save("output/cover.png", cover) +media::save("output/clip.webm", clip) +return {cover = cover, clip = clip, latent = latent} +``` + +`media::save(path, media)` writes these exact bytes, with no re-encoding or +metadata changes. It checks file-write permission and the extension against the +MIME type. Omit the save calls for in-memory results only. The server's DGL +editor displays returned media and ordinary tensor metadata in the job result. + +| Encoding | MIME type | Requirements | +| --- | --- | --- | +| PNG | `image/png` | Built in | +| VP8 WebM | `video/webm` | `SD_WEBM=ON`; uses independent VP8 frames | +| MJPEG + PCM16 AVI | `video/x-msvideo` | `format="avi"`; offered as a download in the editor | + +Unavailable encoders fail explicitly. WebM encoding rejects nonempty audio; +use `video::encode(video, audio=sound, format="avi")` for a PCM16 soundtrack. +Audio is never silently dropped. See [build options](build.md#webp-and-webm-support). +`video::load` still supports only PCM16 WebM audio: pass `audio=false` to read +frames from files with unsupported audio codecs. + +Encoding embeds the current program when the context's `embed_metadata` option +is enabled. `media::save` preserves that decision. The existing `image::save` +and `video::save` functions remain available for direct file output; AVI file +saving continues to stream its packets instead of buffering the entire file. + +### Reading video + +Video frames use U8 tensors shaped `[3,width,height,frame_count]`, with +interleaved RGB channels. Media I/O groups frames and timing in a normal video +dict, and samples and sample rate in a normal audio dict. Computation operates +on the tensors inside these dicts. +`video::load` detects local files by their contents: + +| Input | Supported data | Build option | +| --- | --- | --- | +| AVI | 24-bit RGB or MJPEG, PCM or IEEE float audio | Always available | +| WebP | Static images or one cycle of animation; no audio | `SD_WEBP=ON` | +| WebM | Independent VP8 keyframes and optional PCM16 audio, as written by this project's CLI | `SD_WEBM=ON` | + +WebP animation decoding handles partial frames, blending and disposal before +returning full RGB canvases. Transparent pixels are composited onto black. +WebM interframe VP8, VP9, laced packets and delayed audio are unsupported; +unsupported audio reports an error suggesting `audio=false`. MP4 and segmented +OpenDML AVI are unsupported. Paths support spaces and Unicode. + +```dgl +# version: 0.0.0 + +fn main() { + input = video::load("input.avi", max_frames = 24) + frames = tensor::interpolate(input.video.frames, size = [512, 512], axes = [1, 2]) + video = {frames = frames, fps_num = input.video.fps_num, fps_den = input.video.fps_den} + video::save("output.avi", video, audio = input.audio) + return { frames = frames, audio = input.audio } +} +``` + +Save the preceding program as `video.dgl` and run it with: + +```sh +./build-dgl/bin/sd-cli -M dgl --script video.dgl --tensor frames frames.npy +``` + +`video::load` returns `{video, audio}`. `video` is a normal dict with `frames` +(tensor), `fps_num` and `fps_den`; `audio` is a normal dict with `samples` +(tensor) and `sample_rate`. With no audio stream, or +with `audio=false`, samples are an empty F32 `[1,0]` tensor and the sample rate +is 0. Passing this empty audio to `video::save` writes no audio track. + +Loading defaults to all frames within the 256 MiB tensor limit. Set `max_frames` +to a positive value to read only that many initial frames. Exceeding the limit +fails instead of silently truncating. Frames are decoded as RGB at the first +video stream's rational frame rate. Setting `fps_num` and `fps_den` resamples +by repeating or skipping frames: each output timestamp uses the latest source +frame at or before that timestamp. `max_frames` applies after resampling. +WebP and WebM use frame timestamps to infer a fixed source frame rate. +Variable or unknown rates require explicit `fps_num` / `fps_den`, including +static WebP images without a frame duration. Static WebP returns a single frame +at the requested rate. For example, `video::load("still.webp", fps_num=24)`. +Animated WebP is read once regardless of its loop count. Streams must start at +time zero. AVI streams with dropped frames are unsupported. Audio is limited +to the selected video duration; AVI accepts PCM or IEEE float samples, and WebM +accepts PCM16 without codec delay, concatenating packet samples in stream order. Use `audio=false` to read frames +from files with unsupported audio codecs. + +`video::load` also reads an image directory in filename order. +`image::load_dir(path, max_images=0)` returns a list of individual images in +filename order, which can have different sizes. A positive `max_images` limits +the list; zero loads every supported image. Both directory readers accept PNG, +JPEG and BMP. Use `video::load` when the directory represents a time sequence, +or `image::load_dir` to process independent images. + +`video::split_windows(frames, size, overlap=0)` returns a list of frame tensors. +`video::join_windows(windows, overlap=0)` joins frame tensors, dropping the specified +overlap from the start of each window after the first, then concatenates the +remaining frames without blending. These operations only handle pixels; +keep frame rate and audio outside the window processing and pass them when saving. +A single full-length window or a single-window join borrows the input tensor. +Joined video has a 4 GiB limit. The 256 MiB loading limit +applies when reading source video. + +### Writing video + +`video::save(path, video, codec="auto", quality=90)` writes `.avi` only. +The video dict requires `frames`, `fps_num` and `fps_den`. Both frame-rate +integers must be in [1,1000000]; timing is explicit. +Saving accepts already allocated frame tensors larger than the loading limit +and encodes them one frame at a time. It sets the playback rate without +resampling frames. Supply `audio` for a soundtrack. `trim_audio=true` truncates +audio longer than the video duration; +shorter audio is retained unchanged. The default is `false`. + +```dgl +video = {frames = pixels, fps_num = 24, fps_den = 1} +video::save("output.avi", video, audio = sound, trim_audio = true) +processed = {frames = processed_frames, fps_num = input.video.fps_num, fps_den = input.video.fps_den} +video::save("upscaled.avi", processed, audio = input.audio) +``` + +`codec="auto"` selects `mjpeg`; `quality` ranges from 1 to 90, with higher +values preserving more detail. Use `codec="rgb"` for uncompressed, pixel-exact +RGB output; it ignores `quality` and produces larger files. Both codecs support +odd frame dimensions. Audio is saved as float32 by default; +`audio_format="pcm16"` writes PCM16. AVI output is limited to less than 4 GiB. +Saving has no return value and does not alter the supplied frames or audio. +Return frame tensors, frame rate and audio explicitly when needed as graph +results. Audio trimming applies only to the file. MJPEG decoding need not match +the input pixels exactly. + +### Audio files + +`audio::load(path)` reads WAV with PCM8/16/24/32 or float32 samples. +`audio::save(path, audio, format="f32")` writes WAV, with `pcm16` also available. +`audio::load` and `audio_vae_decode` return a normal dict with `samples` (F32 +`[channels,samples]` tensor) and `sample_rate` (Hz). Construct the same dict to +save generated or processed samples. Rates range from 1,000 to 384,000 Hz, +with 1..32 channels and a 256 MiB sample limit. Samples must be finite. + +```dgl +sound = audio::load("input.wav") +audio::save("output.wav", sound) +track = {samples = sound.samples, sample_rate = sound.sample_rate} +video::save("output.avi", video, audio = track) +``` + +`encode_audio(encoder, samples, sample_rate=...)` and +`audio_vae_encode(vae, samples, sample_rate=...)` accept tensors and an explicit +sample rate. Their existing model-specific resampling remains in effect. +`audio_vae_decode` reports the decoder's actual output sample rate. + +## Regions and masks + +Use detections to select objects, regions to crop rectangles, and masks to +control which pixels a refinement replaces. + +### Rectangular regions + +A region collection is an ordinary dict `{width, height, boxes}`. Canvas dimensions +are integers in `1..16384`; `boxes` is an I64 tensor with shape `[4,N]`, limited to +10,000 boxes. Each column is `[x,y,width,height]` in source-image pixels and covers +`[x,x+width)` by `[y,y+height)`. Box sizes must be positive and boxes must lie +entirely inside the canvas. An empty collection has shape `[4,0]`. + +`regions::from_boxes(width, height, boxes)` validates a flat `list` or an I64 +`[4,N]` tensor and constructs the dict. A valid input tensor is shared without a +copy. `regions::crop(image, regions)` accepts the same dict, checks its canvas +against the image and returns U8 patches in box order. `regions::paste(background, +foregrounds, regions)` resizes each patch with bilinear interpolation and copies +its pixels into the corresponding rectangle. Later boxes overwrite earlier ones, +including the alpha channel; pasting does not alpha-blend. + +```dgl +r = regions::from_boxes(512, 512, [10, 20, 80, 60, 100, 40, 30, 50]) +selected = {width = r.width, height = r.height, boxes = r.boxes[:, 1:2]} +patches = regions::crop(image, selected) +result = regions::paste(image, patches, selected) +``` + +The slice `[:,1:2]` preserves the `[4,1]` collection shape. `[:,1]` produces a +single `[4]` box. Handwritten dicts receive the same validation as constructed +collections. Boxes can be saved and loaded as ordinary tensors: + +```dgl +tensor::save("boxes.npy", r.boxes) +restored = regions::from_boxes(r.width, r.height, tensor::load("boxes.npy")) +selected = {width = restored.width, height = restored.height, boxes = restored.boxes[:, 1:2]} +``` + +### Detections + +Detection results are ordinary dicts with `xyxy` (F32 `[4,N]`), `scores` +(F32 `[N]`) and `class_ids` (I64 `[N]`). The fields share the same ordering and +count, limited to 4,096 detections. Empty results keep shapes `[4,0]`, `[0]` and +`[0]`. Scores must be finite and in `[0,1]`, class IDs must be nonnegative, and +coordinates must be finite. + +`detections::detect(detector, image, confidence=0.3)` runs the detector once. +`detections::filter(image, detections, ...)` filters or sorts all three fields by +the same indices. `detections::box_masks(image, detections)` rasterizes full-canvas +rectangle masks. Filtering and mask creation require boxes inside the image. +`detections::to_regions(image, detections)` rounds starts down and ends up, +clips coordinates to the canvas and skips empty boxes, preserving order. + +```dgl +found = detections::detect(detector, image, confidence = 0.3) +selected = detections::filter(image, found, top_k = 4, top_k_by = "confidence") +r = detections::to_regions(image, selected) +patches = regions::crop(image, r) +result = regions::paste(image, patches, r) +``` + +`regions::plan_mask_crops` returns per-mask `{box, mask, index}` tasks for `fold`, +not a region collection. Masked compositing can be expressed with a crop, +`tensor::lerp` and slice replacement: + +```dgl +background = tensor::crop(image, axes = [1, 2], start = box[:2], size = box[2:]) +patch = tensor::lerp(background, foreground, mask) +rows = tensor::crop(image, axes = [2], start = [box[1]], size = [box[3]]) +band = tensor::replace_slice(rows, patch, axis = 1, start = box[0]) +result = tensor::replace_slice(image, band, axis = 2, start = box[1]) +``` + +### Detail refinement + +`detections::detect(detector, image, confidence=0.3)` returns a dict with F32 +`xyxy` `[4,N]`, F32 `scores` `[N]` and I64 `class_ids` `[N]`. Use `input_size` +to change the detector input size, `nms` for the overlap threshold, and +`max_detections` to cap the result at up to 4,096 objects. +`detections::filter` applies `min_area_ratio` and `max_area_ratio` before +selecting up to `top_k` boxes. Set `top_k=0` to keep every box between the area +limits. Use `top_k_by="area"` or `"confidence"` to rank them for selection, +and `sort_by` to set the output order (`"none"`, `"left_to_right"`, +`"center_to_edge"`, or `"area"`). Coordinates, scores and class IDs stay aligned. +Use `detections::box_masks` to rasterize the selected boxes, or +`detections::to_regions` to crop them without running detection again. + +Apply mask transforms before passing full-canvas masks to +`regions::plan_mask_crops(masks, aspect=[1, 1], padding=32)`. Each nonempty mask produces +a dictionary containing `box` (I64 `[x, y, width, height]`), the original `mask`, +and its zero-based `index` among nonempty masks. Set `only_masked=false` to +use the whole canvas. Choose prompts and seeds in the script. Use `index` to +look up per-region values or to preserve seed offsets when selecting a subset. + +The [ADetailer program](dgl/adetailer/adetailer-existing-image.dgl) uses `fold` to crop and +resize pixels from the latest canvas before inpainting each region. It +defines sampler settings in DGL and uses `tensor::gaussian_blur` on the +full-canvas mask for feathering. It resizes the decoded patch to the box, +blends with `tensor::lerp` and writes it back with `tensor::replace_slice`. +Crop resizing uses the selected box as the interpolation boundary. + +### Mask composition + +Use `tensor::translate` to shift a mask, `tensor::maximum` to merge masks and +`tensor::gaussian_blur` to soften their boundaries before blending a patch. +Convert U8 mask weights to floating point and divide by 255 before using them +with `tensor::lerp`. To create a binary U8 mask from RGB, call +`tensor::grayscale` and then `tensor::threshold` with `low=0, high=255`. +Swap those output values to invert the binary mask. + +Use maximum pooling for dilation and minimum pooling for erosion. Specify +`pad_value=0` for zero-filled borders. For a four-pixel window anchored like +ADetailer, set `padding_before=[2, 2]` and `padding_after=[1, 1]` to preserve +the mask size. The Wan examples fill selected time indices with +`tensor::index_fill` to build a frame mask. + +## Advanced component programs + +Browse the [example index](dgl/README.md) for complete scripts organized by model. + +### Image refinement + +This example encodes an input image, samples the tail of a noise schedule and returns both the refined image and its latent. + +```dgl +# version: 0.0.0 + +var { + weights = "sd15.safetensors" + + input_path = "input.png" + output_path = "output.png" + + prompt = "A small house in a forest clearing" + + seed = 42 +} + +fn refine(image, vae, unet, text, prompt, seed) { + encode_rng = make_rng("cuda", seed = seed) + resized = tensor::interpolate(image, axes = [1, 2], size = [512, 512]) + base = vae_to_unet_latents(vae, vae_encode(vae, resized, rng = encode_rng)) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, ""), prediction = "eps") + guided = cfg(pos, neg, scale = 7) + full_sigmas = make_sigmas(guided, latent = base, scheduler = "karras", steps = 20) + sigmas = full_sigmas[-13:] + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, rng = rng) + return { image = vae_decode(vae, unet_to_vae_latents(vae, latent)), latent = latent } +} + +fn main() { + vae = load_vae(weights) + unet = load_unet(weights) + text = load_text_encoder(weights) + refined = refine(image::load(input_path), vae, unet, text, prompt, seed) + image::save(output_path, refined.image) + return { image = refined.image, latent = refined.latent } +} +``` + +### Conditioning, inpainting and adapters + +- [SD 1.5 ControlNet](dgl/sd/sd1-5-controlnet.dgl) and + [Z-Image ControlNet](dgl/z_image/z-image-turbo-controlnet.dgl) load control + weights with `controlnet::load`. Use `controlnet::apply(condition, model, hint)` + to attach a control to a condition before passing it to `predictor`. Apply + it again on the returned condition to add another control. Set each binding's + `strength` and use `start_sigma` and `end_sigma` for its inclusive range + `end_sigma <= sigma <= start_sigma`. Both bounds are optional. Use + `t_to_sigma` to derive bounds from noise time, for example + `end_sigma=t_to_sigma(pos, t=0.2)`. The same bounds apply after slicing + the sigma tensor. Specify `type` on each binding of a classic Union + checkpoint. Supply RGB float pixels for SD 1.5 or a packed 33-channel + diffusion latent for Z-Image. Z-Image runs control blocks on the DiT compute + backend as part of its graph. +- [Inpainting](dgl/sd/sd1-5-inpainting.dgl) separately encodes the original and + masked pixels. Its `latent_mask` function resizes and broadcasts the mask. + `tensor::max_pool2d` expands it for per-step blending. Pass the clean + `base` and the `denoise_mask` to `sample`. + Set `mask_input=true` for a program that anchors known pixels or keyframes at the + input of each prediction as well. +- [IP-Adapter](dgl/ip_adapter/ip-adapter-sd1-5.dgl) encodes the image with + `encode_vision` and projects both the conditional and unconditional vision + embeddings with `ip_adapter::project`. Attach each set of tokens with + `ip_adapter::apply(condition, adapter, tokens)` before constructing its + predictor. Each call adds an adapter with its own `strength` and optional + `start_sigma` and `end_sigma` bounds. + [Classic and Plus use different vision inputs](models/ip_adapter.md#dgl). +- [PuLID](dgl/pulid/pulid-flux1-schnell.dgl) loads the attention weights with + `pulid::load` and the precomputed identity with `pulid::load_embedding`. + `pulid::apply(condition, pulid, embedding)` binds an identity to one + predictor branch. Set its `strength` and optional `start_sigma` and + `end_sigma` bounds. +- [PhotoMaker](dgl/photo_maker/photomaker-v1-sdxl.dgl) precomputes reusable identity + tokens with `photomaker::encode_images`. `photomaker::encode_prompt` returns the + plain condition, the prompt with identity slots, and a slot mask. + `photomaker::apply` fuses the identity into that condition. + `switch_predictor` selects when to use it. + [PhotoMaker v2](dgl/photo_maker/photomaker-v2-sdxl.dgl) also passes the + float32 face embeddings from `tensor::load` to `photomaker::encode_images`. +- [Inline prompt images](guides/prompt_images.md#dgl) use + `` in `encode_prompt`. DGL reads the file during execution. + `image_bindings` can also supply tensors produced earlier in the graph. + +- [ADetailer](dgl/adetailer/adetailer-existing-image.dgl) filters detections, rasterizes + boxes and uses tensor pooling and blur to transform the masks. Use + `tensor::maximum` in a `fold` to merge selected masks before planning regions. + A separate `fold` composites each result before cropping the next one. + +### Model-specific sampling + +- [SeFi](dgl/sefi_image/sefi-image-5b-rl.dgl) uses `sefi::make_sigmas` for the texture and semantic + schedules as F32 tensors and passes both explicitly to `sefi::sample`. + The SeFi solver uses Euler and accepts repeated sigma values in either + schedule. It shares mask, finish, cache and callback handling with `sample`. + Slice out texture channels `[16, 144)` before converting them for the VAE. +- [AnimateDiff](dgl/animatediff/animatediff-realisticvision-v6-txt2video-cpu-offload.dgl) loads a motion module with + `animatediff::load` and attaches it to a compatible SD 1.5 UNet with + `animatediff::apply`. The frame count comes from the batch axis of the UNet + latent. [Wan I2V](dgl/wan/wan2-1-i2v-14b.dgl), + [VACE](dgl/wan/wan2-1-vace-1-3b-video2video.dgl) and [S2V](dgl/wan/wan2-2-s2v-14b.dgl) + show the vision, control and driving-audio ports respectively. +- [LTX](dgl/ltx2/ltx-2-3-dev-txt2video.dgl) and [MiniMax-H3](dgl/minimax_h3/minimax-h3-text-to-av.dgl) + build video and audio latents separately. Their `pack_av` and `unpack_audio` + functions pack unbatched latents for joint prediction and recover the audio. + Zero-padding the audio tail fills whole video channels. For a packed AV mask, broadcast + the video mask to the video latent shape and fill the packed audio channels + with ones. The video VAE and `audio_vae_decode` run separately before saving. Pass `audio=audio` and + `trim_audio=true` to `video::save` to match the video duration, as in + the MiniMax-H3 and Wan S2V examples. A video model can + receive the audio latent length and frame rate explicitly on its predictor. + The MiniMax-H3 script scales the clean audio by `video_shift / audio_shift` + when packing it for sampling. It divides by that ratio when unpacking the + final latent. For masked sampling, pack the clean `base` with the same + scale. The predictor receives both shifts as explicit inputs. + LTX text encoding also runs the video and audio embedding connectors and + static caption projections. Pass a separate connector file to + `load_text_encoder(connectors_path=...)`; use `projection_path` for static + conditioning weights stored in the diffusion checkpoint. `encode_prompt` + returns the prepared video condition in `crossattn` and the audio condition + in `extra_crossattn[0]`. Both are cached together and passed directly to the + DiT. `load_dit` does not accept `connectors_path`. + +#### Reference inputs and timing + +MiniMax-H3 reference blocks use a native `list` directly, both in +`predictor(..., reference_blocks=...)` and in the condition's `reference_blocks` +field. The former `reference_blocks(...)` packing helper has been removed. +Each block has a `kind` of `image`, `video`, `audio` or `video_audio`. +`image` and `video` require a `video` index into `ref_latents`; `audio` requires +an `audio` index into `ref_audios`; `video_audio` requires both. Indices are +zero-based nonnegative integers, and list order determines reference order. +If `ref_latents` is empty, video indices refer to the condition's `ref_images`. +The explicit argument overrides the condition field, including an empty list. +Malformed blocks or out-of-range indices fail when constructing the predictor, +with the block number and field in the diagnostic. + +```dgl +p = predictor(dit, condition, + ref_latents = [portrait, clip], ref_audios = [soundtrack], + reference_blocks = [ + {kind = "image", video = 0}, + {kind = "video_audio", video = 1, audio = 0} + ]) +``` + +`ltx::video_positions` builds F32 `[2,3,N,1]` token bounds in seconds and pixels. +Pass the target latent before concatenating keyframes. `keyframe_frame_index` +is the keyframe's zero-based position in the output video; +`keyframe_pixel_frames` is its span in original frames; +`keyframe_latent_frames` is the number of appended latent frames. The former +`keyframe_frame` and `keyframe_frames` parameter names are removed. + +`wan::s2v_audio_window(features, latent_frames=...)` aligns audio features to +Wan S2V's timeline. It returns `[feature_dim, 4 * latent_frames, layers]`, +resampling 50 Hz features to 30 Hz before selecting positions at 16 fps. +Samples beyond the audio are zero-filled. The old `frames` argument is removed; +use `latent_frames = tensor::shape(base)[2]` to follow the generated video. + +### Upscaling and hires passes + +- Image hires resizes the first-pass latent and chooses a second-pass sigma + tail with tensor indexing. Keep the last `floor(steps * strength)` steps + and the terminal sigma. + [Video Hires](dgl/ltx2/ltx-2-3-spatial-upscale.dgl) loads a separate + `load_latent_upscaler` resource, runs `upscale_latent`, then repacks + the audio and samples a second time. LTX upscalers take and return VAE + latents, with the scale inferred from the weights. MiniMax H3 upscalers + take and return diffusion latents and accept target `width` and `height` + in latent units. Both adapters accept `[W,H,T,C]` or `[W,H,T,C,1]`, + with channels matching the checkpoint. A single frame uses `T=1`; ordinary + image latents `[W,H,C,B]` are a different layout and are not interchangeable. + The latent must also come from a compatible model/VAE. SeedVR2 uses the + separate pixel-resize, VAE encode, DiT sampling and VAE decode workflow; + it is not a `load_latent_upscaler` backend. The former `upscale_video_latent` + name is removed without an alias. +- [RelayVSR](dgl/relay_vsr/relayvsr-x2-video-upscale.dgl) selects keyframes with tensor + functions and assembles a predictor condition with the checkpoint's + `crossattn` embedding and the low-resolution `lq_frames` tensor. A single + Euler step produces exportable keyframe latents. `relayvsr::decode` reads + those latents, the I64 keyframe indices, and the original U8 frames to + reconstruct the video. Use a matching 2x or 4x DiT and Flash VAE. +- [SeedVR2](dgl/seedvr2/seedvr2-3b-video-upscale.dgl) loads its DiT and VAE with + `load_dit` and `load_vae`. The example resizes and pads each pixel window + with tensor functions, encodes it with `vae_encode`, and explicitly + assembles the predictor's `crossattn` embedding and `concat` condition. + A shared RNG feeds the noise and the one-step Euler sampler. The script + decodes and crops each result before joining the windows. `video::join_windows` discards the + specified overlap from the returned frame tensors. Frame rate and audio are + passed separately to `video::save` after joining. + +### Function names and namespaces + +Generic model components and inference stay at the top level. Family- or +extension-specific operations use their own namespace, such as +`controlnet::load` / `controlnet::apply`, `ip_adapter::project` and +`photomaker::encode_images`. Extension `apply` functions retain their own +execution and resource-lifetime rules; their names do not imply deferred execution. + +Generic `load_lora`, `apply_lora`, `encode_prompt`, `sample` +and component loaders remain top-level. + +The following global names have been replaced without aliases. Parameter names, +argument order, defaults and result fields are unchanged: + +| Previous name | Current name | +|---|---| +| `load_controlnet` | `controlnet::load` | +| `apply_controlnet` | `controlnet::apply` | +| `load_ip_adapter` | `ip_adapter::load` | +| `ip_adapter_tokens` | `ip_adapter::project` | +| `apply_ip_adapter` | `ip_adapter::apply` | +| `load_photomaker` | `photomaker::load` | +| `photomaker_tokens` | `photomaker::encode_images` | +| `encode_photomaker_prompt` | `photomaker::encode_prompt` | +| `apply_photomaker` | `photomaker::apply` | +| `load_pulid` | `pulid::load` | +| `load_pulid_embedding` | `pulid::load_embedding` | +| `apply_pulid` | `pulid::apply` | +| `load_animatediff` | `animatediff::load` | +| `apply_animatediff` | `animatediff::apply` | +| `ltx_video_positions` | `ltx::video_positions` | +| `s2v_audio_window` | `wan::s2v_audio_window` | +| `sefi_sigmas` | `sefi::make_sigmas` | + +## C API + +Include `stable-diffusion.h` for the DGL and tensor APIs. + +Structured results expose `bytes` as `SD_DGL_VALUE_BYTES`. +`sd_dgl_value_get_bytes(value, &data, &size)` returns a borrowed `const void*` +and length, with no terminator or text conversion. The pointer remains valid +until `sd_dgl_result_free`. Existing enum values and getters are unchanged. + +`sd_dgl_check` checks source without creating a context or loading models. +Pass `false` for a self-contained script, as the CLI's `--check` does, or +`true` to allow named tensor parameters in `fn main(...)`. + +```c +const char* source = "fn main() { return load_unet(\"model.safetensors\") }"; +sd_status_t status = sd_dgl_check(source, false); +if (status != SD_STATUS_OK) { + fprintf(stderr, "%s\n", sd_get_last_error()); +} +``` + +Execution requires an explicit context. Create one with `sd_dgl_ctx_create` +to share loaded components across scripts, or `sd_dgl_ctx_create_once` to +release components after their last use in each run. Configure it while idle, +then pass source directly to `sd_dgl_run`. Every run compiles the source once; +there is no public compiled-program handle or graph cache. A normal execution +does not need a preceding `sd_dgl_check` call. + +This example configures a context, runs a script without host inputs, and reads +its structured result: + +```c +const char* source = "fn main() { return { pixels = tensor::zeros([2, 3]) } }"; +sd_dgl_ctx_t* ctx = sd_dgl_ctx_create(); +sd_dgl_result_t* result = NULL; +if (ctx && sd_dgl_ctx_set(ctx, "max_ram", "24")) { + sd_status_t status = sd_dgl_run(ctx, source, NULL, 0, &result); + if (status == SD_STATUS_OK) { + const sd_dgl_value_t* root = sd_dgl_result_root(result); + const sd_tensor_t* pixels = sd_dgl_value_tensor(sd_dgl_value_field(root, "pixels")); + sd_tensor_save(pixels, "pixels.npy"); + } else { + fprintf(stderr, "%s\n", sd_get_last_error()); + } +} +sd_dgl_result_free(result); +sd_dgl_ctx_free(ctx); +``` + +Keep the context alive until all calls using it return. Free it with +`sd_dgl_ctx_free` when its cached components are no longer needed. + +### Host tensor inputs + +Standalone scripts can read tensors with `tensor::load(path)` or embed them +with `tensor::literal`. A C host can pass source with named tensor parameters +directly to `sd_dgl_run`. Supply exactly one binding per parameter. Compilation +always permits these parameters; a missing binding reports a missing input. +Unknown or duplicate names and null tensors are also rejected. +Bindings share the existing immutable tensor handles. The same source can be +run with different bindings on subsequent calls; each call compiles it anew. +Use `sd_dgl_check(source, true)` when only validation is needed. + +```c +/* ctx is an existing DGL context and pixels is an immutable tensor. */ +const char* source = "fn main(pixels) { return { image = pixels, label = \"input\" } }"; +sd_dgl_result_t* result = NULL; +const sd_dgl_tensor_input_t input = {"pixels", pixels}; +sd_status_t status = sd_dgl_run(ctx, source, &input, 1, &result); +if (status == SD_STATUS_OK) { + const sd_dgl_value_t* root = sd_dgl_result_root(result); + const sd_tensor_t* image = sd_dgl_value_tensor(sd_dgl_value_field(root, "image")); + sd_tensor_save(image, "pixels-copy.npy"); +} +sd_dgl_result_free(result); +``` + +### Context execution settings + +Set these options with `sd_dgl_ctx_set` while the context is idle or use the +corresponding `sd-cli` and `sd-server` flags. The settings apply throughout the +context. A `linear_type` context setting overrides the loader's `linear_type` +argument for each selected module. + +| Context key | CLI and server flag | Default | +| --- | --- | --- | +| `n_threads` | `--threads N` or `-t N` | Physical core count | +| `auto_fit` | `--auto-fit on\|off` | On | +| `batched_cfg` | `--batched-cfg on\|off` | On | +| `embed_metadata` | `--disable-image-metadata` to turn off | On | +| `enable_mmap` | `--mmap` | Off | +| `eager_load` | `--eager-load` | Off | +| `disable_prefetch` | `--disable-prefetch` | Off | +| `disable_segmented_compute` | `--disable-segmented-compute` | Off | +| `linear_type` | `--linear-type` with `auto\|i8\|raw` or module assignments such as `dit=i8` | `auto` (currently equivalent to `raw`) | + +The context accepts a thread count from 1 to 4096 and boolean strings such as +`"on"` and `"off"`. Changing threading, placement or weight-loading options +discards cached models so they can be loaded with the new settings on next use. +Models using graph-cut layer splitting prepare weights lazily even when eager +loading is enabled. + +`image::save` (PNG) and `video::save` (AVI) embed the exact executed DGL source +by default. Set `sd_dgl_ctx_set(ctx, "embed_metadata", "off")` to disable this +for all saves in that context. The CLI forwards `--disable-image-metadata` to +this setting in DGL mode. Changing it leaves loaded models cached. Metadata +records the program text; host tensor contents and input files are not embedded. + +`batched_cfg` combines compatible positive and negative `cfg` branches into one +UNet forward with batch size two. The branches must use the same model, matching +conditioning shapes and matching circular settings. Predictors with transforms, +references, ControlNet, IP-Adapter, PuLID, AnimateDiff or active sampling caches +retain separate forwards, as do branches using different models or incompatible +shapes. Branch selection through `switch_predictor` is resolved before checking +compatibility. CFG with scale one only computes the positive branch unless the +sampler also needs the unconditional prediction. Batching uses more compute +memory and can produce small floating-point differences. Set `batched_cfg` to +`"off"` to force separate forwards. Changing it affects subsequent runs without +invalidating loaded models. + +Register RPC devices in the host with `sd_add_rpc_servers` or use +`--rpc-servers HOST:PORT` at CLI or server startup. A loader can then select a +registered RPC device with its `backend` option. + +Set `conditioning_cache_size` with `sd_dgl_ctx_set` or use +`--conditioning-cache-size` with `sd-cli` or `sd-server`. The default is 4 entries +per text encoder instance, including each LoRA variant. Lowering the capacity +evicts the least recently used entries immediately. A capacity of 0 clears the +caches and disables caching. Loaded encoders and their weights are reused when +the capacity changes. + +### File access and memory budgets + +Install a file access callback with `sd_dgl_ctx_set_file_access_callback` before +running scripts in a context. The callback receives a UTF-8 path and an access +type for input reads, model reads or writes. Returning false ends the run with a +file access error. Keep its user data valid throughout the run. Model reads +include checkpoints, referenced shards and external tokenizers. Without a +callback, file access follows the process's permissions. + +#### Memory budgets + +```c +sd_dgl_ctx_t* ctx = sd_dgl_ctx_create(); +sd_dgl_result_t* result_a = NULL; +sd_dgl_result_t* result_b = NULL; +if (ctx && sd_dgl_ctx_set(ctx, "max_ram", "24") && + sd_dgl_ctx_set(ctx, "max_vram", "cuda0=12")) { + /* source_a and source_b can reuse the same encoder and VAE. */ + sd_status_t status = sd_dgl_run(ctx, source_a, NULL, 0, &result_a); + if (status == SD_STATUS_OK) { + status = sd_dgl_run(ctx, source_b, NULL, 0, &result_b); + } + if (status != SD_STATUS_OK) { + fprintf(stderr, "%s\n", sd_get_last_error()); + } +} +sd_dgl_result_free(result_a); +sd_dgl_result_free(result_b); +sd_dgl_ctx_free(ctx); +``` + +The context's `max_vram` applies to all components on each device. Set the +context limits from the CLI with `--max-vram` and `--max-ram`. Idle GPU weights may +stay resident between runs. Under pressure the context reclaims idle buffers +and reloads weights from their configured parameter backend when needed. +With `params_backend="disk"`, weights are read on demand and their buffers +are released after use. + +`max_ram` caps allocated host weight buffers across the context, including +pinned host buffers used by CUDA. Set it in GiB with `sd_dgl_ctx_set`. +A value of `0` disables the explicit cap and keeps the system memory pressure +check, which subtracts 1 GiB from the available RAM reported by the OS. +On Windows, this also accounts for the remaining commit capacity, including +CUDA weight staging, prefetch, and compute buffer allocations under WDDM. Device +allocations reserve commit capacity without charging their size to physical RAM. Graph +metadata allocations request space from the same memory manager and can reclaim +idle weights before creating a scheduler. Temporary graph memory does not count +against the host weight limit. +For CPU execution, automatic placement checks weight storage against this cap +and separately checks weights plus workspace against available system memory. +Lowering the cap trims idle weights immediately. Before a new allocation, +the context can evict old CPU weights together with their idle GPU copies, or +unload an idle component. Reclaimed weights reload from their source files on +the next use. A request whose active weights cannot fit reports the required +and available capacity. Automatic placement also uses the cap when choosing +where to keep new weights. + +The cap covers weight buffers. Allow separate RAM for graph workspaces, +intermediate tensors and other process allocations. The OS manages pages in +read-only weight mappings. With a cap enabled, weights that need writable +mappings for in-place LoRA merges use allocated buffers. + +#### Automatic weight placement + +Set `backend` and `params_backend` on loaders in the script. The context's +`auto_fit` setting can move components to another GPU when `params_backend` +is empty; it is enabled by default and cannot be overridden by individual +loaders. +Each run prepares one weight-placement plan for the graph, including models +already cached in the context. Compilation tracks actual model use separately +from metadata queries and model captures. For example, `latent_shape` does not +need VAE weights, while a VAE preview observer keeps the decoder in the sampling +working set when VAE/TAE preview callbacks are enabled. Unrelated scalar +operations do not change the model-use phases. + +If a loader omits `backend`, the run compares available GPU budgets before +constructing runners and uses the selected device consistently for default +loaders. Explicit backend choices and split layouts remain unchanged. + +Before computation, the runtime constructs missing runner metadata without +loading all weights, then compares registered parameter sizes with device +capacity and the context budgets. Parameters stay on their compute device and +move to RAM, then disk, under pressure, as described in +[weight residency](guides/backend.md#weight-residency). When the main GPU and +RAM cannot hold all weights, components other than diffusion models +(`load_dit` / `load_unet`) move to another GPU that holds all of their weights, +lowest priority first. Explicit backends and split layouts remain constraints. +Under pressure, weights with no remaining use or the farthest next use are +reclaimed first. Idle weights remain cached when there is no pressure. + +GGML sizes compute workspaces from the actual graphs built during execution. +The first plan reserves conservative workspace headroom; actual workspace +allocations and changes in external memory use are still checked at runtime. +Models first encountered inside an iteration join the remaining plan when +their loader executes. LoRA buffers and merged variants also retain runtime +allocation checks. + +### Progress, preview and cancellation + +Register callbacks on an idle context with `sd_dgl_ctx_set_progress_callback` +and `sd_dgl_ctx_set_preview_callback`. They run synchronously on the executing +thread and receive events for that context's current run. A null callback +clears the registration. The sampling pass counter starts at one on each +run. Progress can report model loading in tensors, sampling in steps, video +upscaling in frames, or a stage with no known total. +Without a progress callback, the DGL execution layer displays sampling and +weight-loading progress bars. Set `sd_dgl_ctx_set(ctx, "console_progress", "on")` +on an idle context to display those bars alongside a progress callback. + +The default observer handles previews. Preview mode `proj` uses latent projection. Modes `tae` and `vae` +use the decoder supplied to `preview(decoder=...)`, falling back to projection. A positive interval +previews each matching completed logical step. Intermediate model evaluations, +such as Heun's first evaluation, do not produce duplicate previews or progress +events. Zero previews the final step of the first sampling pass. +A negative interval selects the step at its absolute value. The callback +receives the pass number, total steps and borrowed frame tensors. Use +`sd_tensor_retain` if a frame must outlive the callback. + +`sd_dgl_ctx_cancel` can be called from a callback or another thread. An +idle context accepts the call without queuing a cancellation. The current +run stops at an execution boundary, such as between sampling steps or +after an in-flight model load completes. Cancellation requested during compilation +is checked after compilation, before binding inputs and executing. The API returns +`SD_STATUS_CANCELLED` with a null result. Files already written by the +script remain on disk. Keep the context alive +until calls using it have returned. Concurrent or reentrant runs on the +same context return `SD_STATUS_BUSY`. + +### Results and diagnostics + +`sd_dgl_result_root` exposes the returned value with typed scalar access, +tensor handles and nested dict or list children. Audio and video reads return +ordinary dicts and tensors, using the same result traversal as other values. +Region collections are ordinary dicts with integer `width` and `height` and an +I64 `boxes` tensor shaped `[4,N]`, with `[x, y, width, height]` per column. +A root region dict flattens to `boxes`, `width` and `height`; a field named +`regions` flattens to `regions.boxes`, `regions.width` and `regions.height`. +Export root coordinates with `--tensor boxes boxes.npy`, replacing the old +`--tensor result boxes.npy`. Cast old I32 files to I64 before reuse. Runtime objects such as models and RNGs appear as opaque values. + +A function without a return value has result type `void`, no output tensors, +and an `SD_DGL_VALUE_VOID` root through the structured C API. + +A single returned tensor is named `result`. Named returns retain their names; +lists add numeric path components. Conditioning expands into fields such as +`positive.crossattn` and `positive.vector`. Use `sd_dgl_result_count/name/tensor` +to enumerate the actual outputs. `sd_tensor_save` writes `.npy` using the reversed +shape so NumPy sees normal row-major dimensions; RGB becomes `(height,width,3)`. + +In the flat tensor view, strings are UTF-8 U8 arrays without a terminating zero +byte. + +Values and tensors are borrowed from the result. Use `sd_tensor_retain` +to keep a tensor past the result's lifetime. Results remain valid after +freeing the context. All destructors accept `NULL`. + +Failed runs leave `*result_out` as `NULL`. Both check and run return +`sd_status_t`; compare it explicitly with `SD_STATUS_OK`. Use +`sd_get_last_error()` for the thread-local diagnostic for DGL and other C +API calls. `sd_dgl_error()` reads the same diagnostic. Syntax and +execution diagnostics include source locations when available. diff --git a/docs/dgl/README.md b/docs/dgl/README.md new file mode 100644 index 0000000000..2f25476033 --- /dev/null +++ b/docs/dgl/README.md @@ -0,0 +1,116 @@ +# DGL examples + +Choose a runnable script for [image generation and editing](#image-generation-and-editing), +[video and audio generation](#video-and-audio-generation), or +[adapters, refinement and upscaling](#adapters-refinement-and-upscaling). +Each model name links to its guide for weights and setup. + +## Run an example + +Open the script's `var` block and set the model paths, input files, prompt and +output path. Run the following commands from the CMake build directory. Relative +paths in the script resolve from that directory. + +**Windows (PowerShell, Visual Studio Release)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\sd\sd1-5-txt2img.dgl --check +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\sd\sd1-5-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/sd/sd1-5-txt2img.dgl --check +./bin/sd-cli -M dgl --script ../docs/dgl/sd/sd1-5-txt2img.dgl +``` + +The first command checks the script without loading weights. The second runs it +and writes to the output path in the script. Set context options such as +`--max-vram` and `--auto-fit` on the command line. In the server's DGL editor, +choose model paths under a configured model directory and save results under +`output/`. See the [server guide](../../examples/server/README.md#dgl-editor). + +For a large video input, set `max_frames` on `video::load` to limit how many +frames it decodes. See [video input formats and limits](../dgl.md#reading-video) +and [NumPy tensor files](../dgl.md#tensor-files). + +## Model examples + +### Image generation and editing + +| Model guide | Scripts | +| --- | --- | +| [Anima](../models/anima.md) | [Anima Preview text to image](anima/anima-preview-txt2img.dgl) | +| [Boogu Image](../models/boogu_image.md) | [Text to image](boogu_image/boogu-image-base-txt2img.dgl) · [Image editing](boogu_image/boogu-image-edit.dgl) | +| [Chroma](../models/chroma.md) | [Unlocked v40 text to image](chroma/chroma-unlocked-v40-txt2img.dgl) | +| [Chroma1-Radiance](../models/chroma_radiance.md) | [Text to image](chroma_radiance/chroma1-radiance-v0-4-txt2img.dgl) | +| [Distilled Stable Diffusion models](../models/distilled_sd.md) | [SSD1B](distilled_sd/ssd1b-txt2img.dgl) · [SDXS-512-DreamShaper](distilled_sd/sdxs-512-dreamshaper-txt2img.dgl) | +| [ERNIE-Image](../models/ernie_image.md) | [ERNIE-Image Turbo](ernie_image/ernie-image-turbo-txt2img.dgl) · [ERNIE-Image](ernie_image/ernie-image-txt2img.dgl) | +| [Fibo 2.0](../models/fibo2.md) | [Dev: text to image](fibo2/fibo2-dev-txt2img.dgl) · [Dev: image editing](fibo2/fibo2-dev-edit.dgl) · [Edit Turbo](fibo2/fibo2-edit-turbo.dgl) | +| [FLUX.1](../models/flux.md) | [FLUX.1 dev](flux/flux1-dev-txt2img.dgl) · [FLUX.1 schnell](flux/flux1-schnell-txt2img.dgl) · [FLUX.1 dev with LoRA](flux/flux1-dev-lora.dgl) | +| [FLUX.2 dev](../models/flux2.md) | [Image editing](flux2/flux2-dev-edit.dgl) | +| [FLUX.2 Klein 4B](../models/flux2.md) | [Text to image](flux2/flux2-klein-4b-txt2img.dgl) · [Image editing](flux2/flux2-klein-4b-edit.dgl) · [Base text to image](flux2/flux2-klein-base-4b-txt2img.dgl) | +| [FLUX.2 Klein 9B](../models/flux2.md) | [Text to image](flux2/flux2-klein-9b-txt2img.dgl) · [Image editing](flux2/flux2-klein-9b-edit.dgl) · [Base text to image](flux2/flux2-klein-base-9b-txt2img.dgl) | +| [FLUX.3 Image](../models/flux3.md) | [Klein: text to image](flux3/flux3-image-klein-txt2img.dgl) · [Klein: image editing](flux3/flux3-image-klein-edit.dgl) · [Klein Base: text to image](flux3/flux3-image-klein-base-txt2img.dgl) | +| [HiDream-O1-Image](../models/hidream_o1_image.md) | [Text to image](hidream_o1_image/hidream-o1-image-dev-txt2img.dgl) | +| [Ideogram4](../models/ideogram4.md) | [Text to image](ideogram4/ideogram4-txt2img.dgl) | +| [Iris-3B](../models/iris.md) | [Text to image](iris/iris-3b-txt2img.dgl) | +| [FLUX.1 Kontext](../models/kontext.md) | [Edit with FLUX.1 Kontext dev](kontext/flux1-kontext-dev-edit.dgl) | +| [Krea2](../models/krea2.md) | [Raw text to image](krea2/krea2-raw-txt2img.dgl) | +| [Lens](../models/lens.md) | [Lens](lens/lens-txt2img.dgl) · [Lens Turbo](lens/lens-turbo-txt2img.dgl) | +| [LLaDA-Image](../models/llada_image.md) | [Text to image](llada_image/llada-image-turbo-txt2img.dgl) · [Image editing](llada_image/llada-image-turbo-edit.dgl) | +| [LongCat Image](../models/longcat_image.md) | [Text to image](longcat_image/longcat-image-txt2img.dgl) | +| [Mage-Flow](../models/mage_flow.md) | [Text to image](mage_flow/mage-flow-turbo-txt2img.dgl) · [Image editing](mage_flow/mage-flow-edit.dgl) | +| [Ming-Image](../models/ming_image.md) | [0.1 Design text to image](ming_image/ming-image-0-1-design-txt2img.dgl) | +| [MiniMax-H3-Image](../models/minimax_h3_image.md) | [Text to image](minimax_h3_image/minimax-h3-image-txt2img.dgl) · [Image editing](minimax_h3_image/minimax-h3-image-edit.dgl) | +| [MiniT2I](../models/minit2i.md) | [CUDA](minit2i/minit2i-cuda-txt2img.dgl) · [Metal](minit2i/minit2i-metal-txt2img.dgl) (`--threads 8`) | +| [MOSS-Image](../models/moss_image.md) | [Base: text to image](moss_image/moss-image-base-txt2img.dgl) · [SFT: text to image](moss_image/moss-image-sft-txt2img.dgl) · [Inline images](moss_image/moss-image-sft-inline-images.dgl) · [Image editing (HQ)](moss_image/moss-image-edit.dgl) · [Image editing (chinoll)](moss_image/moss-image-edit-chinoll.dgl) | +| [Ovis-Image](../models/ovis_image.md) | [Text to image](ovis_image/ovis-image-txt2img.dgl) | +| [P-H3-Image](../models/p_h3_image.md) | [Text to image](p_h3_image/p-h3-image-txt2img.dgl) · [Image editing](p_h3_image/p-h3-image-edit.dgl) | +| [PiD](../models/pid.md) | [512 to 2048 pixels](pid/pid-flux1-512-to-2048-txt2img.dgl) | +| [PixArt](../models/pixart.md) | [Sigma XL2 at 1024 pixels](pixart/pixart-sigma-xl2-1024-ms-txt2img.dgl) | +| [Qwen Image](../models/qwen_image.md) | [Text to image](qwen_image/qwen-image-txt2img.dgl) | +| [Qwen Image 2.1](../models/qwen_image_2.1.md) | [Text to image](qwen_image_2.1/qwen-image-2-1-txt2img.dgl) · [Image editing](qwen_image_2.1/qwen-image-2-1-edit.dgl) | +| [Qwen Image Edit](../models/qwen_image_edit.md) | [Qwen Image Edit](qwen_image_edit/qwen-image-edit.dgl) · [Qwen Image Edit 2509](qwen_image_edit/qwen-image-edit-2509.dgl) · [Qwen Image Edit 2511](qwen_image_edit/qwen-image-edit-2511.dgl) | +| [Stable Diffusion – generation](../models/sd.md) | [SD 1.4](sd/sd1-4-txt2img.dgl) · [SD 1.5](sd/sd1-5-txt2img.dgl) · [SDXL](sd/sdxl-txt2img.dgl) · [NitroFusion](sd/nitrosd-realism-nitrofusion.dgl) | +| [Stable Diffusion – image conditioning](../models/sd.md) | [SD 1.4 image to image](sd/sd1-4-img2img.dgl) · [SD 1.5 ControlNet](sd/sd1-5-controlnet.dgl) · [SD 1.5 inpainting](sd/sd1-5-inpainting.dgl) | +| [Stable Diffusion 3](../models/sd3.md) | [SD 3.5 Large text to image](sd3/sd3-5-large-txt2img.dgl) | +| [SeFi-Image](../models/sefi_image.md) | [1B Turbo](sefi_image/sefi-1b-turbo-txt2img.dgl) · [1B Base](sefi_image/sefi-1b-base-txt2img.dgl) · [5B Turbo](sefi_image/sefi-5b-turbo-txt2img.dgl) (`--max-vram 8`) · [5B RL](sefi_image/sefi-image-5b-rl.dgl) | +| [SenseNova U1.5](../models/sensenova_u1.md) | [Text to image on CUDA](sensenova_u1/sensenova-u1-cuda-txt2img.dgl) | +| [Z-Image](../models/z_image.md) | [Turbo: text to image](z_image/z-image-turbo-txt2img.dgl) · [Base: text to image](z_image/z-image-base-txt2img.dgl) · [Turbo with ControlNet](z_image/z-image-turbo-controlnet.dgl) | +| [Z-Image L2P](../models/z_image_l2p.md) | [Text to image](z_image_l2p/z-image-l2p-txt2img.dgl) | + +### Video and audio generation + +| Model guide | Scripts | +| --- | --- | +| [AnimateDiff – text to video](../models/animatediff.md) | [Text to video with CPU offload](animatediff/animatediff-realisticvision-v6-txt2video-cpu-offload.dgl) · [Text to video, 16 frames](animatediff/animatediff-realisticvision-v6-txt2video-16-frames.dgl) · [Text to video with a VRAM budget](animatediff/animatediff-realisticvision-v6-txt2video-vram-budget.dgl) (`--max-vram 2.0`) · [Domain Adapter LoRA](animatediff/animatediff-realisticvision-v6-domain-lora.dgl) | +| [AnimateDiff – image to video](../models/animatediff.md) | [Generate the initial image](animatediff/realisticvision-v6-txt2img.dgl) · [Image to video](animatediff/animatediff-realisticvision-v6-img2video.dgl) | +| [HunyuanVideo 1.5](../models/hunyuan_video.md) | [720p text to video](hunyuan_video/hunyuanvideo1-5-720p-txt2video.dgl) | +| [LingBot-Video](../models/lingbot_video.md) | [Dens 1.3B text to video](lingbot_video/lingbot-video-dens-1-3b-txt2video.dgl) | +| [LTX-2.3](../models/ltx2.md) | [2.3 text to video](ltx2/ltx-2-3-dev-txt2video.dgl) · [2.3 image to video](ltx2/ltx-2-3-dev-img2video.dgl) · [2.3 first/last frames](ltx2/ltx-2-3-dev-first-last-frame.dgl) · [2.3 spatial latent upscale](ltx2/ltx-2-3-spatial-upscale.dgl) | +| [LTX-2.5](../models/ltx2.md) | [2.5 text to video](ltx2/ltx-2-5-dev-txt2video.dgl) · [2.5 image to video](ltx2/ltx-2-5-dev-img2video.dgl) · [2.5 spatial latent upscale](ltx2/ltx-2-5-spatial-upscale.dgl) | +| [MiniMax-H3](../models/minimax_h3.md) | [Text to audio/video](minimax_h3/minimax-h3-text-to-av.dgl) · [pi-H3 four-step text to audio/video](minimax_h3/pi-h3-text-to-av.dgl) · [First/last-frame conditioning](minimax_h3/minimax-h3-first-last-frame.dgl) · [Reference to audio/video](minimax_h3/minimax-h3-reference-to-av.dgl) · [Interpolated latent hires](minimax_h3/minimax-h3-latent-hires.dgl) · [Learned latent hires](minimax_h3/minimax-h3-learned-hires.dgl) · [Audio/video continuation](minimax_h3/minimax-h3-av-continuation.dgl) | +| [Wan 2.1](../models/wan.md) | [Text to video, 1.3B](wan/wan2-1-t2v-1-3b.dgl) · [Text to video, 14B](wan/wan2-1-t2v-14b.dgl) · [Image to video, 14B](wan/wan2-1-i2v-14b.dgl) · [First/last frames, 14B](wan/wan2-1-first-last-frame-14b.dgl) | +| [Wan 2.1 VACE 1.3B](../models/wan.md) | [Text to video](wan/wan2-1-vace-1-3b-txt2video.dgl) · [Reference to video](wan/wan2-1-vace-1-3b-ref2video.dgl) · [Video to video](wan/wan2-1-vace-1-3b-video2video.dgl) | +| [Wan 2.1 VACE 14B](../models/wan.md) | [Text to video](wan/wan2-1-vace-14b-txt2video.dgl) · [Reference to video](wan/wan2-1-vace-14b-ref2video.dgl) · [Video to video](wan/wan2-1-vace-14b-video2video.dgl) | +| [Wan 2.2 A14B](../models/wan.md) | [Text to video](wan/wan2-2-t2v-a14b.dgl) · [Image to video](wan/wan2-2-i2v-a14b.dgl) · [Single image](wan/wan2-2-t2v-a14b-image.dgl) · [Text to video with LoRA](wan/wan2-2-t2v-a14b-lora.dgl) · [First/last frames](wan/wan2-2-first-last-frame-a14b.dgl) | +| [Wan 2.2 TI2V 5B](../models/wan.md) | [Text to video](wan/wan2-2-ti2v-5b-txt2video.dgl) · [Image to video](wan/wan2-2-ti2v-5b-img2video.dgl) | +| [Wan 2.2 S2V](../models/wan.md) | [Speech to video, 14B](wan/wan2-2-s2v-14b.dgl) | +| [Wan 2.2 VACE Fun A14B](../models/wan.md) | [Reference to video](wan/wan2-2-vace-fun-a14b-ref2video.dgl) | + +### Adapters, refinement and upscaling + +| Model guide | Scripts | +| --- | --- | +| [ADetailer](../models/adetailer.md) | [Refine an existing image](adetailer/adetailer-existing-image.dgl) · [Generate and refine](adetailer/adetailer-generated-image.dgl) | +| [ESRGAN and MoSR](../models/esrgan.md) | [Generate and upscale](esrgan/sd1-5-txt2img-esrgan.dgl) · [Upscale an image](esrgan/realesrgan-x4plus-anime-6b-upscale.dgl) | +| [IP-Adapter](../models/ip_adapter.md) | [SD 1.5 Classic](ip_adapter/ip-adapter-sd1-5.dgl) · [SDXL Classic](ip_adapter/ip-adapter-sdxl.dgl) · [SD 1.5 Plus](ip_adapter/ip-adapter-plus-sd1-5.dgl) · [SDXL with ControlNet](ip_adapter/ip-adapter-sdxl-controlnet.dgl) | +| [LCM and LCM-LoRA](../models/lcm.md) | [LCM-LoRA with SD 1.5](lcm/lcm-lora-sd1-5.dgl) | +| [LoRA](../models/lora.md) | [SD 1.5 UNet and text encoder](lora/sd1-5-lora.dgl) | +| [PhotoMaker](../models/photo_maker.md) | [PhotoMaker v1](photo_maker/photomaker-v1-sdxl.dgl) · [PhotoMaker v2](photo_maker/photomaker-v2-sdxl.dgl) | +| [PuLID-Flux](../models/pulid.md) | [Identity-guided generation](pulid/pulid-flux1-schnell.dgl) | +| [RelayVSR](../models/relay_vsr.md) | [Upscale a video](relay_vsr/relayvsr-x2-video-upscale.dgl) · [Upscale an image](relay_vsr/relayvsr-x2-image-upscale.dgl) | +| [SeedVR2](../models/seedvr2.md) | [Upscale an image](seedvr2/seedvr2-3b-image-upscale.dgl) · [Upscale a video](seedvr2/seedvr2-3b-video-upscale.dgl) | +| [TAESD](../models/taesd.md) | [SD 1.5 decoding with TAESD](taesd/sd1-5-taesd-preview.dgl). The CLI writes the final PNG. Intermediate previews require a [host preview callback](../dgl.md#progress-preview-and-cancellation) in `tae` mode. | diff --git a/docs/dgl/adetailer/adetailer-existing-image.dgl b/docs/dgl/adetailer/adetailer-existing-image.dgl new file mode 100644 index 0000000000..66c5a5207a --- /dev/null +++ b/docs/dgl/adetailer/adetailer-existing-image.dgl @@ -0,0 +1,107 @@ +# version: 0.0.0 +# docs/models/adetailer.md — Repair an existing image + +var { + weights = "../models/checkpoints/model.safetensors" + model_path = "../models/detectors/face_yolov8n.safetensors" + + input_path = "input.png" + output_path = "repaired.png" + + detail_prompt = "detailed portrait photo" + negative_prompt = "deformed face" + + seed = 42 + + settings = { + size = [512, 512], + steps = 24, + strength = 0.4, + cfg_scale = 6.0, + method = "dpm++2m", + scheduler = "karras", + mask_blur = 4 + } +} + +fn latent_mask(mask, like) { + shape = tensor::shape(like) + w = shape[0] + h = shape[1] + batch = shape[3] + resized = tensor::interpolate(image::to_f32(mask), size = [w, h], mode = "nearest") + return tensor::broadcast_to(resized, [w, h, 1, batch]) +} + +fn slice_sigmas_by_strength(sigmas, strength) { + steps = tensor::numel(sigmas) - 1 + retained = math::floor(steps * strength) + return sigmas[steps - retained:] +} + +fn dilate(mask) { + return tensor::max_pool2d(mask, kernel = [4, 4], axes = [1, 2], padding_before = [2, 2], padding_after = [1, 1], pad_value = 0) +} + +fn inpaint_patch(image, mask, unet, text, vae, prompt, negative_prompt, seed, settings) { + pixels = image::to_f32(image) + encode_rng = make_rng("cuda", seed = seed) + base = vae_to_unet_latents(vae, vae_encode(vae, pixels, rng = encode_rng)) + latent_region = latent_mask(mask, like = base) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), prediction = "eps") + guided = cfg(pos, neg, scale = settings.cfg_scale) + sigmas = slice_sigmas_by_strength(make_sigmas(guided, latent = base, scheduler = settings.scheduler, steps = settings.steps), strength = settings.strength) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + denoise_mask = tensor::max_pool2d(latent_region, kernel = [3, 3], padding_before = [1, 1]) + latent = sample(start, sigmas, predict = guided, method = settings.method, base = base, denoise_mask = denoise_mask, rng = rng) + return vae_decode(vae, unet_to_vae_latents(vae, latent)) +} + +fn paste_region(canvas, patch, feather, origin, extent) { + background = tensor::crop(canvas, axes = [1, 2], start = origin, size = extent) + foreground = tensor::interpolate(patch, size = extent, axes = [1, 2], mode = "bilinear") + mask = tensor::crop(feather, axes = [1, 2], start = origin, size = extent) + weight = tensor::affine(tensor::cast(mask, "f32"), scale = 0.00392156862745098) + blended = tensor::lerp(background, foreground, weight) + y = origin[1] + rows = tensor::crop(canvas, axes = [2], start = [y], size = [extent[1]]) + band = tensor::replace_slice(rows, blended, axis = 1, start = origin[0]) + return tensor::replace_slice(canvas, band, axis = 2, start = y) +} + +fn refine_region(canvas, region, unet, text, vae, prompt, negative_prompt, seed, settings) { + origin = region.box[:2] + extent = region.box[2:4] + channels = tensor::shape(canvas)[0] + last = channels - 1 + rgb = tensor::index_select(canvas, axis = 0, indices = [0, math::min(1, last), math::min(2, last)]) + image_crop = tensor::crop(rgb, axes = [1, 2], start = origin, size = extent) + mask_crop = tensor::crop(region.mask, axes = [1, 2], start = origin, size = extent) + image = tensor::interpolate(image_crop, size = settings.size, axes = [1, 2], mode = "bilinear") + mask = tensor::interpolate(mask_crop, size = settings.size, axes = [1, 2], mode = "nearest_exact") + region_seed = seed + region.index + patch = inpaint_patch(image, mask, unet, text, vae, prompt, negative_prompt, region_seed, settings) + radius = math::ceil(settings.mask_blur * 2.5) + feather = tensor::gaussian_blur(region.mask, sigma = settings.mask_blur, radius = radius, axes = [1, 2]) + refined = paste_region(rgb, patch, feather, origin, extent) + alpha = canvas[math::min(3, channels):] + return tensor::concat([refined, alpha], axis = 0) +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights) + detector = load_detector(model_path) + image = image::load(input_path) + detections = detections::detect(detector, image, confidence = 0.3) + selected = detections::filter(image, detections, top_k = 4) + masks = map(detections::box_masks(image, selected), process = dilate) + regions = regions::plan_mask_crops(masks, aspect = settings.size, padding = 32) + refined = fold(regions, image, process = refine_region, unet = unet, text = text, vae = vae, + prompt = detail_prompt, negative_prompt = negative_prompt, seed = seed, settings = settings) + image::save(output_path, refined) + return { image = refined, detections = selected, regions = regions } +} diff --git a/docs/dgl/adetailer/adetailer-generated-image.dgl b/docs/dgl/adetailer/adetailer-generated-image.dgl new file mode 100644 index 0000000000..5ccda8ec34 --- /dev/null +++ b/docs/dgl/adetailer/adetailer-generated-image.dgl @@ -0,0 +1,128 @@ +# version: 0.0.0 +# docs/models/adetailer.md — Repair generated images + +var { + weights = "../models/checkpoints/model.safetensors" + model_path = "../models/detectors/face_yolov8n.safetensors" + + output_path = "output.png" + + prompt = "portrait photo" + detail_prompt = "portrait photo, detailed face" + negative_prompt = "" + + seed = 42 + + settings = { + size = [512, 512], + steps = 20, + strength = 0.4, + cfg_scale = 7.0, + method = "euler_a", + scheduler = "karras", + mask_blur = 4 + } +} + +fn latent_mask(mask, like) { + shape = tensor::shape(like) + w = shape[0] + h = shape[1] + batch = shape[3] + resized = tensor::interpolate(image::to_f32(mask), size = [w, h], mode = "nearest") + return tensor::broadcast_to(resized, [w, h, 1, batch]) +} + +fn slice_sigmas_by_strength(sigmas, strength) { + steps = tensor::numel(sigmas) - 1 + retained = math::floor(steps * strength) + return sigmas[steps - retained:] +} + +fn dilate(mask) { + return tensor::max_pool2d(mask, kernel = [4, 4], axes = [1, 2], padding_before = [2, 2], padding_after = [1, 1], pad_value = 0) +} + +fn inpaint_patch(image, mask, unet, text, vae, prompt, negative_prompt, seed, settings) { + pixels = image::to_f32(image) + encode_rng = make_rng("cuda", seed = seed) + base = vae_to_unet_latents(vae, vae_encode(vae, pixels, rng = encode_rng)) + latent_region = latent_mask(mask, like = base) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), prediction = "eps") + guided = cfg(pos, neg, scale = settings.cfg_scale) + sigmas = slice_sigmas_by_strength(make_sigmas(guided, latent = base, scheduler = settings.scheduler, steps = settings.steps), strength = settings.strength) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + denoise_mask = tensor::max_pool2d(latent_region, kernel = [3, 3], padding_before = [1, 1]) + latent = sample(start, sigmas, predict = guided, method = settings.method, base = base, denoise_mask = denoise_mask, rng = rng) + return vae_decode(vae, unet_to_vae_latents(vae, latent)) +} + +fn paste_region(canvas, patch, feather, origin, extent) { + background = tensor::crop(canvas, axes = [1, 2], start = origin, size = extent) + foreground = tensor::interpolate(patch, size = extent, axes = [1, 2], mode = "bilinear") + mask = tensor::crop(feather, axes = [1, 2], start = origin, size = extent) + weight = tensor::affine(tensor::cast(mask, "f32"), scale = 0.00392156862745098) + blended = tensor::lerp(background, foreground, weight) + y = origin[1] + rows = tensor::crop(canvas, axes = [2], start = [y], size = [extent[1]]) + band = tensor::replace_slice(rows, blended, axis = 1, start = origin[0]) + return tensor::replace_slice(canvas, band, axis = 2, start = y) +} + +fn refine_region(canvas, region, unet, text, vae, prompt, negative_prompt, seed, settings) { + origin = region.box[:2] + extent = region.box[2:4] + channels = tensor::shape(canvas)[0] + last = channels - 1 + rgb = tensor::index_select(canvas, axis = 0, indices = [0, math::min(1, last), math::min(2, last)]) + image_crop = tensor::crop(rgb, axes = [1, 2], start = origin, size = extent) + mask_crop = tensor::crop(region.mask, axes = [1, 2], start = origin, size = extent) + image = tensor::interpolate(image_crop, size = settings.size, axes = [1, 2], mode = "bilinear") + mask = tensor::interpolate(mask_crop, size = settings.size, axes = [1, 2], mode = "nearest_exact") + region_seed = seed + region.index + patch = inpaint_patch(image, mask, unet, text, vae, prompt, negative_prompt, region_seed, settings) + radius = math::ceil(settings.mask_blur * 2.5) + feather = tensor::gaussian_blur(region.mask, sigma = settings.mask_blur, radius = radius, axes = [1, 2]) + refined = paste_region(rgb, patch, feather, origin, extent) + alpha = canvas[math::min(3, channels):] + return tensor::concat([refined, alpha], axis = 0) +} + +fn generate_canvas(unet, text, vae, prompt, negative_prompt, seed) { + width = 512 + height = 512 + scheduler = "discrete" + steps = 20 + cfg_scale = 7 + method = "euler_a" + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + rng = make_rng("cuda", seed = seed) + pos = encode_prompt(text, prompt) + neg = encode_prompt(text, negative_prompt) + positive_predictor = predictor(unet, pos, prediction = "eps") + negative_predictor = predictor(unet, neg, prediction = "eps") + guided = cfg(positive_predictor, negative_predictor, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + return vae_decode(vae, unet_to_vae_latents(vae, latent)) +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights) + detector = load_detector(model_path) + image = generate_canvas(unet, text, vae, prompt, negative_prompt, seed) + detections = detections::detect(detector, image, confidence = 0.3) + selected = detections::filter(image, detections, top_k = 4) + masks = map(detections::box_masks(image, selected), process = dilate) + regions = regions::plan_mask_crops(masks, aspect = settings.size, padding = 32) + refined = fold(regions, image, process = refine_region, unet = unet, text = text, vae = vae, + prompt = detail_prompt, negative_prompt = negative_prompt, seed = seed, settings = settings) + image::save(output_path, refined) + return { image = refined, detections = selected, regions = regions } +} diff --git a/docs/dgl/anima/anima-preview-txt2img.dgl b/docs/dgl/anima/anima-preview-txt2img.dgl new file mode 100644 index 0000000000..66d2b12813 --- /dev/null +++ b/docs/dgl/anima/anima-preview-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/anima.md — CLI + +var { + model_path = "../models/diffusion_models/anima-preview.safetensors" + text_path = "../models/text_encoders/qwen_3_06b_base.safetensors" + vae_path = "../models/vae/qwen_image_vae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'anima.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "anima", params_backend = "cpu") + text = load_text_encoder(text_path, family = "anima", params_backend = "cpu") + vae = load_vae(vae_path, family = "anima", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/animatediff/animatediff-realisticvision-v6-domain-lora.dgl b/docs/dgl/animatediff/animatediff-realisticvision-v6-domain-lora.dgl new file mode 100644 index 0000000000..51c93805d4 --- /dev/null +++ b/docs/dgl/animatediff/animatediff-realisticvision-v6-domain-lora.dgl @@ -0,0 +1,45 @@ +# version: 0.0.0 +# docs/models/animatediff.md — v3 + Domain Adapter LoRA + +var { + weights = "../models/checkpoints/realisticVisionV60B1.safetensors" + model_path = "../models/motion_modules/mm_sd15_v3.safetensors" + lora_path = "./loras/v3_sd15_adapter.safetensors" + + output_path = "output.avi" + + prompt = "close up photo of a rabbit" + negative_prompt = "" + + seed = 42 + width = 512 + height = 512 + frames = 16 + fps = 8 + + steps = 20 + cfg_scale = 7.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + original_unet = load_unet(weights) + domain_adapter = load_lora(lora_path) + base_unet = apply_lora(original_unet, domain_adapter) + motion = animatediff::load(model_path) + unet = animatediff::apply(base_unet, motion) + text = load_text_encoder(weights) + vae = load_vae(weights) + base = tensor::zeros(latent_shape(vae, width = width, height = height, batch = frames)) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), prediction = "eps") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + video = vae_decode(vae, unet_to_vae_latents(vae, latent)) + video::save(output_path, {frames = video, fps_num = fps, fps_den = 1}) + return { video = video, latent = latent } +} diff --git a/docs/dgl/animatediff/animatediff-realisticvision-v6-img2video.dgl b/docs/dgl/animatediff/animatediff-realisticvision-v6-img2video.dgl new file mode 100644 index 0000000000..70a3767537 --- /dev/null +++ b/docs/dgl/animatediff/animatediff-realisticvision-v6-img2video.dgl @@ -0,0 +1,49 @@ +# version: 0.0.0 +# docs/models/animatediff.md — img2video + +var { + weights = "../models/checkpoints/realisticVisionV60B1.safetensors" + model_path = "../models/motion_modules/mm_sd15_v3.safetensors" + + input_path = "init.png" + output_path = "out.avi" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + width = 512 + height = 512 + frames = 8 + fps = 8 + + steps = 25 + cfg_scale = 7.0 + method = "euler" + scheduler = "karras" + strength = 0.75 +} + +fn main() { + base_unet = load_unet(weights) + motion = animatediff::load(model_path) + unet = animatediff::apply(base_unet, motion) + text = load_text_encoder(weights) + vae = load_vae(weights) + source = tensor::interpolate(image::load(input_path), size = [width, height], axes = [1, 2]) + encode_rng = make_rng("cuda", seed = seed) + encoded = vae_to_unet_latents(vae, vae_encode(vae, image::to_f32(source), rng = encode_rng)) + base = tensor::broadcast_to(encoded, latent_shape(vae, width = width, height = height, batch = frames)) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), prediction = "eps") + guided = cfg(pos, neg, scale = cfg_scale) + full_sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + retained = math::min(math::floor(steps * strength) + 1, steps) + sigmas = full_sigmas[steps - retained:] + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + video = vae_decode(vae, unet_to_vae_latents(vae, latent)) + video::save(output_path, {frames = video, fps_num = fps, fps_den = 1}) + return { video = video, latent = latent } +} diff --git a/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-16-frames.dgl b/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-16-frames.dgl new file mode 100644 index 0000000000..c7e38fb417 --- /dev/null +++ b/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-16-frames.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/animatediff.md — Text-to-video + +var { + weights = "../models/checkpoints/realisticVisionV60B1.safetensors" + model_path = "../models/motion_modules/animatediff/mm_sd15_v3.safetensors" + + output_path = "out.avi" + + prompt = "photo of coastline, rocks, storm weather, wind, waves, lightning" + negative_prompt = "" + + seed = 42 + width = 384 + height = 384 + frames = 16 + fps = 8 + + steps = 20 + cfg_scale = 8.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + base_unet = load_unet(weights, params_backend = "cpu") + motion = animatediff::load(model_path, params_backend = "cpu") + unet = animatediff::apply(base_unet, motion) + text = load_text_encoder(weights, params_backend = "cpu") + vae = load_vae(weights, params_backend = "cpu") + base = tensor::zeros(latent_shape(vae, width = width, height = height, batch = frames)) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), prediction = "eps") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + video = vae_decode(vae, unet_to_vae_latents(vae, latent)) + video::save(output_path, {frames = video, fps_num = fps, fps_den = 1}) + return { video = video, latent = latent } +} diff --git a/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-cpu-offload.dgl b/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-cpu-offload.dgl new file mode 100644 index 0000000000..bbc9a71707 --- /dev/null +++ b/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-cpu-offload.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/animatediff.md — Text-to-video + +var { + weights = "../models/checkpoints/realisticVisionV60B1.safetensors" + model_path = "../models/motion_modules/animatediff/mm_sd15_v3.safetensors" + + output_path = "out.avi" + + prompt = "a red apple on a wooden table" + negative_prompt = "" + + seed = 42 + width = 512 + height = 512 + frames = 8 + fps = 8 + + steps = 20 + cfg_scale = 8.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + base_unet = load_unet(weights, params_backend = "cpu") + motion = animatediff::load(model_path, params_backend = "cpu") + unet = animatediff::apply(base_unet, motion) + text = load_text_encoder(weights, params_backend = "cpu") + vae = load_vae(weights, params_backend = "cpu") + base = tensor::zeros(latent_shape(vae, width = width, height = height, batch = frames)) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), prediction = "eps") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + video = vae_decode(vae, unet_to_vae_latents(vae, latent)) + video::save(output_path, {frames = video, fps_num = fps, fps_den = 1}) + return { video = video, latent = latent } +} diff --git a/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-vram-budget.dgl b/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-vram-budget.dgl new file mode 100644 index 0000000000..53a90f7682 --- /dev/null +++ b/docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-vram-budget.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# CLI/context: --max-vram 2.0 +# docs/models/animatediff.md — Text-to-video + +var { + weights = "../models/checkpoints/realisticVisionV60B1.safetensors" + model_path = "../models/motion_modules/animatediff/mm_sd15_v3.safetensors" + + output_path = "out.avi" + + prompt = "photo of coastline, rocks, storm weather, wind, waves, lightning" + negative_prompt = "" + + seed = 42 + width = 384 + height = 384 + frames = 8 + fps = 8 + + steps = 20 + cfg_scale = 8.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + base_unet = load_unet(weights) + motion = animatediff::load(model_path) + unet = animatediff::apply(base_unet, motion) + text = load_text_encoder(weights) + vae = load_vae(weights) + base = tensor::zeros(latent_shape(vae, width = width, height = height, batch = frames)) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), prediction = "eps") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + video = vae_decode(vae, unet_to_vae_latents(vae, latent)) + video::save(output_path, {frames = video, fps_num = fps, fps_den = 1}) + return { video = video, latent = latent } +} diff --git a/docs/dgl/animatediff/realisticvision-v6-txt2img.dgl b/docs/dgl/animatediff/realisticvision-v6-txt2img.dgl new file mode 100644 index 0000000000..d185f2d6b3 --- /dev/null +++ b/docs/dgl/animatediff/realisticvision-v6-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/animatediff.md — img2video + +var { + weights = "../models/checkpoints/realisticVisionV60B1.safetensors" + + output_path = "init.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + text = load_text_encoder(weights) + vae = load_vae(weights) + unet = load_unet(weights) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + rng = make_rng("cuda", seed = seed) + pos = encode_prompt(text, prompt) + neg = encode_prompt(text, negative_prompt) + positive_predictor = predictor(unet, pos, prediction = "eps") + negative_predictor = predictor(unet, neg, prediction = "eps") + guided = cfg(positive_predictor, negative_predictor, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent, positive = pos, sigmas = sigmas } +} diff --git a/docs/dgl/boogu_image/boogu-image-base-txt2img.dgl b/docs/dgl/boogu_image/boogu-image-base-txt2img.dgl new file mode 100644 index 0000000000..09f716f6e9 --- /dev/null +++ b/docs/dgl/boogu_image/boogu-image-base-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/boogu_image.md — Boogu Image Base + +var { + model_path = "../models/diffusion_models/boogu_image_base_bf16.safetensors" + text_path = "../models/text_encoders/Qwen3VL-8B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "boogu_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "boogu_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "boogu_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/boogu_image/boogu-image-edit.dgl b/docs/dgl/boogu_image/boogu-image-edit.dgl new file mode 100644 index 0000000000..503274ce80 --- /dev/null +++ b/docs/dgl/boogu_image/boogu-image-edit.dgl @@ -0,0 +1,68 @@ +# version: 0.0.0 +# docs/models/boogu_image.md — Boogu Image Edit + +var { + model_path = "../models/diffusion_models/boogu_image_edit_bf16.safetensors" + text_path = "../models/text_encoders/Qwen3VL-8B-Instruct-Q4_K_M.gguf" + vision_path = "../models/text_encoders/mmproj-Qwen3VL-8B-Instruct-F16.gguf" + vae_path = "../models/vae/ae.sft" + + reference_0_path = "../inputs/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'boogu.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + + steps = 20 + cfg_scale = 7.0 + method = "euler" + scheduler = "discrete" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "boogu_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "boogu_image", params_backend = "cpu", vision_path = vision_path) + vae = load_vae(vae_path, family = "boogu_image", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 16, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + positive = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_original]) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = [reference_0_original]) + pos = predictor(model, positive, ref_latents = [reference_latent_0]) + neg = predictor(model, negative, ref_latents = [reference_latent_0]) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/chroma/chroma-unlocked-v40-txt2img.dgl b/docs/dgl/chroma/chroma-unlocked-v40-txt2img.dgl new file mode 100644 index 0000000000..54fe86d394 --- /dev/null +++ b/docs/dgl/chroma/chroma-unlocked-v40-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/chroma.md — Example + +var { + model_path = "../models/diffusion_models/chroma-unlocked-v40-q8_0.gguf" + text_path = "../models/text_encoders/t5xxl_fp16.safetensors" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'chroma.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 4.0 + method = "euler" + scheduler = "flux" +} + +fn main() { + model = load_dit(model_path, family = "chroma", model_args = "chroma_use_dit_mask=false") + text = load_text_encoder(text_path, backend = "cpu", family = "chroma", model_args = "chroma_use_dit_mask=false", t5_path = text_path) + vae = load_vae(vae_path, family = "chroma", model_args = "chroma_use_dit_mask=false") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/chroma_radiance/chroma1-radiance-v0-4-txt2img.dgl b/docs/dgl/chroma_radiance/chroma1-radiance-v0-4-txt2img.dgl new file mode 100644 index 0000000000..7ea5178892 --- /dev/null +++ b/docs/dgl/chroma_radiance/chroma1-radiance-v0-4-txt2img.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/chroma_radiance.md — CLI + +var { + model_path = "../models/diffusion_models/Chroma1-Radiance-v0.4-Q8_0.gguf" + text_path = "../models/text_encoders/clip/t5xxl_fp16.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'chroma radiance cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 4.0 + method = "euler" + scheduler = "flux" +} + +fn main() { + model = load_dit(model_path, family = "chroma_radiance") + text = load_text_encoder(text_path, family = "chroma_radiance", t5_path = text_path) + vae = load_vae(model_path, family = "chroma_radiance") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/distilled_sd/sdxs-512-dreamshaper-txt2img.dgl b/docs/dgl/distilled_sd/sdxs-512-dreamshaper-txt2img.dgl new file mode 100644 index 0000000000..6caf8743f3 --- /dev/null +++ b/docs/dgl/distilled_sd/sdxs-512-dreamshaper-txt2img.dgl @@ -0,0 +1,36 @@ +# version: 0.0.0 +# docs/models/distilled_sd.md — SDXS-512-DreamShaper + +var { + model_path = "../models/checkpoints/sdxs.safetensors" + + output_path = "output.png" + + prompt = "portrait of a lovely cat" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 1 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + model = load_unet(model_path, family = "sdxs_512_ds") + text = load_text_encoder(model_path, family = "sdxs_512_ds") + vae = load_vae(model_path, family = "sdxs_512_ds") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/distilled_sd/ssd1b-txt2img.dgl b/docs/dgl/distilled_sd/ssd1b-txt2img.dgl new file mode 100644 index 0000000000..7913c81b3d --- /dev/null +++ b/docs/dgl/distilled_sd/ssd1b-txt2img.dgl @@ -0,0 +1,54 @@ +# version: 0.0.0 +# docs/models/distilled_sd.md — SSD1B + +var { + model_path = "../models/checkpoints/SSD-1B-A1111.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + zero_negative = true + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn sdxl_zero_text(cond) { + zeroed = zero_out(cond, fields = ["crossattn"]) + pooled_zeros = tensor::zeros_like(cond.vector[:1280]) + adm = tensor::replace_slice(cond.vector, pooled_zeros, axis = 0, start = 0) + return {crossattn = zeroed.crossattn, vector = adm} +} + +fn main() { + model = load_unet(model_path, family = "sdxl_ssd1b") + text = load_text_encoder(model_path, family = "sdxl_ssd1b") + vae = load_vae(model_path, family = "sdxl_ssd1b", conv_scale = 0.03125) + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative_text = encode_prompt(text, negative_prompt, width = width, height = height) + negative = if zero_negative { + sdxl_zero_text(negative_text) + } else { + {crossattn = negative_text.crossattn, vector = negative_text.vector} + } + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/ernie_image/ernie-image-turbo-txt2img.dgl b/docs/dgl/ernie_image/ernie-image-turbo-txt2img.dgl new file mode 100644 index 0000000000..5cdd6eb280 --- /dev/null +++ b/docs/dgl/ernie_image/ernie-image-turbo-txt2img.dgl @@ -0,0 +1,38 @@ +# version: 0.0.0 +# docs/models/ernie_image.md — ERNIE-Image-Turbo + +var { + model_path = "../models/diffusion_models/ernie-image-turbo.safetensors" + text_path = "../models/text_encoders/ministral-3-3b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 8 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "ernie_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ernie_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "ernie_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/ernie_image/ernie-image-txt2img.dgl b/docs/dgl/ernie_image/ernie-image-txt2img.dgl new file mode 100644 index 0000000000..f6980f54f1 --- /dev/null +++ b/docs/dgl/ernie_image/ernie-image-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/ernie_image.md — ERNIE-Image + +var { + model_path = "../models/diffusion_models/ernie-image-UD-Q4_K_M.gguf" + text_path = "../models/text_encoders/ministral-3-3b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 5.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "ernie_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ernie_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "ernie_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/esrgan/realesrgan-x4plus-anime-6b-upscale.dgl b/docs/dgl/esrgan/realesrgan-x4plus-anime-6b-upscale.dgl new file mode 100644 index 0000000000..0c02c09b2d --- /dev/null +++ b/docs/dgl/esrgan/realesrgan-x4plus-anime-6b-upscale.dgl @@ -0,0 +1,17 @@ +# version: 0.0.0 +# docs/models/esrgan.md — standalone image upscaling + +var { + upscaler_path = "../models/upscale_models/RealESRGAN_x4plus_anime_6B.pth" + + input_path = "input.png" + output_path = "upscaled.png" +} + +fn main() { + upscaler = load_upscaler(upscaler_path) + image = image::load(input_path) + output = upscale(upscaler, image) + image::save(output_path, output) + return output +} diff --git a/docs/dgl/esrgan/sd1-5-txt2img-esrgan.dgl b/docs/dgl/esrgan/sd1-5-txt2img-esrgan.dgl new file mode 100644 index 0000000000..080effd011 --- /dev/null +++ b/docs/dgl/esrgan/sd1-5-txt2img-esrgan.dgl @@ -0,0 +1,44 @@ +# version: 0.0.0 +# docs/models/esrgan.md — CLI + +var { + model_path = "../models/checkpoints/v1-5-pruned-emaonly.safetensors" + upscaler_path = "../models/upscale_models/RealESRGAN_x4plus_anime_6B.pth" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + model = load_unet(model_path, family = "sd1") + text = load_text_encoder(model_path, family = "sd1") + vae = load_vae(model_path, family = "sd1") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + upscaler = load_upscaler(upscaler_path) + enlarged = upscale(upscaler, image) + image::save(output_path, enlarged) + return {image = enlarged, latent = latent} +} diff --git a/docs/dgl/fibo2/fibo2-dev-edit.dgl b/docs/dgl/fibo2/fibo2-dev-edit.dgl new file mode 100644 index 0000000000..ac890f781e --- /dev/null +++ b/docs/dgl/fibo2/fibo2-dev-edit.dgl @@ -0,0 +1,61 @@ +# version: 0.0.0 +# docs/models/fibo2.md — Fibo 2.0 Dev + +var { + model_path = "../models/diffusion_models/fibo2_dev_int8_convrot.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vision_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-mmproj-BF16.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + reference_0_path = "../inputs/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'fibo2.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + + steps = 20 + cfg_scale = 5.0 + method = "euler" + scheduler = "flux" +} + +fn center_crop_reference(input, width, height) { + shape = tensor::shape(input) + scale = tensor::maximum(tensor::vector([width / shape[0]]), tensor::vector([height / shape[1]]))[0] + resized_width = math::ceil(shape[0] * scale) + resized_height = math::ceil(shape[1] * scale) + resized = tensor::interpolate(input, size = [resized_width, resized_height], mode = "lanczos") + return tensor::crop(resized, axes = [0, 1], start = [math::floor((resized_width - width) / 2), math::floor((resized_height - height) / 2)], size = [width, height]) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "fibo2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "fibo2", params_backend = "cpu", vision_path = vision_path) + vae = load_vae(vae_path, family = "fibo2", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = center_crop_reference(reference_0_original, width, height) + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + positive = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_pixels]) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, ref_latents = [reference_latent_0], ref_index_mode = "increase") + neg = predictor(model, negative, ref_latents = [reference_latent_0], ref_index_mode = "increase") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/fibo2/fibo2-dev-txt2img.dgl b/docs/dgl/fibo2/fibo2-dev-txt2img.dgl new file mode 100644 index 0000000000..fa8d213c9f --- /dev/null +++ b/docs/dgl/fibo2/fibo2-dev-txt2img.dgl @@ -0,0 +1,44 @@ +# version: 0.0.0 +# docs/models/fibo2.md — Fibo 2.0 Dev + +var { + model_path = "../models/diffusion_models/fibo2_dev_int8_convrot.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vision_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-mmproj-BF16.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'fibo2.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 5.0 + method = "euler" + scheduler = "flux" +} + +fn main() { + model = load_dit(model_path, family = "fibo2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "fibo2", params_backend = "cpu", vision_path = vision_path) + vae = load_vae(vae_path, family = "fibo2", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/fibo2/fibo2-edit-turbo.dgl b/docs/dgl/fibo2/fibo2-edit-turbo.dgl new file mode 100644 index 0000000000..ac9804bbae --- /dev/null +++ b/docs/dgl/fibo2/fibo2-edit-turbo.dgl @@ -0,0 +1,56 @@ +# version: 0.0.0 +# docs/models/fibo2.md — Fibo 2.0 Edit Turbo + +var { + model_path = "../models/diffusion_models/fibo2_edit_turbo_int8_convrot.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vision_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-mmproj-BF16.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + reference_0_path = "../inputs/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'fibo2.cpp'" + + seed = 42 + rng_type = "cuda" + + steps = 4 + method = "euler" + scheduler = "flux" +} + +fn center_crop_reference(input, width, height) { + shape = tensor::shape(input) + scale = tensor::maximum(tensor::vector([width / shape[0]]), tensor::vector([height / shape[1]]))[0] + resized_width = math::ceil(shape[0] * scale) + resized_height = math::ceil(shape[1] * scale) + resized = tensor::interpolate(input, size = [resized_width, resized_height], mode = "lanczos") + return tensor::crop(resized, axes = [0, 1], start = [math::floor((resized_width - width) / 2), math::floor((resized_height - height) / 2)], size = [width, height]) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "fibo2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "fibo2", params_backend = "cpu", vision_path = vision_path) + vae = load_vae(vae_path, family = "fibo2", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = center_crop_reference(reference_0_original, width, height) + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_pixels]) + predict = predictor(model, condition, ref_latents = [reference_latent_0], ref_index_mode = "increase") + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux/flux1-dev-lora.dgl b/docs/dgl/flux/flux1-dev-lora.dgl new file mode 100644 index 0000000000..9b4fc413a9 --- /dev/null +++ b/docs/dgl/flux/flux1-dev-lora.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/flux.md — Flux-dev q8_0 with LoRA + +var { + model_path = "../models/diffusion_models/flux1-dev-q8_0.gguf" + clip_l_path = "../models/text_encoders/clip_l.safetensors" + t5_path = "../models/text_encoders/t5xxl_fp16.safetensors" + vae_path = "../models/vae/ae.sft" + lora_0_path = "../models/loras/realism_lora_comfy_converted.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'flux.cpp'" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + method = "euler" + scheduler = "flux" +} + +fn main() { + base_model = load_dit(model_path, family = "flux") + text = load_text_encoder(clip_l_path, backend = "cpu", clip_l_path = clip_l_path, family = "flux", t5_path = t5_path) + vae = load_vae(vae_path, family = "flux") + + lora_0 = load_lora(lora_0_path) + model = apply_lora(base_model, lora_0) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux/flux1-dev-txt2img.dgl b/docs/dgl/flux/flux1-dev-txt2img.dgl new file mode 100644 index 0000000000..a5e3a5b9c3 --- /dev/null +++ b/docs/dgl/flux/flux1-dev-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/flux.md — Flux-dev + +var { + model_path = "../models/diffusion_models/flux1-dev-q8_0.gguf" + clip_l_path = "../models/text_encoders/clip_l.safetensors" + t5_path = "../models/text_encoders/t5xxl_fp16.safetensors" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'flux.cpp'" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + method = "euler" + scheduler = "flux" +} + +fn main() { + model = load_dit(model_path, family = "flux") + text = load_text_encoder(clip_l_path, backend = "cpu", clip_l_path = clip_l_path, family = "flux", t5_path = t5_path) + vae = load_vae(vae_path, family = "flux") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux/flux1-schnell-txt2img.dgl b/docs/dgl/flux/flux1-schnell-txt2img.dgl new file mode 100644 index 0000000000..0667f10da7 --- /dev/null +++ b/docs/dgl/flux/flux1-schnell-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/flux.md — Flux-schnell + +var { + model_path = "../models/diffusion_models/flux1-schnell-q8_0.gguf" + clip_l_path = "../models/text_encoders/clip_l.safetensors" + t5_path = "../models/text_encoders/t5xxl_fp16.safetensors" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'flux.cpp'" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 4 + method = "euler" + scheduler = "flux" +} + +fn main() { + model = load_dit(model_path, family = "flux") + text = load_text_encoder(clip_l_path, backend = "cpu", clip_l_path = clip_l_path, family = "flux", t5_path = t5_path) + vae = load_vae(vae_path, family = "flux") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux2/flux2-dev-edit.dgl b/docs/dgl/flux2/flux2-dev-edit.dgl new file mode 100644 index 0000000000..70abada838 --- /dev/null +++ b/docs/dgl/flux2/flux2-dev-edit.dgl @@ -0,0 +1,62 @@ +# version: 0.0.0 +# docs/models/flux2.md — Flux.2-dev + +var { + model_path = "../models/diffusion_models/flux2-dev-Q4_K_S.gguf" + text_path = "../models/text_encoders/Mistral-Small-3.2-24B-Instruct-2506-Q4_K_M.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + reference_0_path = "./kontext_input.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'flux2-dev.cpp'" + + seed = 42 + rng_type = "cuda" + + steps = 20 + method = "euler" + scheduler = "flux2" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "flux2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux2", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux2", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 16, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, ref_latents = [reference_latent_0], ref_index_mode = "increase") + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux2/flux2-klein-4b-edit.dgl b/docs/dgl/flux2/flux2-klein-4b-edit.dgl new file mode 100644 index 0000000000..930faf1a10 --- /dev/null +++ b/docs/dgl/flux2/flux2-klein-4b-edit.dgl @@ -0,0 +1,62 @@ +# version: 0.0.0 +# docs/models/flux2.md — Flux.2 klein 4B / Flux.2 klein base 4B + +var { + model_path = "../models/diffusion_models/flux-2-klein-4b.safetensors" + text_path = "../models/text_encoders/qwen_3_4b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + reference_0_path = "./kontext_input.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'klein.cpp'" + + seed = 42 + rng_type = "cuda" + + steps = 4 + method = "euler" + scheduler = "flux2" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "flux2_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux2_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux2_klein", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 16, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, ref_latents = [reference_latent_0], ref_index_mode = "increase") + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux2/flux2-klein-4b-txt2img.dgl b/docs/dgl/flux2/flux2-klein-4b-txt2img.dgl new file mode 100644 index 0000000000..a33edfa753 --- /dev/null +++ b/docs/dgl/flux2/flux2-klein-4b-txt2img.dgl @@ -0,0 +1,38 @@ +# version: 0.0.0 +# docs/models/flux2.md — Flux.2 klein 4B / Flux.2 klein base 4B + +var { + model_path = "../models/diffusion_models/flux-2-klein-4b.safetensors" + text_path = "../models/text_encoders/qwen_3_4b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 4 + method = "euler" + scheduler = "flux2" +} + +fn main() { + model = load_dit(model_path, family = "flux2_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux2_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux2_klein", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux2/flux2-klein-9b-edit.dgl b/docs/dgl/flux2/flux2-klein-9b-edit.dgl new file mode 100644 index 0000000000..ea145250e6 --- /dev/null +++ b/docs/dgl/flux2/flux2-klein-9b-edit.dgl @@ -0,0 +1,62 @@ +# version: 0.0.0 +# docs/models/flux2.md — Flux.2 klein 9B / Flux.2 klein base 9B + +var { + model_path = "../models/diffusion_models/flux-2-klein-9b.safetensors" + text_path = "../models/text_encoders/qwen_3_8b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + reference_0_path = "./kontext_input.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'klein.cpp'" + + seed = 42 + rng_type = "cuda" + + steps = 4 + method = "euler" + scheduler = "flux2" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "flux2_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux2_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux2_klein", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 16, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, ref_latents = [reference_latent_0], ref_index_mode = "increase") + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux2/flux2-klein-9b-txt2img.dgl b/docs/dgl/flux2/flux2-klein-9b-txt2img.dgl new file mode 100644 index 0000000000..a0ea0957f0 --- /dev/null +++ b/docs/dgl/flux2/flux2-klein-9b-txt2img.dgl @@ -0,0 +1,38 @@ +# version: 0.0.0 +# docs/models/flux2.md — Flux.2 klein 9B / Flux.2 klein base 9B + +var { + model_path = "../models/diffusion_models/flux-2-klein-9b.safetensors" + text_path = "../models/text_encoders/qwen_3_8b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 4 + method = "euler" + scheduler = "flux2" +} + +fn main() { + model = load_dit(model_path, family = "flux2_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux2_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux2_klein", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux2/flux2-klein-base-4b-txt2img.dgl b/docs/dgl/flux2/flux2-klein-base-4b-txt2img.dgl new file mode 100644 index 0000000000..549fbf075c --- /dev/null +++ b/docs/dgl/flux2/flux2-klein-base-4b-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/flux2.md — Flux.2 klein 4B / Flux.2 klein base 4B + +var { + model_path = "../models/diffusion_models/flux-2-klein-base-4b.safetensors" + text_path = "../models/text_encoders/qwen_3_4b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 4.0 + method = "euler" + scheduler = "flux2" +} + +fn main() { + model = load_dit(model_path, family = "flux2_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux2_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux2_klein", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux2/flux2-klein-base-9b-txt2img.dgl b/docs/dgl/flux2/flux2-klein-base-9b-txt2img.dgl new file mode 100644 index 0000000000..17ac175fd6 --- /dev/null +++ b/docs/dgl/flux2/flux2-klein-base-9b-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/flux2.md — Flux.2 klein 9B / Flux.2 klein base 9B + +var { + model_path = "../models/diffusion_models/flux-2-klein-base-9b.safetensors" + text_path = "../models/text_encoders/qwen_3_8b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 4.0 + method = "euler" + scheduler = "flux2" +} + +fn main() { + model = load_dit(model_path, family = "flux2_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux2_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux2_klein", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux3/flux3-image-klein-base-txt2img.dgl b/docs/dgl/flux3/flux3-image-klein-base-txt2img.dgl new file mode 100644 index 0000000000..ebdd4956ca --- /dev/null +++ b/docs/dgl/flux3/flux3-image-klein-base-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/flux3.md — FLUX.3 Image Klein Base + +var { + model_path = "../models/diffusion_models/flux-3-image-klein-base.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'flux3.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 3.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "flux3_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux3_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux3_klein", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux3/flux3-image-klein-edit.dgl b/docs/dgl/flux3/flux3-image-klein-edit.dgl new file mode 100644 index 0000000000..25f519a1e6 --- /dev/null +++ b/docs/dgl/flux3/flux3-image-klein-edit.dgl @@ -0,0 +1,62 @@ +# version: 0.0.0 +# docs/models/flux3.md — FLUX.3 Image Klein + +var { + model_path = "../models/diffusion_models/flux-3-image-klein.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + reference_0_path = "../assets/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'flux3-image-klein.cpp'" + + seed = 42 + rng_type = "cuda" + + steps = 16 + method = "euler" + scheduler = "discrete" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "flux3_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux3_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux3_klein", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 16, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, ref_latents = [reference_latent_0], ref_index_mode = "increase") + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/flux3/flux3-image-klein-txt2img.dgl b/docs/dgl/flux3/flux3-image-klein-txt2img.dgl new file mode 100644 index 0000000000..633e6ce7ea --- /dev/null +++ b/docs/dgl/flux3/flux3-image-klein-txt2img.dgl @@ -0,0 +1,38 @@ +# version: 0.0.0 +# docs/models/flux3.md — FLUX.3 Image Klein + +var { + model_path = "../models/diffusion_models/flux-3-image-klein.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'flux3.cpp'" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 16 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "flux3_klein", params_backend = "cpu") + text = load_text_encoder(text_path, family = "flux3_klein", params_backend = "cpu") + vae = load_vae(vae_path, family = "flux3_klein", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/hidream_o1_image/hidream-o1-image-dev-txt2img.dgl b/docs/dgl/hidream_o1_image/hidream-o1-image-dev-txt2img.dgl new file mode 100644 index 0000000000..c75802865a --- /dev/null +++ b/docs/dgl/hidream_o1_image/hidream-o1-image-dev-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/hidream_o1_image.md — HiDream-O1-Image-Dev + +var { + model_path = "../models/checkpoints/hidream_o1_image_dev_bf16.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'hidream o1 cpp'" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 28 + method = "lcm" + scheduler = "lcm" + noise_scale = 8.0 + extra_sample_args = "noise_scale_start=7.5,noise_scale_end=7.5,noise_clip_std=2.5" +} + +fn main() { + model = load_dit(model_path, family = "hidream_o1") + text = load_text_encoder(model_path, family = "hidream_o1") + vae = load_vae(model_path, family = "hidream_o1") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + noise = tensor::affine(tensor::randn_like(base, rng = rng), scale = noise_scale) + start = add_noise(predict, base, noise, sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng, extra_args = extra_sample_args) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/hunyuan_video/hunyuanvideo1-5-720p-txt2video.dgl b/docs/dgl/hunyuan_video/hunyuanvideo1-5-720p-txt2video.dgl new file mode 100644 index 0000000000..e18ac532ca --- /dev/null +++ b/docs/dgl/hunyuan_video/hunyuanvideo1-5-720p-txt2video.dgl @@ -0,0 +1,46 @@ +# version: 0.0.0 +# docs/models/hunyuan_video.md — Text-to-video example + +var { + model_path = "../models/diffusion_models/hunyuanvideo1.5_720p_t2v_fp16.safetensors" + text_path = "../models/text_encoders/qwen_2.5_vl_7b.safetensors" + t5_path = "../models/text_encoders/byt5_small_glyphxl_fp16.safetensors" + vae_path = "../models/vae/hunyuanvideo15_vae_fp16.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1280 + height = 720 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "hunyuan_video", params_backend = "cpu") + text = load_text_encoder(text_path, family = "hunyuan_video", params_backend = "cpu", t5_path = t5_path) + vae = load_vae(vae_path, family = "hunyuan_video", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent), tiling = tiling()) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/ideogram4/ideogram4-txt2img.dgl b/docs/dgl/ideogram4/ideogram4-txt2img.dgl new file mode 100644 index 0000000000..9eb76448ea --- /dev/null +++ b/docs/dgl/ideogram4/ideogram4-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/ideogram4.md — CLI + +var { + model_path = "../models/diffusion_models/ideogram4-Q8_0.gguf" + negative_model_path = "../models/diffusion_models/ideogram4_uncond-Q8_0.gguf" + text_path = "../models/text_encoders/Qwen3VL-8B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "{\"high_level_description\":\"A square 1024 x 1024 luxury fashion magazine cover featuring exactly one short chubby fluffy cat as the main model. The cat sits on a soft ivory studio floor, facing the viewer with a stylish calm expression, wearing tiny black sunglasses, a red silk scarf, and a small gold collar charm. In front of the cat on the floor is a wide horizontal luxury nameplate that clearly reads ideogram4.cpp. The whole design feels premium, fashionable, clean, and editorial.\",\"style_description\":{\"aesthetics\":\"luxury fashion magazine cover, high-end pet couture campaign, minimalist editorial design, elegant studio photography, soft paper texture, refined typography, fashionable and polished\",\"lighting\":\"Soft diffused studio lighting, gentle spotlight on the cat, subtle floor shadow, warm ivory highlights, clean separation between subject and background\",\"photo\":\"high-resolution fashion editorial photography look, front-facing cat portrait, crisp fur details, glossy sunglasses, clear readable nameplate text, shallow depth of field\",\"medium\":\"mixed media fashion photography and premium editorial graphic design\",\"color_palette\":[\"#F4EFE7\",\"#111111\",\"#D8B56D\",\"#B73A3A\",\"#FFFFFF\",\"#8A7A6A\"]},\"compositional_deconstruction\":{\"canvas\":\"Square 1024 x 1024 canvas with a normal upright orientation. Do not rotate the poster or any text. Use a clean fashion magazine cover layout.\",\"background\":\"Warm ivory studio backdrop with subtle paper grain, a soft spotlight gradient, faint floor shadow, and a few minimal gold editorial lines. The background is spacious, premium, and uncluttered.\",\"layout\":\"Top center has a small elegant headline. Center area features one cat as the main fashion model. Lower foreground has a wide horizontal luxury nameplate placed on the floor in front of the cat. Bottom center has a small footer. All text is horizontal, upright, and readable left to right.\",\"elements\":[{\"type\":\"text\",\"desc\":\"Top center headline reading LOOK WHAT I FOUND in a refined high-fashion serif font. The headline is horizontal, centered, elegant, and secondary to the nameplate text.\"},{\"type\":\"obj\",\"desc\":\"Exactly one short chubby fluffy cat sitting in the center like a luxury fashion model. The cat has a large round head, compact body, short legs, soft detailed fur, expressive eyes, and a calm confident pose. The cat is cute and rounded, not tall, not stretched, not duplicated.\"},{\"type\":\"obj\",\"desc\":\"Tiny glossy black sunglasses worn naturally by the cat, slightly oversized but still showing the cat face clearly. The sunglasses add a chic fashion-editorial attitude.\"},{\"type\":\"obj\",\"desc\":\"A red silk scarf tied neatly around the cat neck, with soft folds and a couture feeling. The scarf must not cover the cat face or the nameplate.\"},{\"type\":\"obj\",\"desc\":\"A small gold collar charm or fashion accessory under the scarf, subtle and premium, adding a luxury campaign detail.\"},{\"type\":\"obj\",\"desc\":\"In the lower foreground, place a wide horizontal luxury nameplate on the floor in front of the cat. The nameplate is low, flat, landscape-oriented, much wider than tall, like a fashion show seat card or premium display plaque. It is centered, front-facing, level, and fully visible. It must not become vertical, tall, standing, rotated, or side-facing.\"},{\"type\":\"text\",\"desc\":\"Print the exact text ideogram4.cpp only on the wide horizontal nameplate. Use clean bold black lettering, perfectly spelled, lowercase, with the number 4 and .cpp extension. The text must fit completely inside the nameplate, stay horizontal, and be readable from left to right.\"},{\"type\":\"obj\",\"desc\":\"Add sparse premium editorial accents around the edges: thin gold lines, small code brackets, tiny cursor marks, subtle dots, and minimal geometric details. No extra cats, no stickers, no animal faces, no busy decorations.\"},{\"type\":\"text\",\"desc\":\"Bottom center footer reading tiny paws, big compile energy in a small refined monospace or editorial font. The footer is horizontal, centered, understated, and much smaller than the nameplate text.\"}]}}" + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 7.0 + method = "euler" + scheduler = "logit_normal" +} + +fn main() { + model = load_dit(model_path, family = "ideogram4", params_backend = "cpu") + negative_model = load_dit(negative_model_path, family = "ideogram4", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ideogram4", params_backend = "cpu") + vae = load_vae(vae_path, family = "ideogram4", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = {vector = tensor::vector([1])} + pos = predictor(model, positive) + neg = predictor(negative_model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(pos, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/ip_adapter/ip-adapter-plus-sd1-5.dgl b/docs/dgl/ip_adapter/ip-adapter-plus-sd1-5.dgl new file mode 100644 index 0000000000..8eb9db4a16 --- /dev/null +++ b/docs/dgl/ip_adapter/ip-adapter-plus-sd1-5.dgl @@ -0,0 +1,49 @@ +# version: 0.0.0 +# docs/models/ip_adapter.md — Plus variants + +var { + weights = "../models/checkpoints/sd_v1.5.safetensors" + vision_encoder_path = "../models/clip_vision/clip_vision_h.safetensors" + ip_adapter_path = "../models/ipadapter/ip-adapter-plus_sd15.safetensors" + + input_path = "../inputs/reference.png" + output_path = "output.png" + + prompt = "a woman, best quality" + negative_prompt = "lowres, bad anatomy" + + seed = 42 + width = 512 + height = 512 + + steps = 30 + cfg_scale = 7.0 + method = "dpm++2m" + scheduler = "karras" +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights) + vision = load_vision_encoder(vision_encoder_path) + adapter = ip_adapter::load(ip_adapter_path, family = "sd1") + reference = image::load(input_path) + embedding = encode_vision(vision, reference) + positive_image = ip_adapter::project(adapter, embedding) + negative_embedding = encode_vision(vision, reference, zero_input = true) + negative_image = ip_adapter::project(adapter, negative_embedding) + positive = ip_adapter::apply(encode_prompt(text, prompt, width = width, height = height), adapter, positive_image, strength = 0.8) + negative = ip_adapter::apply(encode_prompt(text, negative_prompt, width = width, height = height), adapter, negative_image, strength = 0.8) + pos = predictor(unet, positive, prediction = "eps") + neg = predictor(unet, negative, prediction = "eps") + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + rng = make_rng("cuda", seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent, image_tokens = positive_image } +} diff --git a/docs/dgl/ip_adapter/ip-adapter-sd1-5.dgl b/docs/dgl/ip_adapter/ip-adapter-sd1-5.dgl new file mode 100644 index 0000000000..145e90c0f9 --- /dev/null +++ b/docs/dgl/ip_adapter/ip-adapter-sd1-5.dgl @@ -0,0 +1,47 @@ +# version: 0.0.0 +# docs/models/ip_adapter.md — Example (SD 1.5) + +var { + weights = "../models/checkpoints/sd_v1.5.safetensors" + vision_encoder_path = "../models/clip_vision/clip_vision_h.safetensors" + ip_adapter_path = "../models/ipadapter/ip-adapter_sd15.safetensors" + + input_path = "../inputs/reference.png" + output_path = "output.png" + + prompt = "a woman, best quality" + negative_prompt = "lowres, bad anatomy" + + seed = 42 + width = 512 + height = 512 + + steps = 30 + cfg_scale = 7.0 + method = "dpm++2m" + scheduler = "karras" +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights) + vision = load_vision_encoder(vision_encoder_path) + adapter = ip_adapter::load(ip_adapter_path, family = "sd1") + embedding = encode_vision(vision, image::load(input_path), pooled = true) + positive_image = ip_adapter::project(adapter, embedding) + negative_image = ip_adapter::project(adapter, tensor::zeros_like(embedding)) + positive = ip_adapter::apply(encode_prompt(text, prompt, width = width, height = height), adapter, positive_image, strength = 0.8) + negative = ip_adapter::apply(encode_prompt(text, negative_prompt, width = width, height = height), adapter, negative_image, strength = 0.8) + pos = predictor(unet, positive, prediction = "eps") + neg = predictor(unet, negative, prediction = "eps") + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + rng = make_rng("cuda", seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent, image_tokens = positive_image } +} diff --git a/docs/dgl/ip_adapter/ip-adapter-sdxl-controlnet.dgl b/docs/dgl/ip_adapter/ip-adapter-sdxl-controlnet.dgl new file mode 100644 index 0000000000..64a4f7f3dc --- /dev/null +++ b/docs/dgl/ip_adapter/ip-adapter-sdxl-controlnet.dgl @@ -0,0 +1,76 @@ +# version: 0.0.0 +# docs/models/ip_adapter.md — Combining with Control Net + +var { + weights = "../models/checkpoints/sdxl.safetensors" + vision_encoder_path = "../models/clip_vision/clip_vision_h.safetensors" + ip_adapter_path = "../models/ipadapter/ip-adapter_sdxl_vit-h.safetensors" + control_path = "../models/controlnet/OpenPoseXL2.safetensors" + + input_path = "../inputs/character.png" + control_image_path = "../inputs/pose.png" + output_path = "output.png" + + prompt = "a character, side view" + negative_prompt = "" + zero_negative = true + + seed = 42 + width = 1024 + height = 1024 + + steps = 25 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn sdxl_zero_text(cond) { + zeroed = zero_out(cond, fields = ["crossattn"]) + pooled_zeros = tensor::zeros_like(cond.vector[:1280]) + adm = tensor::replace_slice(cond.vector, pooled_zeros, axis = 0, start = 0) + return {crossattn = zeroed.crossattn, vector = adm} +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights, conv_scale = 0.03125) + vision = load_vision_encoder(vision_encoder_path) + adapter = ip_adapter::load(ip_adapter_path, family = "sdxl") + embedding = encode_vision(vision, image::load(input_path), pooled = true) + positive_image = ip_adapter::project(adapter, embedding) + negative_image = ip_adapter::project(adapter, tensor::zeros_like(embedding)) + positive = ip_adapter::apply(encode_prompt(text, prompt, width = width, height = height), adapter, positive_image, strength = 0.9) + negative_text = encode_prompt(text, negative_prompt, width = width, height = height) + negative_condition = if zero_negative { + sdxl_zero_text(negative_text) + } else { + {crossattn = negative_text.crossattn, vector = negative_text.vector} + } + negative = ip_adapter::apply(negative_condition, adapter, negative_image, strength = 0.9) + control = controlnet::load(control_path, family = "sdxl") + hint = fit_canvas(image::load(control_image_path), width, height, mode = "nearest") + controlled_positive = controlnet::apply(positive, control, hint, strength = 0.8) + controlled_negative = controlnet::apply(negative, control, hint, strength = 0.8) + pos = predictor(unet, controlled_positive, prediction = "eps") + neg = predictor(unet, controlled_negative, prediction = "eps") + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + rng = make_rng("cuda", seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent), tiling = tiling()) + image::save(output_path, image) + return { image = image, latent = latent, image_tokens = positive_image } +} diff --git a/docs/dgl/ip_adapter/ip-adapter-sdxl.dgl b/docs/dgl/ip_adapter/ip-adapter-sdxl.dgl new file mode 100644 index 0000000000..86079dd56c --- /dev/null +++ b/docs/dgl/ip_adapter/ip-adapter-sdxl.dgl @@ -0,0 +1,47 @@ +# version: 0.0.0 +# docs/models/ip_adapter.md — Example (SDXL) + +var { + weights = "../models/checkpoints/sdxl.safetensors" + vision_encoder_path = "../models/clip_vision/clip_vision_h.safetensors" + ip_adapter_path = "../models/ipadapter/ip-adapter_sdxl_vit-h.safetensors" + + input_path = "../inputs/reference.png" + output_path = "output.png" + + prompt = "a woman, best quality" + negative_prompt = "lowres, bad anatomy" + + seed = 42 + width = 1024 + height = 1024 + + steps = 25 + cfg_scale = 6.0 + method = "dpm++2m" + scheduler = "karras" +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights, conv_scale = 0.03125) + vision = load_vision_encoder(vision_encoder_path) + adapter = ip_adapter::load(ip_adapter_path, family = "sdxl") + embedding = encode_vision(vision, image::load(input_path), pooled = true) + positive_image = ip_adapter::project(adapter, embedding) + negative_image = ip_adapter::project(adapter, tensor::zeros_like(embedding)) + positive = ip_adapter::apply(encode_prompt(text, prompt, width = width, height = height), adapter, positive_image, strength = 0.8) + negative = ip_adapter::apply(encode_prompt(text, negative_prompt, width = width, height = height), adapter, negative_image, strength = 0.8) + pos = predictor(unet, positive, prediction = "eps") + neg = predictor(unet, negative, prediction = "eps") + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + rng = make_rng("cuda", seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent), tiling = tiling()) + image::save(output_path, image) + return { image = image, latent = latent, image_tokens = positive_image } +} diff --git a/docs/dgl/iris/iris-3b-txt2img.dgl b/docs/dgl/iris/iris-3b-txt2img.dgl new file mode 100644 index 0000000000..8f4844286d --- /dev/null +++ b/docs/dgl/iris/iris-3b-txt2img.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/iris.md — CLI + +var { + model_path = "../models/diffusion_models/iris-3b.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "iris_3b") + text = load_text_encoder(text_path, family = "iris_3b") + base = tensor::zeros([width, height, 3, 1]) + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + pixels = tensor::clamp(tensor::affine(latent, scale = 0.5, offset = 0.5), 0, 1) + image = image::to_u8(pixels) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/kontext/flux1-kontext-dev-edit.dgl b/docs/dgl/kontext/flux1-kontext-dev-edit.dgl new file mode 100644 index 0000000000..a13cb8b897 --- /dev/null +++ b/docs/dgl/kontext/flux1-kontext-dev-edit.dgl @@ -0,0 +1,63 @@ +# version: 0.0.0 +# docs/models/kontext.md — Example + +var { + model_path = "../models/diffusion_models/flux1-kontext-dev-q8_0.gguf" + clip_l_path = "../models/text_encoders/clip_l.safetensors" + t5_path = "../models/text_encoders/t5xxl_fp16.safetensors" + vae_path = "../models/vae/ae.sft" + + reference_0_path = "./flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'kontext.cpp'" + + seed = 42 + rng_type = "cuda" + + steps = 20 + method = "euler" + scheduler = "flux" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "flux") + text = load_text_encoder(clip_l_path, backend = "cpu", clip_l_path = clip_l_path, family = "flux", t5_path = t5_path) + vae = load_vae(vae_path, family = "flux") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 16, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, ref_latents = [reference_latent_0]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/krea2/krea2-raw-txt2img.dgl b/docs/dgl/krea2/krea2-raw-txt2img.dgl new file mode 100644 index 0000000000..621374eec7 --- /dev/null +++ b/docs/dgl/krea2/krea2-raw-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/krea2.md — Krea2 + +var { + model_path = "../models/diffusion_models/Krea-2-Raw-Q8_0.gguf" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'krea2.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "krea2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "krea2", params_backend = "cpu") + vae = load_vae(vae_path, family = "krea2", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/lcm/lcm-lora-sd1-5.dgl b/docs/dgl/lcm/lcm-lora-sd1-5.dgl new file mode 100644 index 0000000000..16895dd9b4 --- /dev/null +++ b/docs/dgl/lcm/lcm-lora-sd1-5.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/lcm.md — LCM-LoRA with SD 1.5 + +var { + model_path = "../models/checkpoints/v1-5-pruned-emaonly.safetensors" + lora_0_path = "../models/loras/lcm-lora-sdv1-5.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 4 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + base_model = load_unet(model_path, family = "sd1") + text = load_text_encoder(model_path, family = "sd1") + vae = load_vae(model_path, family = "sd1") + + lora_0 = load_lora(lora_0_path) + model = apply_lora(base_model, lora_0) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/lens/lens-turbo-txt2img.dgl b/docs/dgl/lens/lens-turbo-txt2img.dgl new file mode 100644 index 0000000000..71299ed635 --- /dev/null +++ b/docs/dgl/lens/lens-turbo-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/lens.md — Lens Turbo + +var { + model_path = "../models/diffusion_models/lens_turbo_bf16.safetensors" + text_path = "../models/text_encoders/gpt-oss-20b-UD-Q8_K_XL.gguf" + tokenizer_path = "../models/tokenizers/tokenizer_gpt_oss.json" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "A crystal dragon soaring through an aurora borealis sky, its entire body made of transparent faceted crystal refracting the green and purple aurora light into rainbow spectra, ice particles trailing from its wings, high fantasy digital art" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 4 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "lens") + text = load_text_encoder(text_path, family = "lens", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "lens") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/lens/lens-txt2img.dgl b/docs/dgl/lens/lens-txt2img.dgl new file mode 100644 index 0000000000..9b39ea9d80 --- /dev/null +++ b/docs/dgl/lens/lens-txt2img.dgl @@ -0,0 +1,44 @@ +# version: 0.0.0 +# docs/models/lens.md — Lens + +var { + model_path = "../models/diffusion_models/lens_bf16.safetensors" + text_path = "../models/text_encoders/gpt-oss-20b-UD-Q8_K_XL.gguf" + tokenizer_path = "../models/tokenizers/tokenizer_gpt_oss.json" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "A crystal dragon soaring through an aurora borealis sky, its entire body made of transparent faceted crystal refracting the green and purple aurora light into rainbow spectra, ice particles trailing from its wings, high fantasy digital art" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 5.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "lens") + text = load_text_encoder(text_path, family = "lens", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "lens") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/lingbot_video/lingbot-video-dens-1-3b-txt2video.dgl b/docs/dgl/lingbot_video/lingbot-video-dens-1-3b-txt2video.dgl new file mode 100644 index 0000000000..197df27b3d --- /dev/null +++ b/docs/dgl/lingbot_video/lingbot-video-dens-1-3b-txt2video.dgl @@ -0,0 +1,45 @@ +# version: 0.0.0 +# docs/models/lingbot_video.md — LingBot-Video T2V + +var { + model_path = "../models/diffusion_models/lingbot-video-dens-1.3b.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.avi" + + negative_prompt = "{\"universal_negative\":{\"visual_quality\":[\"low quality\",\"worst quality\",\"blurry\",\"pixelated\",\"jpeg artifacts\",\"low resolution\",\"unstable color\",\"color flicker\",\"underexposed\",\"overexposed\",\"invisible subject\",\"subject hidden in darkness\"],\"artistic_style\":[\"painting\",\"illustration\",\"drawing\",\"cartoon\",\"3d render\",\"cgi\",\"sketch\",\"digital art\"],\"composition_and_content\":[\"text\",\"watermark\",\"signature\",\"logo\",\"subtitles\",\"pillarboxed\",\"side bars\",\"portrait image in landscape frame\"],\"temporal_and_motion_stability\":[\"flickering\",\"jittery\",\"motion blur\",\"temporal inconsistency\",\"warping\",\"morphing\",\"incoherent motion\",\"unnatural movement\",\"static object with sudden jump\",\"frame-to-frame inconsistency\"],\"material_and_structure\":[\"plastic-like glass\",\"unrealistic texture\",\"deformed bottle\",\"liquid freezing improperly\",\"distorted reflections\"]}}" + prompt = "{\"caption\":{\"comprehensive_description\":\"A lovely cat sits comfortably on a soft cushion near a sunlit window, looking calm, gentle, and adorable. The cat has soft fluffy fur, bright expressive eyes, small rounded ears, delicate whiskers, and a relaxed posture. Warm daylight falls across the cat from one side, creating soft highlights on the fur and a cozy glow around the scene. The background is softly blurred, showing hints of a peaceful indoor home environment with warm tones and gentle natural light. The overall atmosphere is cute, tender, serene, and photorealistic, emphasizing the cats charming appearance, soft texture, and affectionate presence.\",\"camera_info\":{\"color\":\"Warm\",\"frame_size\":\"Close Up\",\"shot_type_angle\":\"Eye level\",\"lens_size\":\"Medium Lens\",\"composition\":\"Centered balanced\",\"lighting\":\"Soft light\",\"lighting_type\":\"Daylight\"},\"world_knowledge\":[],\"prominent_elements\":[{\"name\":\"lovely cat\",\"description\":\"A cute and gentle domestic cat with soft fluffy fur, expressive eyes, and a calm relaxed presence.\",\"location\":\"center of the frame\",\"relative_size\":\"large\",\"shape_and_color\":\"Small animal body with rounded face, triangular ears, bright eyes, and soft fur in warm natural tones\",\"texture\":\"soft, fluffy, silky\",\"appearance_details\":\"The cat has clean well-groomed fur, delicate whiskers, small ears, a cute nose, and bright attentive eyes. Its expression appears calm, affectionate, and slightly curious.\",\"relationship\":\"Acts as the main subject and emotional focal point of the scene.\",\"orientation\":\"facing the camera\",\"pose\":\"sitting comfortably with a relaxed posture\",\"expression\":\"gentle, adorable, calm, slightly curious\",\"clothing\":\"\",\"gender\":\"\",\"skin_tone_and_texture\":\"\"},{\"name\":\"cat eyes\",\"description\":\"Bright expressive eyes that give the cat a sweet and affectionate appearance.\",\"location\":\"upper center of the cat face\",\"relative_size\":\"small\",\"shape_and_color\":\"Round almond-like eyes with glossy reflections\",\"texture\":\"clear, glossy, reflective\",\"appearance_details\":\"The eyes catch the soft daylight, creating small natural highlights that make the cat look vivid and alive.\",\"relationship\":\"Enhance the emotional charm and cuteness of the cat.\",\"orientation\":\"looking toward the camera\",\"pose\":\"\",\"expression\":\"soft and attentive\",\"clothing\":\"\",\"gender\":\"\",\"skin_tone_and_texture\":\"\"},{\"name\":\"soft cushion\",\"description\":\"A comfortable cushion or blanket where the cat is resting.\",\"location\":\"bottom portion of the frame\",\"relative_size\":\"medium\",\"shape_and_color\":\"Soft rounded fabric surface in light warm neutral tones\",\"texture\":\"plush, fabric, cozy\",\"appearance_details\":\"The cushion gently supports the cat and adds a comfortable home-like feeling to the scene.\",\"relationship\":\"Provides a cozy resting place for the cat.\",\"orientation\":\"horizontal\",\"pose\":\"\",\"expression\":\"\",\"clothing\":\"\",\"gender\":\"\",\"skin_tone_and_texture\":\"\"},{\"name\":\"sunlit indoor background\",\"description\":\"A softly blurred indoor background with warm daylight and peaceful home atmosphere.\",\"location\":\"behind the cat, filling the upper and side areas of the frame\",\"relative_size\":\"large\",\"shape_and_color\":\"Soft abstract shapes in warm beige, cream, and pale golden tones\",\"texture\":\"soft, blurry, bokeh-like\",\"appearance_details\":\"The background is intentionally out of focus, keeping attention on the cat while creating a cozy and serene mood.\",\"relationship\":\"Provides a warm and gentle environment that supports the cute domestic scene.\",\"orientation\":\"upright\",\"pose\":\"\",\"expression\":\"\",\"clothing\":\"\",\"gender\":\"\",\"skin_tone_and_texture\":\"\",\"is_cluster\":true,\"number_of_objects\":\"numerous\"}]}}" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "lingbot_video", params_backend = "cpu") + text = load_text_encoder(text_path, family = "lingbot_video", params_backend = "cpu") + vae = load_vae(vae_path, family = "lingbot_video", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/llada_image/llada-image-turbo-edit.dgl b/docs/dgl/llada_image/llada-image-turbo-edit.dgl new file mode 100644 index 0000000000..41037af159 --- /dev/null +++ b/docs/dgl/llada_image/llada-image-turbo-edit.dgl @@ -0,0 +1,48 @@ +# version: 0.0.0 +# docs/models/llada_image.md — Image editing + +var { + model_path = "../models/diffusion_models/llada-image-turbo-f16.gguf" + text_path = "../models/text_encoders/llada-image-turbo-text_encoder-q8_0.gguf" + connectors_path = "../models/text_encoders/llada-image-turbo-connectors-edit.safetensors" + tokenizer_path = "../models/tokenizers/tokenizer.json" + vae_path = "../models/vae/llada_vae.safetensors" + + reference_0_path = "../inputs/input.png" + output_path = "output.png" + + prompt = "change the sign text to 'sd.cpp'" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 4 + method = "euler" + scheduler = "llada_image" +} + +fn main() { + reference_0 = image::load(reference_0_path) + + model = load_dit(model_path, family = "llada_image") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "llada_image", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "llada_image") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = tensor::interpolate(reference_0_original, size = [width, height], mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_pixels]) + predict = predictor(model, condition, ref_latents = [reference_latent_0], force_ref_timestep_zero = true) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/llada_image/llada-image-turbo-txt2img.dgl b/docs/dgl/llada_image/llada-image-turbo-txt2img.dgl new file mode 100644 index 0000000000..8a93fd6c6d --- /dev/null +++ b/docs/dgl/llada_image/llada-image-turbo-txt2img.dgl @@ -0,0 +1,40 @@ +# version: 0.0.0 +# docs/models/llada_image.md — Text to image + +var { + model_path = "../models/diffusion_models/llada-image-turbo-f16.gguf" + text_path = "../models/text_encoders/llada-image-turbo-text_encoder-q8_0.gguf" + connectors_path = "../models/text_encoders/llada-image-turbo-connectors.safetensors" + tokenizer_path = "../models/tokenizers/tokenizer.json" + vae_path = "../models/vae/llada_vae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'llada.cpp'" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 4 + method = "euler" + scheduler = "llada_image" +} + +fn main() { + model = load_dit(model_path, family = "llada_image") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "llada_image", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "llada_image") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/longcat_image/longcat-image-txt2img.dgl b/docs/dgl/longcat_image/longcat-image-txt2img.dgl new file mode 100644 index 0000000000..1f43801b8c --- /dev/null +++ b/docs/dgl/longcat_image/longcat-image-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/longcat_image.md — LongCat Image + +var { + model_path = "../models/diffusion_models/LongCat-Image-Q4_K_M.gguf" + text_path = "../models/text_encoders/Qwen2.5-VL-7B-Instruct-Q8_0.gguf" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'longcat.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 5.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "longcat_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "longcat_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "longcat_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/lora/sd1-5-lora.dgl b/docs/dgl/lora/sd1-5-lora.dgl new file mode 100644 index 0000000000..a8f33799b8 --- /dev/null +++ b/docs/dgl/lora/sd1-5-lora.dgl @@ -0,0 +1,45 @@ +# version: 0.0.0 +# docs/models/lora.md — CLI + +var { + model_path = "../models/checkpoints/v1-5-pruned-emaonly.safetensors" + lora_0_path = "../models/loras/marblesh.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + base_model = load_unet(model_path, family = "sd1") + base_text = load_text_encoder(model_path, family = "sd1") + vae = load_vae(model_path, family = "sd1") + + lora_0 = load_lora(lora_0_path) + model = apply_lora(base_model, lora_0) + text = apply_lora(base_text, lora_0) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/ltx2/ltx-2-3-dev-first-last-frame.dgl b/docs/dgl/ltx2/ltx-2-3-dev-first-last-frame.dgl new file mode 100644 index 0000000000..2ab96e3a6d --- /dev/null +++ b/docs/dgl/ltx2/ltx-2-3-dev-first-last-frame.dgl @@ -0,0 +1,100 @@ +# version: 0.0.0 +# docs/models/ltx2.md — LTX-2.3 dev FLF2V + +var { + model_path = "../models/diffusion_models/ltx-2.3-22b-dev-UD-Q4_K_M.gguf" + text_path = "../models/text_encoders/gemma-3-12b-it-qat-UD-Q4_K_XL.gguf" + connectors_path = "../models/text_encoders/ltx-2.3-22b-dev_embeddings_connectors.safetensors" + vae_path = "../models/vae/ltx-2.3-22b-dev_video_vae.safetensors" + audio_vae_path = "../models/vae/ltx-2.3-22b-dev_audio_vae.safetensors" + + first_frame_path = "../inputs/start_image.png" + last_frame_path = "../inputs/end_image.png" + output_path = "flf2v.avi" + + prompt = "glass flower blossom" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1280 + height = 736 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "ltx2" + strength = 0.75 + audio_scale = 1 +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + first_frame = image::load(first_frame_path) + last_frame = image::load(last_frame_path) + + model = load_dit(model_path, family = "ltxav", params_backend = "cpu") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "ltxav", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "ltxav", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + last_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(last_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + video_shape = tensor::shape(video_base) + video_mask = tensor::full([video_shape[0], video_shape[1], video_shape[2], 1, 1], 1) + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + video_first = tensor::replace_slice(video_base, first_latent, axis = 2, start = 0) + mask_first = tensor::index_fill(video_mask, axis = 2, indices = [0], value = 1 - strength) + last_latent = vae_to_dit_latents(vae, vae_encode(vae, last_frame_pixels, rng = rng)) + tail_mask = tensor::full([video_shape[0], video_shape[1], tensor::shape(last_latent)[2], 1, 1], 1 - strength) + video_conditioned = tensor::concat([video_first, last_latent], axis = 2) + mask_conditioned = tensor::concat([mask_first, tail_mask], axis = 2) + positions = ltx::video_positions(video_first, keyframe_latent_frames = tensor::shape(last_latent)[2], keyframe_frame_index = frames - 1, keyframe_pixel_frames = 1, fps = fps) + audio_vae = load_audio_vae(audio_vae_path, family = "ltxav", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_conditioned, tensor::zeros(audio_shape), audio_scale = audio_scale) + packed_shape = tensor::shape(base) + full_video_mask = tensor::broadcast_to(mask_conditioned, tensor::shape(video_conditioned)) + packed_mask = tensor::concat([full_video_mask, tensor::full([packed_shape[0], packed_shape[1], packed_shape[2], packed_shape[3] - video_shape[3], 1], 1)], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, audio_length = audio_shape[1], fps = fps, video_positions = positions) + neg = predictor(model, negative, audio_length = audio_shape[1], fps = fps, video_positions = positions) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng, base = base, denoise_mask = packed_mask, mask_input = true) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/ltx2/ltx-2-3-dev-img2video.dgl b/docs/dgl/ltx2/ltx-2-3-dev-img2video.dgl new file mode 100644 index 0000000000..13793a8b4d --- /dev/null +++ b/docs/dgl/ltx2/ltx-2-3-dev-img2video.dgl @@ -0,0 +1,92 @@ +# version: 0.0.0 +# docs/models/ltx2.md — LTX-2.3 dev I2V + +var { + model_path = "../models/diffusion_models/ltx-2.3-22b-dev-UD-Q4_K_M.gguf" + text_path = "../models/text_encoders/gemma-3-12b-it-qat-UD-Q4_K_XL.gguf" + connectors_path = "../models/text_encoders/ltx-2.3-22b-dev_embeddings_connectors.safetensors" + vae_path = "../models/vae/ltx-2.3-22b-dev_video_vae.safetensors" + audio_vae_path = "../models/vae/ltx-2.3-22b-dev_audio_vae.safetensors" + + first_frame_path = "../inputs/ernie_image/turbo_example.png" + output_path = "i2v.avi" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1280 + height = 736 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "ltx2" + strength = 0.75 + audio_scale = 1 +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "ltxav", params_backend = "cpu") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "ltxav", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "ltxav", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + video_shape = tensor::shape(video_base) + video_mask = tensor::full([video_shape[0], video_shape[1], video_shape[2], 1, 1], 1) + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + video_conditioned = tensor::replace_slice(video_base, first_latent, axis = 2, start = 0) + mask_conditioned = tensor::index_fill(video_mask, axis = 2, indices = [0], value = 1 - strength) + audio_vae = load_audio_vae(audio_vae_path, family = "ltxav", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_conditioned, tensor::zeros(audio_shape), audio_scale = audio_scale) + packed_shape = tensor::shape(base) + full_video_mask = tensor::broadcast_to(mask_conditioned, tensor::shape(video_conditioned)) + packed_mask = tensor::concat([full_video_mask, tensor::full([packed_shape[0], packed_shape[1], packed_shape[2], packed_shape[3] - video_shape[3], 1], 1)], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, audio_length = audio_shape[1], fps = fps) + neg = predictor(model, negative, audio_length = audio_shape[1], fps = fps) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng, base = base, denoise_mask = packed_mask, mask_input = true) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/ltx2/ltx-2-3-dev-txt2video.dgl b/docs/dgl/ltx2/ltx-2-3-dev-txt2video.dgl new file mode 100644 index 0000000000..2712de41b6 --- /dev/null +++ b/docs/dgl/ltx2/ltx-2-3-dev-txt2video.dgl @@ -0,0 +1,70 @@ +# version: 0.0.0 +# docs/models/ltx2.md — LTX-2.3 dev T2V + +var { + model_path = "../models/diffusion_models/ltx-2.3-22b-dev-UD-Q4_K_M.gguf" + text_path = "../models/text_encoders/gemma-3-12b-it-qat-UD-Q4_K_XL.gguf" + connectors_path = "../models/text_encoders/ltx-2.3-22b-dev_embeddings_connectors.safetensors" + vae_path = "../models/vae/ltx-2.3-22b-dev_video_vae.safetensors" + audio_vae_path = "../models/vae/ltx-2.3-22b-dev_audio_vae.safetensors" + + output_path = "t2v.avi" + + prompt = "a lovely cat" + negative_prompt = "worst quality, low quality, blurry, distorted, artifacts" + + seed = 42 + rng_type = "cuda" + width = 1280 + height = 736 + frames = 33 + fps = 24 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "ltx2" + audio_scale = 1 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + model = load_dit(model_path, family = "ltxav", params_backend = "cpu") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "ltxav", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "ltxav", params_backend = "cpu") + + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "ltxav", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, audio_length = audio_shape[1], fps = fps) + neg = predictor(model, negative, audio_length = audio_shape[1], fps = fps) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/ltx2/ltx-2-3-spatial-upscale.dgl b/docs/dgl/ltx2/ltx-2-3-spatial-upscale.dgl new file mode 100644 index 0000000000..6bb5a1e429 --- /dev/null +++ b/docs/dgl/ltx2/ltx-2-3-spatial-upscale.dgl @@ -0,0 +1,125 @@ +# version: 0.0.0 +# docs/models/ltx2.md — LTX-2.3 spatial latent upscale + +var { + model_path = "../models/diffusion_models/ltx-2.3-22b-dev-UD-Q4_K_M.gguf" + text_path = "../models/text_encoders/gemma-3-12b-it-qat-UD-Q4_K_XL.gguf" + connectors_path = "../models/text_encoders/ltx-2.3-22b-dev_embeddings_connectors.safetensors" + vae_path = "../models/vae/ltx-2.3-22b-dev_video_vae.safetensors" + audio_vae_path = "../models/vae/ltx-2.3-22b-dev_audio_vae.safetensors" + hires_model_path = "../models/latent_upscale_models/ltx-2.3-spatial-upscaler-x2-1.1.safetensors" + + first_frame_path = "../inputs/ernie_image/turbo_example.png" + output_path = "hires_i2v.avi" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 640 + height = 352 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "ltx2" + strength = 0.75 + audio_scale = 1 + + hires_steps = 4 + hires_scheduler_steps = 5 + hires_vae_scale = 32 +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "ltxav", params_backend = "cpu") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "ltxav", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "ltxav", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + video_shape = tensor::shape(video_base) + video_mask = tensor::full([video_shape[0], video_shape[1], video_shape[2], 1, 1], 1) + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + video_conditioned = tensor::replace_slice(video_base, first_latent, axis = 2, start = 0) + mask_conditioned = tensor::index_fill(video_mask, axis = 2, indices = [0], value = 1 - strength) + audio_vae = load_audio_vae(audio_vae_path, family = "ltxav", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_conditioned, tensor::zeros(audio_shape), audio_scale = audio_scale) + packed_shape = tensor::shape(base) + full_video_mask = tensor::broadcast_to(mask_conditioned, tensor::shape(video_conditioned)) + packed_mask = tensor::concat([full_video_mask, tensor::full([packed_shape[0], packed_shape[1], packed_shape[2], packed_shape[3] - video_shape[3], 1], 1)], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, audio_length = audio_shape[1], fps = fps) + neg = predictor(model, negative, audio_length = audio_shape[1], fps = fps) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng, base = base, denoise_mask = packed_mask, mask_input = true) + hires_source = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + hires_upscaler = load_latent_upscaler(hires_model_path, family = "ltxav", params_backend = "cpu") + hires_upscaled = upscale_latent(hires_upscaler, dit_to_vae_latents(vae, hires_source)) + hires_upscaled_shape = tensor::shape(hires_upscaled) + hires_video = vae_to_dit_latents(vae, tensor::reshape(hires_upscaled, [hires_upscaled_shape[0], hires_upscaled_shape[1], hires_upscaled_shape[2], hires_upscaled_shape[3], 1])) + hires_video_shape = tensor::shape(hires_video) + hires_original_audio = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + hires_width = hires_video_shape[0] * hires_vae_scale + hires_height = hires_video_shape[1] * hires_vae_scale + hires_frames = (hires_video_shape[2] - 1) * 8 + 1 + hires_audio_shape = audio_latent_shape(audio_vae, frames = hires_frames, fps = fps) + hires_audio_retained = math::min(audio_shape[1], hires_audio_shape[1]) + hires_audio = tensor::pad(hires_original_audio[:, :hires_audio_retained], [0, 0, 0, hires_audio_shape[1] - hires_audio_retained]) + hires_video_mask = tensor::full([hires_video_shape[0], hires_video_shape[1], hires_video_shape[2], 1, 1], 1) + hires_first_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, hires_width, hires_height, mode = "nearest"), channels = 3), axis = 2) + hires_first_latent = vae_to_dit_latents(vae, vae_encode(vae, hires_first_pixels, rng = rng)) + hires_conditioned = tensor::replace_slice(hires_video, hires_first_latent, axis = 2, start = 0) + hires_condition_mask = tensor::index_fill(hires_video_mask, axis = 2, indices = [0], value = 0) + hires_base = pack_av(hires_conditioned, hires_audio, audio_scale = audio_scale) + hires_packed_shape = tensor::shape(hires_base) + hires_packed_mask = tensor::concat([tensor::broadcast_to(hires_condition_mask, tensor::shape(hires_conditioned)), tensor::full([hires_packed_shape[0], hires_packed_shape[1], hires_packed_shape[2], hires_packed_shape[3] - hires_video_shape[3], 1], 1)], axis = 3) + hires_pos = predictor(model, positive, audio_length = hires_audio_shape[1], fps = fps) + hires_neg = predictor(model, negative, audio_length = hires_audio_shape[1], fps = fps) + hires_guided = cfg(hires_pos, hires_neg, scale = cfg_scale) + hires_schedule = make_sigmas(hires_guided, latent = hires_base, steps = hires_scheduler_steps, scheduler = scheduler) + hires_sigmas = hires_schedule[-(hires_steps + 1):] + hires_start = add_noise(hires_guided, hires_base, tensor::randn_like(hires_base, rng = rng), sigma = hires_sigmas[0]) + hires_latent = sample(hires_start, hires_sigmas, predict = hires_guided, method = method, rng = rng, base = hires_base, denoise_mask = hires_packed_mask, mask_input = true) + video_latent = hires_latent[:, :, :hires_video_shape[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(hires_latent, channels = tensor::shape(video_base)[3], audio_shape = hires_audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = hires_latent, audio = audio} +} diff --git a/docs/dgl/ltx2/ltx-2-5-dev-img2video.dgl b/docs/dgl/ltx2/ltx-2-5-dev-img2video.dgl new file mode 100644 index 0000000000..912af8ac4d --- /dev/null +++ b/docs/dgl/ltx2/ltx-2-5-dev-img2video.dgl @@ -0,0 +1,91 @@ +# version: 0.0.0 +# docs/models/ltx2.md — LTX-2.5 dev I2V + +var { + model_path = "../models/diffusion_models/ltx-2.5-22b-dev-transformer-Q8_0.gguf" + text_path = "../models/text_encoders/gemma4-12b-with-proj-ltx-2.5-Q8_0.gguf" + vae_path = "../models/vae/ltx-2.5-video-vae-conv-bf16.safetensors" + audio_vae_path = "../models/vae/ltx-2.5-audio-vae-bf16.safetensors" + + first_frame_path = "../inputs/ernie_image/turbo_example.png" + output_path = "i2v.avi" + + prompt = "a lovely cat blinking slowly, gentle camera push in" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1280 + height = 736 + frames = 121 + fps = 16 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "ltx2" + strength = 0.75 + audio_scale = 1 +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "ltxav", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ltxav", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "ltxav", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + video_shape = tensor::shape(video_base) + video_mask = tensor::full([video_shape[0], video_shape[1], video_shape[2], 1, 1], 1) + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + video_conditioned = tensor::replace_slice(video_base, first_latent, axis = 2, start = 0) + mask_conditioned = tensor::index_fill(video_mask, axis = 2, indices = [0], value = 1 - strength) + audio_vae = load_audio_vae(audio_vae_path, family = "ltxav", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_conditioned, tensor::zeros(audio_shape), audio_scale = audio_scale) + packed_shape = tensor::shape(base) + full_video_mask = tensor::broadcast_to(mask_conditioned, tensor::shape(video_conditioned)) + packed_mask = tensor::concat([full_video_mask, tensor::full([packed_shape[0], packed_shape[1], packed_shape[2], packed_shape[3] - video_shape[3], 1], 1)], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, audio_length = audio_shape[1], fps = fps) + neg = predictor(model, negative, audio_length = audio_shape[1], fps = fps) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng, base = base, denoise_mask = packed_mask, mask_input = true) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/ltx2/ltx-2-5-dev-txt2video.dgl b/docs/dgl/ltx2/ltx-2-5-dev-txt2video.dgl new file mode 100644 index 0000000000..55e4fdc76a --- /dev/null +++ b/docs/dgl/ltx2/ltx-2-5-dev-txt2video.dgl @@ -0,0 +1,69 @@ +# version: 0.0.0 +# docs/models/ltx2.md — LTX-2.5 dev T2V + +var { + model_path = "../models/diffusion_models/ltx-2.5-22b-dev-transformer-Q8_0.gguf" + text_path = "../models/text_encoders/gemma4-12b-with-proj-ltx-2.5-Q8_0.gguf" + vae_path = "../models/vae/ltx-2.5-video-vae-conv-bf16.safetensors" + audio_vae_path = "../models/vae/ltx-2.5-audio-vae-bf16.safetensors" + + output_path = "t2v.avi" + + prompt = "A wide aerial shot of a red vintage convertible driving along a coastal cliff road at sunset, waves crashing below" + negative_prompt = "worst quality, low quality, blurry, distorted, artifacts" + + seed = 42 + rng_type = "cuda" + width = 1280 + height = 736 + frames = 121 + fps = 24 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "ltx2" + audio_scale = 1 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + model = load_dit(model_path, family = "ltxav", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ltxav", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "ltxav", params_backend = "cpu") + + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "ltxav", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, audio_length = audio_shape[1], fps = fps) + neg = predictor(model, negative, audio_length = audio_shape[1], fps = fps) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/ltx2/ltx-2-5-spatial-upscale.dgl b/docs/dgl/ltx2/ltx-2-5-spatial-upscale.dgl new file mode 100644 index 0000000000..8babae4b9a --- /dev/null +++ b/docs/dgl/ltx2/ltx-2-5-spatial-upscale.dgl @@ -0,0 +1,92 @@ +# version: 0.0.0 +# docs/models/ltx2.md — LTX-2.5 spatial latent upscale + +var { + model_path = "../models/diffusion_models/ltx-2.5-22b-dev-transformer-Q8_0.gguf" + text_path = "../models/text_encoders/gemma4-12b-with-proj-ltx-2.5-Q8_0.gguf" + vae_path = "../models/vae/ltx-2.5-video-vae-conv-bf16.safetensors" + audio_vae_path = "../models/vae/ltx-2.5-audio-vae-bf16.safetensors" + hires_model_path = "../models/latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors" + + output_path = "hires_t2v.avi" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 640 + height = 352 + frames = 121 + fps = 16 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "ltx2" + audio_scale = 1 + + hires_steps = 6 + hires_scheduler_steps = 8 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + model = load_dit(model_path, family = "ltxav", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ltxav", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "ltxav", params_backend = "cpu") + + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "ltxav", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, audio_length = audio_shape[1], fps = fps) + neg = predictor(model, negative, audio_length = audio_shape[1], fps = fps) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + hires_source = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + hires_upscaler = load_latent_upscaler(hires_model_path, family = "ltxav", params_backend = "cpu") + hires_upscaled = upscale_latent(hires_upscaler, dit_to_vae_latents(vae, hires_source)) + hires_upscaled_shape = tensor::shape(hires_upscaled) + hires_video = vae_to_dit_latents(vae, tensor::reshape(hires_upscaled, [hires_upscaled_shape[0], hires_upscaled_shape[1], hires_upscaled_shape[2], hires_upscaled_shape[3], 1])) + hires_video_shape = tensor::shape(hires_video) + hires_original_audio = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + hires_frames = (hires_video_shape[2] - 1) * 8 + 1 + hires_audio_shape = audio_latent_shape(audio_vae, frames = hires_frames, fps = fps) + hires_audio_retained = math::min(audio_shape[1], hires_audio_shape[1]) + hires_audio = tensor::pad(hires_original_audio[:, :hires_audio_retained], [0, 0, 0, hires_audio_shape[1] - hires_audio_retained]) + hires_base = pack_av(hires_video, hires_audio, audio_scale = audio_scale) + hires_pos = predictor(model, positive, audio_length = hires_audio_shape[1], fps = fps) + hires_neg = predictor(model, negative, audio_length = hires_audio_shape[1], fps = fps) + hires_guided = cfg(hires_pos, hires_neg, scale = cfg_scale) + hires_schedule = make_sigmas(hires_guided, latent = hires_base, steps = hires_scheduler_steps, scheduler = scheduler) + hires_sigmas = hires_schedule[-(hires_steps + 1):] + hires_start = add_noise(hires_guided, hires_base, tensor::randn_like(hires_base, rng = rng), sigma = hires_sigmas[0]) + hires_latent = sample(hires_start, hires_sigmas, predict = hires_guided, method = method, rng = rng) + video_latent = hires_latent[:, :, :hires_video_shape[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(hires_latent, channels = tensor::shape(video_base)[3], audio_shape = hires_audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = hires_latent, audio = audio} +} diff --git a/docs/dgl/mage_flow/mage-flow-edit.dgl b/docs/dgl/mage_flow/mage-flow-edit.dgl new file mode 100644 index 0000000000..4b36682a63 --- /dev/null +++ b/docs/dgl/mage_flow/mage-flow-edit.dgl @@ -0,0 +1,52 @@ +# version: 0.0.0 +# docs/models/mage_flow.md — Image editing + +var { + model_path = "../models/diffusion_models/Mage-Flow-Edit.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vision_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-mmproj-BF16.gguf" + vae_path = "../models/vae/mage_vae.safetensors" + + reference_0_path = "../inputs/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'mage.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + + steps = 20 + cfg_scale = 4.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "mage_flow", params_backend = "cpu") + text = load_text_encoder(text_path, family = "mage_flow", params_backend = "cpu", vision_path = vision_path) + vae = load_vae(vae_path, family = "mage_flow", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = tensor::interpolate(reference_0_original, size = [width, height], mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + positive = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_original]) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = [reference_0_original]) + pos = predictor(model, positive, ref_latents = [reference_latent_0], ref_index_mode = "increase") + neg = predictor(model, negative, ref_latents = [reference_latent_0], ref_index_mode = "increase") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/mage_flow/mage-flow-turbo-txt2img.dgl b/docs/dgl/mage_flow/mage-flow-turbo-txt2img.dgl new file mode 100644 index 0000000000..d9bcdc5996 --- /dev/null +++ b/docs/dgl/mage_flow/mage-flow-turbo-txt2img.dgl @@ -0,0 +1,38 @@ +# version: 0.0.0 +# docs/models/mage_flow.md — Text-to-image + +var { + model_path = "../models/diffusion_models/Mage-Flow-Turbo.safetensors" + text_path = "../models/text_encoders/Qwen3-VL-4B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/mage_vae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'mage.cpp'" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 4 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "mage_flow", params_backend = "cpu") + text = load_text_encoder(text_path, family = "mage_flow", params_backend = "cpu") + vae = load_vae(vae_path, family = "mage_flow", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/ming_image/ming-image-0-1-design-txt2img.dgl b/docs/dgl/ming_image/ming-image-0-1-design-txt2img.dgl new file mode 100644 index 0000000000..44814ecd3c --- /dev/null +++ b/docs/dgl/ming_image/ming-image-0-1-design-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/ming_image.md — Text-to-image + +var { + model_path = "../models/diffusion_models/ming_image_0.1_design_bf16.safetensors" + text_path = "../models/text_encoders/ming_image_0.1_ling_mini_2.0_bf16.safetensors" + tokenizer_path = "../models/tokenizers/tokenizer.json" + vae_path = "../models/vae/ming_image_vae_bf16.safetensors" + + output_path = "ming_image.png" + + prompt = "A cheerful orange cat sticker, transparent background" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 12 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "ming_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ming_image", params_backend = "cpu", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "ming_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/minimax_h3/minimax-h3-av-continuation.dgl b/docs/dgl/minimax_h3/minimax-h3-av-continuation.dgl new file mode 100644 index 0000000000..e97b263af5 --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-av-continuation.dgl @@ -0,0 +1,144 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — Generate and join two audio/video segments with a +# shared latent overlap. + +var { + model_path = "../models/diffusion_models/minimax_h3_fl2va-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + vae_backend = "default" + + output_a_path = "continuation-part-a.avi" + output_b_path = "continuation-part-b.avi" + output_path = "continuation-joined.avi" + latent_a_path = "continuation-part-a.npy" + + prompt_a = "A cute American Shorthair silver tabby kitten surfs on a tropical ocean wave, cinematic tracking shot, bright sunlight. Upbeat tropical surf-rock background music with cheerful drums and guitar." + prompt_b = "The same kitten rides the wave toward the beach at sunset, spray in golden light, smooth motion. The surf-rock music continues seamlessly." + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 + + # Maximum overlap in decoded frames. Zero generates two independent clips. + overlap_frames = 22 +} + +fn aligned_overlap(frame_count, requested) { + # Five video latents decode to 17 frames, with a final two-latent block + # producing five frames. A tail of 5 + 17k frames starts on a block boundary. + limit = math::min(requested, math::floor(frame_count / 2)) + aligned = 5 + 17 * math::floor((limit - 5) / 17) + return aligned - math::min(aligned, 0) +} + +# Audio is already scaled in the diffusion latent. The same packing also +# preserves the per-stream mask positions, with ones in unused padding. +fn pack_av(video, audio, pad_value) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(audio, [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count], value = pad_value) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::reshape(flat[:math::product(audio_shape)], audio_shape) +} + +fn continuation_input(latent, video_shape, audio_shape, video_overlap, audio_overlap) { + video_start = video_shape[2] - video_overlap + audio_start = audio_shape[0] - audio_overlap + video_tail = latent[:, :, video_start:, :video_shape[3]] + audio = unpack_audio(latent, video_shape[3], audio_shape) + audio_tail = audio[audio_start:, :, :, :] + + video_pad = [0, 0, 0, 0, 0, video_start] + audio_pad = [0, audio_start] + video_base = tensor::pad(video_tail, video_pad) + audio_base = tensor::pad(audio_tail, audio_pad) + video_mask = tensor::pad(tensor::zeros_like(video_tail), video_pad, value = 1) + audio_mask = tensor::pad(tensor::zeros_like(audio_tail), audio_pad, value = 1) + return {base = pack_av(video_base, audio_base, 0), mask = pack_av(video_mask, audio_mask, 1)} +} + +fn segment_media(decoded_frames, sound, fps, trim_frames) { + frames_kept = tensor::shape(decoded_frames)[3] - trim_frames + sample_start = math::floor(trim_frames * sound.sample_rate / fps) + sample_count = math::floor(frames_kept * sound.sample_rate / fps) + return { + video = {frames = decoded_frames[:, :, :, trim_frames:], fps_num = fps, fps_den = 1}, + audio = {samples = sound.samples[:, sample_start:sample_start + sample_count], sample_rate = sound.sample_rate} + } +} + +fn save_segment(path, vae, audio_vae, latent, channels, audio_shape, audio_scale, fps, trim_frames) { + video_latent = dit_to_vae_latents(vae, latent[:, :, :, :channels]) + decoded_frames = vae_decode(vae, video_latent, tiling = tiling(tile_size_w = 256, tile_size_h = 256)) + audio_latent = tensor::div(unpack_audio(latent, channels, audio_shape), audio_scale) + sound = audio_vae_decode(audio_vae, audio_latent) + media = segment_media(decoded_frames, sound, fps, trim_frames) + video::save(path, media.video, audio = media.audio) + return media +} + +fn main() { + model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", backend = vae_backend, params_backend = "cpu") + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", backend = vae_backend, params_backend = "cpu") + + fps = 24 + requested_frames = 5 + (frames - math::min(frames, 5)) + video_shape = latent_shape(vae, width = width, height = height, frames = requested_frames) + video_length = video_shape[2] + frame_count = 4 * video_length - 3 * math::ceil_div(video_length, 5) + # Round up at 40 audio latents per second so the decoded track can be cut + # to the exact video duration even when it ends between audio latents. + audio_length = math::ceil_div(frame_count * 40, fps) + audio_shape = [audio_length, 2, 32, 1] + trim_frames = aligned_overlap(frame_count, overlap_frames) + video_overlap = math::ceil_div(trim_frames * 5, 17) + audio_overlap = math::ceil_div(trim_frames * 40, fps) + + condition_a = encode_prompt(text, prompt_a, width = width, height = height) + predict_a = predictor(model, condition_a, audio_length = audio_length) + base_a = pack_av(tensor::zeros(video_shape), tensor::zeros(audio_shape), 0) + sigmas_a = make_sigmas(predict_a, latent = base_a, steps = steps, scheduler = scheduler) + rng_a = make_rng(rng_type, seed = seed) + start_a = add_noise(predict_a, base_a, tensor::randn_like(base_a, rng = rng_a), sigma = sigmas_a[0]) + latent_a = sample(start_a, sigmas_a, predict = predict_a, method = method, rng = rng_a) + tensor::save(latent_a_path, latent_a) + part_a = save_segment(output_a_path, vae, audio_vae, latent_a, video_shape[3], audio_shape, audio_scale, fps, 0) + + continuation = continuation_input(latent_a, video_shape, audio_shape, video_overlap, audio_overlap) + condition_b = encode_prompt(text, prompt_b, width = width, height = height) + predict_b = predictor(model, condition_b, audio_length = audio_length) + sigmas_b = make_sigmas(predict_b, latent = continuation.base, steps = steps, scheduler = scheduler) + rng_b = make_rng(rng_type, seed = seed + 1) + start_b = add_noise(predict_b, continuation.base, tensor::randn_like(continuation.base, rng = rng_b), sigma = sigmas_b[0]) + # H3 uses one noise level across each stream. Anchor the denoised prediction + # so Euler keeps the carried input at the current noise level until sigma zero. + latent_b = sample(start_b, sigmas_b, predict = predict_b, method = method, rng = rng_b, + base = continuation.base, denoise_mask = continuation.mask) + part_b = save_segment(output_b_path, vae, audio_vae, latent_b, video_shape[3], audio_shape, audio_scale, fps, trim_frames) + + joined_frames = video::join_windows([part_a.video.frames, part_b.video.frames]) + joined_samples = tensor::concat([part_a.audio.samples, part_b.audio.samples], axis = 1) + video = {frames = joined_frames, fps_num = fps, fps_den = 1} + audio = {samples = joined_samples, sample_rate = part_a.audio.sample_rate} + video::save(output_path, video, audio = audio) + return {video = video, audio = audio, latent_b = latent_b, join = {overlap_frames = trim_frames}} +} diff --git a/docs/dgl/minimax_h3/minimax-h3-first-last-frame.dgl b/docs/dgl/minimax_h3/minimax-h3-first-last-frame.dgl new file mode 100644 index 0000000000..ab0e844ee6 --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-first-last-frame.dgl @@ -0,0 +1,85 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — First/last-frame conditioning + +var { + model_path = "../models/diffusion_models/minimax_h3_fl2va-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + + first_frame_path = "../inputs/ernie_image/turbo_example.png" + output_path = "output.avi" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + fps = 24 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn h3_reference_noise(latent, seed) { + rng = make_rng("cuda", seed = seed) + return tensor::lerp(latent, tensor::randn_like(latent, rng = rng), 0.001) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + h3_visual_0_raw = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + h3_visual_0 = h3_reference_noise(h3_visual_0_raw, seed) + + condition = encode_prompt(text, prompt, width = width, height = height, media = [first_frame_pixels[:, :, 0]]) + predict = predictor(model, condition, audio_length = audio_shape[0], ref_latents = [h3_visual_0], keyframe_indices = [0]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/minimax_h3/minimax-h3-latent-hires.dgl b/docs/dgl/minimax_h3/minimax-h3-latent-hires.dgl new file mode 100644 index 0000000000..f1f3e82ab8 --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-latent-hires.dgl @@ -0,0 +1,81 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — Latent hires second pass (two-stage sampling) + +var { + model_path = "../models/diffusion_models/minimax_h3_fl2va-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + fps = 24 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 + + hires_target_width = 1216 + hires_target_height = 672 + hires_vae_scale = 16 + hires_steps = 4 + hires_scheduler_steps = 9 + hires_mode = "bicubic" +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + model = load_dit(model_path, family = "minimax_h3", flash_attn_mode = "on", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, audio_length = audio_shape[0]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + hires_source = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + hires_video = tensor::interpolate(hires_source, size = [math::floor(hires_target_width / hires_vae_scale), math::floor(hires_target_height / hires_vae_scale)], mode = hires_mode) + hires_video_shape = tensor::shape(hires_video) + hires_original_audio = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + hires_base = pack_av(hires_video, hires_original_audio, audio_scale = audio_scale) + hires_schedule = make_sigmas(predict, latent = hires_base, steps = hires_scheduler_steps, scheduler = scheduler) + hires_sigmas = hires_schedule[-(hires_steps + 1):] + hires_start = add_noise(predict, hires_base, tensor::randn_like(hires_base, rng = rng), sigma = hires_sigmas[0]) + hires_latent = sample(hires_start, hires_sigmas, predict = predict, method = method, rng = rng) + video_latent = hires_latent[:, :, :hires_video_shape[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(hires_latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = hires_latent, audio = audio} +} diff --git a/docs/dgl/minimax_h3/minimax-h3-learned-hires.dgl b/docs/dgl/minimax_h3/minimax-h3-learned-hires.dgl new file mode 100644 index 0000000000..82af9cbf22 --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-learned-hires.dgl @@ -0,0 +1,84 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — Latent hires second pass (two-stage sampling) + +var { + model_path = "../models/diffusion_models/minimax_h3_fl2va-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + hires_model_path = "../models/latent_upscale_models/h3-latent-upscaler-3d.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + fps = 24 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 + + hires_target_width = 1216 + hires_target_height = 672 + hires_vae_scale = 16 + hires_steps = 4 + hires_scheduler_steps = 9 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, audio_length = audio_shape[0]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + hires_source = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + hires_upscaler = load_latent_upscaler(hires_model_path, family = "minimax_h3", params_backend = "cpu") + hires_upscaled = upscale_latent(hires_upscaler, hires_source, width = math::floor(hires_target_width / hires_vae_scale), height = math::floor(hires_target_height / hires_vae_scale)) + hires_upscaled_shape = tensor::shape(hires_upscaled) + hires_video = tensor::reshape(hires_upscaled, [hires_upscaled_shape[0], hires_upscaled_shape[1], hires_upscaled_shape[2], hires_upscaled_shape[3], 1]) + hires_video_shape = tensor::shape(hires_video) + hires_original_audio = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + hires_base = pack_av(hires_video, hires_original_audio, audio_scale = audio_scale) + hires_schedule = make_sigmas(predict, latent = hires_base, steps = hires_scheduler_steps, scheduler = scheduler) + hires_sigmas = hires_schedule[-(hires_steps + 1):] + hires_start = add_noise(predict, hires_base, tensor::randn_like(hires_base, rng = rng), sigma = hires_sigmas[0]) + hires_latent = sample(hires_start, hires_sigmas, predict = predict, method = method, rng = rng) + video_latent = hires_latent[:, :, :hires_video_shape[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(hires_latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = hires_latent, audio = audio} +} diff --git a/docs/dgl/minimax_h3/minimax-h3-reference-to-av.dgl b/docs/dgl/minimax_h3/minimax-h3-reference-to-av.dgl new file mode 100644 index 0000000000..9601aad963 --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-reference-to-av.dgl @@ -0,0 +1,94 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — Reference-to-audio-video conditioning + +var { + model_path = "../models/diffusion_models/minimax_h3_ref2va_pruned-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + + h3_image_0_path = "../inputs/ernie_image/turbo_example.png" + output_path = "output.avi" + + prompt = "Use the cat from as the main character. Keep the cat鈥檚 appearance, fur color, facial features, and identity consistent with the reference image. Create a 2-second cinematic video: start with an extreme close-up shot of the cat鈥檚 face, focusing on its cute expression and detailed fur texture. The camera slowly rotates around the cat鈥檚 head, creating a dynamic reveal. Then smoothly pull back and zoom out to reveal the full scene: the cat is standing confidently on a surfboard, riding ocean waves. Water splashes around the board, sea breeze gently moves the cat鈥檚 fur, and the cat maintains a cute and fearless expression while surfing. Smooth camera movement, cinematic orbit shot, seamless zoom-out transition, low-angle wide shot, realistic ocean environment, golden sunlight, dynamic waves, high-quality realistic style, natural motion, no distortion, keep the cat鈥檚 identity unchanged." + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + fps = 24 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn h3_reference_noise(latent, seed) { + rng = make_rng("cuda", seed = seed) + return tensor::lerp(latent, tensor::randn_like(latent, rng = rng), 0.001) +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + h3_image_0 = image::load(h3_image_0_path) + + model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + h3_image_0_original = image::to_f32(h3_image_0, channels = 3) + h3_image_0_area = math::min(width * height, tensor::shape(h3_image_0_original)[0] * tensor::shape(h3_image_0_original)[1]) + h3_image_0_pixels = fit_reference_area(h3_image_0_original, h3_image_0_area, 32, mode = "bilinear") + h3_visual_0_raw = vae_to_dit_latents(vae, vae_encode(vae, h3_image_0_pixels, rng = rng)) + h3_visual_0 = h3_reference_noise(h3_visual_0_raw, seed) + + condition = encode_prompt(text, prompt, width = width, height = height, media = [{image = h3_image_0_pixels}]) + predict = predictor(model, condition, audio_length = audio_shape[0], ref_latents = [h3_visual_0], reference_blocks = [{kind = "image", video = 0}]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/minimax_h3/minimax-h3-text-to-av.dgl b/docs/dgl/minimax_h3/minimax-h3-text-to-av.dgl new file mode 100644 index 0000000000..57f6942ebb --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-text-to-av.dgl @@ -0,0 +1,65 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — Text-to-audio-video + +var { + model_path = "../models/diffusion_models/minimax_h3_fl2va-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + + output_path = "output.avi" + + prompt = "A cute American Shorthair silver tabby kitten surfs on a tropical ocean wave, riding a white surfboard with the clear text 'sd.cpp' on it. Cinematic tracking shot, realistic water, bright sunlight, smooth motion, and consistent character appearance. Add upbeat tropical surf-rock background music with cheerful drums and guitar, synchronized with the kitten鈥檚 energetic surfing." + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + fps = 24 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn main() { + model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, audio_length = audio_shape[0]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/minimax_h3/pi-h3-text-to-av.dgl b/docs/dgl/minimax_h3/pi-h3-text-to-av.dgl new file mode 100644 index 0000000000..02265dd9be --- /dev/null +++ b/docs/dgl/minimax_h3/pi-h3-text-to-av.dgl @@ -0,0 +1,57 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — pi-H3 four-step generation + +var { + model_path = "../models/diffusion_models/minimax_h3_fl2va_pruned-Q4_K_M.gguf" + adapter_path = "../models/loras/minimax/pi_h3_4step_adapter.safetensors" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + + output_path = "pi-h3-output.avi" + + prompt = "A red fox trots through a snowy pine forest. Snow crunches underfoot and birds chirp in the distance." + seed = 42 + width = 864 + height = 480 + frames = 56 + fps = 24 +} + +fn main() { + base_model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu", weights_override = adapter_path) + model = apply_lora(base_model, load_lora(adapter_path), weight = 1.0) + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + + video_shape = latent_shape(vae, width = width, height = height, frames = frames) + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) + audio_count = math::product(audio_shape) + plane_size = video_shape[0] * video_shape[1] * video_shape[2] + tail_channels = math::ceil_div(audio_count, plane_size) + tail_shape = [video_shape[0], video_shape[1], video_shape[2], tail_channels, 1] + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, audio_length = audio_shape[0], video_sigma_shift = 12, audio_sigma_shift = 3) + # Raw sigmas run from 0.96 to 0.96 * 0.6 / (3 + 0.6) before the H3 video shift. + raw = tensor::vector([0.96, 0.6933333333, 0.4266666667, 0.16, 0.0], dtype = "f32") + sigmas = tensor::div(tensor::mul(raw, 12), tensor::affine(raw, scale = 11, offset = 1)) + rng = make_rng("cpu", seed = seed) + video_noise = tensor::randn_like(tensor::zeros(video_shape), rng = rng) + audio_noise = tensor::randn_like(tensor::zeros([audio_count]), rng = rng) + # The sampler carries audio latents scaled by video sigma / audio sigma. + audio_carrier = tensor::mul(audio_noise, 4 - 3 * sigmas[0]) + audio_tail = tensor::pad(audio_carrier, [0, plane_size * tail_channels - audio_count]) + start = tensor::concat([video_noise, tensor::reshape(audio_tail, tail_shape)], axis = 3) + latent = sample(start, sigmas, predict = predict, method = "euler", rng = rng) + + video_latent = latent[:, :, :video_shape[2], :video_shape[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + tail = latent[:, :, :, video_shape[3]:] + sound = tensor::reshape(tail, [tensor::numel(tail)]) + sound_latent = tensor::div(tensor::reshape(sound[:audio_count], audio_shape), 4) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio, trim_audio = true) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/minimax_h3_image/minimax-h3-image-edit.dgl b/docs/dgl/minimax_h3_image/minimax-h3-image-edit.dgl new file mode 100644 index 0000000000..88b17faed9 --- /dev/null +++ b/docs/dgl/minimax_h3_image/minimax-h3-image-edit.dgl @@ -0,0 +1,73 @@ +# version: 0.0.0 +# docs/models/minimax_h3_image.md — Reference-image editing + +var { + model_path = "../models/diffusion_models/minimax_h3_image_pruned_bf16.safetensors" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_image_vae_fp16.safetensors" + + reference_0_path = "../inputs/ernie_image/turbo_example.png" + output_path = "output.png" + + prompt = "Edit . Put a red scarf on the cat, preserving its face and the background." + + seed = 42 + rng_type = "cpu" + width = 1024 + height = 1024 + + method = "euler" + custom_sigmas = [1.0, 0.9675236940383911, 0.8875485062599182, 0.75, 0.5327739119529724, 0.23200887441635132, 0.0] +} + +fn h3_image_reference_noise(latent, seed) { + shape = tensor::shape(latent) + patches = tensor::zeros([2, 2, shape[-2], math::floor(shape[0] / 2), math::floor(shape[1] / 2)]) + rng = make_rng("cpu", seed = seed) + noise = tensor::reshape(tensor::permute(tensor::randn_like(patches, rng = rng), [0, 3, 1, 4, 2]), shape) + return tensor::lerp(latent, noise, 0.001) +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + + model = load_dit(model_path, family = "minimax_h3_image", flash_attn_mode = "on", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3_image", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) + base = tensor::unsqueeze(image_base, axis = 2) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_short = math::min(tensor::shape(reference_0_original)[0], tensor::shape(reference_0_original)[1]) + reference_0_side = math::min(2048, -math::min(-1024, -reference_0_short)) + reference_0_pixels = fit_reference_area(reference_0_original, tensor::shape(reference_0_original)[0] * tensor::shape(reference_0_original)[1] * reference_0_side * reference_0_side / (reference_0_short * reference_0_short), 32, mode = "lanczos") + reference_latent_0_raw = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng, tiling = tiling())) + reference_latent_0 = h3_image_reference_noise(reference_latent_0_raw, seed) + + condition = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_original]) + predict = predictor(model, condition, video_sigma_shift = 1, reference_blocks = [{kind = "image", video = 0}], ref_latents = [reference_latent_0], ref_index_mode = "increase") + sigmas = tensor::vector(custom_sigmas, dtype = "f32") + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent), tiling = tiling()) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/minimax_h3_image/minimax-h3-image-txt2img.dgl b/docs/dgl/minimax_h3_image/minimax-h3-image-txt2img.dgl new file mode 100644 index 0000000000..3e338d81db --- /dev/null +++ b/docs/dgl/minimax_h3_image/minimax-h3-image-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/minimax_h3_image.md — Text-to-image + +var { + model_path = "../models/diffusion_models/minimax_h3_image_pruned_bf16.safetensors" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_image_vae_fp16.safetensors" + + output_path = "output.png" + + prompt = "A silver tabby kitten holding a sign reading 'sd.cpp', natural daylight" + + seed = 42 + rng_type = "cpu" + width = 1024 + height = 1024 + + method = "euler" + custom_sigmas = [1.0, 0.9675236940383911, 0.8875485062599182, 0.75, 0.5327739119529724, 0.23200887441635132, 0.0] +} + +fn main() { + model = load_dit(model_path, family = "minimax_h3_image", flash_attn_mode = "on", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3_image", params_backend = "cpu") + + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) + base = tensor::unsqueeze(image_base, axis = 2) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, video_sigma_shift = 1) + sigmas = tensor::vector(custom_sigmas, dtype = "f32") + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent), tiling = tiling()) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/minit2i/minit2i-cuda-txt2img.dgl b/docs/dgl/minit2i/minit2i-cuda-txt2img.dgl new file mode 100644 index 0000000000..a218b85e36 --- /dev/null +++ b/docs/dgl/minit2i/minit2i-cuda-txt2img.dgl @@ -0,0 +1,41 @@ +# version: 0.0.0 +# docs/models/minit2i.md — CUDA + +var { + model_path = "../models/diffusion_models/minit2i/diffusion_pytorch_model.safetensors" + text_path = "../models/text_encoders/flan-t5-large/model.safetensors" + + output_path = "minit2i_cuda.png" + + prompt = "a cat" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 100 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "minit2i") + text = load_text_encoder(text_path, family = "minit2i", t5_path = text_path) + base = tensor::zeros([width, height, 3, 1]) + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = zero_out(positive, fields = ["vector"]) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + pixels = tensor::clamp(tensor::affine(latent, scale = 0.5, offset = 0.5), 0, 1) + image = image::to_u8(pixels) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/minit2i/minit2i-metal-txt2img.dgl b/docs/dgl/minit2i/minit2i-metal-txt2img.dgl new file mode 100644 index 0000000000..4d6bc26fe0 --- /dev/null +++ b/docs/dgl/minit2i/minit2i-metal-txt2img.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# CLI/context: --threads 8 +# docs/models/minit2i.md — macOS with Metal + +var { + model_path = "../models/diffusion_models/minit2i/diffusion_pytorch_model.safetensors" + text_path = "../models/text_encoders/flan-t5-large/model.safetensors" + + output_path = "minit2i_metal.png" + + prompt = "a cat" + + seed = 42 + rng_type = "cpu" + width = 512 + height = 512 + + steps = 100 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, backend = "metal", family = "minit2i") + text = load_text_encoder(text_path, backend = "metal", family = "minit2i", t5_path = text_path) + base = tensor::zeros([width, height, 3, 1]) + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = zero_out(positive, fields = ["vector"]) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + pixels = tensor::clamp(tensor::affine(latent, scale = 0.5, offset = 0.5), 0, 1) + image = image::to_u8(pixels) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/moss_image/moss-image-base-txt2img.dgl b/docs/dgl/moss_image/moss-image-base-txt2img.dgl new file mode 100644 index 0000000000..9da3a8c036 --- /dev/null +++ b/docs/dgl/moss_image/moss-image-base-txt2img.dgl @@ -0,0 +1,44 @@ +# version: 0.0.0 +# docs/models/moss_image.md — MOSS-Image Base + +var { + model_path = "../models/diffusion_models/moss_image_base_int8_convrot_attn.safetensors" + text_path = "../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf" + tokenizer_path = "../models/tokenizers/tokenizer_qwen3.5.json" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'moss-image.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "moss_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "moss_image", params_backend = "cpu", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "moss_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative, skip_layers = [22]) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/moss_image/moss-image-edit-chinoll.dgl b/docs/dgl/moss_image/moss-image-edit-chinoll.dgl new file mode 100644 index 0000000000..d03021fe84 --- /dev/null +++ b/docs/dgl/moss_image/moss-image-edit-chinoll.dgl @@ -0,0 +1,63 @@ +# version: 0.0.0 +# docs/models/moss_image.md — chinoll/Moss-Image-Edit + +var { + model_path = "../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors" + text_path = "../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf" + tokenizer_path = "../models/tokenizers/tokenizer_qwen3.5.json" + vae_path = "../models/vae/flux2_ae.safetensors" + lora_path = "../models/loras/moss/moss-edit-lora.safetensors" + lora_weight = 1.0 + + reference_paths = ["../assets/flux/flux1-dev-q8_0.png"] + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'moss.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "discrete" +} + +fn encode_reference(path, vae, rng) { + image = image::to_f32(image::load(path), channels = 3) + shape = tensor::shape(image) + long_edge = shape[0] + shape[1] - math::min(shape[0], shape[1]) + scale = math::min(1024, long_edge) / long_edge + rounded = [math::round(shape[0] * scale / 16) * 16, math::round(shape[1] * scale / 16) * 16] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], 16, dtype = "i64")) + pixels = tensor::interpolate(image, size = size, mode = "bilinear") + return vae_to_dit_latents(vae, vae_encode(vae, pixels, rng = rng)) +} + +fn main() { + base_model = load_dit(model_path, family = "moss_image") + model = apply_lora(base_model, load_lora(lora_path), weight = lora_weight, mode = "auto") + text = load_text_encoder(text_path, family = "moss_image", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "moss_image") + + encode_rng = make_rng(rng_type, seed = seed) + references = map(reference_paths, process = encode_reference, vae = vae, rng = encode_rng) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) + neg = predictor(model, negative, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "text_start", force_ref_timestep_zero = true) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/moss_image/moss-image-edit.dgl b/docs/dgl/moss_image/moss-image-edit.dgl new file mode 100644 index 0000000000..2417f494c2 --- /dev/null +++ b/docs/dgl/moss_image/moss-image-edit.dgl @@ -0,0 +1,69 @@ +# version: 0.0.0 +# docs/models/moss_image.md — MOSS-Image-Edit-HQ + +var { + model_path = "../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors" + text_path = "../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf" + vision_path = "../models/text_encoders/Qwen3.5-9B-mmproj-BF16.gguf" + tokenizer_path = "../models/tokenizers/tokenizer_qwen3.5.json" + vae_path = "../models/vae/flux2_ae.safetensors" + lora_path = "../models/loras/moss/armV5-moss-edit-lora.safetensors" + lora_weight = 1.0 + + reference_paths = ["../assets/flux/flux1-dev-q8_0.png"] + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'moss.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "discrete" +} + +fn load_reference(path) { + return image::to_f32(image::load(path), channels = 3) +} + +fn encode_reference(image, vae, rng) { + shape = tensor::shape(image) + long_edge = shape[0] + shape[1] - math::min(shape[0], shape[1]) + scale = math::min(1024, long_edge) / long_edge + rounded = [math::round(shape[0] * scale / 16) * 16, math::round(shape[1] * scale / 16) * 16] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], 16, dtype = "i64")) + pixels = tensor::interpolate(image, size = size, mode = "bilinear") + return vae_to_dit_latents(vae, vae_encode(vae, pixels, rng = rng)) +} + +fn main() { + base_model = load_dit(model_path, family = "moss_image") + model = apply_lora(base_model, load_lora(lora_path), weight = lora_weight, mode = "auto") + text = load_text_encoder(text_path, family = "moss_image", + tokenizer = tokenizer_path, vision_path = vision_path) + vae = load_vae(vae_path, family = "moss_image") + + encode_rng = make_rng(rng_type, seed = seed) + images = map(reference_paths, process = load_reference) + references = map(images, process = encode_reference, vae = vae, rng = encode_rng) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height, media = images) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = images) + pos = predictor(model, positive, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true) + neg = predictor(model, negative, ref_latents = references, + ref_index_mode = "increase", ref_rope_anchor = "image_start", force_ref_timestep_zero = true, skip_layers = [22]) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/moss_image/moss-image-sft-inline-images.dgl b/docs/dgl/moss_image/moss-image-sft-inline-images.dgl new file mode 100644 index 0000000000..40dbe5deea --- /dev/null +++ b/docs/dgl/moss_image/moss-image-sft-inline-images.dgl @@ -0,0 +1,45 @@ +# version: 0.0.0 + +var { + weights = "MOSS-Image-SFT-Q8_0.gguf" + encoder_path = "Qwen3.5-9B-Q4_K_M.gguf" + vision_path = "Qwen3.5-9B-mmproj-BF16.gguf" + tokenizer_path = "tokenizer_qwen3.5.json" + vae_path = "flux2_ae.safetensors" + + image_path = "subject.png" + output_path = "moss-image-prompt.png" + + prompt = "Draw the subject from in watercolor." + negative_prompt = "" + + seed = 42 + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 3 +} + +fn main() { + dit = load_dit(weights) + encoder = load_text_encoder(encoder_path, family_from = weights, + tokenizer = tokenizer_path, vision_path = vision_path) + vae = load_vae(vae_path, family_from = weights) + subject = image::load(image_path) + positive = encode_prompt(encoder, prompt, + image_bindings = {subject = subject}, width = width, height = height) + negative = encode_prompt(encoder, negative_prompt, width = width, height = height) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + rng = make_rng("cuda", seed = seed) + noise = tensor::randn_like(base, rng = rng) + positive_predictor = predictor(dit, positive) + negative_predictor = predictor(dit, negative, skip_layers = [22]) + guided = cfg(positive_predictor, negative_predictor, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps) + start = add_noise(guided, base, noise, sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, rng = rng) + output = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, output) + return output +} diff --git a/docs/dgl/moss_image/moss-image-sft-txt2img.dgl b/docs/dgl/moss_image/moss-image-sft-txt2img.dgl new file mode 100644 index 0000000000..6ef4d7a30a --- /dev/null +++ b/docs/dgl/moss_image/moss-image-sft-txt2img.dgl @@ -0,0 +1,44 @@ +# version: 0.0.0 +# docs/models/moss_image.md — MOSS-Image SFT + +var { + model_path = "../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors" + text_path = "../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf" + tokenizer_path = "../models/tokenizers/tokenizer_qwen3.5.json" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'moss-image.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 3.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "moss_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "moss_image", params_backend = "cpu", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "moss_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative, skip_layers = [22]) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/ovis_image/ovis-image-txt2img.dgl b/docs/dgl/ovis_image/ovis-image-txt2img.dgl new file mode 100644 index 0000000000..9b844a5dd5 --- /dev/null +++ b/docs/dgl/ovis_image/ovis-image-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/ovis_image.md — CLI + +var { + model_path = "../models/diffusion_models/ovis_image-Q4_0.gguf" + text_path = "../models/text_encoders/ovis_2.5.safetensors" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 5.0 + method = "euler" + scheduler = "flux" +} + +fn main() { + model = load_dit(model_path, family = "ovis_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "ovis_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "ovis_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/p_h3_image/p-h3-image-edit.dgl b/docs/dgl/p_h3_image/p-h3-image-edit.dgl new file mode 100644 index 0000000000..fdcc65bcdb --- /dev/null +++ b/docs/dgl/p_h3_image/p-h3-image-edit.dgl @@ -0,0 +1,71 @@ +# version: 0.0.0 +# docs/models/p_h3_image.md — Image editing + +var { + model_path = "../models/diffusion_models/p-h3-image_int8_convrot.safetensors" + text_path = "../models/text_encoders/qwen3vl_4b_bf16.safetensors" + connectors_path = "../models/text_encoders/p-h3-image_text_connector.safetensors" + vae_path = "../models/vae/p-h3-image_vae_bf16.safetensors" + + reference_0_path = "source.png" + reference_1_path = "reference.png" + output_path = "output.png" + + prompt = "Edit . Give the cat the scarf from , preserving its face and the background." + + seed = 42 + rng_type = "cpu" + width = 2912 + height = 2912 + + method = "euler" + custom_sigmas = [1.0, 0.9847530126571655, 0.9679049849510193, 0.9516879916191101, 0.9253720045089722, 0.8819230198860168, 0.8100829720497131, 0.5287179946899414, 0.0] +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + reference_1 = image::load(reference_1_path) + + model = load_dit(model_path, family = "p_h3_image", params_backend = "cpu") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "p_h3_image", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "p_h3_image", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) + image_shape = tensor::shape(image_base) + image_video = tensor::unsqueeze(image_base, axis = 2) + audio_channels = math::ceil_div(128, image_shape[0] * image_shape[1]) + base = tensor::concat([image_video, tensor::zeros([image_shape[0], image_shape[1], 1, audio_channels, 1])], axis = 3) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(width * height, tensor::shape(reference_0_original)[0] * tensor::shape(reference_0_original)[1]), 32, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + reference_1_original = image::to_f32(reference_1, channels = 3) + reference_1_pixels = fit_reference_area(reference_1_original, math::min(width * height, tensor::shape(reference_1_original)[0] * tensor::shape(reference_1_original)[1]), 32, mode = "bilinear") + reference_latent_1 = vae_to_dit_latents(vae, vae_encode(vae, reference_1_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_original, reference_1_original]) + predict = predictor(model, condition, video_sigma_shift = 1, audio_length = 2, audio_sigma_shift = 1, reference_blocks = [{kind = "image", video = 0}, {kind = "image", video = 1}], ref_latents = [reference_latent_0, reference_latent_1], ref_index_mode = "increase") + sigmas = tensor::vector(custom_sigmas, dtype = "f32") + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, :, :24])) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/p_h3_image/p-h3-image-txt2img.dgl b/docs/dgl/p_h3_image/p-h3-image-txt2img.dgl new file mode 100644 index 0000000000..e8090c398e --- /dev/null +++ b/docs/dgl/p_h3_image/p-h3-image-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/p_h3_image.md — Text-to-image + +var { + model_path = "../models/diffusion_models/p-h3-image_int8_convrot.safetensors" + text_path = "../models/text_encoders/qwen3vl_4b_bf16.safetensors" + connectors_path = "../models/text_encoders/p-h3-image_text_connector.safetensors" + vae_path = "../models/vae/p-h3-image_vae_bf16.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat holding a sign says 'p-h3-image.cpp'" + + seed = 42 + rng_type = "cpu" + width = 2912 + height = 2912 + + method = "euler" + custom_sigmas = [1.0, 0.9847530126571655, 0.9679049849510193, 0.9516879916191101, 0.9253720045089722, 0.8819230198860168, 0.8100829720497131, 0.5287179946899414, 0.0] +} + +fn main() { + model = load_dit(model_path, family = "p_h3_image", params_backend = "cpu") + text = load_text_encoder(text_path, connectors_path = connectors_path, family = "p_h3_image", params_backend = "cpu", projection_path = model_path) + vae = load_vae(vae_path, family = "p_h3_image", params_backend = "cpu") + + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) + image_shape = tensor::shape(image_base) + image_video = tensor::unsqueeze(image_base, axis = 2) + audio_channels = math::ceil_div(128, image_shape[0] * image_shape[1]) + base = tensor::concat([image_video, tensor::zeros([image_shape[0], image_shape[1], 1, audio_channels, 1])], axis = 3) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, video_sigma_shift = 1, audio_length = 2, audio_sigma_shift = 1) + sigmas = tensor::vector(custom_sigmas, dtype = "f32") + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, :, :24])) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/photo_maker/photomaker-v1-sdxl.dgl b/docs/dgl/photo_maker/photomaker-v1-sdxl.dgl new file mode 100644 index 0000000000..88336dc53c --- /dev/null +++ b/docs/dgl/photo_maker/photomaker-v1-sdxl.dgl @@ -0,0 +1,49 @@ +# version: 0.0.0 +# docs/models/photo_maker.md — PhotoMaker Version 1 + +var { + weights = "../models/checkpoints/sdxlUnstableDiffusers_v11.safetensors" + model_path = "../models/photomaker/photomaker-v1.safetensors" + vae_path = "../models/vae/sdxl_vae.safetensors" + + image_dir = "../inputs/photomaker_examples/scarletthead_woman" + output_path = "output.png" + + prompt = "a girl img, retro futurism, retro game art style but extremely beautiful, intricate details, masterpiece, best quality, space-themed, cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed" + negative_prompt = "realistic, photo-realistic, worst quality, greyscale, bad anatomy, bad hands, error, text" + + seed = 42 + width = 1024 + height = 1024 + + steps = 50 + cfg_scale = 5.0 + method = "euler" + scheduler = "discrete" + style_strength = 10.0 +} + +fn main() { + base_unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(vae_path, conv_scale = 0.03125, backend = "cpu") + photomaker = photomaker::load(model_path, family = "sdxl") + photomaker_lora = load_lora(model_path) + unet = apply_lora(base_unet, photomaker_lora) + tokens = photomaker::encode_images(photomaker, image::load_dir(image_dir)) + conditions = photomaker::encode_prompt(text, prompt, tokens, width = width, height = height) + identity = photomaker::apply(conditions.condition, photomaker, tokens, conditions.mask) + plain_predictor = predictor(unet, conditions.plain) + identity_predictor = predictor(unet, identity) + pos = switch_predictor(plain_predictor, identity_predictor, after_steps = math::floor(steps * style_strength / 100)) + neg = predictor(unet, encode_prompt(text, negative_prompt, width = width, height = height)) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng("cuda", seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent, identity = identity } +} diff --git a/docs/dgl/photo_maker/photomaker-v2-sdxl.dgl b/docs/dgl/photo_maker/photomaker-v2-sdxl.dgl new file mode 100644 index 0000000000..73a45991d2 --- /dev/null +++ b/docs/dgl/photo_maker/photomaker-v2-sdxl.dgl @@ -0,0 +1,52 @@ +# version: 0.0.0 +# docs/models/photo_maker.md — PhotoMaker Version 2 + +var { + weights = "../models/checkpoints/sdxlUnstableDiffusers_v11.safetensors" + model_path = "../models/photomaker/photomaker-v2.safetensors" + vae_path = "../models/vae/sdxl_vae.safetensors" + + image_dir = "../inputs/photomaker_examples/scarletthead_woman" + embedding_path = "../inputs/photomaker_examples/scarletthead_woman/id_embeds.npy" + output_path = "output.png" + + prompt = "a girl img, retro futurism, retro game art style but extremely beautiful, intricate details, masterpiece, best quality, space-themed, cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed" + negative_prompt = "realistic, photo-realistic, worst quality, greyscale, bad anatomy, bad hands, error, text" + + seed = 42 + width = 1024 + height = 1024 + + steps = 50 + cfg_scale = 5.0 + method = "euler" + scheduler = "discrete" + style_strength = 10.0 +} + +fn main() { + base_unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(vae_path, conv_scale = 0.03125, backend = "cpu") + photomaker = photomaker::load(model_path, family = "sdxl") + images = image::load_dir(image_dir) + identity = tensor::load(embedding_path) + photomaker_lora = load_lora(model_path) + unet = apply_lora(base_unet, photomaker_lora) + tokens = photomaker::encode_images(photomaker, images, id_embedding = identity) + conditions = photomaker::encode_prompt(text, prompt, tokens, width = width, height = height) + fused = photomaker::apply(conditions.condition, photomaker, tokens, conditions.mask) + plain_predictor = predictor(unet, conditions.plain) + identity_predictor = predictor(unet, fused) + pos = switch_predictor(plain_predictor, identity_predictor, after_steps = math::floor(steps * style_strength / 100)) + neg = predictor(unet, encode_prompt(text, negative_prompt, width = width, height = height)) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng("cuda", seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, output) + return output +} diff --git a/docs/dgl/pid/pid-flux1-512-to-2048-txt2img.dgl b/docs/dgl/pid/pid-flux1-512-to-2048-txt2img.dgl new file mode 100644 index 0000000000..2718743c7d --- /dev/null +++ b/docs/dgl/pid/pid-flux1-512-to-2048-txt2img.dgl @@ -0,0 +1,47 @@ +# version: 0.0.0 +# docs/models/pid.md — CLI + +var { + model_path = "../models/diffusion_models/pid_flux1_512_to_2048_4step_bf16.safetensors" + text_path = "../models/text_encoders/gemma_2_2b_it_elm_bf16.safetensors" + tokenizer_path = "../models/tokenizers/tokenizer_gemma2.json" + vae_path = "../models/vae/ae.sft" + + reference_0_path = "../inputs/ernie_image/turbo_example.png" + output_path = "output.png" + + prompt = "a lovely cat" + + seed = 42 + rng_type = "cpu" + width = 2048 + height = 2048 + + steps = 4 + method = "lcm" + scheduler = "lcm" +} + +fn main() { + reference_0 = image::load(reference_0_path) + + model = load_dit(model_path, family = "pid") + text = load_text_encoder(text_path, family = "pid", tokenizer = tokenizer_path) + vae = load_vae(vae_path, family = "pid", vae_format = "flux") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros([width, height, 3, 1]) + reference_0_pixels = image::to_f32(reference_0, channels = 3) + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition, ref_latents = [reference_latent_0]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + pixels = tensor::clamp(tensor::affine(latent, scale = 0.5, offset = 0.5), 0, 1) + image = image::to_u8(pixels) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/pixart/pixart-sigma-xl2-1024-ms-txt2img.dgl b/docs/dgl/pixart/pixart-sigma-xl2-1024-ms-txt2img.dgl new file mode 100644 index 0000000000..63796d0c82 --- /dev/null +++ b/docs/dgl/pixart/pixart-sigma-xl2-1024-ms-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/pixart.md — CLI + +var { + model_path = "../models/diffusion_models/pixart_sigma_xl2_1024_ms.safetensors" + text_path = "../models/text_encoders/t5xxl.safetensors" + vae_path = "../models/vae/pixart_vae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 4.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "pixart") + text = load_text_encoder(text_path, family = "pixart", t5_path = text_path) + vae = load_vae(vae_path, family = "pixart") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/pulid/pulid-flux1-schnell.dgl b/docs/dgl/pulid/pulid-flux1-schnell.dgl new file mode 100644 index 0000000000..2e9d949566 --- /dev/null +++ b/docs/dgl/pulid/pulid-flux1-schnell.dgl @@ -0,0 +1,41 @@ +# version: 0.0.0 +# docs/models/pulid.md — CLI + +var { + dit_path = "../models/diffusion_models/flux1-schnell-Q4_K_S.gguf" + pulid_path = "../models/pulid/pulid_flux_v0.9.1.safetensors" + encoder_path = "../models/text_encoders/t5xxl_fp16.safetensors" + clip_l_path = "../models/text_encoders/clip_l.safetensors" + vae_path = "../models/vae/ae.safetensors" + + identity_path = "../inputs/source.pulidembd" + output_path = "out.png" + + prompt = "candid photograph of a young woman on a beach at sunset" + + seed = 42 + width = 512 + height = 512 + + steps = 4 + method = "euler" + scheduler = "flux" +} + +fn main() { + dit = load_dit(dit_path) + pulid = pulid::load(pulid_path) + text = load_text_encoder(encoder_path, family = "flux", clip_l_path = clip_l_path, backend = "cpu") + vae = load_vae(vae_path, family = "flux") + identity = pulid::load_embedding(identity_path) + condition = pulid::apply(encode_prompt(text, prompt), pulid, identity, strength = 1.0) + predict = predictor(dit, condition) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + sigmas = make_sigmas(predict, latent = base, scheduler = scheduler, steps = steps) + rng = make_rng("cuda", seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent } +} diff --git a/docs/dgl/qwen_image/qwen-image-txt2img.dgl b/docs/dgl/qwen_image/qwen-image-txt2img.dgl new file mode 100644 index 0000000000..6cafcb0f2c --- /dev/null +++ b/docs/dgl/qwen_image/qwen-image-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/qwen_image.md — CLI + +var { + model_path = "../models/diffusion_models/qwen-image-Q8_0.gguf" + text_path = "../models/text_encoders/Qwen2.5-VL-7B-Instruct-Q8_0.gguf" + vae_path = "../models/vae/qwen_image_vae.safetensors" + + output_path = "output.png" + + negative_prompt = "" + prompt = "一个穿着\"QWEN\"标志的T恤的中国美女正拿着黑色的马克笔面相镜头微笑。她身后的玻璃板上手写体写着 “一、Qwen-Image的技术路线: 探索视觉生成基础模型的极限,开创理解与生成一体化的未来。二、Qwen-Image的模型特色:1、复杂文字渲染。支持中英渲染、自动布局; 2、精准图像编辑。支持文字编辑、物体增减、风格变换。三、Qwen-Image的未来愿景:赋能专业内容创作、助力生成式AI发展。”" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 2.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "qwen_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "qwen_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "qwen_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/qwen_image_2.1/qwen-image-2-1-edit.dgl b/docs/dgl/qwen_image_2.1/qwen-image-2-1-edit.dgl new file mode 100644 index 0000000000..7bf61621a6 --- /dev/null +++ b/docs/dgl/qwen_image_2.1/qwen-image-2-1-edit.dgl @@ -0,0 +1,68 @@ +# version: 0.0.0 +# docs/models/qwen_image_2.1.md — Image editing + +var { + model_path = "../models/diffusion_models/qwen_image_2.1_int8_convrot.safetensors" + text_path = "../models/text_encoders/Qwen3VL-8B-Instruct-Q4_K_M.gguf" + vision_path = "../models/text_encoders/Qwen3VL-8B-Instruct-mmproj-BF16.gguf" + vae_path = "../models/vae/qwen_image_2.1_vae_bf16.safetensors" + + reference_0_path = "../inputs/qwen/qwen_image_2.1.png" + output_path = "qwen_image_2.1_edit.png" + + prompt = "change 'qwen2.1.cpp' to 'sd.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "flux" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "qwen_image_2_1", params_backend = "cpu") + text = load_text_encoder(text_path, family = "qwen_image_2_1", params_backend = "cpu", vision_path = vision_path) + vae = load_vae(vae_path, family = "qwen_image_2_1", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 4) + reference_0_pixels = fit_reference_area(reference_0_original, width * height, 32, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + positive = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_pixels]) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = [reference_0_pixels]) + pos = predictor(model, positive, ref_latents = [reference_latent_0], ref_index_mode = "increase") + neg = predictor(model, negative, ref_latents = [reference_latent_0], ref_index_mode = "increase") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/qwen_image_2.1/qwen-image-2-1-txt2img.dgl b/docs/dgl/qwen_image_2.1/qwen-image-2-1-txt2img.dgl new file mode 100644 index 0000000000..169ba1c172 --- /dev/null +++ b/docs/dgl/qwen_image_2.1/qwen-image-2-1-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/qwen_image_2.1.md — Text to image + +var { + model_path = "../models/diffusion_models/qwen_image_2.1_int8_convrot.safetensors" + text_path = "../models/text_encoders/Qwen3VL-8B-Instruct-Q4_K_M.gguf" + vae_path = "../models/vae/qwen_image_2.1_vae_bf16.safetensors" + + output_path = "qwen_image_2.1.png" + + prompt = "a lovely cat holding a sign says 'qwen2.1.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "flux" +} + +fn main() { + model = load_dit(model_path, family = "qwen_image_2_1", params_backend = "cpu") + text = load_text_encoder(text_path, family = "qwen_image_2_1", params_backend = "cpu") + vae = load_vae(vae_path, family = "qwen_image_2_1", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/qwen_image_edit/qwen-image-edit-2509.dgl b/docs/dgl/qwen_image_edit/qwen-image-edit-2509.dgl new file mode 100644 index 0000000000..99876a30a3 --- /dev/null +++ b/docs/dgl/qwen_image_edit/qwen-image-edit-2509.dgl @@ -0,0 +1,68 @@ +# version: 0.0.0 +# docs/models/qwen_image_edit.md — Qwen Image Edit 2509 + +var { + model_path = "../models/diffusion_models/Qwen-Image-Edit-2509-Q4_K_S.gguf" + text_path = "../models/text_encoders/Qwen2.5-VL-7B-Instruct-Q8_0.gguf" + vision_path = "../models/text_encoders/Qwen2.5-VL-7B-Instruct.mmproj-Q8_0.gguf" + vae_path = "../models/vae/qwen_image_vae.safetensors" + + reference_0_path = "../inputs/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'Qwen Image Edit 2509'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + + steps = 20 + cfg_scale = 2.5 + method = "euler" + scheduler = "discrete" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "qwen_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "qwen_image", params_backend = "cpu", vision_path = vision_path) + vae = load_vae(vae_path, family = "qwen_image", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 32, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + positive = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_original]) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = [reference_0_original]) + pos = predictor(model, positive, ref_latents = [reference_latent_0], ref_index_mode = "increase") + neg = predictor(model, negative, ref_latents = [reference_latent_0], ref_index_mode = "increase") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/qwen_image_edit/qwen-image-edit-2511.dgl b/docs/dgl/qwen_image_edit/qwen-image-edit-2511.dgl new file mode 100644 index 0000000000..426372efd4 --- /dev/null +++ b/docs/dgl/qwen_image_edit/qwen-image-edit-2511.dgl @@ -0,0 +1,67 @@ +# version: 0.0.0 +# docs/models/qwen_image_edit.md — Qwen Image Edit 2511 + +var { + model_path = "../models/diffusion_models/qwen-image-edit-2511-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen_2.5_vl_7b.safetensors" + vae_path = "../models/vae/qwen_image_vae.safetensors" + + reference_0_path = "../inputs/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'edit.cpp'" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + + steps = 20 + cfg_scale = 2.5 + method = "euler" + scheduler = "discrete" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "qwen_image", model_args = "qwen_image_zero_cond_t=true", params_backend = "cpu") + text = load_text_encoder(text_path, family = "qwen_image", model_args = "qwen_image_zero_cond_t=true", params_backend = "cpu") + vae = load_vae(vae_path, family = "qwen_image", model_args = "qwen_image_zero_cond_t=true", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 32, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + positive = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_original]) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = [reference_0_original]) + pos = predictor(model, positive, ref_latents = [reference_latent_0], ref_index_mode = "increase") + neg = predictor(model, negative, ref_latents = [reference_latent_0], ref_index_mode = "increase") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/qwen_image_edit/qwen-image-edit.dgl b/docs/dgl/qwen_image_edit/qwen-image-edit.dgl new file mode 100644 index 0000000000..f25aa376f5 --- /dev/null +++ b/docs/dgl/qwen_image_edit/qwen-image-edit.dgl @@ -0,0 +1,67 @@ +# version: 0.0.0 +# docs/models/qwen_image_edit.md — Qwen Image Edit + +var { + model_path = "../models/diffusion_models/Qwen_Image_Edit-Q8_0.gguf" + text_path = "../models/text_encoders/qwen_2.5_vl_7b.safetensors" + vae_path = "../models/vae/qwen_image_vae.safetensors" + + reference_0_path = "../inputs/flux/flux1-dev-q8_0.png" + output_path = "output.png" + + prompt = "change 'flux.cpp' to 'edit.cpp'" + negative_prompt = "" + + seed = 1118877715456453 + rng_type = "cuda" + + steps = 20 + cfg_scale = 2.5 + method = "euler" + scheduler = "discrete" +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn main() { + reference_0 = image::load(reference_0_path) + width = tensor::shape(reference_0)[1] + height = tensor::shape(reference_0)[2] + + model = load_dit(model_path, family = "qwen_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "qwen_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "qwen_image", params_backend = "cpu") + + encode_rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + reference_0_original = image::to_f32(reference_0, channels = 3) + reference_0_pixels = fit_reference_area(reference_0_original, math::min(1048576, width * height), 32, mode = "bilinear") + reference_latent_0 = vae_to_dit_latents(vae, vae_encode(vae, reference_0_pixels, rng = encode_rng)) + + positive = encode_prompt(text, prompt, width = width, height = height, media = [reference_0_original]) + negative = encode_prompt(text, negative_prompt, width = width, height = height, media = [reference_0_original]) + pos = predictor(model, positive, ref_latents = [reference_latent_0], ref_index_mode = "increase") + neg = predictor(model, negative, ref_latents = [reference_latent_0], ref_index_mode = "increase") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/relay_vsr/relayvsr-x2-image-upscale.dgl b/docs/dgl/relay_vsr/relayvsr-x2-image-upscale.dgl new file mode 100644 index 0000000000..cc790d133d --- /dev/null +++ b/docs/dgl/relay_vsr/relayvsr-x2-image-upscale.dgl @@ -0,0 +1,47 @@ +# version: 0.0.0 +# docs/models/relay_vsr.md — CLI + +var { + dit_path = "../models/diffusion_models/relayvsr_x2_lightx2v_int8_convrot.safetensors" + vae_path = "../models/vae/relayvsr_flash_vae_x2_fp32.safetensors" + + input_path = "input.png" + output_path = "output.png" + + seed = 42 + window_size = 16 + + sampler = "euler" +} + +fn keyframe_indices(frames, stride) { + count = tensor::shape(frames)[3] + last = count - 1 + regular = tensor::arange(0, last, step = stride) + return tensor::concat([regular, tensor::vector([last], dtype = "i64")], axis = 0) +} + +fn upscale_window(frames, dit, flash, rng, window_size, sampler) { + indices = keyframe_indices(frames, stride = window_size - 1) + keyframes = tensor::index_select(frames, axis = 3, indices = indices) + positive = { crossattn = relayvsr::positive_embedding(dit), lq_frames = keyframes } + base = tensor::zeros(relayvsr::latent_shape(dit, keyframes)) + noise = tensor::randn_like(base, rng = rng) + sigmas = tensor::vector([1.0, 0.0]) + positive_predictor = predictor(dit, positive) + latent = sample(noise, sigmas, predict = positive_predictor, method = sampler, rng = rng) + return relayvsr::decode(flash, latent, frames, keyframe_indices = indices) +} + +fn main() { + dit = load_dit(dit_path) + flash = load_vae(vae_path) + image = image::load(input_path) + frames = tensor::unsqueeze(image, axis = 3) + rng = make_rng("cuda", seed = seed) + windows = video::split_windows(frames, size = window_size, overlap = 1) + enhanced = map(windows, process = upscale_window, dit = dit, flash = flash, rng = rng, window_size = window_size, sampler = sampler) + pixels = video::join_windows(enhanced, overlap = 1) + image::save(output_path, pixels[:, :, :, 0]) + return { video = pixels } +} diff --git a/docs/dgl/relay_vsr/relayvsr-x2-video-upscale.dgl b/docs/dgl/relay_vsr/relayvsr-x2-video-upscale.dgl new file mode 100644 index 0000000000..c678a131e6 --- /dev/null +++ b/docs/dgl/relay_vsr/relayvsr-x2-video-upscale.dgl @@ -0,0 +1,48 @@ +# version: 0.0.0 +# docs/models/relay_vsr.md — CLI + +var { + dit_path = "../models/diffusion_models/relayvsr_x2_lightx2v_int8_convrot.safetensors" + vae_path = "../models/vae/relayvsr_flash_vae_x2_fp32.safetensors" + + input_path = "input_frames" + output_path = "output.avi" + + seed = 42 + fps = 24 + window_size = 16 + + sampler = "euler" +} + +fn keyframe_indices(frames, stride) { + count = tensor::shape(frames)[3] + last = count - 1 + regular = tensor::arange(0, last, step = stride) + return tensor::concat([regular, tensor::vector([last], dtype = "i64")], axis = 0) +} + +fn upscale_window(frames, dit, flash, rng, window_size, sampler) { + indices = keyframe_indices(frames, stride = window_size - 1) + keyframes = tensor::index_select(frames, axis = 3, indices = indices) + positive = { crossattn = relayvsr::positive_embedding(dit), lq_frames = keyframes } + base = tensor::zeros(relayvsr::latent_shape(dit, keyframes)) + noise = tensor::randn_like(base, rng = rng) + sigmas = tensor::vector([1.0, 0.0]) + positive_predictor = predictor(dit, positive) + latent = sample(noise, sigmas, predict = positive_predictor, method = sampler, rng = rng) + return relayvsr::decode(flash, latent, frames, keyframe_indices = indices) +} + +fn main() { + dit = load_dit(dit_path) + flash = load_vae(vae_path) + clip = video::load(input_path, fps_num = fps) + frames = clip.video.frames + rng = make_rng("cuda", seed = seed) + windows = video::split_windows(frames, size = window_size, overlap = 1) + enhanced = map(windows, process = upscale_window, dit = dit, flash = flash, rng = rng, window_size = window_size, sampler = sampler) + pixels = video::join_windows(enhanced, overlap = 1) + video::save(output_path, {frames = pixels, fps_num = clip.video.fps_num, fps_den = clip.video.fps_den}, audio = clip.audio) + return { video = pixels } +} diff --git a/docs/dgl/sd/nitrosd-realism-nitrofusion.dgl b/docs/dgl/sd/nitrosd-realism-nitrofusion.dgl new file mode 100644 index 0000000000..75ab934dc6 --- /dev/null +++ b/docs/dgl/sd/nitrosd-realism-nitrofusion.dgl @@ -0,0 +1,46 @@ +# version: 0.0.0 + +var { + model_path = "nitrosd-realism_f16.gguf" + + output_path = "nitrofusion.png" + + prompt = "cute cat" + + seed = 2024 + width = 1024 + height = 1024 + + steps = 1 + timestep_limit = 250 + scheduler = "sgm_uniform" +} + +fn nitrofusion_step(step, options) { + time_scale = options.timestep_limit / 1000 + timestep = math::min(math::round(step.timestep * time_scale), 999) + t = timestep / 999 + sigma = t_to_sigma(options.predict, t) + scales = denoiser_scalings(options.predict, sigma) + skip = scales.skip_scale * step.input_scale / scales.input_scale + return { timestep = timestep, skip_scale = skip, output_scale = scales.output_scale } +} + +fn main() { + unet = load_unet(model_path) + text = load_text_encoder(model_path) + vae = load_vae(model_path, conv_scale = 0.03125) + shape = latent_shape(vae, width = width, height = height) + base = tensor::zeros(shape) + rng = make_rng("cuda", seed = seed) + pos_text = encode_prompt(text, prompt, width = width, height = height) + sampling_predict = predictor(unet, pos_text) + sigmas = make_sigmas(sampling_predict, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(sampling_predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + options = { predict = sampling_predict, timestep_limit = timestep_limit } + predict = predictor(unet, pos_text, transform = nitrofusion_step, transform_args = options) + latent = sample(start, sigmas, predict = predict, method = "euler_a", rng = rng) + pixels = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, pixels) + return { image = pixels, latent = latent } +} diff --git a/docs/dgl/sd/sd1-4-img2img.dgl b/docs/dgl/sd/sd1-4-img2img.dgl new file mode 100644 index 0000000000..b6d218b08b --- /dev/null +++ b/docs/dgl/sd/sd1-4-img2img.dgl @@ -0,0 +1,63 @@ +# version: 0.0.0 +# docs/models/sd.md — img2img example + +var { + model_path = "../models/checkpoints/sd-v1-4.ckpt" + + input_image_path = "./output.png" + output_path = "img2img_output.png" + + prompt = "cat with blue eyes" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + + steps = 20 + strength = 0.4000000059604645 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn slice_sigmas_by_strength(sigmas, strength) { + steps = tensor::numel(sigmas) - 1 + retained = math::min(math::floor(steps * strength) + 1, steps) + return sigmas[steps - retained:] +} + +fn main() { + input_image = image::load(input_image_path) + width = tensor::shape(input_image)[1] + height = tensor::shape(input_image)[2] + + model = load_unet(model_path, family = "sd1") + text = load_text_encoder(model_path, family = "sd1") + vae = load_vae(model_path, family = "sd1") + + encode_rng = make_rng(rng_type, seed = seed) + source = fit_canvas(input_image, width, height, mode = "nearest") + base = vae_to_unet_latents(vae, vae_encode(vae, image::to_f32(source, channels = 3), rng = encode_rng)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + full_sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + sigmas = slice_sigmas_by_strength(full_sigmas, strength) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/sd/sd1-4-txt2img.dgl b/docs/dgl/sd/sd1-4-txt2img.dgl new file mode 100644 index 0000000000..bd74c2a37c --- /dev/null +++ b/docs/dgl/sd/sd1-4-txt2img.dgl @@ -0,0 +1,41 @@ +# version: 0.0.0 +# docs/models/sd.md — SD 1.4 + +var { + model_path = "../models/checkpoints/sd-v1-4.ckpt" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + model = load_unet(model_path, family = "sd1") + text = load_text_encoder(model_path, family = "sd1") + vae = load_vae(model_path, family = "sd1") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/sd/sd1-5-controlnet.dgl b/docs/dgl/sd/sd1-5-controlnet.dgl new file mode 100644 index 0000000000..a465cd0288 --- /dev/null +++ b/docs/dgl/sd/sd1-5-controlnet.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 + +var { + weights = "sd15.safetensors" + model_path = "control_openpose-fp16.safetensors" + + input_path = "pose.png" + output_path = "controlnet.png" + + prompt = "A dancer in a bright studio" + negative_prompt = "" + + seed = 42 + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7 + scheduler = "karras" +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights) + control = controlnet::load(model_path, family = "sd1") + pose = tensor::interpolate(image::load(input_path), size = [width, height], axes = [1, 2]) + pixels = image::to_f32(pose, channels = 3) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + rng = make_rng("cuda", seed = seed) + positive = controlnet::apply(encode_prompt(text, prompt), control, pixels) + negative = controlnet::apply(encode_prompt(text, negative_prompt), control, pixels) + pos = predictor(unet, positive, prediction = "eps") + neg = predictor(unet, negative, prediction = "eps") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent } +} diff --git a/docs/dgl/sd/sd1-5-inpainting.dgl b/docs/dgl/sd/sd1-5-inpainting.dgl new file mode 100644 index 0000000000..bb91ad67b0 --- /dev/null +++ b/docs/dgl/sd/sd1-5-inpainting.dgl @@ -0,0 +1,62 @@ +# version: 0.0.0 + +var { + weights = "sd-v1-5-inpainting.safetensors" + + input_path = "input.png" + mask_path = "mask.png" + output_path = "inpaint.png" + + prompt = "A red flower in the masked area" + negative_prompt = "" + + seed = 42 + + strength = 0.8 + steps = 20 + cfg_scale = 7 + scheduler = "karras" +} + +fn latent_mask(mask, like) { + shape = tensor::shape(like) + w = shape[0] + h = shape[1] + batch = shape[3] + resized = tensor::interpolate(image::to_f32(mask), size = [w, h], mode = "nearest") + return tensor::broadcast_to(resized, [w, h, 1, batch]) +} + +fn slice_sigmas_by_strength(sigmas, strength) { + steps = tensor::numel(sigmas) - 1 + retained = math::floor(steps * strength) + return sigmas[steps - retained:] +} + +fn main() { + unet = load_unet(weights) + text = load_text_encoder(weights) + vae = load_vae(weights) + source = tensor::interpolate(image::load(input_path), size = [512, 512], axes = [1, 2]) + gray = tensor::grayscale(image::load(mask_path), axis = 0) + binary_mask = tensor::threshold(gray, threshold = 128, low = 0, high = 255) + region = tensor::interpolate(binary_mask, size = [512, 512], axes = [1, 2], mode = "nearest_exact") + pixels = image::to_f32(source) + masked = tensor::lerp(pixels, 0.5, image::to_f32(region)) + encode_rng = make_rng("cuda", seed = seed) + base = vae_to_unet_latents(vae, vae_encode(vae, pixels, rng = encode_rng)) + cond_image = vae_to_unet_latents(vae, vae_encode(vae, masked, rng = encode_rng)) + region_latent = latent_mask(region, like = base) + condition = tensor::concat([region_latent, cond_image], axis = 2) + denoise_mask = tensor::max_pool2d(region_latent, kernel = [3, 3], padding_before = [1, 1]) + rng = make_rng("cuda", seed = seed) + pos = predictor(unet, encode_prompt(text, prompt), concat = condition, prediction = "eps") + neg = predictor(unet, encode_prompt(text, negative_prompt), concat = condition, prediction = "eps") + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = slice_sigmas_by_strength(make_sigmas(guided, latent = base, scheduler = scheduler, steps = steps), strength = strength) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, base = base, denoise_mask = denoise_mask, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent, mask = denoise_mask } +} diff --git a/docs/dgl/sd/sd1-5-txt2img.dgl b/docs/dgl/sd/sd1-5-txt2img.dgl new file mode 100644 index 0000000000..5057b2a2ee --- /dev/null +++ b/docs/dgl/sd/sd1-5-txt2img.dgl @@ -0,0 +1,41 @@ +# version: 0.0.0 +# docs/models/sd.md — SD 1.5 + +var { + model_path = "../models/checkpoints/v1-5-pruned-emaonly.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + model = load_unet(model_path, family = "sd1") + text = load_text_encoder(model_path, family = "sd1") + vae = load_vae(model_path, family = "sd1") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/sd/sdxl-txt2img.dgl b/docs/dgl/sd/sdxl-txt2img.dgl new file mode 100644 index 0000000000..bb875a4b0b --- /dev/null +++ b/docs/dgl/sd/sdxl-txt2img.dgl @@ -0,0 +1,55 @@ +# version: 0.0.0 +# docs/models/sd.md — SDXL + +var { + model_path = "../models/checkpoints/sd_xl_base_1.0.safetensors" + vae_path = "../models/vae/sdxl_vae-fp16-fix.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + zero_negative = true + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn sdxl_zero_text(cond) { + zeroed = zero_out(cond, fields = ["crossattn"]) + pooled_zeros = tensor::zeros_like(cond.vector[:1280]) + adm = tensor::replace_slice(cond.vector, pooled_zeros, axis = 0, start = 0) + return {crossattn = zeroed.crossattn, vector = adm} +} + +fn main() { + model = load_unet(model_path, family = "sdxl") + text = load_text_encoder(model_path, family = "sdxl") + vae = load_vae(vae_path, family = "sdxl", conv_scale = 0.03125) + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative_text = encode_prompt(text, negative_prompt, width = width, height = height) + negative = if zero_negative { + sdxl_zero_text(negative_text) + } else { + {crossattn = negative_text.crossattn, vector = negative_text.vector} + } + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/sd3/sd3-5-large-txt2img.dgl b/docs/dgl/sd3/sd3-5-large-txt2img.dgl new file mode 100644 index 0000000000..b5594aef57 --- /dev/null +++ b/docs/dgl/sd3/sd3-5-large-txt2img.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/sd3.md — SD3.5 Large + +var { + model_path = "../models/checkpoints/sd3.5_large.safetensors" + clip_l_path = "../models/text_encoders/clip_l.safetensors" + clip_g_path = "../models/text_encoders/clip_g.safetensors" + t5_path = "../models/text_encoders/t5xxl_fp16.safetensors" + + output_path = "output.png" + negative_prompt = "" + prompt = "a lovely cat holding a sign says \\\"Stable diffusion 3.5 Large\\\"" + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 20 + cfg_scale = 4.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "sd3") + text = load_text_encoder(model_path, backend = "cpu", clip_g_path = clip_g_path, clip_l_path = clip_l_path, family = "sd3", t5_path = t5_path) + vae = load_vae(model_path, family = "sd3") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/seedvr2/seedvr2-3b-image-upscale.dgl b/docs/dgl/seedvr2/seedvr2-3b-image-upscale.dgl new file mode 100644 index 0000000000..6d1d67dfb8 --- /dev/null +++ b/docs/dgl/seedvr2/seedvr2-3b-image-upscale.dgl @@ -0,0 +1,65 @@ +# version: 0.0.0 +# docs/models/seedvr2.md — Upscale an image + +var { + dit_path = "../models/diffusion_models/seedvr2_3b_int8_convrot.safetensors" + vae_path = "../models/vae/seedvr2_ema_vae_fp16.safetensors" + + input_path = "input.png" + output_path = "restored.png" + + seed = 42 + window_size = 5 + factor = 2 +} + +fn prepare_seedvr2_frames(frames, width, height, count) { + aligned_width = math::ceil_div(width, 16) * 16 + aligned_height = math::ceil_div(height, 16) * 16 + padded_count = math::ceil_div(count - 1, 4) * 4 + 1 + planar = tensor::permute(tensor::cast(frames, "f32"), axes = [1, 2, 3, 0]) + pixels = tensor::div(planar, 255.0) + scaled = tensor::clamp(tensor::interpolate(pixels, [width, height], mode = "bicubic"), min = 0, max = 1) + padded = tensor::pad(scaled, [0, aligned_width - width, 0, aligned_height - height]) + tail = tensor::full([padded_count - count], count - 1, dtype = "i64") + indices = tensor::concat([tensor::arange(0, count), tail], axis = 0) + extended = tensor::index_select(padded, axis = 2, indices = indices) + return tensor::reshape(extended, [aligned_width, aligned_height, padded_count, 3, 1]) +} + +fn upscale_window(frames, dit, vae, embedding, factor, rng) { + shape = tensor::shape(frames) + width = shape[1] * factor + height = shape[2] * factor + count = shape[3] + pixels = prepare_seedvr2_frames(frames, width, height, count) + encoded = vae_encode(vae, pixels, rng = rng, posterior = "mode") + condition_latent = vae_to_dit_latents(vae, encoded) + encoded_shape = tensor::shape(encoded) + mask_shape = [encoded_shape[0], encoded_shape[1], encoded_shape[2], 1, encoded_shape[4]] + mask = tensor::full(mask_shape, 1) + condition = { crossattn = embedding, concat = tensor::concat([condition_latent, mask], axis = 3) } + noise = tensor::randn_like(condition_latent, rng = rng) + sigmas = tensor::vector([1.0, 0.0]) + sampling_predictor = predictor(dit, condition) + latent = sample(noise, sigmas, predict = sampling_predictor, method = "euler", rng = rng) + decoded = vae_decode(vae, dit_to_vae_latents(vae, latent), dtype = "f32") + cropped = tensor::crop(decoded, axes = [0, 1, 2], start = [0, 0, 0], size = [width, height, count]) + planar = tensor::reshape(cropped, [width, height, count, 3]) + output = tensor::cast(tensor::mul(tensor::permute(planar, axes = [3, 0, 1, 2]), 255.0), "u8") + return output +} + +fn main() { + dit = load_dit(dit_path) + vae = load_vae(vae_path) + image = image::load(input_path) + source_frames = tensor::unsqueeze(image, axis = 3) + rng = make_rng("cuda", seed = seed) + embedding = seedvr2::positive_embedding(dit) + windows = video::split_windows(source_frames, size = window_size) + upscaled = map(windows, process = upscale_window, dit = dit, vae = vae, embedding = embedding, factor = factor, rng = rng) + output = video::join_windows(upscaled) + image::save(output_path, output[:, :, :, 0]) + return output +} diff --git a/docs/dgl/seedvr2/seedvr2-3b-video-upscale.dgl b/docs/dgl/seedvr2/seedvr2-3b-video-upscale.dgl new file mode 100644 index 0000000000..c5ca43c54f --- /dev/null +++ b/docs/dgl/seedvr2/seedvr2-3b-video-upscale.dgl @@ -0,0 +1,65 @@ +# version: 0.0.0 +# docs/models/seedvr2.md — Upscale a video + +var { + dit_path = "../models/diffusion_models/seedvr2_3b_int8_convrot.safetensors" + vae_path = "../models/vae/seedvr2_ema_vae_fp16.safetensors" + + input_path = "frames" + output_path = "restored.avi" + + seed = 42 + fps = 24 + window_size = 1 + factor = 2 +} + +fn prepare_seedvr2_frames(frames, width, height, count) { + aligned_width = math::ceil_div(width, 16) * 16 + aligned_height = math::ceil_div(height, 16) * 16 + padded_count = math::ceil_div(count - 1, 4) * 4 + 1 + planar = tensor::permute(tensor::cast(frames, "f32"), axes = [1, 2, 3, 0]) + pixels = tensor::div(planar, 255.0) + scaled = tensor::clamp(tensor::interpolate(pixels, [width, height], mode = "bicubic"), min = 0, max = 1) + padded = tensor::pad(scaled, [0, aligned_width - width, 0, aligned_height - height]) + tail = tensor::full([padded_count - count], count - 1, dtype = "i64") + indices = tensor::concat([tensor::arange(0, count), tail], axis = 0) + extended = tensor::index_select(padded, axis = 2, indices = indices) + return tensor::reshape(extended, [aligned_width, aligned_height, padded_count, 3, 1]) +} + +fn upscale_window(frames, dit, vae, embedding, factor, rng) { + shape = tensor::shape(frames) + width = shape[1] * factor + height = shape[2] * factor + count = shape[3] + pixels = prepare_seedvr2_frames(frames, width, height, count) + encoded = vae_encode(vae, pixels, rng = rng, posterior = "mode") + condition_latent = vae_to_dit_latents(vae, encoded) + encoded_shape = tensor::shape(encoded) + mask_shape = [encoded_shape[0], encoded_shape[1], encoded_shape[2], 1, encoded_shape[4]] + mask = tensor::full(mask_shape, 1) + condition = { crossattn = embedding, concat = tensor::concat([condition_latent, mask], axis = 3) } + noise = tensor::randn_like(condition_latent, rng = rng) + sigmas = tensor::vector([1.0, 0.0]) + sampling_predictor = predictor(dit, condition) + latent = sample(noise, sigmas, predict = sampling_predictor, method = "euler", rng = rng) + decoded = vae_decode(vae, dit_to_vae_latents(vae, latent), dtype = "f32") + cropped = tensor::crop(decoded, axes = [0, 1, 2], start = [0, 0, 0], size = [width, height, count]) + planar = tensor::reshape(cropped, [width, height, count, 3]) + output = tensor::cast(tensor::mul(tensor::permute(planar, axes = [3, 0, 1, 2]), 255.0), "u8") + return output +} + +fn main() { + dit = load_dit(dit_path) + vae = load_vae(vae_path) + clip = video::load(input_path, fps_num = fps) + rng = make_rng("cuda", seed = seed) + embedding = seedvr2::positive_embedding(dit) + windows = video::split_windows(clip.video.frames, size = window_size) + upscaled = map(windows, process = upscale_window, dit = dit, vae = vae, embedding = embedding, factor = factor, rng = rng) + output = video::join_windows(upscaled) + video::save(output_path, {frames = output, fps_num = clip.video.fps_num, fps_den = clip.video.fps_den}, audio = clip.audio) + return output +} diff --git a/docs/dgl/sefi_image/sefi-1b-base-txt2img.dgl b/docs/dgl/sefi_image/sefi-1b-base-txt2img.dgl new file mode 100644 index 0000000000..c1dc15e4f9 --- /dev/null +++ b/docs/dgl/sefi_image/sefi-1b-base-txt2img.dgl @@ -0,0 +1,44 @@ +# version: 0.0.0 +# docs/models/sefi_image.md — 1B / 2B base + +var { + model_path = "../models/diffusion_models/sefi_1b_base.safetensors" + text_path = "../models/text_encoders/qwen3_vl_2b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "out.png" + + prompt = "a photograph of an orange tabby cat sitting on a couch" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 50 + cfg_scale = 4.0 + method = "euler" +} + +fn main() { + model = load_dit(model_path, family = "sefi_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "sefi_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "sefi_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + dual_schedule = sefi::make_sigmas(steps = steps) + sigmas = dual_schedule.sigmas + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sefi::sample(start, sigmas, predict = guided, semantic_sigmas = dual_schedule.semantic_sigmas, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 16:144])) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/sefi_image/sefi-1b-turbo-txt2img.dgl b/docs/dgl/sefi_image/sefi-1b-turbo-txt2img.dgl new file mode 100644 index 0000000000..c8bbde270b --- /dev/null +++ b/docs/dgl/sefi_image/sefi-1b-turbo-txt2img.dgl @@ -0,0 +1,39 @@ +# version: 0.0.0 +# docs/models/sefi_image.md — 1B / 2B turbo + +var { + model_path = "../models/diffusion_models/sefi_1b_turbo.safetensors" + text_path = "../models/text_encoders/qwen3_vl_2b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "out.png" + + prompt = "a photograph of an orange tabby cat sitting on a couch" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 4 + method = "euler" +} + +fn main() { + model = load_dit(model_path, family = "sefi_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "sefi_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "sefi_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + dual_schedule = sefi::make_sigmas(steps = steps) + sigmas = dual_schedule.sigmas + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sefi::sample(start, sigmas, predict = predict, semantic_sigmas = dual_schedule.semantic_sigmas, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 16:144])) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/sefi_image/sefi-5b-turbo-txt2img.dgl b/docs/dgl/sefi_image/sefi-5b-turbo-txt2img.dgl new file mode 100644 index 0000000000..07571de65d --- /dev/null +++ b/docs/dgl/sefi_image/sefi-5b-turbo-txt2img.dgl @@ -0,0 +1,40 @@ +# version: 0.0.0 +# CLI/context: --max-vram 8 +# docs/models/sefi_image.md — 5B (needs streaming on 12 GiB VRAM) + +var { + model_path = "../models/diffusion_models/sefi_5b_turbo.safetensors" + text_path = "../models/text_encoders/qwen3_vl_4b.safetensors" + vae_path = "../models/vae/flux2_ae.safetensors" + + output_path = "out.png" + + prompt = "a photograph of an orange tabby cat sitting on a couch" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 4 + method = "euler" +} + +fn main() { + model = load_dit(model_path, family = "sefi_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "sefi_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "sefi_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + dual_schedule = sefi::make_sigmas(steps = steps) + sigmas = dual_schedule.sigmas + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sefi::sample(start, sigmas, predict = predict, semantic_sigmas = dual_schedule.semantic_sigmas, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 16:144])) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/sefi_image/sefi-image-5b-rl.dgl b/docs/dgl/sefi_image/sefi-image-5b-rl.dgl new file mode 100644 index 0000000000..08b69fc9a4 --- /dev/null +++ b/docs/dgl/sefi_image/sefi-image-5b-rl.dgl @@ -0,0 +1,36 @@ +# version: 0.0.0 + +var { + dit_path = "SeFi-Image-5B-RL.safetensors" + encoder_path = "Qwen3-VL-4B-Instruct.gguf" + vae_path = "flux2_ae.safetensors" + + output_path = "sefi.png" + + prompt = "A small house in a forest clearing, warm afternoon light" + negative_prompt = "" + + seed = 42 + width = 1024 + height = 1024 + + cfg_scale = 4 +} + +fn main() { + dit = load_dit(dit_path) + text = load_text_encoder(encoder_path, family = "sefi_image") + vae = load_vae(vae_path, family = "sefi_image") + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + schedule = sefi::make_sigmas(steps = 20) + rng = make_rng("cuda", seed = seed) + pos = predictor(dit, encode_prompt(text, prompt)) + neg = predictor(dit, encode_prompt(text, negative_prompt)) + guided = cfg(pos, neg, scale = cfg_scale) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = schedule.sigmas[0]) + latent = sefi::sample(start, schedule.sigmas, predict = guided, semantic_sigmas = schedule.semantic_sigmas, finish = true, rng = rng) + texture = latent[:, :, 16:144] + image = vae_decode(vae, dit_to_vae_latents(vae, texture)) + image::save(output_path, image) + return { image = image, latent = latent } +} diff --git a/docs/dgl/sensenova_u1/sensenova-u1-cuda-txt2img.dgl b/docs/dgl/sensenova_u1/sensenova-u1-cuda-txt2img.dgl new file mode 100644 index 0000000000..bd269964d5 --- /dev/null +++ b/docs/dgl/sensenova_u1/sensenova-u1-cuda-txt2img.dgl @@ -0,0 +1,41 @@ +# version: 0.0.0 +# docs/models/sensenova_u1.md — CUDA + +var { + model_path = "../models/checkpoints/SenseNova-U1.5-8B-MoT" + + output_path = "output.png" + + negative_prompt = "<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n" + prompt = "a red cube on a white background" + + seed = 42 + rng_type = "cuda" + width = 2048 + height = 2048 + + steps = 50 + cfg_scale = 4.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "sensenova_u1_5") + text = load_text_encoder(model_path, family = "sensenova_u1_5") + vae = load_vae(model_path, family = "sensenova_u1_5") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height, raw = true) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/taesd/sd1-5-taesd-preview.dgl b/docs/dgl/taesd/sd1-5-taesd-preview.dgl new file mode 100644 index 0000000000..ef09c17b1f --- /dev/null +++ b/docs/dgl/taesd/sd1-5-taesd-preview.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/taesd.md — CLI + +var { + model_path = "../models/checkpoints/v1-5-pruned-emaonly.safetensors" + vae_path = "../models/vae/diffusion_pytorch_model.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 512 + + steps = 20 + cfg_scale = 7.0 + method = "euler_a" + scheduler = "discrete" +} + +fn main() { + model = load_unet(model_path, family = "sd1") + text = load_text_encoder(model_path, family = "sd1") + vae = load_tae(vae_path, family = "sd1") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng, observer = preview(decoder = vae)) + image = vae_decode(vae, unet_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/wan/wan2-1-first-last-frame-14b.dgl b/docs/dgl/wan/wan2-1-first-last-frame-14b.dgl new file mode 100644 index 0000000000..e87960b2da --- /dev/null +++ b/docs/dgl/wan/wan2-1-first-last-frame-14b.dgl @@ -0,0 +1,78 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.1 FLF2V 14B + +var { + model_path = "../models/diffusion_models/wan2.1-flf2v-14b-720p-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + vision_path = "../models/clip_vision/clip_vision_h.safetensors" + + first_frame_path = "../inputs/start_image.png" + last_frame_path = "../inputs/end_image.png" + output_path = "output.avi" + + prompt = "glass flower blossom" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 480 + height = 832 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + last_frame = image::load(last_frame_path) + + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + last_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(last_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + condition_blank = tensor::full([width, height, frames, 3, 1], 0.5) + condition_first = tensor::replace_slice(condition_blank, first_frame_pixels, axis = 2, start = 0) + condition_pixels = tensor::replace_slice(condition_first, last_frame_pixels, axis = 2, start = frames - 1) + condition_latent = vae_to_dit_latents(vae, vae_encode(vae, condition_pixels, rng = rng)) + condition_shape = tensor::shape(condition_latent) + mask_blank = tensor::zeros([condition_shape[0], condition_shape[1], condition_shape[2], 4, 1]) + first_mask = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 1) + last_mask = tensor::index_fill(first_mask[:, :, :, 3:4], axis = 2, indices = [condition_shape[2] - 1], value = 1) + image_mask = tensor::replace_slice(first_mask, last_mask, axis = 3, start = 3) + video_concat = tensor::concat([image_mask, condition_latent], axis = 3) + vision = load_vision_encoder(vision_path, family = "wan2", params_backend = "cpu") + vision_first = encode_vision(vision, image::to_u8(first_frame_pixels[:, :, 0])) + vision_end = encode_vision(vision, image::to_u8(last_frame_pixels[:, :, 0])) + vision_condition = tensor::concat([vision_first, vision_end], axis = 1) + positive_text = encode_prompt(text, prompt, width = width, height = height) + negative_text = encode_prompt(text, negative_prompt, width = width, height = height) + positive = {crossattn = positive_text.crossattn, vector = vision_condition} + negative = {crossattn = negative_text.crossattn, vector = vision_condition} + pos = predictor(model, positive, concat = video_concat) + neg = predictor(model, negative, concat = video_concat) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-i2v-14b.dgl b/docs/dgl/wan/wan2-1-i2v-14b.dgl new file mode 100644 index 0000000000..5b227a9352 --- /dev/null +++ b/docs/dgl/wan/wan2-1-i2v-14b.dgl @@ -0,0 +1,70 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.1 I2V 14B + +var { + model_path = "../models/diffusion_models/wan2.1-i2v-14b-480p-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + vision_path = "../models/clip_vision/clip_vision_h.safetensors" + + first_frame_path = "../inputs/cat_with_sd_cpp_42.png" + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 480 + height = 832 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + condition_blank = tensor::full([width, height, frames, 3, 1], 0.5) + condition_pixels = tensor::replace_slice(condition_blank, first_frame_pixels, axis = 2, start = 0) + condition_latent = vae_to_dit_latents(vae, vae_encode(vae, condition_pixels, rng = rng)) + condition_shape = tensor::shape(condition_latent) + mask_blank = tensor::zeros([condition_shape[0], condition_shape[1], condition_shape[2], 4, 1]) + image_mask = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 1) + video_concat = tensor::concat([image_mask, condition_latent], axis = 3) + vision = load_vision_encoder(vision_path, family = "wan2", params_backend = "cpu") + vision_condition = encode_vision(vision, image::to_u8(first_frame_pixels[:, :, 0])) + positive_text = encode_prompt(text, prompt, width = width, height = height) + negative_text = encode_prompt(text, negative_prompt, width = width, height = height) + positive = {crossattn = positive_text.crossattn, vector = vision_condition} + negative = {crossattn = negative_text.crossattn, vector = vision_condition} + pos = predictor(model, positive, concat = video_concat) + neg = predictor(model, negative, concat = video_concat) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-t2v-1-3b.dgl b/docs/dgl/wan/wan2-1-t2v-1-3b.dgl new file mode 100644 index 0000000000..756bcc6fb4 --- /dev/null +++ b/docs/dgl/wan/wan2-1-t2v-1-3b.dgl @@ -0,0 +1,45 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.1 T2V 1.3B + +var { + model_path = "../models/diffusion_models/wan2.1_t2v_1.3B_fp16.safetensors" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "wan2") + text = load_text_encoder(text_path, family = "wan2", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2") + + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-t2v-14b.dgl b/docs/dgl/wan/wan2-1-t2v-14b.dgl new file mode 100644 index 0000000000..848790a565 --- /dev/null +++ b/docs/dgl/wan/wan2-1-t2v-14b.dgl @@ -0,0 +1,45 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.1 T2V 14B + +var { + model_path = "../models/diffusion_models/wan2.1-t2v-14b-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-vace-1-3b-ref2video.dgl b/docs/dgl/wan/wan2-1-vace-1-3b-ref2video.dgl new file mode 100644 index 0000000000..b55492430f --- /dev/null +++ b/docs/dgl/wan/wan2-1-vace-1-3b-ref2video.dgl @@ -0,0 +1,71 @@ +# version: 0.0.0 +# docs/models/wan.md — R2V + +var { + model_path = "../models/diffusion_models/wan2.1-vace-1.3b-q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + first_frame_path = "../inputs/cat_with_sd_cpp_42.png" + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) + vace_reference = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + reference_context = tensor::concat([vace_reference, tensor::zeros_like(vace_reference)], axis = 3) + vace_pixels = tensor::concat([reference_context, vace_video], axis = 2) + vace_masks = tensor::pad(vace_mask, [0, 0, 0, 0, 1, 0]) + base = tensor::pad(video_base, [0, 0, 0, 0, 1, 0]) + vace_context = tensor::concat([vace_pixels, vace_masks], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, vace_context = vace_context) + neg = predictor(model, negative, vace_context = vace_context) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 1:])) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-vace-1-3b-txt2video.dgl b/docs/dgl/wan/wan2-1-vace-1-3b-txt2video.dgl new file mode 100644 index 0000000000..e9adb73115 --- /dev/null +++ b/docs/dgl/wan/wan2-1-vace-1-3b-txt2video.dgl @@ -0,0 +1,53 @@ +# version: 0.0.0 +# docs/models/wan.md — T2V + +var { + model_path = "../models/diffusion_models/wan2.1-vace-1.3b-q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.png" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 1 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) + vace_context = tensor::concat([vace_video, vace_mask], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, vace_context = vace_context) + neg = predictor(model, negative, vace_context = vace_context) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, output_frames[:, :, :, 0]) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-vace-1-3b-video2video.dgl b/docs/dgl/wan/wan2-1-vace-1-3b-video2video.dgl new file mode 100644 index 0000000000..2032bf3769 --- /dev/null +++ b/docs/dgl/wan/wan2-1-vace-1-3b-video2video.dgl @@ -0,0 +1,84 @@ +# version: 0.0.0 +# docs/models/wan.md — V2V + +var { + model_path = "../models/diffusion_models/wan2.1-vace-1.3b-q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + first_frame_path = "../inputs/dance_girl.jpg" + control_video_path = "./post+depth" + output_path = "output.avi" + + prompt = "The girl is dancing in a sea of flowers, slowly moving her hands. There is a close - up shot of her upper body. The character is surrounded by other transparent glass flowers in the style of Nicoletta Ceccoli, creating a beautiful, surreal, and emotionally expressive movie scene with a white. transparent feel and a dreamyl atmosphere." + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 480 + height = 832 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn control_frame_pixels(index, args) { + pixels = image::to_f32(fit_canvas(args.frames[:, :, :, index], args.width, args.height, mode = "nearest"), channels = 3) + return tensor::unsqueeze(pixels, axis = 2) +} + +fn main() { + control_video_media = video::load(control_video_path, max_frames = frames, fps_num = fps, audio = false) + control_video = control_video_media.video.frames + control_count = tensor::shape(control_video)[3] + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) + control_indices = tensor::to_list(tensor::arange(0, control_count)) + control_parts = map(control_indices, process = control_frame_pixels, args = {frames = control_video, width = width, height = height}) + control_short = tensor::concat(control_parts, axis = 2) + control_pixels = tensor::pad(control_short, [0, 0, 0, 0, 0, frames - tensor::shape(control_short)[2]], value = 0.5) + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_pixels, rng = rng)) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) + vace_reference = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + reference_context = tensor::concat([vace_reference, tensor::zeros_like(vace_reference)], axis = 3) + vace_pixels = tensor::concat([reference_context, vace_video], axis = 2) + vace_masks = tensor::pad(vace_mask, [0, 0, 0, 0, 1, 0]) + base = tensor::pad(video_base, [0, 0, 0, 0, 1, 0]) + vace_context = tensor::concat([vace_pixels, vace_masks], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, vace_context = vace_context) + neg = predictor(model, negative, vace_context = vace_context) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 1:])) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-vace-14b-ref2video.dgl b/docs/dgl/wan/wan2-1-vace-14b-ref2video.dgl new file mode 100644 index 0000000000..392cd97d75 --- /dev/null +++ b/docs/dgl/wan/wan2-1-vace-14b-ref2video.dgl @@ -0,0 +1,71 @@ +# version: 0.0.0 +# docs/models/wan.md — R2V + +var { + model_path = "../models/diffusion_models/Wan2.1_14B_VACE-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + first_frame_path = "../inputs/cat_with_sd_cpp_42.png" + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) + vace_reference = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + reference_context = tensor::concat([vace_reference, tensor::zeros_like(vace_reference)], axis = 3) + vace_pixels = tensor::concat([reference_context, vace_video], axis = 2) + vace_masks = tensor::pad(vace_mask, [0, 0, 0, 0, 1, 0]) + base = tensor::pad(video_base, [0, 0, 0, 0, 1, 0]) + vace_context = tensor::concat([vace_pixels, vace_masks], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, vace_context = vace_context) + neg = predictor(model, negative, vace_context = vace_context) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 1:])) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-vace-14b-txt2video.dgl b/docs/dgl/wan/wan2-1-vace-14b-txt2video.dgl new file mode 100644 index 0000000000..3bc41ad954 --- /dev/null +++ b/docs/dgl/wan/wan2-1-vace-14b-txt2video.dgl @@ -0,0 +1,53 @@ +# version: 0.0.0 +# docs/models/wan.md — T2V + +var { + model_path = "../models/diffusion_models/Wan2.1_14B_VACE-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) + vace_context = tensor::concat([vace_video, vace_mask], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, vace_context = vace_context) + neg = predictor(model, negative, vace_context = vace_context) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-1-vace-14b-video2video.dgl b/docs/dgl/wan/wan2-1-vace-14b-video2video.dgl new file mode 100644 index 0000000000..372b230275 --- /dev/null +++ b/docs/dgl/wan/wan2-1-vace-14b-video2video.dgl @@ -0,0 +1,84 @@ +# version: 0.0.0 +# docs/models/wan.md — V2V + +var { + model_path = "../models/diffusion_models/Wan2.1_14B_VACE-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + first_frame_path = "../inputs/dance_girl.jpg" + control_video_path = "./post+depth" + output_path = "output.avi" + + prompt = "The girl is dancing in a sea of flowers, slowly moving her hands. There is a close - up shot of her upper body. The character is surrounded by other transparent glass flowers in the style of Nicoletta Ceccoli, creating a beautiful, surreal, and emotionally expressive movie scene with a white. transparent feel and a dreamyl atmosphere." + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 480 + height = 832 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn control_frame_pixels(index, args) { + pixels = image::to_f32(fit_canvas(args.frames[:, :, :, index], args.width, args.height, mode = "nearest"), channels = 3) + return tensor::unsqueeze(pixels, axis = 2) +} + +fn main() { + control_video_media = video::load(control_video_path, max_frames = frames, fps_num = fps, audio = false) + control_video = control_video_media.video.frames + control_count = tensor::shape(control_video)[3] + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) + control_indices = tensor::to_list(tensor::arange(0, control_count)) + control_parts = map(control_indices, process = control_frame_pixels, args = {frames = control_video, width = width, height = height}) + control_short = tensor::concat(control_parts, axis = 2) + control_pixels = tensor::pad(control_short, [0, 0, 0, 0, 0, frames - tensor::shape(control_short)[2]], value = 0.5) + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_pixels, rng = rng)) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) + vace_reference = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + reference_context = tensor::concat([vace_reference, tensor::zeros_like(vace_reference)], axis = 3) + vace_pixels = tensor::concat([reference_context, vace_video], axis = 2) + vace_masks = tensor::pad(vace_mask, [0, 0, 0, 0, 1, 0]) + base = tensor::pad(video_base, [0, 0, 0, 0, 1, 0]) + vace_context = tensor::concat([vace_pixels, vace_masks], axis = 3) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, vace_context = vace_context) + neg = predictor(model, negative, vace_context = vace_context) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 1:])) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-first-last-frame-a14b.dgl b/docs/dgl/wan/wan2-2-first-last-frame-a14b.dgl new file mode 100644 index 0000000000..3c41d8dfac --- /dev/null +++ b/docs/dgl/wan/wan2-2-first-last-frame-a14b.dgl @@ -0,0 +1,80 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.2 FLF2V 14B + +var { + model_path = "../models/diffusion_models/Wan2.2-I2V-A14B-LowNoise-Q8_0.gguf" + high_model_path = "../models/diffusion_models/Wan2.2-I2V-A14B-HighNoise-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + first_frame_path = "../inputs/start_image.png" + last_frame_path = "../inputs/end_image.png" + output_path = "output.avi" + + prompt = "glass flower blossom" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 480 + height = 832 + frames = 33 + fps = 16 + + steps = 18 + high_noise_steps = 8 + cfg_scale = 3.5 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + last_frame = image::load(last_frame_path) + + model = load_dit(model_path, family = "wan2_2_i2v", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2_2_i2v", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2_2_i2v", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + last_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(last_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + condition_blank = tensor::full([width, height, frames, 3, 1], 0.5) + condition_first = tensor::replace_slice(condition_blank, first_frame_pixels, axis = 2, start = 0) + condition_pixels = tensor::replace_slice(condition_first, last_frame_pixels, axis = 2, start = frames - 1) + condition_latent = vae_to_dit_latents(vae, vae_encode(vae, condition_pixels, rng = rng)) + condition_shape = tensor::shape(condition_latent) + mask_blank = tensor::zeros([condition_shape[0], condition_shape[1], condition_shape[2], 4, 1]) + first_mask = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 1) + last_mask = tensor::index_fill(first_mask[:, :, :, 3:4], axis = 2, indices = [condition_shape[2] - 1], value = 1) + image_mask = tensor::replace_slice(first_mask, last_mask, axis = 3, start = 3) + video_concat = tensor::concat([image_mask, condition_latent], axis = 3) + high_base = load_dit(high_model_path, family = "wan2_2_i2v", params_backend = "cpu") + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, concat = video_concat) + neg = predictor(model, negative, concat = video_concat) + guided = cfg(pos, neg, scale = cfg_scale) + high_pos = predictor(high_base, positive, concat = video_concat) + high_neg = predictor(high_base, negative, concat = video_concat) + high_guided = cfg(high_pos, high_neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + split = math::min(high_noise_steps, tensor::numel(sigmas) - 1) + handoff = sample(start, sigmas[:split + 1], predict = high_guided, method = method, rng = rng) + latent = sample(handoff, sigmas[split:], predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-i2v-a14b.dgl b/docs/dgl/wan/wan2-2-i2v-a14b.dgl new file mode 100644 index 0000000000..fb85a76105 --- /dev/null +++ b/docs/dgl/wan/wan2-2-i2v-a14b.dgl @@ -0,0 +1,74 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.2 I2V A14B + +var { + model_path = "../models/diffusion_models/Wan2.2-I2V-A14B-LowNoise-Q8_0.gguf" + high_model_path = "../models/diffusion_models/Wan2.2-I2V-A14B-HighNoise-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + first_frame_path = "../inputs/cat_with_sd_cpp_42.png" + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 18 + high_noise_steps = 8 + cfg_scale = 3.5 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2_2_i2v", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2_2_i2v", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2_2_i2v", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + condition_blank = tensor::full([width, height, frames, 3, 1], 0.5) + condition_pixels = tensor::replace_slice(condition_blank, first_frame_pixels, axis = 2, start = 0) + condition_latent = vae_to_dit_latents(vae, vae_encode(vae, condition_pixels, rng = rng)) + condition_shape = tensor::shape(condition_latent) + mask_blank = tensor::zeros([condition_shape[0], condition_shape[1], condition_shape[2], 4, 1]) + image_mask = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 1) + video_concat = tensor::concat([image_mask, condition_latent], axis = 3) + high_base = load_dit(high_model_path, family = "wan2_2_i2v", params_backend = "cpu") + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, concat = video_concat) + neg = predictor(model, negative, concat = video_concat) + guided = cfg(pos, neg, scale = cfg_scale) + high_pos = predictor(high_base, positive, concat = video_concat) + high_neg = predictor(high_base, negative, concat = video_concat) + high_guided = cfg(high_pos, high_neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + split = math::min(high_noise_steps, tensor::numel(sigmas) - 1) + handoff = sample(start, sigmas[:split + 1], predict = high_guided, method = method, rng = rng) + latent = sample(handoff, sigmas[split:], predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-s2v-14b.dgl b/docs/dgl/wan/wan2-2-s2v-14b.dgl new file mode 100644 index 0000000000..9a1c004e68 --- /dev/null +++ b/docs/dgl/wan/wan2-2-s2v-14b.dgl @@ -0,0 +1,70 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.2 S2V 14B + +var { + model_path = "../models/diffusion_models/wan2.2_s2v-14B-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + audio_encoder_path = "../models/text_encoders/audio_encoders/wav2vec2_large_english_fp16.safetensors" + + first_frame_path = "../inputs/cat_with_sd_cpp_42.png" + driving_audio_path = "./input/speech.wav" + output_path = "output.avi" + + prompt = "a person is talking" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 81 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + driving_audio_media = audio::load(driving_audio_path) + sample_rate = driving_audio_media.sample_rate + driving_audio = driving_audio_media.samples + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2_2_s2v", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2_2_s2v", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2_2_s2v", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + reference_video = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng, tiling = tiling())) + reference_shape = tensor::shape(reference_video) + reference_latent = tensor::reshape(reference_video, reference_shape[:4]) + audio_encoder = load_audio_encoder(audio_encoder_path, family = "wan2_2_s2v", params_backend = "cpu") + speech = encode_audio(audio_encoder, driving_audio, sample_rate = sample_rate) + audio_embedding = wan::s2v_audio_window(speech, latent_frames = tensor::shape(base)[2]) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, ref_latents = [reference_latent], audio_embedding = audio_embedding) + neg = predictor(model, negative, ref_latents = [reference_latent], audio_embedding = audio_embedding) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent), tiling = tiling()) + audio = {samples = driving_audio[:, :math::floor(sample_rate * frames / fps)], sample_rate = sample_rate} + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/dgl/wan/wan2-2-t2v-a14b-image.dgl b/docs/dgl/wan/wan2-2-t2v-a14b-image.dgl new file mode 100644 index 0000000000..ad1dc2a46c --- /dev/null +++ b/docs/dgl/wan/wan2-2-t2v-a14b-image.dgl @@ -0,0 +1,54 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.2 T2V A14B T2I + +var { + model_path = "../models/diffusion_models/Wan2.2-T2V-A14B-LowNoise-Q8_0.gguf" + high_model_path = "../models/diffusion_models/Wan2.2-T2V-A14B-HighNoise-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 9 + fps = 16 + + steps = 18 + high_noise_steps = 8 + cfg_scale = 3.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + high_base = load_dit(high_model_path, family = "wan2", params_backend = "cpu") + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + high_pos = predictor(high_base, positive) + high_neg = predictor(high_base, negative) + high_guided = cfg(high_pos, high_neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + split = math::min(high_noise_steps, tensor::numel(sigmas) - 1) + handoff = sample(start, sigmas[:split + 1], predict = high_guided, method = method, rng = rng) + latent = sample(handoff, sigmas[split:], predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-t2v-a14b-lora.dgl b/docs/dgl/wan/wan2-2-t2v-a14b-lora.dgl new file mode 100644 index 0000000000..53555ac457 --- /dev/null +++ b/docs/dgl/wan/wan2-2-t2v-a14b-lora.dgl @@ -0,0 +1,60 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.2 T2V 14B with Lora + +var { + model_path = "../models/diffusion_models/Wan2.2-T2V-A14B-LowNoise-Q8_0.gguf" + high_model_path = "../models/diffusion_models/Wan2.2-T2V-A14B-HighNoise-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + lora_0_path = "../models/loras/wan2.2_t2v_lightx2v_4steps_lora_v1.1_low_noise" + lora_1_path = "../models/loras/wan2.2_t2v_lightx2v_4steps_lora_v1.1_high_noise" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 8 + high_noise_steps = 4 + cfg_scale = 3.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + base_model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + lora_0 = load_lora(lora_0_path) + model = apply_lora(base_model, lora_0) + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + high_unpatched = load_dit(high_model_path, family = "wan2", params_backend = "cpu") + lora_1 = load_lora(lora_1_path) + high_base = apply_lora(high_unpatched, lora_1) + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + high_pos = predictor(high_base, positive) + high_neg = predictor(high_base, negative) + high_guided = cfg(high_pos, high_neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + split = math::min(high_noise_steps, tensor::numel(sigmas) - 1) + handoff = sample(start, sigmas[:split + 1], predict = high_guided, method = method, rng = rng) + latent = sample(handoff, sigmas[split:], predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-t2v-a14b.dgl b/docs/dgl/wan/wan2-2-t2v-a14b.dgl new file mode 100644 index 0000000000..2c8e6b2177 --- /dev/null +++ b/docs/dgl/wan/wan2-2-t2v-a14b.dgl @@ -0,0 +1,54 @@ +# version: 0.0.0 +# docs/models/wan.md — Wan2.2 T2V A14B + +var { + model_path = "../models/diffusion_models/Wan2.2-T2V-A14B-LowNoise-Q8_0.gguf" + high_model_path = "../models/diffusion_models/Wan2.2-T2V-A14B-HighNoise-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 18 + high_noise_steps = 8 + cfg_scale = 3.5 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + high_base = load_dit(high_model_path, family = "wan2", params_backend = "cpu") + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + high_pos = predictor(high_base, positive) + high_neg = predictor(high_base, negative) + high_guided = cfg(high_pos, high_neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + split = math::min(high_noise_steps, tensor::numel(sigmas) - 1) + handoff = sample(start, sigmas[:split + 1], predict = high_guided, method = method, rng = rng) + latent = sample(handoff, sigmas[split:], predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-ti2v-5b-img2video.dgl b/docs/dgl/wan/wan2-2-ti2v-5b-img2video.dgl new file mode 100644 index 0000000000..19b6a93ef8 --- /dev/null +++ b/docs/dgl/wan/wan2-2-ti2v-5b-img2video.dgl @@ -0,0 +1,63 @@ +# version: 0.0.0 +# docs/models/wan.md — I2V + +var { + model_path = "../models/diffusion_models/wan2.2_ti2v_5B_fp16.safetensors" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan2.2_vae.safetensors" + + first_frame_path = "../inputs/cat_with_sd_cpp_42.png" + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 480 + height = 832 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2_2_ti2v", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2_2_ti2v", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2_2_ti2v", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + video_shape = tensor::shape(video_base) + mask_blank = tensor::full([video_shape[0], video_shape[1], video_shape[2], 1, 1], 1) + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + base = tensor::replace_slice(video_base, first_latent, axis = 2, start = 0) + video_mask = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 0) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng, base = base, denoise_mask = video_mask, mask_input = true) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-ti2v-5b-txt2video.dgl b/docs/dgl/wan/wan2-2-ti2v-5b-txt2video.dgl new file mode 100644 index 0000000000..d4c69cf108 --- /dev/null +++ b/docs/dgl/wan/wan2-2-ti2v-5b-txt2video.dgl @@ -0,0 +1,45 @@ +# version: 0.0.0 +# docs/models/wan.md — T2V + +var { + model_path = "../models/diffusion_models/wan2.2_ti2v_5B_fp16.safetensors" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan2.2_vae.safetensors" + + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 480 + height = 832 + frames = 33 + fps = 16 + + steps = 20 + cfg_scale = 6.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "wan2_2_ti2v", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2_2_ti2v", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2_2_ti2v", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler, flow_shift = 3.0) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent)) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/wan/wan2-2-vace-fun-a14b-ref2video.dgl b/docs/dgl/wan/wan2-2-vace-fun-a14b-ref2video.dgl new file mode 100644 index 0000000000..46120ca5b0 --- /dev/null +++ b/docs/dgl/wan/wan2-2-vace-fun-a14b-ref2video.dgl @@ -0,0 +1,80 @@ +# version: 0.0.0 +# docs/models/wan.md — R2V + +var { + model_path = "../models/diffusion_models/Wan2.2-VACE-Fun-A14B-low-noise-Q8_0.gguf" + high_model_path = "../models/diffusion_models/Wan2.2-VACE-Fun-A14B-high-noise-Q8_0.gguf" + text_path = "../models/text_encoders/umt5-xxl-encoder-Q8_0.gguf" + vae_path = "../models/vae/wan_2.1_vae.safetensors" + + first_frame_path = "../inputs/cat_with_sd_cpp_42.png" + output_path = "output.avi" + + prompt = "a lovely cat" + negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部, 畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" + + seed = 42 + rng_type = "cuda" + width = 832 + height = 480 + frames = 33 + fps = 16 + + steps = 18 + high_noise_steps = 8 + cfg_scale = 3.5 + method = "euler" + scheduler = "discrete" +} + +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn main() { + first_frame = image::load(first_frame_path) + + model = load_dit(model_path, family = "wan2", params_backend = "cpu") + text = load_text_encoder(text_path, family = "wan2", params_backend = "cpu", t5_path = text_path) + vae = load_vae(vae_path, family = "wan2", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = rng)) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) + vace_reference = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = rng)) + reference_context = tensor::concat([vace_reference, tensor::zeros_like(vace_reference)], axis = 3) + vace_pixels = tensor::concat([reference_context, vace_video], axis = 2) + vace_masks = tensor::pad(vace_mask, [0, 0, 0, 0, 1, 0]) + base = tensor::pad(video_base, [0, 0, 0, 0, 1, 0]) + vace_context = tensor::concat([vace_pixels, vace_masks], axis = 3) + high_base = load_dit(high_model_path, family = "wan2", params_backend = "cpu") + + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive, vace_context = vace_context) + neg = predictor(model, negative, vace_context = vace_context) + guided = cfg(pos, neg, scale = cfg_scale) + high_pos = predictor(high_base, positive, vace_context = vace_context) + high_neg = predictor(high_base, negative, vace_context = vace_context) + high_guided = cfg(high_pos, high_neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + split = math::min(high_noise_steps, tensor::numel(sigmas) - 1) + handoff = sample(start, sigmas[:split + 1], predict = high_guided, method = method, rng = rng) + latent = sample(handoff, sigmas[split:], predict = guided, method = method, rng = rng) + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 1:])) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = {}) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {}} +} diff --git a/docs/dgl/z_image/z-image-base-txt2img.dgl b/docs/dgl/z_image/z-image-base-txt2img.dgl new file mode 100644 index 0000000000..37f5fc3cf1 --- /dev/null +++ b/docs/dgl/z_image/z-image-base-txt2img.dgl @@ -0,0 +1,43 @@ +# version: 0.0.0 +# docs/models/z_image.md — Z-Image-Base + +var { + model_path = "../models/diffusion_models/z_image_bf16.safetensors" + text_path = "../models/text_encoders/qwen_3_4b.safetensors" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + negative_prompt = "" + prompt = "A cinematic, melancholic photograph of a solitary hooded figure walking through a sprawling, rain-slicked metropolis at night. The city lights are a chaotic blur of neon orange and cool blue, reflecting on the wet asphalt. The scene evokes a sense of being a single component in a vast machine. Superimposed over the image in a sleek, modern, slightly glitched font is the philosophical quote: 'THE CITY IS A CIRCUIT BOARD, AND I AM A BROKEN TRANSISTOR.' -- moody, atmospheric, profound, dark academic" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 1024 + + steps = 20 + cfg_scale = 5.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "z_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "z_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "z_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/z_image/z-image-turbo-controlnet.dgl b/docs/dgl/z_image/z-image-turbo-controlnet.dgl new file mode 100644 index 0000000000..890df2ba2d --- /dev/null +++ b/docs/dgl/z_image/z-image-turbo-controlnet.dgl @@ -0,0 +1,46 @@ +# version: 0.0.0 + +var { + dit_path = "z_image_turbo_bf16.safetensors" + encoder_path = "qwen_3_4b.safetensors" + vae_path = "ae.sft" + controlnet_path = "z-image-control.safetensors" + + input_path = "pose.png" + output_path = "z-image-controlnet.png" + + prompt = "A dancer in a bright studio" + + seed = 42 + width = 512 + height = 512 + + steps = 8 +} + +fn z_image_control_hint(vae, image, rng) { + encoded = vae_encode(vae, image, rng = rng, posterior = "mode") + latent = vae_to_dit_latents(vae, encoded) + return tensor::pad(latent, [0, 0, 0, 0, 0, 17]) +} + +fn main() { + dit = load_dit(dit_path, family = "z_image") + text = load_text_encoder(encoder_path, family = "z_image") + vae = load_vae(vae_path, family = "z_image") + control = controlnet::load(controlnet_path, family = "z_image") + pose = tensor::interpolate(image::load(input_path), size = [width, height], axes = [1, 2]) + rng = make_rng("cuda", seed = seed) + hint = z_image_control_hint(vae, pose, rng) + condition = controlnet::apply(encode_prompt(text, prompt, width = width, height = height), + control, hint, strength = 0.8) + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + noise = tensor::randn_like(base, rng = rng) + sampling_predictor = predictor(dit, condition) + sigmas = make_sigmas(sampling_predictor, latent = base, scheduler = "discrete", steps = steps) + start = add_noise(sampling_predictor, base, noise, sigma = sigmas[0]) + latent = sample(start, sigmas, predict = sampling_predictor, method = "euler", rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return { image = image, latent = latent } +} diff --git a/docs/dgl/z_image/z-image-turbo-txt2img.dgl b/docs/dgl/z_image/z-image-turbo-txt2img.dgl new file mode 100644 index 0000000000..1f7600fda3 --- /dev/null +++ b/docs/dgl/z_image/z-image-turbo-txt2img.dgl @@ -0,0 +1,38 @@ +# version: 0.0.0 +# docs/models/z_image.md — Z-Image-Turbo + +var { + model_path = "../models/diffusion_models/z_image_turbo-Q3_K.gguf" + text_path = "../models/text_encoders/Qwen3-4B-Instruct-2507-Q4_K_M.gguf" + vae_path = "../models/vae/ae.sft" + + output_path = "output.png" + + prompt = "A cinematic, melancholic photograph of a solitary hooded figure walking through a sprawling, rain-slicked metropolis at night. The city lights are a chaotic blur of neon orange and cool blue, reflecting on the wet asphalt. The scene evokes a sense of being a single component in a vast machine. Superimposed over the image in a sleek, modern, slightly glitched font is the philosophical quote: 'THE CITY IS A CIRCUIT BOARD, AND I AM A BROKEN TRANSISTOR.' -- moody, atmospheric, profound, dark academic" + + seed = 42 + rng_type = "cuda" + width = 512 + height = 1024 + + steps = 8 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "z_image", params_backend = "cpu") + text = load_text_encoder(text_path, family = "z_image", params_backend = "cpu") + vae = load_vae(vae_path, family = "z_image", params_backend = "cpu") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + condition = encode_prompt(text, prompt, width = width, height = height) + predict = predictor(model, condition) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/dgl/z_image_l2p/z-image-l2p-txt2img.dgl b/docs/dgl/z_image_l2p/z-image-l2p-txt2img.dgl new file mode 100644 index 0000000000..5521b7f786 --- /dev/null +++ b/docs/dgl/z_image_l2p/z-image-l2p-txt2img.dgl @@ -0,0 +1,42 @@ +# version: 0.0.0 +# docs/models/z_image_l2p.md — Text-to-image + +var { + model_path = "../models/diffusion_models/model-1k-merge.safetensors" + text_path = "../models/text_encoders/qwen_3_4b.safetensors" + + output_path = "z_image_l2p.png" + + prompt = "an origami pig on fire in the middle of a dark room with a pentagram on the floor" + negative_prompt = "" + + seed = 42 + rng_type = "cuda" + width = 1024 + height = 1024 + + steps = 30 + cfg_scale = 2.0 + method = "euler" + scheduler = "discrete" +} + +fn main() { + model = load_dit(model_path, family = "z_image_l2p", wtype = "bf16") + text = load_text_encoder(text_path, family = "z_image_l2p", wtype = "bf16") + vae = load_vae(model_path, family = "z_image_l2p", wtype = "bf16") + + base = tensor::zeros(latent_shape(vae, width = width, height = height)) + positive = encode_prompt(text, prompt, width = width, height = height) + negative = encode_prompt(text, negative_prompt, width = width, height = height) + pos = predictor(model, positive) + neg = predictor(model, negative) + guided = cfg(pos, neg, scale = cfg_scale) + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = rng) + image = vae_decode(vae, dit_to_vae_latents(vae, latent)) + image::save(output_path, image) + return {image = image, latent = latent} +} diff --git a/docs/ecosystem.md b/docs/ecosystem.md index dc150c2e0d..f5a4fd7822 100644 --- a/docs/ecosystem.md +++ b/docs/ecosystem.md @@ -30,3 +30,4 @@ applications that integrate it as an image generation backend. - [NodeTool](https://github.com/nodetool-ai/nodetool) - [Quo](https://github.com/quo-ai/quo) - [Prisme](https://github.com/d3Ita/prisme) +- [Off Grid AI](https://github.com/off-grid-ai/OGAD) diff --git a/docs/embeddings.md b/docs/embeddings.md new file mode 100644 index 0000000000..49c4fe6826 --- /dev/null +++ b/docs/embeddings.md @@ -0,0 +1,108 @@ +# Textual Inversion Embeddings + +Textual inversion embeddings add a new trigger word (or a few vectors) to the +CLIP text encoder. They are supported for **SD 1.x, SD 2.x and SDXL** +checkpoints, which use `FrozenCLIPEmbedderWithCustomWords`. Other families +(SD3, FLUX, Qwen Image, ...) do not use this code path and ignore `--embd-dir`. + +Supported weight files are `.safetensors`, `.pt`, `.ckpt` and `.gguf`. + +## Directory layout + +Point `--embd-dir` at the folder holding the embedding files. Only the top +level of the directory is scanned; subdirectory files are not discovered: + +```sh +./bin/sd-cli -m ../models/v1-5-pruned-emaonly.safetensors \ + --embd-dir ../models/embeddings \ + -p "easynegative, girl playing the guitar" \ + --steps 20 -o output.png +``` + +The trigger word defaults to the file name without its extension. For +`embeddings/easynegative.safetensors` the trigger word is `easynegative`. + +Run with `-v` to list the discovered embeddings at startup: + +```text +embedding_dir: "/path/to/embeddings", +embeddings: { + "easynegative": "/path/to/embeddings/easynegative.safetensors", + ... +} +``` + +The same `--embd-dir` startup option applies to `sd-server`; prompts sent to +the server resolve the same way. + +## Using embeddings in prompts + +The CLI and the server both accept the two forms below in `prompt` and +`negative_prompt`. Prompt weights, token chunks and SDXL dual-CLIP +zero-padding still apply. + +### 1. Bare trigger word via `--embd-dir` + +Type the trigger word like any other word: + +```text +easynegative, girl playing the guitar +``` + +Before generation the prompt is scanned for `--embd-dir` file stems. +Matching is case-insensitive, longest-stem-first and word-boundary aware, and +existing `<...>` tags are left untouched. A match is rewritten to an explicit +`` tag with the stored file path, so the vectors replace token +embeddings before CLIP adds positional embeddings. + +Normal prompt weighting applies, so `(easynegative:1.2)` boosts it and +`[easynegative]` weakens it. + +### 2. Explicit `` tag + +Reference a file directly by path: + +```text +a lovely cat, +``` + +Rules: + +- The content is a file path, not a trigger word. Paths resolve from the + process working directory and are canonicalized before loading. The server + also requires the path to pass its model-directory allowlist. +- `` follows the same path and escaping rules as + ``. Use `\` for literal text. A bare filename + without `--embd-dir` is ordinary text in DGL `encode_prompt`; use the tag. +- The tag requires an SD 1.x, SD 2.x or SDXL CLIP encoder. Other encoders + reject it, and a missing file fails generation. +- A path may not contain `>`. +- Replacing the file invalidates the cached condition without rebuilding the + text encoder. + +Weight follows the normal attention syntax around the tag: + +```text +a lovely cat, (:0.8) +``` + +### DGL + +```dgl +text = load_text_encoder(model_path) +negative = encode_prompt(text, ", blurry") +``` + +No tokenizer aliases or loader `embeddings` argument are used. + +## Troubleshooting + +- `cannot inspect textual inversion '...'`: the path is wrong, the file is + unreadable, or file access (`SD_DGL_FILE_READ_MODEL` and the server + allowlist) rejected it. +- No visible effect: make sure the checkpoint is SD 1.x, SD 2.x or SDXL. + Other models reject embedding markers. +- Bare word does nothing: the file is not directly under `--embd-dir`, has an + unsupported extension, collided with another stem, or was split by prompt + weighting punctuation. Check the verbose startup listing for the exact key, + and prefer unique stems. diff --git a/docs/guides/backend.md b/docs/guides/backend.md index f7edddf592..53397fc4b6 100644 --- a/docs/guides/backend.md +++ b/docs/guides/backend.md @@ -1,12 +1,17 @@ # Backend selection +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + `stable-diffusion.cpp` has two backend assignments: - `--backend` selects the runtime backend used to execute model graphs. - `--params-backend` selects where model parameters are kept. -If `--params-backend` is not set, auto-fit chooses parameter placement. With -`--auto-fit off`, parameters use the same backend as their module runtime backend. +If `--params-backend` is not set, parameters are kept on their module runtime +backend and move to RAM or disk when it runs out of memory. Auto-fit can move +components to another GPU. ## Syntax @@ -16,6 +21,7 @@ A backend assignment can be a single backend name: sd-cli -m model.safetensors -p "a cat" --backend cpu ``` + This applies to every module that does not have a more specific assignment. Assignments can also target individual modules: @@ -24,29 +30,35 @@ Assignments can also target individual modules: sd-cli -m model.safetensors -p "a cat" --backend te=cpu,vae=cuda0,diffusion=vulkan0 ``` + The same syntax is used for parameter placement: ```shell sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend te=cpu,vae=cpu ``` + `--params-backend` also accepts the special value `disk`: ```shell sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend disk ``` + `--max-vram` can target resolved backend/device names: ```shell sd-cli -m model.safetensors -p "a cat" --backend diffusion=cuda0,vae=vulkan0 --max-vram cuda0=6,vulkan0=2 ``` -The value is a shared per-device budget for managed weights and registered -runner compute/cache buffers. Live free memory can lower the effective limit -for each graph run. Driver contexts and allocations made outside the managed -model runners are not part of this accounting, so it is not a hard physical -VRAM cap. + +The value is a shared per-device budget for managed weights, registered runner +compute and cache buffers, and idle buffers retained for reuse by ggml. The +runner trims the idle pool to make room for allocations. If a prefetch already +requires weight eviction, it can reuse a matching weight buffer directly. +Live free memory and a safety reserve also constrain allocations. Device-wide +VRAM usage can include driver contexts, unregistered backend scratch allocations, +and other processes. Module names are case-insensitive. Hyphens and underscores in module names are ignored, so `clip_vision`, `clip-vision`, and `clipvision` are equivalent. @@ -56,6 +68,7 @@ Module names are case-insensitive. Hyphens and underscores in module names are i sd-cli -m model.safetensors -p "a cat" --backend all=cuda0,te=cpu ``` + ## Multiple devices per module (layer split) A `--backend` module assignment can list several devices separated by `&`: @@ -64,6 +77,7 @@ A `--backend` module assignment can list several devices separated by `&`: sd-cli -m model.safetensors -p "a cat" --backend "diffusion=cuda0&cuda1" ``` + The module's transformer blocks are then distributed across the listed devices in contiguous ranges sized proportionally to each device's free memory (minus a compute-buffer headroom of about 2 GiB per device), and the @@ -78,11 +92,10 @@ applies to the dominant text encoder (`t5xxl` or the LLM); other modules accept only a single device. If the module has no recognizable transformer blocks, the assignment falls back to the first listed device. -`--params-backend` accepts no device lists. If the module has no explicit -params assignment, each block range's parameters are loaded directly to (and, -with `--params-backend diffusion=disk`, released directly from) its own device; -an explicit assignment such as `te=cpu` keeps the parameters on that backend -and stages each range to its device on demand. +`--params-backend` accepts no device lists. Each block range's parameters load +directly to its own device. A params assignment such as `te=cpu` or +`diffusion=disk` sets where the ranges move when device memory is needed, as +described in [weight residency](#weight-residency). Layer split uses the fixed graph-cut plan to assign blocks across devices, but single-device segmented execution and next-segment prefetch are disabled for @@ -102,6 +115,7 @@ sd-cli -m model.safetensors -p "a cat" --backend "diffusion=cuda0&cuda1" --split sd-cli -m model.safetensors -p "a cat" --backend "diffusion=cuda0&cuda1,te=cuda0&cuda1" --split-mode diffusion=row,te=layer ``` + In row mode the module keeps executing on its main (first listed) device, but its transformer-block matmul weights are allocated in the backend's row-split buffer type, which slices each weight's rows across the listed devices in @@ -139,9 +153,8 @@ the discrete GPU with the largest positive memory budget (the first device on a tie), falling back to integrated GPUs when no discrete GPU has a positive budget. An integrated GPU's shared system memory does not give it priority over a discrete GPU. Explicit assignments such as `--backend Vulkan1` still select that device. -It then derives parameter placements from the model metadata, each module's -compute devices, and the remaining memory budgets. The chosen backend -specifications are printed. +It then checks whether the weights fit the remaining memory budgets and moves +components to other GPUs when they do not. The plan is printed with `-v`. ```shell sd-cli -m model.safetensors -p "a cat" --auto-fit on @@ -151,6 +164,7 @@ sd-cli -m model.safetensors -p "a cat" --backend diffusion=cuda0,te=cpu,vae=cuda sd-cli -m model.safetensors -p "a cat" --auto-fit off ``` + Budgets reuse `--max-vram`: a positive per-device value caps what auto-fit plans with on that device, a negative value means "free memory minus that many GiB", and with no budget set each device's free memory minus a 512 MiB margin @@ -170,62 +184,37 @@ With `--mmap`, device-backed mappings count toward these budgets at their full mapped-file size, once per device buffer even when multiple parameter blocks share it. Mappings retained in the loader cache continue to count. -Components are considered in `diffusion`, `te`, `vae` order so that repeatedly -used diffusion weights have priority. Each component's weights use the first -storage location with enough remaining budget: - -1. The component's compute GPU, leaving estimated space for computation and weight staging. -2. CPU RAM, reserving the larger of 2 GiB or 10% of available RAM for other work. -3. Another GPU, choosing the one with the largest remaining budget that fits. -4. Disk, reloading weights on demand. - -GPU cache space follows the same component priority. Before a lower-priority -component can become permanently resident, the planner leaves room for the full -weights and estimated compute space of higher-priority offloaded components. -If offloaded diffusion already needs the entire main GPU budget, TE and VAE also -use offloaded parameters. GPU copies remain cached across sampling steps while -a component's execution is active and are released under memory pressure. -Ending a component's execution releases its staged GPU copies, disk-backed -weight buffers, temporary compute buffers and execution caches. Parameters -assigned permanently to a backend remain resident. Hires model upscaling shares -the runtime budget and can -reclaim idle weight copies from other components. -Reclamation releases idle compute buffers first, then cached weight allocations -until the current work fits. Weights used by active computation or pending +Auto-fit plans with whole-component weight sizes and a compute reserve of +2 GiB for `diffusion` and `te` and 1 GiB for other components. Components keep +their runtime backend as their params backend; weights that do not fit move to +RAM, then disk, as described in [weight residency](#weight-residency). When the +main GPU and the RAM available for weights cannot hold all weights, components +other than `diffusion` move to another GPU, starting from the lowest priority in +`diffusion`, `te`, `vae` order. A component moves only to a GPU whose remaining +budget holds all of its weights and compute reserve, and it then runs there and +keeps its weights there. Components with an explicit `--backend` assignment are +not moved. A GPU exposed by several backends, such as CUDA and Vulkan, counts +once. + +Hires model upscaling shares the runtime budget and can reclaim idle weight +copies from other components. Weights used by active computation or pending transfers stay protected. -For CPU computation with disk-backed parameters, cached weights are released -when execution ends so they do not accumulate in RAM across components. -CPU parameter residency allows GPU weight caching; it does not force every -weight to be copied again at every step. - -RAM and GPU budgets are shared across components. Each component uses a single -parameter backend; several other GPUs' capacities are not combined to store -one component. If available RAM cannot be queried, RAM residency is skipped. -Weights stored on another GPU are copied to the component's compute devices for -execution. CPU modules use RAM or disk. Compute reserves and cache priority are -accounted for separately on each device, so a CPU module does not reserve GPU -space. Storage on another module's GPU also leaves room for that module's work. Auto-fit does not select multi-GPU layer/row computation itself. Explicit device lists and `--split-mode` still control that computation. Before the runners have built their split plans, auto-fit conservatively counts the full component size -on each listed GPU when checking residency and cache space. This can offload -parameters even when a split layout would fit; use `--auto-fit off` to keep the -default split-device parameter placement. +on each listed GPU when checking whether weights fit. This can move other +components to another GPU even when a split layout would fit; use +`--auto-fit off` to keep every component on its selected backend. For example, a diffusion model whose full weights exceed the main GPU's budget -can use `--backend diffusion=cuda0 --params-backend diffusion=cpu` when RAM is -sufficient. Automatic graph segmentation can then load the required weights -for each segment and reclaim idle GPU copies. `--disable-segmented-compute` -still disables segmentation. - -Initial compute reserves are estimates (2 GiB for diffusion and text encoders, -1 GiB for VAE); higher-priority placements also leave staging space for the -largest weight tensor of each lower-priority offloaded component. Actual segment -weights, compute buffers and caches must -still fit the runner's capacity checks. Offloading weights does not guarantee -that every resolution or frame count will fit, and auto-fit does not change a -component to CPU computation solely because its full weights exceed VRAM. +keeps the weights that fit on the GPU and stores the rest in RAM. Automatic graph +segmentation then loads the required weights for each segment. +`--disable-segmented-compute` still disables segmentation. Compute reserves are +estimates. Actual segment weights, compute buffers and caches must still fit the +runner's capacity checks, so not every resolution or frame count is guaranteed to +fit, and auto-fit does not change a component to CPU computation solely because +its full weights exceed VRAM. If a VAE decode fails, decoding retries with spatial tiling even when `--auto-fit` is off; supported video decoders try temporal tiling first and can then add spatial tiling. Spatial retries use half-size tiles along each latent dimension. @@ -241,6 +230,7 @@ sd-cli -m model.safetensors -p "a cat" --conv-direct auto,vae=off sd-cli -m model.safetensors -p "a cat" --conv-direct off,diffusion=on ``` + - `on` requests direct 2D and 3D convolution. - `off` uses the existing im2col-based convolution paths. - `auto` first checks support for a representative F16-weight/F32-input direct @@ -291,6 +281,7 @@ sd-cli -m model.safetensors -p "a cat" --flash-attn auto,te=off,vae=on sd-cli -m model.safetensors -p "a cat" --flash-attn off,diffusion=auto ``` + Supported modules are `diffusion`, `te`, `clip_vision`, `vae`, `controlnet`, and `audio_encoder`. Modules without an assignment use the default (`auto` if no default is supplied). A bare mode or `all=`, `default=`, or `*=` sets the default; @@ -351,6 +342,7 @@ sd-cli -m model.safetensors -p "a cat" --flash-attn auto sd-cli -m model.safetensors -p "a cat" --flash-attn off ``` + ## Modules | Module | Purpose | Accepted names | @@ -391,7 +383,8 @@ For example: sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend cpu ``` -This runs all modules on `cuda0`, but stores parameters in CPU RAM. During execution, parameters are moved to the runtime backend as needed. + +This runs all modules on `cuda0` and keeps parameters in CPU RAM. Each module copies the parameters it needs to `cuda0` while it runs. For example: @@ -399,9 +392,65 @@ For example: sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend disk ``` -This runs all modules on `cuda0`, reloads parameters from the model file as needed, and releases those parameter buffers after use. -Outside `--auto-fit`, `disk` is never selected implicitly. If `--params-backend` is not set, parameters use the runtime backend. +This runs all modules on `cuda0` and reloads parameters from the model file instead of keeping them in RAM. + +`disk` is never selected implicitly. If `--params-backend` is not set, parameters are kept on the runtime backend. + +## Weight residency + +Weights load into their params backend on first use. When a location runs out +of memory, weights move down a residency chain: + +| `--params-backend` | Residency chain | +| --- | --- | +| Not set, or the runtime backend | runtime device, RAM, disk | +| Another GPU | that GPU, RAM, disk | +| `cpu` | RAM, disk | +| `disk` | disk | + +With `--mmap`, weights read from the mapped model file skip RAM because +reloads come from the page cache. Weights used by an operation that the compute +device cannot run, such as INT8 tensorwise embeddings, are stored in RAM. + +A first load does not displace weights already resident in the params backend +unless they belong to another component that is needed no sooner. Otherwise the +new weights start at the next location on the chain. With CPU params and GPU +compute, weights that do not fit in RAM can load directly from the model file +into their compute buffers. Weights that need host storage still require RAM. + +When a weight leaves a location, it is released if the next location already +holds a copy, and copied there otherwise. If the next location lacks capacity, +weights there with a lower priority are released to make room; they are not +copied further. If room still cannot be made, the weight moves on to the +following location. Reaching disk releases the weight without writing to the +model file. Weights needed sooner by the current plan, then more recently used +weights, have priority. + +Weights stored away from the compute device are copied to it while a component +runs. These copies are released when the component finishes, so `cpu`, +another GPU, or `disk` keeps device memory free between components. Copies of +weights whose params backend is the compute device, made after those weights +moved to RAM or disk, stay until device memory is needed. When device memory is +needed, GPU originals of weights with a separate merged LoRA copy move first, +then copies that can be dropped, then resident weights that must be copied to +the next location, then idle compute buffers. The capacity check that decides +whether a graph needs segmentation counts the same actions. + +`--eager-load` reads weights when a model loads instead of on first use. Each +weight takes the highest location on its chain with free capacity, leaving a +2 GiB compute reserve on GPUs, without releasing resident weights. Weights that +do not fit load on first use. + +Weights with an immediately applied LoRA follow the same chain. Releasing a +merged weight to disk discards the merge, and the next use merges again. When +immediate LoRA application stages a separate compute copy of shared weights, +the unmerged originals also follow the chain; if no location can hold them, +compute copies load from the model file. Later LoRA variants reuse cached +originals when available. When merged copies are released from the GPU, +available RAM can cache them for later use unless the weights prefer disk. +During a batched immediate merge, disk-resident weights can use temporary RAM +to retain their merged values until the graph's weights are ready. Per-module assignments can be mixed: @@ -409,6 +458,7 @@ Per-module assignments can be mixed: sd-cli -m model.safetensors -p "a cat" --backend diffusion=cuda0,te=cpu,vae=cpu --params-backend diffusion=cuda0,te=cpu,vae=cpu ``` + This keeps text encoding and VAE execution on CPU while the diffusion model runs on GPU. ## Backend sharing and lifetime @@ -427,7 +477,7 @@ uses one shared CPU backend for both `te` and `vae` runtime execution. Runtime and parameter assignments also share the same backend cache. If `--backend diffusion=cuda0` and `--params-backend diffusion=cuda0` resolve to the same device, both use the same backend instance. -`--params-backend disk` does not create a separate backend instance. Parameters are loaded lazily using the module runtime backend. +`--params-backend disk` does not create a separate backend instance. Parameters are loaded on use with the module runtime backend. `SDBackendManager` owns the backend instances and frees them when the context or upscaler is destroyed. Model runners receive non-owning runtime and parameter backend pointers and do not free them. @@ -448,7 +498,7 @@ The example CLI/server still accepts these older CPU placement flags as compatib --params-backend '*=cpu' ``` -Because this default is inserted first, later explicit `--params-backend` entries can still override it, for example `--offload-to-cpu --params-backend te=disk` keeps non-TE parameters on CPU and reloads TE parameters from disk. +Because this default is inserted first, later explicit `--params-backend` entries can still override it, for example `--offload-to-cpu --params-backend te=disk` makes non-TE parameters prefer CPU RAM and TE parameters prefer disk. Library callers should set `backend` and `params_backend` directly. `sd_ctx_params_init()` enables `auto_fit` by default; a nonempty `params_backend` assignment disables it. diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index 055056d57e..0ee98d30be 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -1,5 +1,8 @@ # C API +Handwritten equivalents of the generated image/video programs are available in +the [DGL documentation examples](../dgl/README.md). + Use purpose-specific opaque options for model loading, generation and postprocessing, and opaque `sd_result_t` objects to read generated outputs. The library allocates and @@ -42,7 +45,7 @@ int generate(const char* model_path) { for (size_t i = 0; i < sd_result_get_image_count(result); ++i) { const sd_tensor_t* image = sd_result_get_image(result, i); const char* info = sd_result_get_generation_info(result, i); - /* Read pixels with sd_tensor_data(image), and consume the UTF-8 JSON info. */ + /* Read pixels with sd_tensor_data(image), and consume the UTF-8 DGL source. */ (void) image; (void) info; } @@ -59,6 +62,33 @@ cleanup: } ``` +`sd_ctx_create()` retains the model configuration. The first generation call +loads the components it needs and reports any loading errors through its return +status. Weight residency follows `eager_load` and the memory budgets. Capability +queries can probe the model family and reuse the detected type. Components stay +loaded between generation calls. With `run_once`, read when the context is +created, each component is released after its last use in a generation run +instead, and every run, including each image of a batch, loads the components +again. + +Use `sd_ctx_set_model_options()` on an idle context to replace its model +configuration. It copies the options and resets model detection. Later +`sd_generate_image()` and `sd_generate_video()` calls use the new configuration. +Use `sd_ctx_set_model_options_for_generation()` to probe the candidate against +`SD_RESULT_IMAGE` or `SD_RESULT_VIDEO` before applying it. A failed check +preserves the current configuration. Model setters return `SD_STATUS_BUSY` +while model probing is in progress, including from file-access callbacks. +The execution settings and component cache continue to serve generation and the +DGL context borrowed through `sd_ctx_get_dgl_ctx()`. The borrowed pointer stays +valid until `sd_ctx_free()`. Run scripts and generation calls one at a time. Set +file-access callbacks for generated programs and scripts through +`sd_ctx_set_file_access_callback()` and `sd_dgl_ctx_set_file_access_callback()` +respectively. + +Use `sd_dgl_ctx_unload_models()` to release cached model components and reload +them on demand. It clears idle buffer caches on supported backends and returns +`SD_STATUS_BUSY` while the context is running a script or generation. + Use `sd_generate_video()` with options from `sd_vid_gen_opt_create()` to generate video. Its result exposes frames through the same image accessors, optional audio through `sd_result_get_audio()`, and effective frame rate through `sd_result_get_fps()`. @@ -87,10 +117,6 @@ are required and set to `NULL` on failure. All outputs use `sd_result_t`. | `sd_vid_gen_opt_create()` | `sd_generate_video()` | | `sd_upscaler_opt_create()` | `sd_upscaler_create()` | | `sd_upscale_opt_create()` | `sd_upscale()` | -| `sd_vid_upscaler_opt_create()` | `sd_vid_upscaler_create()` | -| `sd_vid_upscale_opt_create()` | `sd_upscale_video()` | -| `sd_adetailer_opt_create()` | `sd_adetailer_create()` | -| `sd_adetail_opt_create()` | `sd_adetail()` | Image upscaling loads `model_path` with optional `n_threads`, `backend`, `params_backend`, `conv_direct` and `tile_size` (default 128). Execution takes @@ -118,22 +144,20 @@ sd_upscaler_free(upscaler); sd_opt_free(load); ``` -Video-upscaler loading requires `diffusion_model_path`, `vae_path` and -`upscale_factor`; backend/thread/attention settings are optional. The scale must -match both checkpoints (RelayVSR uses 2 or 4). Execution takes RGB `frames` with -equal dimensions. Defaults are FPS 24, seed 42, RelayVSR `window_size` 16, and -SeedVR2 `temporal_chunk_size` 5. Free the model with `sd_vid_upscaler_free()`. - -ADetailer loading takes the detector `model_path` and optional backend/thread -settings. Call `sd_adetail(adetailer, diffusion_ctx, opt, &result)` with an -`sd_adetail_opt_t`. Set `image` for the source image, and reuse the applicable -image-generation keys for inpainting: `prompt`, `negative_prompt`, dimensions, -strength, seed, sampling, LoRAs, cache, VAE tiling and circular axes. Inpainting -defaults to 512×512 and strength 0.4. `adetail.prompt` and -`adetail.negative_prompt` supply region prompt overrides; `adetail.args` accepts -the existing detector/mask/inpaint argument string documented by the CLI -`--extra-ad-args` option. Reference/control images, hires and batching are not -ADetailer options. Free the detector with `sd_adetailer_free()`. +ADetailer, independent video upscaling, AnimateDiff, PhotoMaker, PuLID, +IP-Adapter, custom preprocessing, SLG, timestep shifting and +automatic post-generation upscaling are explicit DGL workflows. Their former +C operation handles or parameter keys are unavailable. Ordinary ControlNet +remains supported with a configured model and a direct control image. + +Contexts retain configuration snapshots and a persistent DGL execution context. +Model metadata is probed lazily and cached with file dependencies. Creation can +succeed before a missing or invalid model is discovered by a capability query +or generation call. Component weights are loaded and reused by dgl. + +Reference inputs follow model defaults. Custom reference resizing, cropping, +position indexing and conditioning must be written in DGL; there is no +`ref_image_args` override string. ## String-valued modes @@ -261,8 +285,7 @@ needed independently. Types below correspond to `sd_opt_set_()`. `context`, `image` and `video` refer to model loading and image/video generation. Other operation labels match -the corresponding option constructor, such as `vid_upscale` for -`sd_vid_upscale_opt_create()`. +the corresponding option constructor, `upscaler` or `upscale`. Array lengths are supplied to setters; there are no separately writable count keys. Top-level keys retain their existing parameter meanings. Nested names map as follows: @@ -270,90 +293,115 @@ Top-level keys retain their existing parameter meanings. Nested names map as fol | Key prefix | Configuration | | --- | --- | | `sample.*` | Base sampling settings; `method`, `steps`, `sigmas`, `args` select the sampler, step count, custom schedule and extra arguments. | -| `high_noise_sample.*` | High-noise sampling settings for two-stage video models. | -| `sample.guidance.*` | Text/image CFG, distilled guidance and SLG settings. | +| `sample.guidance.*` | Text/image CFG and distilled guidance settings. | | `cache.*` | [Inference cache](caching.md) settings. | -| `hires.*` | High-resolution second pass and upscaling settings. | | `vae_tiling.*` | Spatial/temporal VAE tiling settings. | -| `photomaker.*` | PhotoMaker identity images/embedding and style strength. | -| `pulid.*` | PuLID identity embedding path and weight. | -| `image_preprocess.rules` | [Image preprocessing](image_preprocessing.md) rule string. | -The library supplies inference defaults. CLI/server inputs that are omitted do -not override them. Model recipes may supply presets; explicit startup options +The library supplies inference defaults. Omitted server inputs do not override +them. The CLI retains its historical seed default of 42; `--seed -1` requests +a random seed. Other omitted CLI inference options use the library defaults. +Model recipes may supply presets; explicit startup options and request fields take priority over recipe values. A supplied value equal to a default is still explicit and undergoes model applicability checks. Generation defaults include 512×512, a random seed (`-1`), 20 sampling steps, model-selected sampler/scheduler, text CFG 7, distilled guidance 3.5, strength -0.75, and disabled caching/hires/tiling. Image batches default to 1; videos default +0.75, and disabled caching/tiling. Image batches default to 1; videos default to 6 requested frames at 16 FPS, subject to model alignment. Omitted eta, flow shift and image CFG retain automatic defaults; do not pass infinity to request defaults. -Use `unset`. High-noise steps default to `-1` (automatic allocation). The high-noise pass -shares the base scheduler, sigmas, flow shift and timestep shifting; set those -through `sample.*`. Separate high-noise keys for these settings are not supported. +Use `unset`. Wan dual experts share one `sample.*` configuration and one +sigma sequence. `high_noise_sample.steps` defaults to -1: `sample.steps` is the +total, split using `moe_boundary` (default 0.875). With a nonnegative high-noise +count, the total is `sample.steps + high_noise_sample.steps`; the high-noise +expert runs that prefix and the low-noise expert runs the remaining steps. +Zero selects only the low-noise expert. Without a high-noise model this setting +is ignored. Custom sigmas fix the total; a positive high-noise count is adjusted +to retain the requested low-noise count when possible. Independent high-noise +CFG and sampler overrides still require dgl. + +Image and LTX/MiniMax-H3 video hires passes use the same DGL execution path. +Set `hires.enabled=true`. The default is latent bilinear upscaling by 2, +followed by refinement with the original model and prompt conditions. +`hires.steps=0` inherits the base step count; denoising strength defaults to +0.7. The automatic schedule uses `floor(steps / strength)` intervals and keeps +the last `steps + 1` entries. If strength is below 1 and rounding would leave +the full schedule in place, one extra interval is generated so the first sigma +is trimmed. Refinement still runs for the requested step count. `hires.sigmas` +supplies the complete refinement schedule and is used directly. + +`hires.target_width` and `hires.target_height` override the scale. Supplying +only one makes a square target. Output dimensions follow model alignment. +Image upscalers are `latent`, `latent_nearest`, `latent_nearest_exact`, +`latent_antialiased`, `latent_bicubic`, `latent_bicubic_antialiased`, `lanczos`, +`nearest`, `model`, or `none`. `model` requires `hires.model_path`; images use +an image upscaler and then VAE re-encoding. Videos accept latent interpolation +or a compatible latent upscaler. LTX learned upscalers determine their output +size and frame count from the checkpoint, overriding target dimensions; +audio duration and keyframe conditioning follow that output. H3 learned +upscalers use the requested target size. Other video families require an +explicit DGL refinement workflow. Sampler/scheduler values follow the [sampling guide](sampling.md); `"auto"` requests automatic selection. RNG values are `std_default`, `cuda`, `cpu`, `auto`. -Prediction modes are `auto`, `eps`, `v`, `edm_v`, `sd3_flow`, `flux_flow`, +Prediction modes are `auto`, `eps`, `v`, `edm_v`, `flow`, `flux_flow`, `sefi_flow`, `minit2i_flow`, `sensenova_u1_flow`, `flux3_flow`, `h3_av_flow`, `ming_image_flow`. Weight types use the names returned by `sd_type_name()`, plus `auto`. VAE formats are `auto`, `flux`, `sd3`, `flux2`, `wan`. LoRA apply modes are `auto`, `immediately`, `at_runtime`. Cache modes are `disabled`, `easycache`, `ucache`, `dbcache`, `taylorseer`, `cache_dit`, `spectrum`. Control types are `none`, `openpose`, `depth`, `scribble`, `canny`, `normal`, -`segment`, `tile`, `repaint`, with the existing aliases such as `hed` and `lineart`. Hires upscalers are `none`, `latent`, -`latent_nearest`, `latent_nearest_exact`, `latent_antialiased`, `latent_bicubic`, -`latent_bicubic_antialiased`, `lanczos`, `nearest`, `model`. +`segment`, `tile`, `repaint`, with the existing aliases such as `hed` and `lineart`. Integers must fit the underlying field (32 bits except `seed`, which is signed 64-bit). Dimensions, batch size, video frames, FPS and base steps are positive. Floating-point settings must be finite and fit float32; strength, denoising strength, percent/range settings and MOE boundary lie in [0, 1]. Custom sigma arrays are empty or strictly decreasing nonnegative finite values ending in zero, -with at least two entries. SLG layer indices are nonnegative integers. +with at least two entries. + +For SDXL's bundled VAE (no `vae_path`), generation emits +`conv_scale = 0.03125` in the generated DGL to avoid FP16 overflow. Set +`force_sdxl_vae_conv_scale = true` to apply the same scaling to an explicit +`vae_path`. TAE decoding retains its own scaling. | Key | Setter type | Operation | | --- | --- | --- | -| `adetail.args` | `string` | adetail | -| `adetail.negative_prompt` | `string` | adetail | -| `adetail.prompt` | `string` | adetail | | `attn_scale` | `float` | context | | `audio_encoder_path` | `string` | context | | `audio_vae_path` | `string` | context | | `auto_fit` | `bool` | context | -| `backend` | `string` | context, upscaler, vid_upscaler, adetailer | +| `backend` | `string` | context, upscaler | | `batch_count` | `int` | image | | `batched_cfg` | `bool` | context | -| `cache.bn_compute_blocks` | `int` | image, video, adetail | -| `cache.end_percent` | `float` | image, video, adetail | -| `cache.error_decay_rate` | `float` | image, video, adetail | -| `cache.fn_compute_blocks` | `int` | image, video, adetail | -| `cache.max_cached_steps` | `int` | image, video, adetail | -| `cache.max_continuous_cached_steps` | `int` | image, video, adetail | -| `cache.max_warmup_steps` | `int` | image, video, adetail | -| `cache.mode` | `string` | image, video, adetail | -| `cache.reset_error_on_compute` | `bool` | image, video, adetail | -| `cache.residual_diff_threshold` | `float` | image, video, adetail | -| `cache.reuse_threshold` | `float` | image, video, adetail | -| `cache.scm_mask` | `string` | image, video, adetail | -| `cache.scm_policy_dynamic` | `bool` | image, video, adetail | -| `cache.spectrum_flex_window` | `float` | image, video, adetail | -| `cache.spectrum_lam` | `float` | image, video, adetail | -| `cache.spectrum_m` | `int` | image, video, adetail | -| `cache.spectrum_stop_percent` | `float` | image, video, adetail | -| `cache.spectrum_w` | `float` | image, video, adetail | -| `cache.spectrum_warmup_steps` | `int` | image, video, adetail | -| `cache.spectrum_window_size` | `int` | image, video, adetail | -| `cache.start_percent` | `float` | image, video, adetail | -| `cache.taylorseer_n_derivatives` | `int` | image, video, adetail | -| `cache.taylorseer_skip_interval` | `int` | image, video, adetail | -| `cache.use_relative_threshold` | `bool` | image, video, adetail | -| `circular_x` | `bool` | image, video, adetail | -| `circular_y` | `bool` | image, video, adetail | +| `cache.bn_compute_blocks` | `int` | image, video | +| `cache.end_percent` | `float` | image, video | +| `cache.error_decay_rate` | `float` | image, video | +| `cache.fn_compute_blocks` | `int` | image, video | +| `cache.max_cached_steps` | `int` | image, video. Negative values mean no limit. | +| `cache.max_continuous_cached_steps` | `int` | image, video. Negative values mean no limit. | +| `cache.max_warmup_steps` | `int` | image, video | +| `cache.mode` | `string` | image, video | +| `cache.reset_error_on_compute` | `bool` | image, video | +| `cache.residual_diff_threshold` | `float` | image, video | +| `cache.reuse_threshold` | `float` | image, video | +| `cache.scm_mask` | `string` | image, video | +| `cache.scm_policy_dynamic` | `bool` | image, video | +| `cache.spectrum_flex_window` | `float` | image, video | +| `cache.spectrum_lam` | `float` | image, video | +| `cache.spectrum_m` | `int` | image, video | +| `cache.spectrum_stop_percent` | `float` | image, video | +| `cache.spectrum_w` | `float` | image, video | +| `cache.spectrum_warmup_steps` | `int` | image, video | +| `cache.spectrum_window_size` | `int` | image, video | +| `cache.start_percent` | `float` | image, video | +| `cache.taylorseer_n_derivatives` | `int` | image, video | +| `cache.taylorseer_skip_interval` | `int` | image, video | +| `cache.use_relative_threshold` | `bool` | image, video | +| `circular_x` | `bool` | image, video | +| `circular_y` | `bool` | image, video | | `clip_g_path` | `string` | context | | `clip_l_path` | `string` | context | -| `clip_skip` | `int` | image, video, adetail | +| `clip_skip` | `int` | image, video. Nonpositive values use the model default. | | `clip_vision_path` | `string` | context | | `conditioning_cache_size` | `int` | context | | `control_frames` | `tensor` | video | @@ -362,10 +410,10 @@ with at least two entries. SLG layer indices are nonnegative integers. | `control_strength` | `float` | image | | `control_type` | `string` | image | | `conv_direct` | `bool` | upscaler | -| `conv_direct_mode` | `string` | context, vid_upscaler | +| `conv_direct_mode` | `string` | context | | `diffusion_conv_direct` | `bool` | context | | `diffusion_flash_attn` | `bool` | context | -| `diffusion_model_path` | `string` | context, vid_upscaler | +| `diffusion_model_path` | `string` | context | | `disable_prefetch` | `bool` | context | | `disable_segmented_compute` | `bool` | context | | `eager_load` | `bool` | context | @@ -374,113 +422,82 @@ with at least two entries. SLG layer indices are nonnegative integers. | `enable_mmap` | `bool` | context | | `end_image` | `tensor` | video | | `flash_attn` | `bool` | context | -| `flash_attn_mode` | `string` | context, vid_upscaler | +| `flash_attn_mode` | `string` | context | | `force_sdxl_vae_conv_scale` | `bool` | context | -| `fps` | `int` | video, vid_upscale | -| `frames` | `tensor` | vid_upscale | -| `height` | `int` | image, video, adetail | +| `fps` | `int` | video | +| `height` | `int` | image, video | | `high_noise_diffusion_model_path` | `string` | context | -| `high_noise_sample.args` | `string` | video | -| `high_noise_sample.eta` | `float` | video | -| `high_noise_sample.guidance.distilled_guidance` | `float` | video | -| `high_noise_sample.guidance.img_cfg` | `float` | video | -| `high_noise_sample.guidance.slg.layer_end` | `float` | video | -| `high_noise_sample.guidance.slg.layer_start` | `float` | video | -| `high_noise_sample.guidance.slg.layers` | `ints` | video | -| `high_noise_sample.guidance.slg.scale` | `float` | video | -| `high_noise_sample.guidance.txt_cfg` | `float` | video | -| `high_noise_sample.method` | `string` | video | -| `high_noise_sample.steps` | `int` | video | -| `hires.denoising_strength` | `float` | image, video | -| `hires.enabled` | `bool` | image, video | -| `hires.model_path` | `string` | image, video | -| `hires.scale` | `float` | image, video | -| `hires.sigmas` | `floats` | image, video | -| `hires.steps` | `int` | image, video | -| `hires.target_height` | `int` | image, video | -| `hires.target_width` | `int` | image, video | -| `hires.upscale_tile_size` | `int` | image, video | -| `hires.upscaler` | `string` | image, video | -| `image` | `tensor` | upscale, adetail | -| `image_preprocess.rules` | `string` | image, video | +| `image` | `tensor` | upscale | | `init_image` | `tensor` | image, video | -| `ip_adapter_image` | `tensor` | image | -| `ip_adapter_path` | `string` | context | -| `ip_adapter_strength` | `float` | image | | `linear_scale` | `float` | context | +| `linear_type` | `string` | context, upscaler. `auto` (default), `i8`, `raw`, or module assignments such as `dit=i8,te=raw` | | `llm_path` | `string` | context | | `llm_vision_path` | `string` | context | | `lora_apply_mode` | `string` | context | -| `loras` | `loras` | image, video, adetail | +| `loras` | `loras` | image, video | | `mask_image` | `tensor` | image | +| `max_ram` | `string` | context | | `max_vram` | `string` | context | | `model_args` | `string` | context | -| `model_path` | `string` | context, upscaler, adetailer | +| `model_path` | `string` | context, upscaler | | `moe_boundary` | `float` | video | -| `motion_module_path` | `string` | context | -| `n_threads` | `int` | context, upscaler, vid_upscaler, adetailer | -| `negative_prompt` | `string` | image, video, adetail | -| `params_backend` | `string` | context, upscaler, vid_upscaler, adetailer | -| `photo_maker_path` | `string` | context | -| `photomaker.id_embed_path` | `string` | image | -| `photomaker.id_images` | `tensors` | image | -| `photomaker.style_strength` | `float` | image | +| `high_noise_sample.steps` | `int` | video; -1 or nonnegative | +| `hires.enabled` | `bool` | image, video | +| `hires.upscaler`, `hires.model_path` | `string` | image, video | +| `hires.scale` | `float` | image, video; positive, default 2 | +| `hires.target_width`, `hires.target_height` | `int` | image, video; 0 selects scale | +| `hires.steps` | `int` | image, video; 0 inherits base steps | +| `hires.denoising_strength` | `float` | image, video; 0.0001..1 | +| `hires.upscale_tile_size` | `int` | image model upscaling; default 128 | +| `hires.sigmas` | `floats` | image, video; optional refinement schedule | +| `n_threads` | `int` | context, upscaler | +| `negative_prompt` | `string` | image, video | +| `params_backend` | `string` | context, upscaler | | `prediction` | `string` | context | -| `prompt` | `string` | image, video, adetail | -| `pulid.id_embedding_path` | `string` | image | -| `pulid.id_weight` | `float` | image | -| `pulid_weights_path` | `string` | context | +| `prompt` | `string` | image, video | | `qwen_image_layers` | `int` | image | | `ref_audios` | `audios` | video | -| `ref_image_args` | `string` | image, video | | `ref_images` | `tensors` | image, video | | `ref_videos` | `videos` | video | | `rng_type` | `string` | context | | `rpc_servers` | `string` | context | +| `run_once` | `bool` | context | | `sage_attn` | `bool` | context | -| `sample.args` | `string` | image, video, adetail | -| `sample.eta` | `float` | image, video, adetail | -| `sample.flow_shift` | `float` | image, video, adetail | -| `sample.guidance.distilled_guidance` | `float` | image, video, adetail | -| `sample.guidance.img_cfg` | `float` | image, video, adetail | -| `sample.guidance.slg.layer_end` | `float` | image, video, adetail | -| `sample.guidance.slg.layer_start` | `float` | image, video, adetail | -| `sample.guidance.slg.layers` | `ints` | image, video, adetail | -| `sample.guidance.slg.scale` | `float` | image, video, adetail | -| `sample.guidance.txt_cfg` | `float` | image, video, adetail | -| `sample.method` | `string` | image, video, adetail | -| `sample.scheduler` | `string` | image, video, adetail | -| `sample.shifted_timestep` | `int` | image, video, adetail | -| `sample.sigmas` | `floats` | image, video, adetail | -| `sample.steps` | `int` | image, video, adetail | +| `sample.args` | `string` | image, video | +| `sample.eta` | `float` | image, video | +| `sample.flow_shift` | `float` | image, video | +| `sample.guidance.distilled_guidance` | `float` | image, video | +| `sample.guidance.img_cfg` | `float` | image, video | +| `sample.guidance.txt_cfg` | `float` | image, video | +| `sample.method` | `string` | image, video | +| `sample.scheduler` | `string` | image, video | +| `sample.sigmas` | `floats` | image, video | +| `sample.steps` | `int` | image, video | | `sampler_rng_type` | `string` | context | -| `seed` | `int` | image, video, vid_upscale, adetail | +| `seed` | `int` | image, video | | `split_mode` | `string` | context | -| `strength` | `float` | image, video, adetail | +| `strength` | `float` | image, video | | `t5xxl_path` | `string` | context | | `tae_preview_only` | `bool` | context | | `taesd_path` | `string` | context | -| `temporal_chunk_size` | `int` | vid_upscale | | `tensor_type_rules` | `string` | context | | `tile_size` | `int` | upscaler | | `tokenizer` | `string` | context | | `uncond_diffusion_model_path` | `string` | context | -| `upscale_factor` | `int` | vid_upscaler | | `vace_strength` | `float` | video | | `vae_conv_direct` | `bool` | context | | `vae_format` | `string` | context | -| `vae_path` | `string` | context, vid_upscaler | -| `vae_tiling.enabled` | `bool` | image, video, adetail | -| `vae_tiling.extra_tiling_args` | `string` | image, video, adetail | -| `vae_tiling.rel_size_h` | `float` | image, video, adetail | -| `vae_tiling.rel_size_w` | `float` | image, video, adetail | -| `vae_tiling.target_overlap` | `float` | image, video, adetail | -| `vae_tiling.temporal_tiling` | `bool` | image, video, adetail | -| `vae_tiling.tile_size_h` | `int` | image, video, adetail | -| `vae_tiling.tile_size_w` | `int` | image, video, adetail | +| `vae_path` | `string` | context | +| `vae_tiling.enabled` | `bool` | image, video | +| `vae_tiling.extra_tiling_args` | `string` | image, video | +| `vae_tiling.rel_size_h` | `float` | image, video | +| `vae_tiling.rel_size_w` | `float` | image, video | +| `vae_tiling.target_overlap` | `float` | image, video | +| `vae_tiling.temporal_tiling` | `bool` | image, video | +| `vae_tiling.tile_size_h` | `int` | image, video | +| `vae_tiling.tile_size_w` | `int` | image, video | | `video_frames` | `int` | video | -| `width` | `int` | image, video, adetail | -| `window_size` | `int` | vid_upscale | +| `width` | `int` | image, video | | `wtype` | `string` | context | ## Migration @@ -495,13 +512,39 @@ Create context/image/video options with the corresponding constructor, populate them through the shared typed setters, and use `sd_ctx_create()`, `sd_generate_image()` and `sd_generate_video()`. Read or retain outputs through `sd_result_get_*()` and `sd_tensor_retain()` and release the result with -`sd_result_free()`. ADetailer and image/video upscalers use purpose-specific opt constructors and -return the same opaque result type. Their former public parameter structures, -long positional signatures and bool-returning entry points have been removed. -Device selection and cancellation controls retain their interfaces. Preview -registration now uses a mode string and returns a status. - -Native generation JSON retains its existing schema and names, including -`sample_params.sample_method`; translate these to the corresponding option keys -(`sample.method`, etc.) when replaying metadata. See -[generation results and metadata](generation_metadata.md). +`sd_result_free()`. Standalone image upscaling retains its purpose-specific +options and actual-scale queries. ADetailer and standalone video-upscale C +handles have been removed; use explicit DGL workflows. + +Generation results now contain the exact executed DGL source. They no longer +contain generation JSON. See [generation results and metadata](generation_metadata.md). +Context creation is lazy, and model errors can first surface in a capability +query or generation call. Context options are copied, while media handles are +retained. Cancellation, progress and preview retain their public contracts. + +### DGL region results + +DGL regions are ordinary dictionaries with integer `width` and `height` fields +and an I64 `boxes` tensor shaped `[4,N]`. The dedicated region value kind has +been removed. `SD_DGL_VALUE_OPAQUE` remains `11` and `SD_DGL_VALUE_VOID` remains +`12`. + +Returning a region dict directly now gives a `SD_DGL_VALUE_DICT` root and flat +outputs `boxes`, `width` and `height`. Returning `{regions=r}` gives the flat +names `regions.boxes`, `regions.width` and `regions.height`. Replace root-region +exports such as `--tensor result boxes.npy` with `--tensor boxes boxes.npy`. +Coordinate tensors now use I64; cast old I32 files explicitly with +`tensor::cast(boxes, "i64")` before passing them to `regions::from_boxes`. + +Detection results are also ordinary dicts: F32 `xyxy` `[4,N]`, F32 `scores` +`[N]`, and I64 `class_ids` `[N]`, with at most 4,096 items. Empty results preserve +all three fields and ranks. `detections::detect`, `detections::filter`, +`detections::box_masks` and `detections::to_regions` replace the previous global +detection helpers. Use `detections::detect` followed by `detections::to_regions` +to replace the old direct-to-regions `detect` shortcut; detection executes once. + +Use `regions::from_boxes`, `regions::crop`, `regions::paste` and +`regions::plan_mask_crops` for rectangle and mask tasks. The previous global +region function names are no longer registered. See +[DGL rectangular regions](../dgl.md#rectangular-regions) for validation and +composition rules. diff --git a/docs/guides/caching.md b/docs/guides/caching.md index 66dfc27a00..3ddf5e984e 100644 --- a/docs/guides/caching.md +++ b/docs/guides/caching.md @@ -1,5 +1,9 @@ ## Caching +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + Caching methods accelerate diffusion inference by reusing intermediate computations when changes between steps are small. ### Conditioning Cache @@ -31,6 +35,7 @@ UCache caches the residual difference (output - input) and reuses it when input sd-cli -m model.safetensors -p "a cat" --cache-mode ucache --cache-option "threshold=1.5" ``` + #### Parameters | Parameter | Description | Default | @@ -67,11 +72,12 @@ Condition-level caching for DiT models. Caches and reuses outputs when input cha ### Cache-DIT (DiT Models) -For DiT models like FLUX and QWEN, use block-level caching modes. +For DiT models like FLUX and QWEN, these modes cache each model condition's +raw output. This path does not perform block-level caching. #### DBCache -Caches blocks based on L1 residual difference threshold: +Reuses whole-model input/output residuals when input changes pass the L1 difference threshold: ```bash --cache-mode dbcache --cache-option "threshold=0.25,warmup=4" @@ -79,7 +85,7 @@ Caches blocks based on L1 residual difference threshold: #### TaylorSeer -Uses Taylor series approximation to predict block outputs: +Uses Taylor series approximation to predict each condition's raw model output: ```bash --cache-mode taylorseer @@ -97,11 +103,15 @@ Combines DBCache and TaylorSeer: | Parameter | Description | Default | |-----------|-------------|---------| -| `Fn` | Front blocks to always compute | 8 | -| `Bn` | Back blocks to always compute | 0 | +| `Fn`, `Bn` | Legacy options: ignored with a warning; block counts are not supported | No effect | | `threshold` | L1 residual difference threshold | 0.08 | | `warmup` | Steps before caching starts | 8 | +Explicit `Fn`/`Bn` settings, including their former defaults, produce a warning. +The C API keys `cache.fn_compute_blocks` and `cache.bn_compute_blocks` remain +accepted for compatibility and also warn when set. They have no effect on cache +execution. Omitted options do not warn. + #### SCM Options Steps Computation Mask controls which steps can be cached: @@ -112,10 +122,10 @@ Steps Computation Mask controls which steps can be cached: Mask values: `1` = compute, `0` = can cache. -| Policy | Description | -|--------|-------------| -| `dynamic` | Check threshold before caching | -| `static` | Always cache on cacheable steps | +The native `--scm-policy` option is retained for compatibility. Its `dynamic` +and `static` values do not change this condition-level implementation: a mask +value of `1` forces computation; `0` permits reuse subject to the cache's gates +and available history. ```bash --scm-policy dynamic @@ -129,6 +139,7 @@ Spectrum uses Chebyshev polynomial fitting blended with Taylor extrapolation to sd-cli -m model.safetensors -p "a cat" --cache-mode spectrum ``` + #### Parameters | Parameter | Description | Default | diff --git a/docs/guides/edit.md b/docs/guides/edit.md index 942c395f3d..ac7ef2031a 100644 --- a/docs/guides/edit.md +++ b/docs/guides/edit.md @@ -1,114 +1,57 @@ -# Image Editing - -Image editing in `stable-diffusion.cpp` allows you to use reference images to guide the generation process, enabling tasks like identity preservation, style transfer, or layout modification. - - -## Supported Models - -Depending on the architecture, different models handle reference images differently. - -| Model | Default Preset | -| :--- | :--- | -| [**FLUX.1-Kontext-dev**](../models/kontext.md) | `flux_kontext` | -| [**LongCat Image Edit**](../models/longcat_image.md) | `longcat` | -| [**Qwen Image Edit**](../models/qwen_image_edit.md) | `qwen` | -| **Qwen Image LAYERED** | `qwen_layered` | -| [**Flux.2 [Dev] / Flux.2 [Klein]**](../models/flux2.md) | `flux2` | -| [**FLUX.3 Image Klein / Klein Base**](../models/flux3.md) | `flux2` | -| [**Boogu Image Edit**](../models/boogu_image.md) | `z_image_omni` | -| **Krea2 (Community Edit LoRAs)** | `krea2_ostris_edit` | -| [**Mage-Flow-Edit**](../models/mage_flow.md#image-editing) | `mage_flow` | -| [**LLaDA-Image**](../models/llada_image.md#image-editing) | `llada_image` | -| [**Fibo 2.0 Dev / Edit Turbo**](../models/fibo2.md#fibo-20-edit-turbo) | `fibo2` | -| **Anima (Community Edit LoRAs)** | `cosmos_reference` | - -Stable-diffusion.spp also supports basic Unet-based editing models like instruct-pix2pix or CosXL-Edit. This document is not about those. - ---- - -## Configuring Reference Modes (`--ref-image-args`) - -For a one-time input transform before reference presets and model processing, -including cropping, padding, and resizing algorithms, see [Image preprocessing](./image_preprocessing.md). - -Different DiT-based editing models require different configurations to process reference images correctly (e.g., whether to use a Vision Language Model (VLM) encoder or pass VAE-encoded images directly to the DiT). - -To simplify this, we provide **Presets**. By default, the system automatically selects the best preset based on the model architecture. However, you can override this using the `--ref-image-args` argument. - -### Usage -The `--ref-image-args` argument accepts a comma-separated list of key-value pairs: - -**Using a preset:** -`--ref-image-args "preset=qwen_layered"` - -**Using a preset with a specific override:** -`--ref-image-args "preset=krea2_edit,force_ref_timestep_zero=true"` - -### Available Presets - -| Preset | Primary Use Case | -| :--- | :--- | -| `flux_kontext` | FLUX.1 Kontext | -| `longcat` | LongCat Image Edit | -| `flux2` | FLUX.2 models | -| `fibo2` | Fibo 2.0 Dev / Edit Turbo | -| `qwen` | Qwen Image Edit | -| `qwen_layered` | Qwen Image Layered | -| `z_image_omni` | Boogu, Z-Image Omni | -| `krea2_ostris_edit` | Most Krea2 Community edit LoRAs (trained with Ostris script) | -| `mage_flow` | Mage-Flow-Edit | -| `krea2_edit` | Specifically for [lbouaraba/krea2edit](https://huggingface.co/conradlocke/krea2-identity-edit). (or similar) | -| `cosmos_reference` | For Anima | -| `default` | Uses the automatic detection based on model architecture. | - ---- - -## Advanced Parameter Reference - -If presets are insufficient, you can manually configure the following parameters via `--ref-image-args`: - -| Key | Type | Description | Allowed Values | -| :--- | :--- | :--- | :--- | -| `preset` | string | Overrides the automatic preset. | (See the Presets table above) | -| `pass_to_vlm` | bool | Whether reference images are passed to the VLM encoder. | `true`, `false` | -| `pass_to_dit` | bool | Whether VAE-encoded references are passed directly to the DiT. | `true`, `false` | -| `ref_index_mode` | string | Behavior of the RoPE index. | `fixed`, `increase`, `decrease` | -| `force_ref_timestep_zero` | bool | Forces timestep=0 for reference tokens. | `true`, `false` (Krea2 only) | -| `resize_before_vae` | bool | Whether reference images are resized before VAE encoding. | `true`, `false` | -| `resize_vae_to_target` | bool | Use output dimensions for every reference, overriding area-based sizing. | `true`, `false` | -| `resize_single_ref_to_target` | bool | Use output dimensions when exactly one reference is supplied. | `true`, `false` | -| `vae_size_buckets` | bool | Choose aligned dimensions within ±10% of the requested area, minimizing aspect-ratio cropping. Ignored when using output dimensions. | `true`, `false` | -| `vae_center_crop` | bool | Scale to cover the selected dimensions with Lanczos, then center-crop. Otherwise resize directly. | `true`, `false` | -| `vae_input_max_pixels` | int | VAE area budget, also capped by output area in ordinary resizing. With size buckets, this is the target area and output area does not cap it. | Integer | -| `vlm_use_vae_input` | bool | Reuse the resized/cropped VAE input for the VLM, before the VLM's own resize. Has no effect when `resize_before_vae=false`. | `true`, `false` | -| `vlm_resize_mode` | string | How to resize VLM reference inputs. | `longest_side`, `area`, `none` | -| `vlm_max_size` | int | Maximum VLM input size; interpreted according to `vlm_resize_mode`. | Integer | -| `vlm_min_size` | int | Minimum VLM input size; interpreted according to `vlm_resize_mode`. | Integer | -| `vlm_size` | int | Shortcut to set both VLM min and max size to the same value. | Integer | -| `ref_image_size` | string | MiniMax-H3 reference image sizing before VAE encoding. `match` scales each reference down to the generation's pixel area; `max` uses a 2048 px short edge. Only references above the limit are downscaled; each axis is then snapped to the nearest 32 px multiple (an axis of at least 16 px grows by at most 16 px, and references are never narrower than 32 px). | `match`, `max` | - -`ref_image_size` applies to `vid_gen` with MiniMax-H3 Ref2VA. Reference latents are attended to at every sampling step, so `max` can be several times slower. - -### Preset Default Values - -For a technical overview of how each preset is configured, see the table below. - -| Preset | VLM | RoPE Index | Cond Resize | Special Notes | -| :--- | :---: | :---: | :---: | :--- | -| `flux_kontext` | No | `fixed` | `none` | | -| `longcat` | Yes | `fixed` | `area` | | -| `flux2` | No | `increase` | `none` | | -| `fibo2` | Yes | `increase` | `longest` | Shared reference crops; clean reference timesteps; see [Fibo 2.0](../models/fibo2.md) | -| `qwen` | Yes | `increase` | `area` | | -| `qwen_layered` | Yes | `decrease` | `area` | | -| `mage_flow` | Yes | `increase` | `longest` | `vlm_max_size = 384`, VAE input resized to target | -| `z_image_omni` | Yes | `fixed` | `area` | | -| `krea2_ostris_edit`| Yes | `increase` | `area` | `force_ref_timestep_zero = true` | -| `krea2_edit` | Yes | `increase` | `longest` | `vlm_size = 768` | -| `cosmos_reference` | No | `fixed` | `none` | `resize_before_vae = false` | - -**Additional Default Notes:** -- **VLM Input Sizes:** For most presets, `vlm_max_size` and `vlm_min_size` are set to `-1`, meaning the values are model-dependent and handled automatically. In `area` mode they represent pixel area; in `longest_side` mode they represent a side length in pixels. -- **VAE Input Size:** `vae_input_max_pixels` defaults to $1024 \times 1024$ pixels (`1048576`). -- **VAE Geometry:** `resize_vae_to_target` defaults to `true` for Mage-Flow and LLaDA-Image. Fibo enables `resize_single_ref_to_target`, `vae_size_buckets`, and `vae_center_crop`. These options are otherwise `false`. Bucket dimensions use the model's alignment (normally 16, Qwen Image 32), with a minimum side of four alignment units; if no bucket fits, output dimensions are used. -- **Shared Encoder Input:** `vlm_use_vae_input` defaults to `true` for Fibo and Qwen Image 2.1, otherwise `false`. All these options can be overridden individually after selecting a preset. +# Image editing + +Reference images can guide identity, appearance, layout and instruction editing. +Pass them with `-r IMAGE` in the CLI or `ref_images` in the C API. The generated +DGL follows the selected model's default reference policy. + +`--img-cfg-scale` (`sample.guidance.img_cfg` in the C API) controls image guidance +for inpainting, UNet editing and supported reference-latent models such as +FLUX, Qwen Image Edit, LongCat and Mage Flow. A value other than 1 uses separate +positive, negative-with-image and negative-without-image predictions. The +generated DGL preserves this split during hires refinement. Models or inputs +that do not support image guidance report an error. + +## Model defaults + +| Model | Reference handling | +| --- | --- | +| FLUX.1 Kontext | VAE reference latents with fixed position indexing | +| FLUX.2 / FLUX.3 Klein | VAE reference latents with increasing position indexing | +| Qwen Image Edit | Vision inputs and VAE reference latents | +| Qwen Image 2.1 | Vision inputs derived from the VAE reference pixels | +| Qwen Image Layered | References use decreasing position indexing | +| Fibo 2.0 | Shared center crops for VAE and vision encoding; multiple references use aspect-ratio buckets | +| [Anima Edit](../models/anima.md) | Matching community editing LoRA; VAE reference latents | +| [Krea2 Edit](../models/krea2.md) | Matching community editing LoRA; vision inputs and VAE reference latents | +| [MOSS-Image Edit](../models/moss_image.md#moss-image-edit) | HQ LoRA with VAE reference latents and optional vision conditioning | +| LLaDA-Image | Reference pixels go to the text encoder's native image components and reference latents to the diffusion model | +| MiniMax-H3 | Aspect-preserving references aligned to the model grid | + +See the [model guides](../models/README.md) for required components and supported +editing checkpoints. Select community editing LoRAs separately; reference-image +inputs and editing recipes do not load them automatically. +Instruct-Pix2Pix and CosXL-Edit also use `-r` for their source +image; they construct concatenated image conditioning rather than DiT reference +token sequences. + +## Custom reference processing + +Reference-policy overrides are not native generation parameters. Write a DGL +program to choose resizing, cropping, model inputs and reference position rules. +`--ref-image-args` and the C API `ref_image_args` key have been removed. + +For example, a script can prepare its VAE input explicitly: + +```dgl +source = image::load("reference.png") +pixels = image::to_f32(tensor::interpolate(source, size = [1024, 768], axes = [1, 2])) +reference = vae_to_dit_latents(vae, vae_encode(vae, pixels, rng = rng)) +condition = encode_prompt(text, prompt, media = [pixels]) +pos = predictor(dit, condition, ref_latents = [reference], ref_index_mode = "increase") +``` + +These lines belong inside a complete DGL program with explicit model and RNG +loading. Start from the [Qwen Image 2.1 edit example](../dgl/qwen_image_2.1/qwen-image-2-1-edit.dgl). +Vision and VAE inputs can be prepared separately when a workflow needs different +reference images on those paths. Required model alignment and encoder-native +preprocessing still apply. diff --git a/docs/guides/generation_metadata.md b/docs/guides/generation_metadata.md index f24bda25fb..9cdaab65a3 100644 --- a/docs/guides/generation_metadata.md +++ b/docs/guides/generation_metadata.md @@ -1,166 +1,98 @@ # Generation results and metadata -`sd_generate_image()`, `sd_generate_video()`, `sd_adetail()`, `sd_upscale()` and -`sd_upscale_video()` return opaque `sd_result_t` objects containing generated media -and generation metadata. See the [C API guide](c_api.md) for option creation and -migration from the removed parameter/result structures. - -```c -sd_img_gen_opt_t* opt = sd_img_gen_opt_create(); -sd_result_t* result = NULL; -if (opt && sd_opt_set_string(opt, "prompt", "a small house") == SD_STATUS_OK && - sd_generate_image(ctx, opt, &result) == SD_STATUS_OK) { - for (size_t i = 0; i < sd_result_get_image_count(result); ++i) { - const sd_tensor_t* image = sd_result_get_image(result, i); - const char* info = sd_result_get_generation_info(result, i); - /* Consume image and info together. */ - } -} -sd_result_free(result); -sd_opt_free(opt); -``` - -`result_out` is required and set to `NULL` on failure. Successful results own -their pixels, audio and UTF-8 JSON independently of the generation context. -Video results expose effective FPS and frame count through accessors; each valid -frame index returns the shared video generation record. Result views are borrowed -until `sd_result_free()`. Use `sd_tensor_retain()` to keep media independently, -and release the retained handle with `sd_tensor_free()`. Free functions accept `NULL`. - -## Reproduction parameters - -The `sdcpp.generation/v1` JSON is a snapshot of generation parameters for the -same loaded context and the same input images, masks, reference media and other -assets. It is created after `GenerationRequest` resolves the request, before -preprocessing or sampling. A failed call returns no result or metadata. - -The JSON schema retains its established generation field names: `prompt`, `negative_prompt`, -`width`, `height`, `seed`, `sample_params`, `hires`, `cache`, -`vae_tiling_params`, `image_preprocess`, and the image/video-specific options. -`kind` distinguishes image and video parameters. There is no inferred `task`. -Enums use their API string names. Seeds are decimal strings to preserve their -full integer range. Omitted optional fields retain the parameter initializer's -defaults, including automatic values represented by infinity in the C API. - -Disabled optional features are omitted entirely: `cache`, `hires`, VAE tiling, -zero/nonpositive `shifted_timestep`, inactive SLG, false circular axes, and empty -preprocessing/reference arguments. SLG layers remain present when `slg_uncond` -is enabled even with zero SLG scale. Enabled caches store their mode's parameters; -TaylorSeer retains the shared DBCache thresholds and limits used by the runtime. -Image CFG at its neutral value of 1 is omitted and resolves back to 1 by default. - -Image strength, ControlNet/IP-Adapter strength and PhotoMaker settings are stored -when their corresponding input images are supplied. PuLID requires an embedding -path. Layer count is stored for layered generation; video VACE and high-noise -settings require those models. High-noise settings omit scheduler, custom sigmas, -flow shift and timestep shifting because that pass shares the base configuration. -Explicit nonempty argument strings are retained without rewriting their contents. -Core sampling values such as seed, sampler, scheduler, steps and guidance remain -explicit even when equal to their defaults. ADetailer always retains its inpaint -strength because its input crops are created later. -Model-required VAE tiling is resolved before serialization, so forced tiling -(such as MiniMax-H3) remains present even if the caller did not enable it. - -The request fixes the seed, dimensions, clip skip, guidance, sampler, scheduler -and eta before taking the snapshot. `custom_sigmas` is stored only when supplied -as an input. Automatically computed schedules, preprocessing transforms, -conditioning/cache decisions, detector regions and output statistics are not -stored: they are recomputed from the same parameters and inputs. - -Each image records the seed used to sample its latent. `batch_count` is omitted; -replay image parameters with `batch_count = 1`. Layers or frames decoded from -the same latent share its seed, so layered generation reproduces that group of -layers. Video frames share the video request. Partial batch cancellation returns -metadata only for completed outputs. Full cancellation returns no result. - -The current image pipeline prepares input latents once using the starting seed -and shares them across a batch. With a stochastic VAE encoder, replaying a later -image alone using its sampling seed can change those input latents. Per-image -seeds therefore do not guarantee independent reproduction for these paths. - -To replay a record, create image/video options, translate JSON fields to the documented C API -keys, restore the same input buffers, and call generation with the same context. -Setters copy strings and numeric arrays and retain media tensors; keep options alive -for the call. Paths supplied as generation parameters (LoRAs, hires models and identity -embeddings) are retained. `models` identifies successfully loaded context model -files by component (`model`, `diffusion_model`, `clip_l`, `vae`, etc.), using -filenames with extensions and omitting directories. Optional components disabled -for the request and preview-only TAE are omitted. WebUI text includes `Model` -(the diffusion model when supplied separately, otherwise the checkpoint, without -the extension) and `VAE` for a separate active VAE. These names are identifiers, -not hashes or sufficient configuration to rebuild a context; replay still requires -the same model files and context settings. The JSON does not embed media buffers -or model weights. - -When `--lora-model-dir` is configured, CLI/server output records express LoRA -paths relative to that directory, preserving subdirectories and file extensions -and using `/` separators. This applies to file metadata, API responses and -ADetailer records. Resolve these paths against the same LoRA directory before -passing them back to the C API. Core results retain the supplied loading paths. -Files outside the directory retain `..` components; paths on another volume, -or records without a configured LoRA directory, retain their original paths. - -## Postprocessing - -Upscale records `upscale.upscale_factor`. ADetailer records `adetailer` and -`inpaint_params`, with a concrete starting seed chosen before detection. These -operations require the same upscaler/detector context and source image on replay. -They do not store detection results or per-region generation traces. - -The CLI/server append operation parameter snapshots to `postprocess` in call -order. The source generation parameters remain unchanged. Frame postprocessing -uses the same operation parameters for each video frame. Standalone -postprocessing does not invent source diffusion parameters for an input image. +`sd_generate_image()`, `sd_generate_video()` and `sd_upscale()` all execute dgl. +`sd_result_get_generation_info(result, index)` returns the exact UTF-8 program +submitted to the DGL compiler. It is not a JSON parameter snapshot. + +Debug logging also prints the actual compiled program immediately before +execution. Use `--log-level debug` in the CLI. Each image in a batch +logs its own resolved program and seed. Source logging is independent of file +metadata embedding; tensor bindings remain separate inputs and are not dumped. + +## Results and rerunning + +Each generated image records its actual seed and executed source. Image batches +execute individual programs in the same context, reusing loaded models. Multiple +layers decoded from one latent share the same source. A video records one +program for the entire sequence, returned for every valid frame index. +Partial batch cancellation returns records only for completed images; full +cancellation returns no result. + +Rerun a self-contained program through `sd-cli -M dgl --script FILE` or the +DGL C API. Programs with `fn main(input_image, ...)` require the original host +tensor bindings through the DGL C API. Generated programs retain component paths, +resolved options and ordinary LoRA application order. They do not embed model +weights or input media. Keep the same files, inputs and backends when comparing +numerical results. + +Standalone image upscaling records the complete DGL operation, including every +requested repeat. No source diffusion settings are invented for an imported +image. There is no postprocessing JSON merge or separate replay mode. + +## WebUI infotext + +CLI and server derive WebUI infotext from the DGL source on a best-effort basis. +Known image flows can expose prompts, seed, dimensions, sampler, scheduler, +steps, CFG, strength, components and ordinary LoRAs. Ambiguous multi-stage fields +are omitted. Conversion never changes the executed source or causes inference +to fail. Standalone upscaling can have empty infotext. + +`sd_get_generation_metadata(source)` returns UTF-8 JSON containing these +parameters and an `infotext` field in one call. It does not execute the program +or read model files. Unrecognized image flows return `{}`. The returned string +is borrowed until the next call on the same thread; copy or parse it before then. +A null result indicates an API error available through `sd_get_last_error()`. + +Native server `generation_info` values are DGL strings. WebUI-compatible routes +also fill `infotexts` separately. Clients must not parse the DGL string as JSON. ## File metadata -Image encoders accept the native record and derive WebUI infotext from it. -Images use the existing metadata locations and combined text layout: -`, SDCPP: `. Standalone postprocessing without -source diffusion parameters stores only native JSON. Video metadata stores -only native JSON. - -| Container | Metadata location | -| --- | --- | -| PNG | `tEXt`, keyword `parameters` | -| JPEG | COM segment, `parameters` label followed by a NUL byte | -| WebP image / animated WebP | XMP property `sdcpp:parameters` | -| AVI | RIFF INFO `ICMT` | -| WebM | `COMMENT` tag | - -Inspect images or videos with `sd-cli -M metadata --image `; the same -command supports all containers above, with `--metadata-format json` for a -structured report. Video metadata inspection does not require a model or video -decoder. -Matroska containers are also supported, including `.webm` outputs whose audio -codec causes the muxer to select the Matroska document type. - -The XMP namespace is `https://github.com/leejet/stable-diffusion.cpp/ns/1.0/`. -PNG and JPEG retain the existing UTF-8 text payload convention. Memory encoding -and file saving use the same implementation. The core result and API -`generation_info` fields remain pure JSON; the combined layout applies only -to embedded image metadata. - -WebUI conversion is lossy: known samplers and schedules have explicit name -mappings; unsupported ones use `SDCPP Sampler`/`SDCPP Schedule` fields. Hires -keeps the base request size and separate configured hires size/steps. The native -record retains the full generation parameters. Standalone postprocessing has no WebUI -infotext because its original diffusion settings are unknown. - -WebUI prompt text appends ordinary LoRAs as ``. -Directory components are omitted to match WebUI's filename lookup; the native -`loras` array retains relative paths and weights. High-noise-only LoRAs and names -that cannot be represented by this tag syntax remain in the native record only. -The native prompt is not modified, and postprocessing LoRAs are not added to the -source generation prompt. - -JPEG requires the COM payload, including the label and terminating NUL bytes, -to fit within 65,533 bytes. Larger records fail encoding with an error rather -than being truncated. Use PNG or WebP for larger records. - -Disabling file metadata omits both image representations, but does not disable -the core generation record or its API response. Native async image results and -OpenAI image response items contain `generation_info`; video results contain a -sequence-level `generation_info`. The SD API `info` object contains per-output -`generation_info` alongside derived `infotexts` and each image's seed. Its outer -`parameters` field continues to echo the request. +The CLI and server image writers store native DGL and WebUI text separately: + +| Container | DGL source | WebUI text | +| --- | --- | --- | +| PNG | UTF-8 `iTXt`, keyword `dgl` | UTF-8 `iTXt`, keyword `parameters` | +| JPEG | COM segment labeled `dgl` | COM segment labeled `parameters` | +| WebP / animated WebP | XMP `sdcpp:dgl` | XMP `sdcpp:parameters` | +| AVI | RIFF INFO `ICMT` | Not stored separately | +| WebM / Matroska | `COMMENT` tag | Not stored separately | + +Video comments contain the DGL program. The XMP namespace is +`https://github.com/leejet/stable-diffusion.cpp/ns/1.0/`. +JPEG labels and values are separated by NUL bytes. A JPEG COM payload is limited +to 65,533 bytes including labels and terminators; an oversized record makes +encoding fail rather than silently truncating the program. Other container +capacity checks follow the same rule. + +Memory encoding and file saving use the same metadata writer. Disabling metadata +still disables embedding. Previously generated files with combined WebUI text +and `SDCPP:` JSON remain readable. + +DGL `image::save` (PNG) and `video::save` (AVI) also embed the exact program +source by default, using `dgl` and `ICMT` respectively. `image::encode` and +`video::encode` embed it during encoding; `media::save` writes those bytes +unchanged. WebM uses the `COMMENT` tag. These script functions store the program +itself without deriving WebUI infotext. Set the DGL context +option `embed_metadata` to `off` to omit it; `sd-cli -M dgl` forwards +`--disable-image-metadata` to that option. The switch also disables embedding +in the ordinary CLI image and video output paths. It does not affect tensor +data or the source returned by `sd_result_get_generation_info`. + +Inspect metadata with `sd-cli -M metadata --image FILE`, optionally adding +`--metadata-format json` for a structured report. This command reads container +metadata without loading a model. + +The C API provides the same reader through `sd_read_metadata(path, flags)`. +Use zero for the default text report, or combine `SD_METADATA_READ_JSON`, +`SD_METADATA_READ_RAW`, `SD_METADATA_READ_BRIEF` and +`SD_METADATA_READ_STRUCTURAL`. A null return indicates an error; inspect +`sd_get_last_error()`. The returned UTF-8 report is borrowed until the next +call to this function on the same thread. + +For applications that encode their own files, `sd_get_metadata_chunk()` builds +PNG iTXt chunks, JPEG COM segments, XMP text or an AVI INFO chunk. It returns +borrowed bytes and their exact size; copy them before the next call on the same +thread. PNG chunks are inserted after IHDR, JPEG segments after SOI, XMP is +stored in the container's XMP field, and AVI INFO is a RIFF chunk. Empty source +returns an empty chunk. This function does not write a file. diff --git a/docs/guides/image_preprocessing.md b/docs/guides/image_preprocessing.md index dc0aca8bc3..4375959348 100644 --- a/docs/guides/image_preprocessing.md +++ b/docs/guides/image_preprocessing.md @@ -1,180 +1,29 @@ # Image preprocessing -Use `--image-preprocess` to transform each image input once, before generation: - -```sh -sd-cli ... \ - --image-preprocess "target=init,mode=crop-resize,filter=lanczos,antialias=true" \ - --image-preprocess "target=mask,filter=nearest-exact" \ - --image-preprocess "target=ref,index=0,mode=fit-pad,width=768,height=768,filter=bicubic" +Custom input transformations are expressed in [DGL](../dgl.md). Native CLI and +C API generation use the model's default canvas and reference-image rules. +The former `--image-preprocess` flag, server `image_preprocess` field and C API +`image_preprocess.rules` option have been removed. Express their transformations +in DGL instead. `--ref-image-args` and `ref_image_args` have also been removed. + +Use tensor operations to make the transformations visible in the program: + +```dgl +image = image::load("input.png") +cropped = tensor::crop(image, start = [32, 16], size = [512, 384], axes = [1, 2]) +resized = tensor::interpolate(cropped, size = [768, 512], axes = [1, 2], mode = "lanczos") +pixels = image::to_f32(resized) ``` -CLI and server image loaders decode at the original resolution. The generation -entry point merges input defaults with user rules and prepares one transformed -image per input. The original pipeline then consumes those images, including -its mandatory canvas adaptation, reference resizing, and encoder preprocessing. - -```text -native-resolution image - -> input defaults + user overrides - -> one input transform - -> original generation pipeline and model-specific processing -``` - -These rules do not override internal VAE, CLIP/VLM, ControlNet, or pixel-patch preprocessing. -`--ref-image-args` retains its existing meaning and runs after this input transform. - -## Inputs and defaults - -| `target` | Input | Default geometry | Indexed? | -| --- | --- | --- | --- | -| `init` | img2img image or video first frame | Center crop to the generation aspect ratio, then resize | No | -| `end` | Video last frame | Center crop, then resize | No | -| `mask` | Inpainting mask | Inherit init geometry; otherwise center crop, then resize | No | -| `control` | Control image | Center crop, then resize | No | -| `ref` | Reference images | Preserve source dimensions | Yes | -| `ip-adapter` | IP-Adapter image | Preserve source dimensions | No | -| `id` | PhotoMaker identity images | Preserve source dimensions | Yes | -| `control-frame` | Control video frames | Center crop, then resize | Yes | - -Canvas defaults use the aligned generation dimensions. Reference, IP-Adapter, -and identity inputs use their original dimensions unless overridden. Default -resampling is nearest for images and nearest-exact for masks. - -These defaults are shared by CLI, server, and C API. Moving geometry out of -the loaders replaces the previous CLI/server BOX/sRGB resizing, so default -pixels are not guaranteed to match earlier builds. - -Reference video and audio preprocessing are outside these image rules. -Preprocessing options apply to `img_gen` and `vid_gen`, not standalone upscale -or ADetailer mode. ADetailer clears the user's rules for its internal crops. - -## Rules - -Rules are comma-separated `key=value` lists. Repeat the CLI option or separate -rules with semicolons. Every rule requires a `target` and at least one option. -Rule syntax and input compatibility are checked when image/video generation -starts. Unknown keys, invalid values, duplicate keys in a rule, missing images, -and out-of-range indices cause generation to fail with an error log. - -Omit `index` to configure every image of that type; otherwise use a zero-based -index. CLI directory inputs follow filename order. Indexed rules override -type-wide rules field by field, regardless of order. At equal specificity, -the last value for a field wins. `auto` selects the input preset. - -| `mode` | Input transform | -| --- | --- | -| `auto` | Use the input's default geometry | -| `none` | Keep source dimensions without resizing, cropping, or padding | -| `stretch` | Resize to the target dimensions | -| `crop` | Crop a target-sized rectangle without resizing; fail if the source is too small | -| `crop-resize` | Crop to the target aspect ratio, then resize | -| `fit-pad` | Fit the entire image inside the target dimensions, preserving aspect ratio, then pad | - -`width` and `height` must be specified together as positive integers. They -override the input transform's dimensions, not the generation or encoder size. -For a native-size preset, specifying dimensions without a mode selects stretch. -`mode=none` with explicit dimensions different from the source is contradictory -and is rejected. - -`anchor=center|top|bottom|left|right` selects crop/padding placement. -`pad_color=#RRGGBB` or `#RRGGBBAA` selects padding, defaulting to opaque black. -A grayscale mask uses the first color component. - -`filter=auto|nearest|nearest-exact|bilinear|bicubic|lanczos` selects resampling. -`antialias=auto|true|false` enables antialiasing automatically for filtered -downscaling; explicit true requires bilinear, bicubic, or Lanczos. -Filtered RGBA resizing uses premultiplied alpha. - -`canny=true|false` enables edge detection for any supported image target, -defaulting to `false`. It runs once after geometry, before the original -generation pipeline, including with `mode=none`. Grayscale, grayscale-alpha, -RGB, and RGBA inputs are supported; alpha is preserved. - -Each input has its own Canny setting. Indexed rules can enable or disable it -for individual references, identity images, or video control frames. - -```sh ---image-preprocess "target=init,mode=fit-pad,canny=true" ---image-preprocess "target=ref,index=0,mode=none,canny=true" ---image-preprocess "target=control-frame,index=2,canny=true" -``` - -If init and mask source dimensions differ, the mask is first center-cropped to -the init source aspect ratio and resized to the init source dimensions using -nearest-exact interpolation. The mask then inherits the init crop, resize, and -padding coordinates, while retaining its own filter, padding value, and Canny -setting for that transform. Explicit mask geometry is evaluated after this -alignment; conflicting geometry is rejected. An omitted mask remains absent -until the original pipeline creates its default mask. - -## Downstream behavior - -`mode=none` only skips the input geometry transform. For example: - -```sh ---image-preprocess "target=init,mode=none" \ ---image-preprocess "target=ref,mode=none" -``` - -The init image is still adapted to the generation canvas by the original -pipeline. Reference images still follow `--ref-image-args` and model-specific -resizing. CLIP retains its fixed input dimensions and normalization. HiDream-O1 -retains its original pixel-reference and visual preprocessing. - -Existing sharing between consumers is preserved: for example, Wan img2video -uses the same adapted first frame for VAE conditioning and CLIP. High-resolution -passes reuse the prepared images and apply their original size adaptation; -they do not apply the user's crop a second time. - -To disable reference resizing before VAE encoding, use -`--ref-image-args "resize_before_vae=false"` or the server field -`"ref_image_args": "resize_before_vae=false"`. This is separate from -`target=ref,mode=none`, which only skips input geometry. Model constraints -still apply; MiniMax-H3 requires 32-pixel-aligned references and warns instead -of honoring the switch. - -## Server requests - -Native image/video requests and SDAPI accept `image_preprocess` as a string or -an array of rule strings: - -```json -{ - "image_preprocess": [ - "target=init,mode=fit-pad,filter=bicubic", - "target=mask,filter=nearest-exact", - "target=ref,index=0,mode=none" - ] -} -``` - -OpenAI-compatible requests accept it through -`{...}` in the prompt. -Request rules replace server-default rules. Generation metadata records the -user rules for replay with the same input images; image encodings and channel conventions are unchanged. - -## C API - -Set the `image_preprocess.rules` key on image/video options. Generation returns -media and actual parameters together; see [generation metadata](generation_metadata.md): - -```c -sd_img_gen_opt_t* opt = sd_img_gen_opt_create(); -sd_result_t* result = NULL; -/* Set prompt, original-resolution input images, and generation options. */ -sd_status_t status = sd_opt_set_string(opt, "image_preprocess.rules", - "target=init,mode=crop-resize,filter=lanczos;target=mask,filter=nearest-exact"); -if (status == SD_STATUS_OK) - status = sd_generate_image(ctx, opt, &result); -/* Read outputs through sd_result_get_*() on success. */ -sd_result_free(result); -sd_opt_free(opt); -``` +For a mask, use `mode = "nearest_exact"` when resizing and explicitly convert to +the expected mask layout. For an edge hint, use `image::canny(image)` and pass +the result to the ControlNet workflow. `tensor::pad`, `tensor::crop` and +`tensor::interpolate` can express fitting, padding and aspect-ratio handling. -Leaving the key unset selects input presets. Rule strings are copied by setters. -The library owns temporary transformed pixels; caller images and arrays are -not modified. Add `canny=true` to the desired target's rule in -`image_preprocess.rules` to enable Canny. +These operations do not disable mandatory VAE or vision-encoder constraints. +Prepare an input that already satisfies those constraints to avoid automatic +alignment. Different encoders may receive different prepared tensors. -The parameter structs have grown; applications and bindings must be rebuilt. +See the [editing guide](edit.md), the +[ControlNet example](../dgl/sd/sd1-5-controlnet.dgl), and the +[built-in catalog](../dgl-builtins.md) for complete interfaces. diff --git a/docs/guides/int8_convrot.md b/docs/guides/int8_convrot.md index c105f15bb1..f67a467745 100644 --- a/docs/guides/int8_convrot.md +++ b/docs/guides/int8_convrot.md @@ -1,5 +1,9 @@ # INT8 Convrot Safetensors +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + sd.cpp can load and execute ComfyUI `int8_tensorwise` safetensors with `convrot` metadata directly. The stored INT8 weights are not converted to another weight type at load time. This uses sd.cpp's INT8 tensorwise/convrot operators through the patched GGML @@ -27,7 +31,7 @@ A supported configuration has this form: } ``` -The convrot group size must be a power of four and must divide the input feature dimension. The commonly used configuration is H256, with `convrot_groupsize` set to `256`. +When `convrot` is enabled, `convrot_groupsize` defaults to `256` (H256). The group size must be a power of four no greater than `256` and must divide the input feature dimension. ## How INT8 convrot works @@ -94,14 +98,34 @@ The packed runtime activation tensor contains the I8 activation rows and their f - CPU provides the portable regular Hadamard, activation quantization, INT8 matrix multiplication, and scale restoration implementations. - Metal supports INT8 tensorwise and convrot on Apple silicon (Apple GPU family 7 or newer). It keeps weights in INT8 and rotates and quantizes activations on the GPU. On macOS/iOS 26 or newer, it probes Metal TensorOps `matmul2d` with INT8 inputs and INT32 cooperative results. It combines 1024-product partial sums using wrapping integer addition to preserve exact accumulation on older GPUs, then applies scales and bias in registers. Older systems or unavailable TensorOps pipelines use SIMD-group matrix multiplication: INT8 tiles are converted to FP16, and FP32 partial sums cover at most 256 products before being combined as integers, preserving the I32 accumulation contract. Convrot groups 1, 4, 16, 64, and 256 are supported. These kernels require the patched GGML Metal extension services and are enabled by `SD_METAL=ON`. -- NVIDIA CUDA devices with compute capability 7.5 or newer use the native accelerated path. For H256, CUDA fuses the rotation, row-wise maximum reduction, and activation quantization. Eligible shapes use the CUTLASS INT8 implementation when enabled. For linear layers, it restores scales and adds any aligned bias before writing the result; other supported shapes use cuBLAS for I8 x I8 to I32 GEMM and a CUDA kernel for scale restoration and bias addition. -- AMD HIP devices in the CDNA, RDNA3 (including RDNA3.5), and RDNA4 families use the same INT8/H256 kernels with hipBLAS for I8 x I8 to I32 GEMM. Other AMD architectures fall back to CPU for INT8 matrix multiplication. -- MUSA shares the CUDA-style H256 activation kernels. INT8 GEMM falls back to CPU because the MUSA backend does not advertise INT8 BLAS support. -- Vulkan provides H256 activation quantization and INT8 matrix multiplication when the build and device support accelerated packed INT8 dot products. Unsupported configurations and GPU backends without these kernels use the backend scheduler to fall back to CPU. - -LoRA adapters are applied at runtime without modifying the INT8 weights. The INT8 convrot path computes the base linear output, while LoRA, LoHa, LoKr, and raw weight-difference adapters compute their output corrections from the original, unrotated activation and add them to the base output. `--lora-apply-mode auto` selects this path for models containing INT8 tensorwise weights. If `immediately` is requested, sd.cpp falls back to runtime application because merging an adapter would require dequantizing and rotating its weight update, then recalculating the per-row scales and requantizing the result. - -The shared CUDA/HIP/MUSA convrot activation paths support H64 and H256. Vulkan also supports H64 activation quantization; its INT8 matrix multiplication path currently requires H256. +- CUDA uses CUTLASS for eligible shapes when enabled, and cuBLAS for other eligible shapes on Turing and newer. HIP uses hipBLAS or hipBLASLt on supported targets, including RDNA2, RDNA3, RDNA3.5, RDNA4 (`gfx120x`), and CDNA. +- CUDA, HIP, and MUSA share a tiled INT8 dot-product fallback. It handles devices without INT8 BLAS and projections whose output width is not divisible by four. It uses packed byte-dot instructions where available. +- Vulkan supports unrotated rowwise, H64, and H256 activation quantization and packed-activation INT8 matrix multiplication with input widths divisible by 64. It requires integer dot product support and uses cooperative matrices when available. Unsupported configurations use the scheduler's CPU fallback. + +`--lora-apply-mode auto` selects immediate merging for INT8 tensorwise models +on the compute backend without row splitting. Use `--lora-apply-mode at_runtime` +to compute each adapter's correction from the original activation and add it to +the INT8 linear output. + +Immediate mode merges an adapter into INT8 tensorwise weights on first use. +For convrot weights, sd.cpp rotates the adapter update before adding it to the +dequantized weights. It then recalculates the weight +scales and requantizes the result to INT8. The merge runs on the selected +backend when it supports the operation, with ggml's usual CPU fallback. + +Requantizing can drop an adapter's effect entirely. Each row of an INT8 weight +can only change in steps of its scale, the row's largest magnitude divided by +127. The original values lie exactly on those steps, so while the row's scale +stays the same, an update smaller than half a step rounds back to the original +INT8 value. The scale changes only when the update changes the row's largest +magnitude; the new scale then moves every value in the row, so small updates +can shift the result even though each one alone would round away. +Many adapters, such as distillation LoRAs with small updates, fall below that +threshold for nearly every weight; immediate mode then produces almost the same +output as running without the adapter. Larger updates survive only partly. Use +`--lora-apply-mode at_runtime` when the adapter must match its intended effect. + +The shared CUDA/HIP/MUSA convrot activation paths support H64 and H256. ## Packed INT4 convrot @@ -115,55 +139,78 @@ converted to GGUF Q4 blocks at load time. the format name does not select a native INT4 activation kernel. - `asym_w4a8_int8`: 4-bit indices into `weight_codebook` (16 F32 values), F32 `weight_s_channel`, and F8_E4M3 `weight_s_rel` per 16 input features. The - metadata must specify `group_size: 16`. CPU evaluates the floating-point - codebook; GPU kernels requantize it to INT8 with `amax / 127`, introducing a - small additional rounding error. + weight group size must be 16 and defaults to 16 when omitted. Both formats imply convrot rotation even without a `convrot` flag; missing `convrot_groupsize` defaults to 256. Both formats reuse the convrot activation cache when the input scale is `1` and -produce F32 outputs with optional bias. CPU provides a portable implementation. -CUDA/HIP/MUSA use shared packed-weight kernels without requiring INT8 BLAS. -With CUTLASS enabled, NVIDIA -SM80 and newer devices use mixed-input S8 x S4 GEMM for eligible W4A4 shapes, -reusing the INT8 scale epilogue without expanding the full weight tensor. W4A8 -uses CUTLASS integer MMA per 16-value group with FP32 scale restoration. -Other CUDA shapes and builds retain the packed byte-dot path. Set -`GGML_CUDA_W4_FORCE_DP4A=1` to compare against that path. Supported AMD targets -use packed byte-dot instructions, with portable byte arithmetic for other targets. -Vulkan requires integer dot product support and at least 13312 bytes of shared -memory for W4A4 or 16452 bytes for W4A8. GPU W4 kernels require the logical input -width to be divisible by 64; H64 and H256 are supported. When supported by the -compiler and device, Vulkan uses NV cooperative matrix integer GEMM. W4A4 -decodes packed weights directly into cooperative matrices for aligned input -and output widths. Complete activation tiles and the final partial tile use -separate shader specializations. Other W4A4 shapes use double-buffered weight -and activation tiles (20480 bytes of shared memory, or 30720 for larger tiles). -W4A8 stages both weights and activations in shared memory in K=64 tiles, -reusing them for each 16-value group's integer -MMA and FP32 scale restoration. FP8 scales use a shared lookup table, and -expanding projections visit activation tiles in groups of weight panels for -cache reuse. Adjacent groups share a K=32 activation fragment, with -complementary zero padding in the weights to preserve each group's scale. -This path uses 17476 bytes of shared memory, or 22596 for larger tiles. -Both paths use 256-thread workgroups and keep the model's -weights packed; neither expands a full layer in device memory. Other Vulkan -devices retain the packed dot-product path; set `GGML_VK_W4_FORCE_DP4A=1` to compare -against it. FP32 accumulation order can differ between these paths. -Other shapes use CPU fallback. HIP W4A8 selects wave64 WMMA by the active -compilation target's intrinsic support, preferring the GFX12 fragment layout -over the GFX11 layout. -There is no GPU architecture allowlist: newer targets supporting either -intrinsic automatically use its matching layout. Selection happens per device -image, including multi-architecture builds; targets supporting neither intrinsic -retain the integer-dot fallback. W4A4 retains integer dot products on HIP. +produce F32 outputs with optional bias. + +W4A8 multiplies the codebook value by the group's relative scale, rounds to nearest even, +and clamps to `[-127, 127]`. The linear operation decodes weights into temporary workspace, +then runs the same INT8 GEMM as W8A8 with `weight_s_channel` as the per-output +scale. Eligible large CUDA projections decode slices and write GEMM results +directly into the corresponding output columns. CPU, CUDA/HIP/MUSA, Vulkan, +and Metal provide weight decoders. The checkpoint's packed weights stay in +their original layout. + +If the decoded W4A8 weights exceed the Vulkan device's `maxStorageBufferRange`, +the linear operation decodes slices of output channels into shared workspace +and writes each GEMM result directly to the corresponding output columns. An +`8192 × 24576` projection needs 192 MiB after decoding and can run on a device +with a 128 MiB storage-buffer range. The packed weights, activations, scales, +and FP32 output must still fit their respective bindings. Projections that +exceed those limits fall back to CPU. + +W4A4 uses packed-weight kernels. Eligible CUDA SM80+ shapes can use CUTLASS mixed +S8 x S4 GEMM. Vulkan uses cooperative matrices where supported and requires a +logical input width divisible by 64. Use `GGML_CUDA_W4_FORCE_DP4A=1` or +`GGML_VK_W4_FORCE_DP4A=1` to select packed byte dots for W4A4 on the corresponding +backend. LoRA application remains at runtime, using the original unrotated activations and logical weight dimensions. Packed weights and their codebook/scale tensors are excluded from weight type conversion. `SD_USE_UPSTREAM_GGML` builds reject these formats because they require the application extension API. +## Runtime requantization to INT8 + +Use `--linear-type i8` to run eligible Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K, +Q4_K, Q5_K, Q6_K, and Q8_K linear layers through INT8 GEMM on CUDA, HIP, MUSA, +and Vulkan. A bare mode applies to all models in the context, including +diffusion models and text encoders loaded with `--llm`. The default is `auto`, +which currently behaves like `raw`. With +`--linear-type raw`, each layer uses its original execution path. Native INT8 +weights use their INT8 path in all three modes. For floating-point checkpoints, +use `--type q4_0` (or another supported weight type) to quantize eligible weights +at load time. + +Use module assignments to apply a mode selectively. For example, +`--linear-type dit=i8` selects runtime conversion for the diffusion module. +The text encoder and other modules use `auto`. Use `--linear-type i8,te=raw` to +enable conversion globally while keeping the text encoders on their original +paths. Module names and aliases are shared with [backend selection](backend.md). +Module assignments override the default regardless of their order. Within +the same string, the last value for a module or the default wins. + +Runtime conversion uses H256 for weights and activations. Eligible linear +layers have an input width divisible by 256. Vulkan also requires integer +dot products and compatible storage buffer sizes and alignment. The C API option is +`linear_type`. In DGL, set the mode on a model loader, for example +`load_dit(path, linear_type = "i8")`. To override loader settings by module, +use `sd_dgl_ctx_set(ctx, "linear_type", "dit=i8")` or pass +`--linear-type dit=i8` when running the script from the CLI. + +At runtime, sd.cpp dequantizes the weight blocks, rotates the weights, and +requantizes them to INT8 with one scale per output channel. It applies the +same rotation to the activations before quantizing each input row. The +converted matrix uses temporary GPU memory and feeds the standard INT8 kernels +and their fusions. The checkpoint file stays in its original format. +Requantization changes numerical results, and conversion overhead depends on +matrix shape. Row-split models and unsupported layers use their original +execution paths. + ## Example ComfyUI INT8 convrot safetensors can be passed to `--diffusion-model` without conversion: diff --git a/docs/guides/performance.md b/docs/guides/performance.md index 76fb3da9eb..edbd6e2997 100644 --- a/docs/guides/performance.md +++ b/docs/guides/performance.md @@ -1,5 +1,9 @@ ## Use Flash Attention to save memory and improve speed. +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + Enabling flash attention for the diffusion model reduces memory usage by varying amounts of MB. eg.: - flux 768x768 ~600mb @@ -49,6 +53,11 @@ run qualifies for it. Use `--batched-cfg off` to force separate conditional and unconditional forwards. +In DGL mode the flag sets `batched_cfg` on the execution context. Compatible +`cfg(positive, negative, ...)` branches use batching automatically; combinations +that require separate forwards retain their original execution. See +[DGL context execution settings](../dgl.md#context-execution-settings). + ## Use VAE tiling to reduce encode and decode memory usage. `--vae-tiling` enables spatial tiling for both VAE encoding and decoding. The @@ -105,7 +114,7 @@ Using `--offload-to-cpu` allows you to offload weights to the CPU, saving VRAM w ## Use params backend to reduce VRAM or RAM usage. -`--params-backend` controls where model parameters are kept. If it is not set, auto-fit chooses parameter placement while preserving `--backend`. With `--auto-fit off`, parameters use the same backend as `--backend`, so a GPU runtime backend also keeps parameters in VRAM. +`--params-backend` controls where model parameters are kept. If it is not set, parameters are kept on the `--backend` device, and weights that do not fit move to RAM, then disk. See [weight residency](backend.md#weight-residency). Use CPU params to reduce VRAM usage: @@ -139,13 +148,15 @@ See [backend selection](./backend.md) for full syntax. `--offload-to-cpu` keeps the source parameters in system RAM and creates compute-side GPU replicas on demand. Unpinned replicas remain resident for reuse, but automatic graph-cut execution evicts them from the last segment backward when the next weight or compute allocation needs space. Disk-backed parameters follow the same policy without retaining a RAM source copy. -When a graph has cut markers and its missing weights plus incremental compute workspace exceed the available device headroom, it runs its fixed segment list in order. A reusable monolithic compute buffer is not counted as a new allocation. An explicit `--max-vram` budget deducts already-resident managed weights and compute/cache buffers registered by every runner sharing the device, so later graph runs remain segmented when the full graph exceeds the budget. The current segment's weights are pinned during compute, and the next parameter-bearing segment is prefetched when the device supports asynchronous transfer. No opt-in streaming flag is required. +On Vulkan, CPU-offloaded weights use pageable system RAM, leaving the driver's host buffer capacity available for transfers. -When choosing between monolithic and segmented execution, the runner requires -an additional 128 MiB of headroom in both available device memory and any explicit -managed budget. This planning headroom absorbs small allocation estimate changes; -subsequent capacity checks can consume it while still preserving the 512 MiB device -scratch reserve and respecting the managed budget. +When a graph has cut markers and its missing weights plus incremental compute workspace exceed the available device headroom, it runs its fixed segment list in order. An existing monolithic workspace can be reused without a new allocation. An explicit `--max-vram` budget includes resident managed weights, compute and cache buffers registered by runners sharing the device, and ggml's idle buffer pool. The current segment's weights are pinned during compute, and the next parameter-bearing segment is prefetched when the device supports asynchronous transfer. No opt-in streaming flag is required. + +When planning a new monolithic workspace allocation, the runner requires an +additional 128 MiB in both available device memory and any explicit managed +budget. New device allocations also reserve 512 MiB for backend scratch +buffers, or 1 GiB on Windows CUDA. A graph that reuses its resident weights and +workspace still checks the managed budget. - `--max-vram ` optionally lowers the live-memory limit. A positive value is a managed per-device budget, `0` uses the device's current free memory without an explicit budget, and a negative value snapshots free memory at startup while reserving that many GiB (`--max-vram -1` reserves about 1 GiB). Driver contexts and unrelated external allocations remain outside the managed budget. - `--disable-prefetch` disables asynchronous next-segment prefetch while retaining synchronous loading, eviction, and segmented execution. @@ -161,12 +172,14 @@ allocator/scheduler capacity. Compatible gallocr reservations are reused across graphs; idle workspaces can be reclaimed under pressure and are freed at runner completion. Cross-graph caches survive individual graphs, but cut buffers do not. -On discrete Vulkan devices, runners reuse released device buffers of the same -size to reduce allocation overhead during segmented execution. This idle buffer -cache is limited to 1 GiB per device and is reclaimed before allocating a new -size or at runner completion. It is outside the managed `--max-vram` budget, -so physical VRAM usage can be higher. Set `GGML_VK_REUSE_BUFFERS=0` to disable -it. Unified-memory and host-memory modes do not use this cache. +CUDA, HIP, and discrete Vulkan can reuse released device buffers of the same +size. The pool retains up to 4 GiB per device for CUDA and HIP and up to 1 GiB +for Vulkan, subject to the remaining device budget. Under pressure, the runner +trims idle buffers and can pass a matching evicted CUDA or HIP weight buffer +directly to a prefetch. Set +`GGML_CUDA_REUSE_BUFFERS=0` for CUDA or HIP, or `GGML_VK_REUSE_BUFFERS=0` for +Vulkan, to disable the pool. Vulkan also disables the pool when it prefers host +memory. Unified-memory mode disables the pool. Discrete NVIDIA and non-GCN AMD Vulkan devices use a separate transfer queue by default when available and graphics queue use is disabled, so weight prefetch can overlap compute. Set @@ -187,6 +200,7 @@ sd-cli --diffusion-model flux1-dev.safetensors ... \ --offload-to-cpu --max-vram -1 ``` + - `--offload-to-cpu`: params in RAM, staged as needed. - `--max-vram -1`: reserve about 1 GiB from the startup free-memory snapshot; live free memory can still lower the effective limit for every graph. diff --git a/docs/guides/prompt_images.md b/docs/guides/prompt_images.md index e6c301f0c4..69dce1b8a0 100644 --- a/docs/guides/prompt_images.md +++ b/docs/guides/prompt_images.md @@ -75,8 +75,36 @@ within one prompt are loaded once and appear at every specified position. Resolved image pixels participate in conditioning-cache comparisons. Register or clear the callback while the context is idle. Different contexts -have independent callbacks. Generation parameter structures and generation -entry points are unchanged. +have independent callbacks. + +## DGL +The complete [MOSS-Image prompt-image example](../dgl/moss_image/moss-image-sft-inline-images.dgl) +loads all components, binds the prompt image and saves the generated result. +See the [DGL example collection](../dgl/README.md) for run instructions. + +Use the same markers with `encode_prompt`. DGL reads image paths relative to the +working directory. +LLM encoders accept `system` to customize the template while retaining image +inputs. `raw=true` is the complete text-tokenizer-input path and cannot be +combined with image/video bindings or `system`. See +[prompt formatting](../dgl.md#independent-generation-components). + +```text +condition = encode_prompt(encoder, "Draw in watercolor.") +``` + +To compose images inside the graph, pass a dictionary of tensors with keys +matching the markers. Explicit bindings take precedence over opening a path. +Only referenced bindings enter conditioning; additional dictionary entries do +not add images. A referenced binding must contain a valid image tensor. If a +name is absent, the normal file reader and permission callback still apply, +including when the encoder has cached a previous result. + +```text +subject = image::load("inputs/subject.png") +condition = encode_prompt(encoder, "Draw in watercolor.", + image_bindings = {subject = subject}) +``` ## Server diff --git a/docs/guides/rpc.md b/docs/guides/rpc.md index 6edd61da8f..bbd78f85e7 100644 --- a/docs/guides/rpc.md +++ b/docs/guides/rpc.md @@ -1,5 +1,9 @@ # Building and Using the RPC Server with `stable-diffusion.cpp` +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + This guide covers how to build a version of [the RPC server from `llama.cpp`](https://github.com/ggml-org/llama.cpp/blob/master/tools/rpc/README.md) that is compatible with your version of `stable-diffusion.cpp` to manage multi-backends setups. RPC allows you to offload specific model components to a remote server. > **Note on Model Location:** The model files (e.g., `.safetensors` or `.gguf`) remain on the **Client** machine. The client parses the file and transmits the necessary tensor data and computational graphs to the server. The server does not need to store the model files locally. @@ -165,6 +169,7 @@ Example: Setting the main backend to the RPC0 device for doing all the work on t ./sd-cli -m models/sd1.5.safetensors -p "A cat" --rpc-servers localhost:50052 --backend RPC0 ``` + --- ## 5. Scaling: Multiple RPC Servers @@ -211,6 +216,7 @@ Pass multiple server addresses separated by commas. ./sd-cli --rpc-servers 192.168.1.10:50052,192.168.1.10:50053,192.168.1.11:50052 [...] ``` + The client will map these servers to sequential device IDs (e.g., RPC0 from the first server, RPC2, RPC3 from the second, and RPC4 from the third). With this setup, you could for example use RPC0 for the main backend, RPC1 and RPC2 for the text encoders, and RPC3 for the VAE. --- diff --git a/docs/guides/sage_attention.md b/docs/guides/sage_attention.md index 2f3a0d09ca..9243d15ced 100644 --- a/docs/guides/sage_attention.md +++ b/docs/guides/sage_attention.md @@ -1,5 +1,9 @@ # SageAttention +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + `--sage-attn` enables native CUDA SageAttention in the diffusion model, including the high-noise diffusion model when present. Python, PyTorch, and Triton are not required at build time or runtime. @@ -42,10 +46,11 @@ Add `--sage-attn` to enable SageAttention. For example, from the build directory: ```powershell -.\bin\Release\sd-cli.exe -M vid_gen --diffusion-model ..\models\diffusion_models\Wan2.2-T2V-A14B-LowNoise-Q8_0.gguf --high-noise-diffusion-model ..\models\diffusion_models\Wan2.2-T2V-A14B-HighNoise-Q8_0.gguf --vae ..\models\vae\wan_2.1_vae.safetensors --t5xxl ..\models\text_encoders\umt5-xxl-encoder-Q8_0.gguf -p "a lovely cat" --cfg-scale 3.5 --sampling-method euler --steps 10 --high-noise-cfg-scale 3.5 --high-noise-sampling-method euler --high-noise-steps 8 -v -n "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的, +.\bin\Release\sd-cli.exe -M vid_gen --diffusion-model ..\models\diffusion_models\Wan2.2-T2V-A14B-LowNoise-Q8_0.gguf --high-noise-diffusion-model ..\models\diffusion_models\Wan2.2-T2V-A14B-HighNoise-Q8_0.gguf --vae ..\models\vae\wan_2.1_vae.safetensors --t5xxl ..\models\text_encoders\umt5-xxl-encoder-Q8_0.gguf -p "a lovely cat" --cfg-scale 3.5 --sampling-method euler --steps 10 --high-noise-steps 8 -v -n "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的, 形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走" -W 832 -H 480 --offload-to-cpu --video-frames 33 --sage-attn ``` + SageAttention currently handles unmasked attention with head dimensions from 1 through 128, including grouped-query attention, different query/key lengths, and multiple batches. Dimensions below 64 are zero-padded to 64; dimensions diff --git a/docs/guides/sampling.md b/docs/guides/sampling.md index 7955ce1f35..d89ecfa312 100644 --- a/docs/guides/sampling.md +++ b/docs/guides/sampling.md @@ -1,5 +1,9 @@ # Sampling methods and schedulers +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + The sampling method controls how each denoising step updates the image or video latent. The scheduler chooses the noise levels (sigmas) used across those steps. Choose both according to the [model guide](../models/README.md) for your checkpoint. @@ -31,6 +35,7 @@ For example, using the Stable Diffusion 1.5 checkpoint from the -p "a lovely cat" ``` + Run the example from the build directory. See the [shared command conventions](../models/README.md#example-conventions) for build layouts and platform-specific syntax. @@ -40,7 +45,7 @@ layouts and platform-specific syntax. | `--sampling-method NAME` | Select the sampling method. | | `--scheduler NAME` | Select the sigma scheduler. | | `--steps N` | Set the number of sampling steps. | -| `--high-noise-sampling-method NAME` | Select the high-noise sampler for two-stage video models. | +| `--high-noise-steps N` | Set the high-noise stage length for two-stage video models. | | `--sigmas VALUES_OR_PRESET` | Supply a custom schedule instead of generating one with the scheduler. | | `--hires-sigmas VALUES_OR_PRESET` | Supply a custom schedule for the highres fix second pass. | @@ -51,6 +56,10 @@ For native server requests, use `sample_params.sample_method` and `sample_params.scheduler`. See the [server API reference](../../examples/server/api.md) for request fields and capability discovery. +Native two-stage video generation shares sampling and guidance settings between +the high- and low-noise stages. Use a DGL workflow to give each stage a different +sampler or guidance configuration. + ## Sampling methods | Method | CLI value | diff --git a/docs/guides/tokenizers.md b/docs/guides/tokenizers.md index fb93550a9d..3d4e3f9930 100644 --- a/docs/guides/tokenizers.md +++ b/docs/guides/tokenizers.md @@ -1,5 +1,9 @@ # JSON tokenizers +DGL versions of the generation examples are linked below. Edit each script's +`var` block and follow the [DGL run instructions](../dgl/README.md). + + Use a Hugging Face `tokenizer.json` to supply the tokenizer vocabulary, merges, added tokens, and processing stages. **PiD (including PiD 1.5) and Lens (including Lens Turbo) require an external JSON**; their Gemma 2 and GPT-OSS tokenizers are @@ -11,6 +15,7 @@ sd-cli --diffusion-model model.gguf --llm text_encoder.gguf \ --tokenizer tokenizer_gemma2.json --vae vae.safetensors -p "a cat" ``` + Choose the JSON belonging to the text encoder checkpoint. Checking that IDs fit the embedding table does not establish that two vocabularies have the same meaning. The JSON file is loaded when the text encoder is created; its embedded @@ -52,6 +57,7 @@ sd-cli --diffusion-model sd3.gguf --clip_l clip_l.safetensors \ -p "a cat" ``` + The C API accepts the same string through the `tokenizer` context-option key. An unset or empty value keeps an embedded tokenizer where available; PiD and Lens require a nonempty main tokenizer path. The CLI passes the string through; diff --git a/docs/models/README.md b/docs/models/README.md index 24da05cee8..06820fac5b 100644 --- a/docs/models/README.md +++ b/docs/models/README.md @@ -10,6 +10,12 @@ for guide structure, examples, and index updates. ## Example conventions +Standalone [DGL versions of the documentation examples](../dgl/README.md) +are grouped by model under `docs/dgl/`. Edit each script's +`var` block and run it with `sd-cli -M dgl --script FILE.dgl`. Features currently +available only through DGL are marked in their guides; use the server's DGL +editor for those workflows rather than a native recipe. + Run the executable examples from the CMake build directory, for example after `cd build` from the repository root. Each guide gives both command forms: @@ -73,7 +79,7 @@ variant; a VAE or TAE selection must match that model. - [SenseNova U1.5](sensenova_u1.md) - [Stable Diffusion 1.x, 2.x, and SDXL, including Turbo variants](sd.md) - [Stable Diffusion 3 / 3.5](sd3.md) -- [Z-Image](z_image.md) +- [Z-Image](z_image.md), including [DGL ControlNet](z_image.md#controlnet) - [Z-Image L2P](z_image_l2p.md) ## Image editing diff --git a/docs/models/adetailer.md b/docs/models/adetailer.md index 2072644beb..54823bc046 100644 --- a/docs/models/adetailer.md +++ b/docs/models/adetailer.md @@ -1,22 +1,23 @@ # ADetailer -`sd-cli` can run a YOLOv8 object detector on an existing or newly generated -image, and `sd-server` can run it after image generation. Both perform a cropped -inpaint pass for every detected object. The implementation supports YOLOv8 +A DGL script runs a YOLOv8 object detector on an existing or newly generated +image, then performs a cropped inpaint pass for each selected object. The implementation supports YOLOv8 detection checkpoints. YOLOv8 segmentation and MediaPipe models are not supported yet. +**Currently supported only through dgl.** + ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL usage | Requirement | | --- | --- | --- | --- | -| Base image model | [Compatible image-generation model](README.md) | `-m` / model component options | Required for the inpainting pass | -| YOLOv8 detector | Converted Safetensors checkpoint prepared below | `--ad-model` | Required; detection checkpoints only | +| Base image model | [Compatible image-generation model](README.md) | `load_unet`, `load_text_encoder`, `load_vae` | Required for the inpainting pass | +| YOLOv8 detector | Converted Safetensors checkpoint prepared below | `load_detector` | Required; detection checkpoints only | ### Prepare the detector Run the conversion command from the source repository root, then place the -converted file at the path used by `--ad-model`. +converted file at the script's `model_path`. Ultralytics checkpoints must be converted before use. The converter writes the Safetensors detector used by sd.cpp. @@ -40,176 +41,79 @@ trusted source. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). +### DGL -### CLI +| Example | Description | +| --- | --- | +| [Repair an existing image](../dgl/adetailer/adetailer-existing-image.dgl) | Detect objects and inpaint selected crops. | +| [Generate and refine](../dgl/adetailer/adetailer-generated-image.dgl) | Generate the starting image, then run the same detail pass. | -#### Repair an existing image +#### Run a script -Use the dedicated `adetailer` mode to detect and repair objects in an existing -image: +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - -M adetailer ` - -m ..\models\checkpoints\model.safetensors ` - --ad-model ..\models\detectors\face_yolov8n.safetensors ` - -i input.png ` - -p "detailed portrait photo" ` - --negative-prompt "deformed face" ` - --steps 24 ` - --cfg-scale 6 ` - --strength 0.4 ` - --sampling-method dpm++2m ` - --scheduler karras ` - --extra-ad-args "confidence=0.3,inpaint_padding=32,mask_blur=4" ` - -o repaired.png +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\adetailer\adetailer-existing-image.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - -M adetailer \ - -m ../models/checkpoints/model.safetensors \ - --ad-model ../models/detectors/face_yolov8n.safetensors \ - -i input.png \ - -p "detailed portrait photo" \ - --negative-prompt "deformed face" \ - --steps 24 \ - --cfg-scale 6 \ - --strength 0.4 \ - --sampling-method dpm++2m \ - --scheduler karras \ - --extra-ad-args confidence=0.3,inpaint_padding=32,mask_blur=4 \ - -o repaired.png +./bin/sd-cli -M dgl --script ../docs/dgl/adetailer/adetailer-existing-image.dgl ``` -This mode reuses the normal image-generation options for the detail pass: - -- `--init-img`, `--output`, `--prompt`, and `--negative-prompt` -- `--steps`, `--cfg-scale`, `--sampling-method`, and `--scheduler` -- `--strength`, `--seed`, LoRA settings, VAE tiling, and backend assignments -- `--width` and `--height`, which also resize the input when specified - -`--ad-prompt` and `--ad-negative-prompt` optionally override the normal prompts. -Values provided in `--extra-ad-args`, such as `steps`, `cfg_scale`, -`denoising_strength`, or `inpaint_width`, take precedence over inherited values. - -#### Repair generated images - -ADetailer can also run automatically after normal image generation: - -**Windows (PowerShell)** +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. -```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\model.safetensors ` - --ad-model ..\models\detectors\face_yolov8n.safetensors ` - -p "portrait photo" ` - --ad-prompt "[PROMPT], detailed face" ` - --ad-negative-prompt "" ` - --extra-ad-args "confidence=0.3,denoising_strength=0.4,inpaint_width=512,inpaint_height=512" -``` +The [ADetailer script](../dgl/adetailer/adetailer-existing-image.dgl) loads a YOLOv8 detector +and an inpainting model. Set `confidence` and `nms` on `detections::detect`, and use +`detections::filter` to select the boxes to repaint. The script converts +the boxes to masks, plans crops with `regions::plan_mask_crops`, then assigns prompts and +seeds and blends each inpainted crop into the current image. See +[DGL detail refinement](../dgl.md#detail-refinement) for the data layout. -**Linux/macOS** - -```sh -./bin/sd-cli \ - -m ../models/checkpoints/model.safetensors \ - --ad-model ../models/detectors/face_yolov8n.safetensors \ - -p "portrait photo" \ - --ad-prompt "[PROMPT], detailed face" \ - --ad-negative-prompt "" \ - --extra-ad-args confidence=0.3,denoising_strength=0.4,inpaint_width=512,inpaint_height=512 -``` - -The same options can be supplied when starting `sd-server`. When `--ad-model` is set, its detector runs after OpenAI-compatible and native asynchronous image generation. SDAPI requests enable ADetailer through `alwayson_scripts`, as described below. If no object is detected, the original image is returned unchanged. RGBA output keeps its original alpha channel, including when detected regions are repaired. Detector initialization or detail-pass failures are reported as request failures. - -Server image-generation requests limit base, hires, and detail-pass dimensions to 4096 pixels per side. ADetailer step overrides are limited to 1–100; `steps=0` in `extra_ad_args` keeps inheriting the main generation steps. These limits also apply to inherited dimensions and `extra_ad_args` overrides. Requests exceeding the limits return a parameter error before generation. CLI limits are unchanged. - -### SDAPI requests +#### Repair an existing image -`/sdapi/v1/txt2img` and `/sdapi/v1/img2img` accept the WebUI ADetailer argument format: +The script loads `input_path`, detects objects and repairs their crops. -```json -{ - "prompt": "portrait photo", - "alwayson_scripts": { - "ADetailer": { - "args": [true, false, { - "ad_model": "face_yolov8n.pt", - "ad_prompt": "[PROMPT], detailed face", - "ad_use_steps": true, - "ad_steps": 20 - }] - } - } -} -``` +Edit `detail_prompt`, `negative_prompt`, `seed` and the `settings` dict in the +script. The detector and mask operations are explicit, so filtering and crop +geometry can be changed independently. -The detector must be configured at server startup with `--ad-model`. `ad_model` must match that file's basename; the original `.pt` basename is also accepted for a converted detector. Requests cannot load arbitrary detector paths. Omitting the script, setting its first argument to `false`, selecting `"None"`, or setting `ad_tab_enable` to `false` disables detailing. Dictionary-only argument arrays are also accepted. Multiple enabled dictionaries run in order using the configured detector. +#### Repair generated images -Supported settings include prompts, confidence, mask filtering by area or confidence, mask count and area ratios, dilation/erosion, offsets, mask merging/inversion, blur, denoising strength, masked or full-image inpainting, padding, and optional overrides for inpaint dimensions, steps, CFG, sampler/scheduler, and CLIP skip. The corresponding `ad_use_*` flags control whether overrides apply. Otherwise dimensions, steps, CFG, sampler, scheduler, and CLIP skip inherit the main request. Denoising strength defaults to `0.4`. Pixel mask settings are limited to the larger output dimension, with a minimum limit of 32 and a maximum of 16384 pixels. +This script generates the starting image, then runs the same detail pass. -Model/VAE switching, non-default noise multipliers, face restoration, ControlNet, and skipping the initial img2img pass are not supported; active requests for these features return an error. Unknown settings and invalid active values also return errors. During detailing, `/sdapi/v1/progress` remains active with an `adetailer` job; its percentage and preview stay fixed until detailing finishes. +If no object is detected, `fold` returns the original image unchanged. +The crop/paste helpers preserve the original alpha channel. Detector or detail +failures stop the script. Run the same program through the server's DGL editor; +the removed native ADetailer mode and SDAPI recipe are not execution paths. ## Options -An empty ADetailer prompt inherits the main prompt. `[PROMPT]` inserts the main -prompt, `[SEP]` assigns different prompts to consecutive masks, and `[SKIP]` -skips the corresponding mask. - -All settings other than the detector path and prompts are passed through -`--extra-ad-args` as a comma-separated `key=value` list: - -| Key | Default | Description | -| --- | ---: | --- | -| `input_size` | `640` | Square YOLO input size; must be a multiple of 32 | -| `confidence` | `0.3` | Detection confidence threshold | -| `nms` | `0.45` | NMS IoU threshold | -| `max_detections` | `100` | Maximum detections retained after NMS | -| `mask_k_largest` | `0` | Keep only the largest K masks; zero keeps all | -| `mask_filter_method` | `area` | Rank retained masks by `area` or `confidence` | -| `mask_min_ratio` | `0` | Minimum bbox area relative to the image | -| `mask_max_ratio` | `1` | Maximum bbox area relative to the image | -| `dilate_erode` | `4` | Positive values dilate; negative values erode | -| `x_offset`, `y_offset` | `0` | Mask offset in pixels; positive Y moves upward | -| `mask_mode` | `none` | `none`, `merge`, or `merge_invert` | -| `merge_masks`, `invert_mask` | `false` | Boolean alternatives to `mask_mode` | -| `mask_blur` | `4` | Final composite feather radius | -| `inpaint_padding` | `32` | Padding around the detected region | -| `inpaint_only_masked` | `true` | Crop to the detected region; `false` uses the full image with the detection mask | -| `inpaint_width`, `inpaint_height` | mode-specific | `512x512` after generation; input/output size in `adetailer` mode | -| `denoising_strength` | mode-specific | `0.4` after generation; inherits `--strength` in `adetailer` mode | -| `steps` | `0` | Detail steps; zero inherits the main generation | -| `cfg_scale` | `-1` | Detail CFG; a negative value inherits the main generation | -| `sample_method` | inherited | Detail sampler name | -| `scheduler` | inherited | Detail scheduler name | -| `sort_by` | `none` | `none`, `left_to_right`, `center_to_edge`, or `area` | - -Multiple masks are processed serially. Each completed inpaint becomes the input -for the next mask, and the seed is incremented by the mask index. Use -`mask_mode=merge` to process all detections in one inpaint pass. - -The detector uses the `detector` backend module. For example, keep detection on -the CPU while diffusion runs on CUDA: - -**Windows (PowerShell) arguments** - -```text ---backend "diffusion=cuda0,detector=cpu" -``` +The example's `settings` dict controls crop size, steps, denoising strength, +CFG, sampler, scheduler and mask blur. Each stage has its own parameters: -**Linux/macOS arguments** +| Stage | DGL operation | Settings | +| --- | --- | --- | +| Detection | `detections::detect` | `input_size`, `confidence`, `nms`, `max_detections` | +| Selection | `detections::filter` | `top_k`, `top_k_by`, area ratios and ordering | +| Masks | `detections::box_masks` and tensor operations | Dilation, offsets, merging and blur | +| Crop planning | `regions::plan_mask_crops` | `aspect`, `padding` | +| Refinement | `fold(..., process=refine_region)` | Prompts, `seed + region.index`, `settings` | -```text ---backend diffusion=cuda0,detector=cpu -``` +Crops are processed in order; each repaired image becomes the next iteration's +canvas. To run detection on CPU and diffusion on CUDA, set `backend="cpu"` on +`load_detector` and `backend="cuda0"` on `load_unet`. The script decides prompt +assignment explicitly; it does not parse legacy `[SEP]` / `[SKIP]` directives or +`--extra-ad-args`. ## Notes and limitations -YOLOv8 segmentation and MediaPipe detectors are not supported. See the -[server API reference](../../examples/server/api.md) for request schemas. +YOLOv8 segmentation and MediaPipe detectors are not supported. +Use the [DGL API](../dgl.md#c-api) to run a complete program from a library caller. diff --git a/docs/models/anima.md b/docs/models/anima.md index 38f19f612a..8a928cca17 100644 --- a/docs/models/anima.md +++ b/docs/models/anima.md @@ -12,8 +12,6 @@ Anima generates images from text using a Qwen3 text encoder and a compatible Qwe ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -24,12 +22,47 @@ Use the files and compatibility requirements in [Model files](#model-files). | Recipe | Component slots | | --- | --- | | Anima (`anima`) | `diffusion_model`, `llm`, `vae`, `tae` | +| Anima Edit (`anima-edit`) | `diffusion_model`, `llm`, `vae`, `tae` | Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +For Anima Edit, select a matching community editing LoRA separately and provide +reference images. The references are VAE-encoded for diffusion conditioning; +selecting the recipe does not load the LoRA automatically. + +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/anima/anima-preview-txt2img.dgl) | Anima Preview. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\anima\anima-preview-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/anima/anima-preview-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/animatediff.md b/docs/models/animatediff.md index ef110febcc..0e1fcc9700 100644 --- a/docs/models/animatediff.md +++ b/docs/models/animatediff.md @@ -6,6 +6,8 @@ Use the SD 1.5 checkpoint for the desired characters and style, and choose the motion module and resolution below. See the [AnimateDiff paper](https://arxiv.org/abs/2307.04725) for the model reference. +**Currently supported only through dgl.** + ## Supported variants Per [animatediff.net/models](https://animatediff.net/models): @@ -18,17 +20,17 @@ Per [animatediff.net/models](https://animatediff.net/models): | `v3_sd15_mm.ckpt` | 1.5 | 512x512 | smoothest, highest quality; pairs with a Domain Adapter LoRA | | `mm_sdxl_v10_beta` | SDXL | 512x512 | experimental, not yet supported here | -Match your `-H -W` to the module's native resolution for best results. v3 is +Match `height` and `width` to the module's native resolution for best results. v3 is trained at 512x512 - going smaller (e.g. 384x384) still works but the motion character is closer to v2. ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL usage | Requirement | | --- | --- | --- | --- | -| SD 1.5 checkpoint | [Compatible SD 1.5 checkpoint](sd.md) | `-m` / `--model` | Required; SDXL motion modules are not supported | -| Motion module | v1/v2/v3 motion weights listed below | `--motion-module` | Required; match the resolution and version | -| Domain adapter LoRA | v3 adapter listed below | `--lora-model-dir` and prompt | Optional; v3 only | +| SD 1.5 checkpoint | [Compatible SD 1.5 checkpoint](sd.md) | `load_unet`, `load_text_encoder`, `load_vae` | Required; SDXL motion modules are not supported | +| Motion module | v1/v2/v3 motion weights listed below | `animatediff::load` | Required; match the resolution and version | +| Domain adapter LoRA | v3 adapter listed below | `load_lora`, `apply_lora` | Optional; v3 only | - Motion module (v3, recommended) - fp16 safetensors: https://huggingface.co/conrevo/AnimateDiff-A1111/resolve/main/motion_module/mm_sd15_v3.safetensors @@ -39,170 +41,73 @@ character is closer to v2. - Domain Adapter LoRA (optional, v3 only, sharpens the base UNet's output toward the motion module's trained distribution) - ckpt: https://huggingface.co/guoyww/animatediff/resolve/main/v3_sd15_adapter.ckpt - - place under your `--lora-model-dir` and reference in the prompt as - ``. + - load it with `load_lora` and apply it to the UNet with `apply_lora`. The motion module is `~836 MB` and loads alongside the SD 1.5 UNet via -`--motion-module`. +`animatediff::load` / `animatediff::apply`. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI -Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the -server, then select the recipe matching your weights. Fill the component slots -below and click **Load models**. -Use the files and compatibility requirements in [Model files](#model-files). +Open the server's **DGL editor**, edit the same script, and submit it. +Model and input paths must satisfy the server's file-access policy; save outputs +inside its `output/` directory. See the [Web UI guide](../../examples/server/README.md#web-ui). -| Recipe | Component slots | +### DGL + +| Example | Description | | --- | --- | -| AnimateDiff SD 1.5 (`animatediff-sd15`) | `model`, `motion_module`, `vae`, `tae` | +| [Text to video with CPU offload](../dgl/animatediff/animatediff-realisticvision-v6-txt2video-cpu-offload.dgl) | 8 frames at 512 x 512. | +| [Text to video, 16 frames](../dgl/animatediff/animatediff-realisticvision-v6-txt2video-16-frames.dgl) | Native motion-module context at 384 x 384. | +| [Text to video with a VRAM budget](../dgl/animatediff/animatediff-realisticvision-v6-txt2video-vram-budget.dgl) | Run with `--max-vram 2.0`. | +| [Domain Adapter LoRA](../dgl/animatediff/animatediff-realisticvision-v6-domain-lora.dgl) | Add the v3 adapter before sampling. | +| [Generate the initial image](../dgl/animatediff/realisticvision-v6-txt2img.dgl) | Prepare a still image for the image-to-video example. | +| [Image to video](../dgl/animatediff/animatediff-realisticvision-v6-img2video.dgl) | Animate an existing image. | -Slot IDs correspond to CLI component options: `diffusion_model` uses -`--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. -Select optional components when required by your checkpoint or task. +#### Run a script -### CLI - -#### Text-to-video - -Generate an 8-frame animation at 512x512, seed 42, 20 steps. The sampler / -scheduler / CFG values below match what mm_sd15_v3 was trained with; using -SD 1.5 defaults (euler_a, low CFG) produces noise-like output. +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - -M vid_gen ` - --model ..\models\checkpoints\realisticVisionV60B1.safetensors ` - --motion-module ..\models\motion_modules\animatediff\mm_sd15_v3.safetensors ` - -p "a red apple on a wooden table" ` - --cfg-scale 8.0 ` - --sampling-method euler ` - --scheduler discrete ` - --steps 20 ` - -H 512 ` - -W 512 ` - --video-frames 8 ` - --fps 8 ` - --offload-to-cpu ` - -s 42 ` - -o out.avi +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\animatediff\animatediff-realisticvision-v6-txt2video-cpu-offload.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - -M vid_gen \ - --model ../models/checkpoints/realisticVisionV60B1.safetensors \ - --motion-module ../models/motion_modules/animatediff/mm_sd15_v3.safetensors \ - -p "a red apple on a wooden table" \ - --cfg-scale 8.0 \ - --sampling-method euler \ - --scheduler discrete \ - --steps 20 \ - -H 512 \ - -W 512 \ - --video-frames 8 \ - --fps 8 \ - --offload-to-cpu \ - -s 42 \ - -o out.avi +./bin/sd-cli -M dgl --script ../docs/dgl/animatediff/animatediff-realisticvision-v6-txt2video-cpu-offload.dgl ``` -Generate at the motion module's native 16-frame context (recommended for -best temporal quality). Needs more VRAM at 512x512, so drop to 384x384 or -use layer streaming: +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. -**Windows (PowerShell)** +Load the SD 1.5 UNet with `load_unet` and the motion weights with +`animatediff::load`. Use the same compute backend for both models. +`animatediff::apply(unet, motion)` returns a denoiser that shares the original +UNet and adds the motion module. Pass it to both CFG predictors and set the +frame count through the latent shape, for example with +`latent_shape(vae, width = 512, height = 512, batch = 16)`. +The motion checkpoint's positional encoding sets the frame limit. -```powershell -.\bin\Release\sd-cli.exe ` - -M vid_gen ` - --model ..\models\checkpoints\realisticVisionV60B1.safetensors ` - --motion-module ..\models\motion_modules\animatediff\mm_sd15_v3.safetensors ` - -p "photo of coastline, rocks, storm weather, wind, waves, lightning" ` - --cfg-scale 8.0 ` - --sampling-method euler ` - --scheduler discrete ` - --steps 20 ` - -H 384 ` - -W 384 ` - --video-frames 16 ` - --fps 8 ` - --offload-to-cpu ` - -s 42 ` - -o out.avi -``` +Use `load_lora` and `apply_lora` for an optional v3 domain adapter. -**Linux/macOS** - -```sh -./bin/sd-cli \ - -M vid_gen \ - --model ../models/checkpoints/realisticVisionV60B1.safetensors \ - --motion-module ../models/motion_modules/animatediff/mm_sd15_v3.safetensors \ - -p "photo of coastline, rocks, storm weather, wind, waves, lightning" \ - --cfg-scale 8.0 \ - --sampling-method euler \ - --scheduler discrete \ - --steps 20 \ - -H 384 \ - -W 384 \ - --video-frames 16 \ - --fps 8 \ - --offload-to-cpu \ - -s 42 \ - -o out.avi -``` - -Low-VRAM streaming (verified with a 2 GiB cap on RTX 3060): - -**Windows (PowerShell)** +#### Text-to-video -```powershell -.\bin\Release\sd-cli.exe ` - -M vid_gen ` - --model ..\models\checkpoints\realisticVisionV60B1.safetensors ` - --motion-module ..\models\motion_modules\animatediff\mm_sd15_v3.safetensors ` - -p "photo of coastline, rocks, storm weather, wind, waves, lightning" ` - --cfg-scale 8.0 ` - --sampling-method euler ` - --scheduler discrete ` - --steps 20 ` - -H 384 ` - -W 384 ` - --video-frames 8 ` - --fps 8 ` - --max-vram 2.0 ` - -s 42 ` - -o out.avi -``` +Generate an 8-frame animation at 512x512, seed 42, 20 steps. The sampler / +scheduler / CFG values in the scripts match what mm_sd15_v3 was trained with; using +SD 1.5 defaults (euler_a, low CFG) produces noise-like output. -**Linux/macOS** +Generate at the motion module's native 16-frame context (recommended for +best temporal quality). Needs more VRAM at 512x512, so drop to 384x384 or +use the VRAM-budget example. -```sh -./bin/sd-cli \ - -M vid_gen \ - --model ../models/checkpoints/realisticVisionV60B1.safetensors \ - --motion-module ../models/motion_modules/animatediff/mm_sd15_v3.safetensors \ - -p "photo of coastline, rocks, storm weather, wind, waves, lightning" \ - --cfg-scale 8.0 \ - --sampling-method euler \ - --scheduler discrete \ - --steps 20 \ - -H 384 \ - -W 384 \ - --video-frames 8 \ - --fps 8 \ - --max-vram 2.0 \ - -s 42 \ - -o out.avi -``` +The streaming example uses `--max-vram 2.0` (verified on RTX 3060). #### Reference-quality reproduction @@ -245,97 +150,29 @@ prompt, seed, config as above: Individual fur strands, glowing inner-ear, and richer forest detail become visible compared to the no-LoRA rendering. -**Windows (PowerShell)** - -```powershell -.\bin\Release\sd-cli.exe ` - -M vid_gen ` - --model ..\models\checkpoints\realisticVisionV60B1.safetensors ` - --motion-module ..\models\motion_modules\mm_sd15_v3.safetensors ` - --lora-model-dir .\loras ` - -p "close up photo of a rabbit ..." ... -``` - -**Linux/macOS** - -```sh -./bin/sd-cli \ - -M vid_gen \ - --model ../models/checkpoints/realisticVisionV60B1.safetensors \ - --motion-module ../models/motion_modules/mm_sd15_v3.safetensors \ - --lora-model-dir ./loras \ - -p "close up photo of a rabbit ..." ... -``` - #### img2video -Pass a pre-rendered image via `-i / --init-img` to animate FROM it. All N output frames start from the encoded init latent, then per-frame noise is added at `--strength`. Character identity, composition, and quality are anchored by the init image; the motion module adds subtle motion on top. +Set `input_path` to the pre-rendered image. All output frames start from its encoded latent, then receive noise according to `strength`. Character identity, composition, and quality are anchored by the init image; the motion module adds subtle motion on top. -Left: init image rendered with `-M img_gen`. Right: 8-frame vid_gen output. +Left: generated starting image. Right: 8-frame AnimateDiff output. -**Windows (PowerShell)** - -```powershell -.\bin\Release\sd-cli.exe ` - -M img_gen ... ` - -o init.png "#" any high-quality still -.\bin\Release\sd-cli.exe ` - -M vid_gen ` - --motion-module ..\models\motion_modules\mm_sd15_v3.safetensors ` - -i init.png ` - -p ... ` - --strength 0.75 ` - --cfg-scale 7.0 ` - --sampling-method euler ` - --scheduler karras ` - --steps 25 ` - -H 512 ` - -W 512 ` - --video-frames 8 ` - -s 42 ` - -o out.avi -``` - -**Linux/macOS** - -```sh -./bin/sd-cli \ - -M img_gen ... \ - -o init.png "#" any high-quality still -./bin/sd-cli \ - -M vid_gen \ - --motion-module ../models/motion_modules/mm_sd15_v3.safetensors \ - -i init.png \ - -p ... \ - --strength 0.75 \ - --cfg-scale 7.0 \ - --sampling-method euler \ - --scheduler karras \ - --steps 25 \ - -H 512 \ - -W 512 \ - --video-frames 8 \ - -s 42 \ - -o out.avi -``` - -`--strength` controls how far the motion module is allowed to deviate from the init image (higher = more motion, lower = more static). +`strength` controls how far the motion module is allowed to deviate from the init image (higher = more motion, lower = more static). ## Notes and limitations - The motion module was trained at `video_length=16`. Running with - `--video-frames 16` gives the best coherence; F=8 works but shows a shorter + `frames = 16` gives the best coherence; F=8 works but shows a shorter motion arc. Frame counts up to 32 are supported by the positional encoding but exceed the trained regime and produce more static output. -- At `--video-frames 1` the motion module is skipped entirely and the output - is bit-identical to `-M img_gen`. This avoids the single-token +- At `frames = 1` the motion module is skipped entirely and the output + is bit-identical to ordinary image sampling. This avoids the single-token temporal-attention degeneracy that would otherwise emit an untrained-magnitude residual on a single-frame sample. - The base UNet is frozen, so character identity and style follow the SD 1.5 - checkpoint you pass to `--model`. LoRAs and prompt weighting attach to the + checkpoint selected by `weights`. LoRAs and prompt weighting attach to the base model in the usual way. - No mid_block motion module in v3. `mm_sdxl_v10_beta` (SDXL variant) is not supported yet. -- Output is written as MJPEG AVI. Use `--fps` to set playback speed. +- Output is written as MJPEG AVI. Use `fps` to set playback speed. diff --git a/docs/models/boogu_image.md b/docs/models/boogu_image.md index d7d133cd3f..7aeff1bbb6 100644 --- a/docs/models/boogu_image.md +++ b/docs/models/boogu_image.md @@ -12,8 +12,6 @@ Boogu Image uses a Boogu diffusion transformer, the FLUX VAE, and Qwen3-VL as th ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -30,7 +28,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/boogu_image/boogu-image-base-txt2img.dgl) | Boogu Image Base. | +| [Image editing](../dgl/boogu_image/boogu-image-edit.dgl) | Boogu Image Edit. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\boogu_image\boogu-image-base-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/boogu_image/boogu-image-base-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Boogu Image Base diff --git a/docs/models/chroma.md b/docs/models/chroma.md index 51c9685981..c02ce567fd 100644 --- a/docs/models/chroma.md +++ b/docs/models/chroma.md @@ -45,8 +45,6 @@ You can download the preconverted gguf weights from [silveroxides/Chroma-GGUF](h ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -62,7 +60,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/chroma/chroma-unlocked-v40-txt2img.dgl) | Chroma Unlocked v40. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\chroma\chroma-unlocked-v40-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/chroma/chroma-unlocked-v40-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Example diff --git a/docs/models/chroma_radiance.md b/docs/models/chroma_radiance.md index dbb8ad5744..0a938dc7de 100644 --- a/docs/models/chroma_radiance.md +++ b/docs/models/chroma_radiance.md @@ -11,8 +11,6 @@ Chroma1-Radiance generates images directly in pixel space using T5-XXL. No VAE i ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -28,7 +26,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/chroma_radiance/chroma1-radiance-v0-4-txt2img.dgl) | Generate pixels directly, without a VAE. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\chroma_radiance\chroma1-radiance-v0-4-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/chroma_radiance/chroma1-radiance-v0-4-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/distilled_sd.md b/docs/models/distilled_sd.md index 30e75aa4bc..3a3f53a698 100644 --- a/docs/models/distilled_sd.md +++ b/docs/models/distilled_sd.md @@ -131,8 +131,6 @@ For the use of this model, both options `--cfg-scale 1` and `--steps 1` are agai ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -151,7 +149,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [SSD1B](../dgl/distilled_sd/ssd1b-txt2img.dgl) | Text-to-image generation. | +| [SDXS-512-DreamShaper](../dgl/distilled_sd/sdxs-512-dreamshaper-txt2img.dgl) | Distilled text-to-image generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\distilled_sd\ssd1b-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/distilled_sd/ssd1b-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### SSD1B @@ -197,6 +226,9 @@ SSD-1B, Vega, and Tiny SD variants reduce the base model size. Details are in th [SSD-1B paper](https://arxiv.org/abs/2401.02677v1) and [Tiny SD paper](https://arxiv.org/pdf/2305.15798.pdf). Follow the [SDXS generation settings](#sdxs-512-dreamshaper); CFG 1 and one step are required. +For SDXS, a configured `taesd_path` is used for final output even when +`tae_preview_only` is enabled, because these models require the tiny autoencoder. + Run the Python conversion commands in [Model files](#model-files) from the source repository root, with the listed conversion script and Python dependencies installed. Return to the build directory for the platform-specific CLI commands. diff --git a/docs/models/ernie_image.md b/docs/models/ernie_image.md index e4e30698af..41e0d3b1bb 100644 --- a/docs/models/ernie_image.md +++ b/docs/models/ernie_image.md @@ -16,8 +16,6 @@ You can run ERNIE-Image with stable-diffusion.cpp on GPUs with 4GB of VRAM — o ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -34,7 +32,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [ERNIE-Image Turbo](../dgl/ernie_image/ernie-image-turbo-txt2img.dgl) | Text-to-image generation. | +| [ERNIE-Image](../dgl/ernie_image/ernie-image-txt2img.dgl) | Text-to-image generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\ernie_image\ernie-image-turbo-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/ernie_image/ernie-image-turbo-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### ERNIE-Image-Turbo diff --git a/docs/models/esrgan.md b/docs/models/esrgan.md index 3d1a589e28..42e820ec1a 100644 --- a/docs/models/esrgan.md +++ b/docs/models/esrgan.md @@ -1,40 +1,48 @@ # ESRGAN and MoSR -ESRGAN and compatible MoSR weights upscale generated images. Pass the chosen -upscaler with `--upscale-model`. +ESRGAN and compatible MoSR weights upscale images. **Chaining generation and +upscaling is currently supported only through DGL**, as shown below. Standalone +CLI upscaling remains available with `-M upscale --upscale-model FILE -i INPUT`. ## Model files | Component | Weights and downloads | CLI option | Requirement | | --- | --- | --- | --- | | Base model | [Stable Diffusion checkpoint](sd.md) | `-m` / `--model` | Required for generation below | -| ESRGAN upscaler | [RealESRGAN_x4plus_anime_6B.pth](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth) | `--upscale-model` | Choose a compatible upscaler | -| MoSR upscaler | [4xNomos2_hq_mosr.pth](https://github.com/Phhofm/models/releases/download/4xNomos2_hq_mosr/4xNomos2_hq_mosr.pth) | `--upscale-model` | Alternative; requires the PixelShuffle upsampler | +| ESRGAN upscaler | [RealESRGAN_x4plus_anime_6B.pth](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth) | `load_upscaler` (DGL) / `--upscale-model` (standalone CLI) | Choose a compatible upscaler | +| MoSR upscaler | [4xNomos2_hq_mosr.pth](https://github.com/Phhofm/models/releases/download/4xNomos2_hq_mosr/4xNomos2_hq_mosr.pth) | `load_upscaler` (DGL) / `--upscale-model` (standalone CLI) | Alternative; requires the PixelShuffle upsampler | ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). +### DGL -### CLI +| Example | Description | +| --- | --- | +| [Generate and upscale](../dgl/esrgan/sd1-5-txt2img-esrgan.dgl) | SD 1.5 generation followed by RealESRGAN. | +| [Upscale an image](../dgl/esrgan/realesrgan-x4plus-anime-6b-upscale.dgl) | Run RealESRGAN on an existing image. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\v1-5-pruned-emaonly.safetensors ` - --upscale-model ..\models\upscale_models\RealESRGAN_x4plus_anime_6B.pth ` - -p "a lovely cat" +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\esrgan\sd1-5-txt2img-esrgan.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - -m ../models/checkpoints/v1-5-pruned-emaonly.safetensors \ - --upscale-model ../models/upscale_models/RealESRGAN_x4plus_anime_6B.pth \ - -p "a lovely cat" +./bin/sd-cli -M dgl --script ../docs/dgl/esrgan/sd1-5-txt2img-esrgan.dgl ``` +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + ## Notes and limitations RGBA output retains its alpha channel during model upscaling and hires fix. diff --git a/docs/models/fibo2.md b/docs/models/fibo2.md index 4919bda126..429c42a307 100644 --- a/docs/models/fibo2.md +++ b/docs/models/fibo2.md @@ -17,8 +17,6 @@ INT8 convrot weights load directly; see [INT8 convrot](../guides/int8_convrot.md ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -35,7 +33,39 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Dev: text to image](../dgl/fibo2/fibo2-dev-txt2img.dgl) | Generate an image from a prompt. | +| [Dev: image editing](../dgl/fibo2/fibo2-dev-edit.dgl) | Edit a reference image. | +| [Edit Turbo](../dgl/fibo2/fibo2-edit-turbo.dgl) | Image editing with distilled weights. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\fibo2\fibo2-dev-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/fibo2/fibo2-dev-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Fibo 2.0 Dev @@ -147,8 +177,9 @@ Edit Turbo is distilled for reference-image editing in 4 steps with CFG 1. The BF16 files accept the same options. Use dimensions divisible by 16. Repeat `-r` to use multiple reference images; instructions can refer to ``, ``, etc. See [Image Editing](../guides/edit.md) for reference-image preprocessing options. Separate GGUF text encoders need their vision projector passed with `--llm_vision` for editing. -The automatic `fibo2` reference preset combines `resize_single_ref_to_target=true`, `vae_size_buckets=true`, `vae_center_crop=true`, and `vlm_use_vae_input=true`. A single reference is scaled to cover the output dimensions and center-cropped. Multiple references use dimensions divisible by 16, chosen within ±10% of one megapixel to minimize cropping for each image's aspect ratio; `vae_input_max_pixels` overrides that target area. The VAE and vision encoder receive the same crops, with smaller copies used by the vision encoder. These are generic reference-image options and can be overridden individually: for example, `--ref-image-args vae_center_crop=false` uses direct resizing, while `resize_before_vae=false` skips this automatic crop and resize step entirely. - -The vision encoder defaults to `vlm_resize_mode=longest_side,vlm_max_size=768`. Override these with `--ref-image-args`, for example `vlm_max_size=512`, or use `vlm_resize_mode=none` to skip size-based scaling. Vision inputs are still aligned to the encoder's patch grid. - -Plain prompts and structured JSON captions are accepted. This integration uses the caption-only text-rendering path (`render_text_images=False`); it does not generate auxiliary glyph images or expand prompts with Bria VGL. Native Fibo mask preprocessing is not connected to `--mask`. +The default reference policy scales and center-crops a single reference to +the output dimensions. Multiple references use aspect-ratio buckets near one +megapixel, aligned to 16 pixels. VAE and vision encoding share those crops; +the vision encoder uses a smaller copy with a maximum side of 768 pixels. +Use a [DGL editing workflow](../guides/edit.md#custom-reference-processing) for +custom geometry or different VAE and vision inputs. diff --git a/docs/models/flux.md b/docs/models/flux.md index dd67bbd67a..eec26dc8c0 100644 --- a/docs/models/flux.md +++ b/docs/models/flux.md @@ -47,8 +47,6 @@ For example: ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -65,7 +63,39 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [FLUX.1 dev](../dgl/flux/flux1-dev-txt2img.dgl) | Text-to-image generation. | +| [FLUX.1 schnell](../dgl/flux/flux1-schnell-txt2img.dgl) | Distilled text-to-image generation. | +| [FLUX.1 dev with LoRA](../dgl/flux/flux1-dev-lora.dgl) | Apply a LoRA before generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\flux\flux1-dev-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/flux/flux1-dev-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). - `--cfg-scale` is recommended to be set to 1. diff --git a/docs/models/flux2.md b/docs/models/flux2.md index fdca1b2456..2e9fdf4890 100644 --- a/docs/models/flux2.md +++ b/docs/models/flux2.md @@ -35,8 +35,6 @@ the text encoder matching the transformer variant. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -56,7 +54,43 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Dev: image editing](../dgl/flux2/flux2-dev-edit.dgl) | Edit a reference image. | +| [Klein 4B: text to image](../dgl/flux2/flux2-klein-4b-txt2img.dgl) | Distilled 4B checkpoint. | +| [Klein 4B: image editing](../dgl/flux2/flux2-klein-4b-edit.dgl) | Distilled 4B checkpoint. | +| [Klein Base 4B: text to image](../dgl/flux2/flux2-klein-base-4b-txt2img.dgl) | Base 4B checkpoint. | +| [Klein 9B: text to image](../dgl/flux2/flux2-klein-9b-txt2img.dgl) | Distilled 9B checkpoint. | +| [Klein 9B: image editing](../dgl/flux2/flux2-klein-9b-edit.dgl) | Distilled 9B checkpoint. | +| [Klein Base 9B: text to image](../dgl/flux2/flux2-klein-base-9b-txt2img.dgl) | Base 9B checkpoint. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\flux2\flux2-dev-edit.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/flux2/flux2-dev-edit.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Flux.2-dev diff --git a/docs/models/flux3.md b/docs/models/flux3.md index 7591d7cd13..5fde15fb5d 100644 --- a/docs/models/flux3.md +++ b/docs/models/flux3.md @@ -15,8 +15,6 @@ Use the root `model.safetensors` for the diffusion model. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -33,7 +31,39 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Klein: text to image](../dgl/flux3/flux3-image-klein-txt2img.dgl) | Distilled checkpoint. | +| [Klein: image editing](../dgl/flux3/flux3-image-klein-edit.dgl) | Edit a reference image. | +| [Klein Base: text to image](../dgl/flux3/flux3-image-klein-base-txt2img.dgl) | Base checkpoint. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\flux3\flux3-image-klein-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/flux3/flux3-image-klein-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### FLUX.3 Image Klein diff --git a/docs/models/hidream_o1_image.md b/docs/models/hidream_o1_image.md index 09f7ac725f..713a9b49e7 100644 --- a/docs/models/hidream_o1_image.md +++ b/docs/models/hidream_o1_image.md @@ -1,24 +1,40 @@ # HiDream-O1-Image -HiDream-O1-Image uses a bundled model checkpoint. The example below uses the Dev checkpoint. +HiDream-O1-Image supports text-to-image generation and reference-image editing +with a bundled model checkpoint. Choose the Dev or full checkpoint. + +## Supported variants + +Use the settings below for text-to-image in stable-diffusion.cpp. + +| Checkpoint | `--steps` | `--cfg-scale` | `-W` / `-H` | Sampling options | +| --- | --- | --- | --- | --- | +| Dev (distilled) | 28 | 1.0 | 1024 | `--sampling-method lcm --extra-sample-args noise_scale_start=7.5,noise_scale_end=7.5,noise_clip_std=2.5` | +| HiDream-O1-Image (full) | 50 | 5.0 | 2048 (1024 works) | `--sampling-method euler` | + +For Dev, use `lcm` with the noise settings above to reduce white speckles seen +with `euler`. The default LCM noise settings can produce nearly flat images. +The Dev settings were tested with Q5_0 GGUF weights at 768×768 and 1024×1024. +Use the default flow shift for the full checkpoint. ## Model files | Component | Weights and downloads | CLI option | Requirement | | --- | --- | --- | --- | -| HiDream-O1-Image-Dev | [Safetensors](https://huggingface.co/Comfy-Org/HiDream-O1-Image/tree/main/checkpoints) | `--model` | Choose matching variant | -| HiDream-O1-Image | [Safetensors](https://huggingface.co/Comfy-Org/HiDream-O1-Image/tree/main/checkpoints) | `--model` | Choose matching variant | +| HiDream-O1-Image-Dev | [Safetensors](https://huggingface.co/Comfy-Org/HiDream-O1-Image/tree/main/checkpoints), [GGUF](https://huggingface.co/Solictous/HiDream-O1-Image-GGUF/blob/main/hidream_o1_image_dev_q5_0_akv.gguf) | `--model` | Choose matching variant | +| HiDream-O1-Image | [Safetensors](https://huggingface.co/Comfy-Org/HiDream-O1-Image/tree/main/checkpoints), [GGUF](https://huggingface.co/Solictous/HiDream-O1-Image-GGUF/blob/main/hidream_o1_image_q5_0_akv.gguf) | `--model` | Choose matching variant | ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the server, then select the recipe matching your weights. Fill the component slots below and click **Load models**. Use the files and compatibility requirements in [Model files](#model-files). +The Dev recipe preselects `euler` in the Web UI sampler menu. To pass the LCM +noise arguments for Dev text-to-image, use the [DGL script](#dgl) or the +[Legacy CLI example](#hidream-o1-image-dev). | Recipe | Component slots | | --- | --- | @@ -28,7 +44,49 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/hidream_o1_image/hidream-o1-image-dev-txt2img.dgl) | HiDream O1 Image Dev. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\hidream_o1_image\hidream-o1-image-dev-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/hidream_o1_image/hidream-o1-image-dev-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +HiDream O1 uses initial Gaussian noise with a standard deviation of 8. The DGL +example controls this with `noise_scale` before `add_noise`: + +```text +noise = tensor::affine(tensor::randn_like(base, rng = rng), scale = noise_scale) +start = add_noise(predict, base, noise, sigma = sigmas[0]) +``` + +Use the same RNG for initial noise and sampling. The initial noise scale is +independent of the sampler's `eta` parameter. The script passes +`extra_sample_args` to `sample` to control the noise added between LCM steps. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### HiDream-O1-Image-Dev @@ -38,7 +96,10 @@ Select optional components when required by your checkpoint or task. .\bin\Release\sd-cli.exe ` -m ..\models\checkpoints\hidream_o1_image_dev_bf16.safetensors ` -p "a lovely cat holding a sign says 'hidream o1 cpp'" ` + --steps 28 ` --cfg-scale 1.0 ` + --sampling-method lcm ` + --extra-sample-args noise_scale_start=7.5,noise_scale_end=7.5,noise_clip_std=2.5 ` -H 1024 ` -W 1024 ` -v @@ -50,10 +111,48 @@ Select optional components when required by your checkpoint or task. ./bin/sd-cli \ -m ../models/checkpoints/hidream_o1_image_dev_bf16.safetensors \ -p "a lovely cat holding a sign says 'hidream o1 cpp'" \ + --steps 28 \ --cfg-scale 1.0 \ + --sampling-method lcm \ + --extra-sample-args noise_scale_start=7.5,noise_scale_end=7.5,noise_clip_std=2.5 \ -H 1024 \ -W 1024 \ -v ``` HiDream-O1-Image-Dev example + +#### HiDream-O1-Image (full) + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe ` + -m ..\models\checkpoints\hidream_o1_image_bf16.safetensors ` + -p "a lovely cat holding a sign says 'hidream o1 cpp'" ` + --steps 50 ` + --cfg-scale 5.0 ` + --sampling-method euler ` + -H 1024 ` + -W 1024 ` + -v +``` + +**Linux/macOS** + +```sh +./bin/sd-cli \ + -m ../models/checkpoints/hidream_o1_image_bf16.safetensors \ + -p "a lovely cat holding a sign says 'hidream o1 cpp'" \ + --steps 50 \ + --cfg-scale 5.0 \ + --sampling-method euler \ + -H 1024 \ + -W 1024 \ + -v +``` + +## Options + +The initial noise scale defaults to 8. Use `--eta` (`sample.eta` in the C API) +to override it. The same scale applies to the initial and hires sampling stages. diff --git a/docs/models/hunyuan_video.md b/docs/models/hunyuan_video.md index f31f8cfbd2..38d93089c5 100644 --- a/docs/models/hunyuan_video.md +++ b/docs/models/hunyuan_video.md @@ -14,8 +14,6 @@ and ByT5 Small GlyphXL for glyph-aware text conditioning. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -35,7 +33,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to video](../dgl/hunyuan_video/hunyuanvideo1-5-720p-txt2video.dgl) | HunyuanVideo 1.5, 720p. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\hunyuan_video\hunyuanvideo1-5-720p-txt2video.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/hunyuan_video/hunyuanvideo1-5-720p-txt2video.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text-to-video example diff --git a/docs/models/ideogram4.md b/docs/models/ideogram4.md index 64e8121631..3a797deb45 100644 --- a/docs/models/ideogram4.md +++ b/docs/models/ideogram4.md @@ -91,8 +91,6 @@ If you want lower VRAM usage, you can change the quantization from q8_0 to a low ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -108,7 +106,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/ideogram4/ideogram4-txt2img.dgl) | Ideogram4 generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\ideogram4\ideogram4-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/ideogram4/ideogram4-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/ip_adapter.md b/docs/models/ip_adapter.md index 854ed88d78..c8ca32a7ae 100644 --- a/docs/models/ip_adapter.md +++ b/docs/models/ip_adapter.md @@ -5,219 +5,105 @@ to guide SD 1.5 or SDXL generation alongside the text prompt. Classic and Plus adapters are supported, including combination with Control Net. +**Currently supported only through dgl.** + ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL usage | Requirement | | --- | --- | --- | --- | -| Base checkpoint | [SD 1.5 or SDXL](sd.md) | `-m` / `--model` | Required; match adapter family | -| CLIP Vision H | `clip_vision_h.safetensors` from [IP-Adapter](https://huggingface.co/h94/IP-Adapter) | `--clip_vision` | Required; ViT-H/14 | -| SD 1.5 adapter | [`models/ip-adapter_sd15.safetensors`](https://huggingface.co/h94/IP-Adapter) | `--ip-adapter` | For SD 1.5 | -| SDXL adapter | [`sdxl_models/ip-adapter_sdxl_vit-h.safetensors`](https://huggingface.co/h94/IP-Adapter) | `--ip-adapter` | For SDXL | -| SD 1.5 Plus | [`models/ip-adapter-plus_sd15.safetensors`](https://huggingface.co/h94/IP-Adapter) | `--ip-adapter` | Alternative for SD 1.5 | -| SDXL Plus | [`sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors`](https://huggingface.co/h94/IP-Adapter) | `--ip-adapter` | Alternative for SDXL | +| Base checkpoint | [SD 1.5 or SDXL](sd.md) | `load_unet`, `load_text_encoder`, `load_vae` | Required; match adapter family | +| CLIP Vision H | `clip_vision_h.safetensors` from [IP-Adapter](https://huggingface.co/h94/IP-Adapter) | `load_vision_encoder` | Required; ViT-H/14 | +| SD 1.5 adapter | [`models/ip-adapter_sd15.safetensors`](https://huggingface.co/h94/IP-Adapter) | `ip_adapter::load` | For SD 1.5 | +| SDXL adapter | [`sdxl_models/ip-adapter_sdxl_vit-h.safetensors`](https://huggingface.co/h94/IP-Adapter) | `ip_adapter::load` | For SDXL | +| SD 1.5 Plus | [`models/ip-adapter-plus_sd15.safetensors`](https://huggingface.co/h94/IP-Adapter) | `ip_adapter::load` | Alternative for SD 1.5 | +| SDXL Plus | [`sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors`](https://huggingface.co/h94/IP-Adapter) | `ip_adapter::load` | Alternative for SDXL | ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI -Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the -server, then select the recipe matching your weights. Fill the component slots -below and click **Load models**. -Use the files and compatibility requirements in [Model files](#model-files). +Open the server's **DGL editor**, edit the same script, and submit it. +Model and input paths must satisfy the server's file-access policy; save outputs +inside its `output/` directory. See the [Web UI guide](../../examples/server/README.md#web-ui). -| Recipe | Component slots | -| --- | --- | -| SD 1.5 IP-Adapter / Plus (`sd1-ip-adapter`) | `model`, `clip_vision`, `ip_adapter`, `vae`, `tae` | -| SDXL IP-Adapter / Plus (`sdxl-ip-adapter`) | `model`, `clip_vision`, `ip_adapter`, `vae`, `tae` | +### DGL -Slot IDs correspond to CLI component options: `diffusion_model` uses -`--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. -Select optional components when required by your checkpoint or task. +| Example | Description | +| --- | --- | +| [SD 1.5 Classic](../dgl/ip_adapter/ip-adapter-sd1-5.dgl) | Use a reference image with SD 1.5. | +| [SDXL Classic](../dgl/ip_adapter/ip-adapter-sdxl.dgl) | Use a reference image with SDXL. | +| [SD 1.5 Plus](../dgl/ip_adapter/ip-adapter-plus-sd1-5.dgl) | Use unpooled CLIP Vision features. | +| [SDXL with ControlNet](../dgl/ip_adapter/ip-adapter-sdxl-controlnet.dgl) | Combine appearance and pose conditions. | -### CLI +#### Run a script -#### Example (SD 1.5) +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\sd_v1.5.safetensors ` - --clip_vision ..\models\clip_vision\clip_vision_h.safetensors ` - --ip-adapter ..\models\ipadapter\ip-adapter_sd15.safetensors ` - --ip-adapter-image ..\inputs\reference.png ` - -p "a woman, best quality" ` - -n "lowres, bad anatomy" ` - --cfg-scale 7 ` - --steps 30 ` - --sampling-method dpm++2m ` - --scheduler karras ` - -W 512 ` - -H 512 ` - --ip-adapter-strength 0.8 +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\ip_adapter\ip-adapter-sd1-5.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - -m ../models/checkpoints/sd_v1.5.safetensors \ - --clip_vision ../models/clip_vision/clip_vision_h.safetensors \ - --ip-adapter ../models/ipadapter/ip-adapter_sd15.safetensors \ - --ip-adapter-image ../inputs/reference.png \ - -p "a woman, best quality" \ - -n "lowres, bad anatomy" \ - --cfg-scale 7 \ - --steps 30 \ - --sampling-method dpm++2m \ - --scheduler karras \ - -W 512 \ - -H 512 \ - --ip-adapter-strength 0.8 +./bin/sd-cli -M dgl --script ../docs/dgl/ip_adapter/ip-adapter-sd1-5.dgl ``` -#### Example (SDXL) - -**Windows (PowerShell)** - -```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\sdxl.safetensors ` - --clip_vision ..\models\clip_vision\clip_vision_h.safetensors ` - --ip-adapter ..\models\ipadapter\ip-adapter_sdxl_vit-h.safetensors ` - --ip-adapter-image ..\inputs\reference.png ` - -p "a woman, best quality" ` - -n "lowres, bad anatomy" ` - --cfg-scale 6 ` - --steps 25 ` - --sampling-method dpm++2m ` - --scheduler karras ` - -W 1024 ` - -H 1024 ` - --ip-adapter-strength 0.8 ` - --vae-tiling +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +The [SD 1.5 Classic example](../dgl/ip_adapter/ip-adapter-sd1-5.dgl) loads the +image and attention projections from one checkpoint with `ip_adapter::load`. +`ip_adapter::project` returns the projected image tokens as a tensor. +`ip_adapter::apply` binds those tokens to one text condition, so the positive +and negative CFG branches can use different tensors. Apply it again to the +returned condition to add another adapter. `strength` scales each adapter's +attention contribution. `start_sigma` and `end_sigma` bound the contribution +from high to low noise. Use `t_to_sigma` to convert a noise time to a bound. + +Classic projects a pooled CLIP Vision embedding for the positive branch and a +zero embedding for the negative branch. Plus uses penultimate hidden states +from the reference image and from a zeroed, preprocessed CLIP Vision input. +Use the Plus checkpoint and these calls in the example for Plus. + +```dgl +reference = image::load(input_path) +embedding = encode_vision(vision, reference, pooled = false, clip_skip = 2) +empty_embedding = encode_vision(vision, reference, pooled = false, clip_skip = 2, zero_input = true) +positive_image = ip_adapter::project(adapter, embedding) +negative_image = ip_adapter::project(adapter, empty_embedding) ``` -**Linux/macOS** +For SDXL use an SDXL checkpoint and `family = "sdxl"` on `ip_adapter::load`. -```sh -./bin/sd-cli \ - -m ../models/checkpoints/sdxl.safetensors \ - --clip_vision ../models/clip_vision/clip_vision_h.safetensors \ - --ip-adapter ../models/ipadapter/ip-adapter_sdxl_vit-h.safetensors \ - --ip-adapter-image ../inputs/reference.png \ - -p "a woman, best quality" \ - -n "lowres, bad anatomy" \ - --cfg-scale 6 \ - --steps 25 \ - --sampling-method dpm++2m \ - --scheduler karras \ - -W 1024 \ - -H 1024 \ - --ip-adapter-strength 0.8 \ - --vae-tiling -``` +#### Example (SDXL) -The SDXL VAE decode at 1024x1024 is memory heavy; add `--vae-tiling` (and -`--offload-to-cpu`) on GPUs with limited VRAM. +The SDXL example passes `tiling()` to `vae_decode` to reduce decode memory. +Set `params_backend="cpu"` on a loader to offload its weights. #### Plus variants -Use the Plus weights matching your base model. The same IP-Adapter options -apply; no extra flag is needed. Plus can also be combined with Control Net. - -**Windows (PowerShell)** - -```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\sd_v1.5.safetensors ` - --clip_vision ..\models\clip_vision\clip_vision_h.safetensors ` - --ip-adapter ..\models\ipadapter\ip-adapter-plus_sd15.safetensors ` - --ip-adapter-image ..\inputs\reference.png ` - -p "a woman, best quality" ` - -n "lowres, bad anatomy" ` - --cfg-scale 7 ` - --steps 30 ` - --sampling-method dpm++2m ` - --scheduler karras ` - -W 512 ` - -H 512 ` - --ip-adapter-strength 0.8 -``` - -**Linux/macOS** - -```sh -./bin/sd-cli \ - -m ../models/checkpoints/sd_v1.5.safetensors \ - --clip_vision ../models/clip_vision/clip_vision_h.safetensors \ - --ip-adapter ../models/ipadapter/ip-adapter-plus_sd15.safetensors \ - --ip-adapter-image ../inputs/reference.png \ - -p "a woman, best quality" \ - -n "lowres, bad anatomy" \ - --cfg-scale 7 \ - --steps 30 \ - --sampling-method dpm++2m \ - --scheduler karras \ - -W 512 \ - -H 512 \ - --ip-adapter-strength 0.8 -``` +Use Plus weights matching the base model. The Plus script requests unpooled +CLIP Vision features and encodes a zero input for its negative image condition. +Use the SDXL with ControlNet script to combine both conditions. The startup log line `IP-Adapter: 16 image tokens` (versus `4` for the classic adapters) confirms a Plus file was loaded. #### Combining with Control Net -Add the usual Control Net options to keep the reference appearance while -controlling the pose: - -**Windows (PowerShell)** - -```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\sdxl.safetensors ` - --clip_vision ..\models\clip_vision\clip_vision_h.safetensors ` - --ip-adapter ..\models\ipadapter\ip-adapter_sdxl_vit-h.safetensors ` - --control-net ..\models\controlnet\OpenPoseXL2.safetensors ` - --ip-adapter-image ..\inputs\character.png ` - --control-image ..\inputs\pose.png ` - -p "a character, side view" ` - --cfg-scale 6 ` - --steps 25 ` - -W 1024 ` - -H 1024 ` - --ip-adapter-strength 0.9 ` - --control-strength 0.8 ` - --vae-tiling -``` - -**Linux/macOS** - -```sh -./bin/sd-cli \ - -m ../models/checkpoints/sdxl.safetensors \ - --clip_vision ../models/clip_vision/clip_vision_h.safetensors \ - --ip-adapter ../models/ipadapter/ip-adapter_sdxl_vit-h.safetensors \ - --control-net ../models/controlnet/OpenPoseXL2.safetensors \ - --ip-adapter-image ../inputs/character.png \ - --control-image ../inputs/pose.png \ - -p "a character, side view" \ - --cfg-scale 6 \ - --steps 25 \ - -W 1024 \ - -H 1024 \ - --ip-adapter-strength 0.9 \ - --control-strength 0.8 \ - --vae-tiling -``` +Apply `controlnet::apply` and `ip_adapter::apply` to the same condition to +preserve the reference appearance while controlling pose. ## Options -- `--ip-adapter ` path to the IP-Adapter weight file. -- `--ip-adapter-image ` path to the reference image. -- `--ip-adapter-strength ` strength of the IP-Adapter injection - (default 1.0). Lower values let the text prompt dominate; 0.6 to 0.8 is - a good starting range. +Set the reference path and component paths in `var`. `ip_adapter::apply`'s +`strength` scales the image attention contribution; 0.6–0.8 is a useful starting +range. Optional `start_sigma` / `end_sigma` restrict its sampling interval. +Classic and Plus use different CLIP Vision representations as shown above. +Use `controlnet::apply` independently for pose or edge conditioning. diff --git a/docs/models/iris.md b/docs/models/iris.md index 643b0d2fb4..efd86ee51b 100644 --- a/docs/models/iris.md +++ b/docs/models/iris.md @@ -11,8 +11,6 @@ Iris-3B generates images directly in pixel space and uses Qwen3-VL-4B-Instruct a ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -28,7 +26,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/iris/iris-3b-txt2img.dgl) | Iris-3B generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\iris\iris-3b-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/iris/iris-3b-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/kontext.md b/docs/models/kontext.md index c711f3227d..b40fbf8c0f 100644 --- a/docs/models/kontext.md +++ b/docs/models/kontext.md @@ -46,8 +46,6 @@ You can download the preconverted gguf weights from [FLUX.1-Kontext-dev-GGUF](ht ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -63,7 +61,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Image editing](../dgl/kontext/flux1-kontext-dev-edit.dgl) | Edit a reference image with FLUX.1 Kontext dev. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\kontext\flux1-kontext-dev-edit.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/kontext/flux1-kontext-dev-edit.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). - `--cfg-scale` is recommended to be set to 1. diff --git a/docs/models/krea2.md b/docs/models/krea2.md index c6367111ed..3fa24f4409 100644 --- a/docs/models/krea2.md +++ b/docs/models/krea2.md @@ -13,8 +13,6 @@ Krea2 uses a Krea2 diffusion transformer, the Wan2.1 VAE, and Qwen3-VL 4B as the ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -26,12 +24,50 @@ Use the files and compatibility requirements in [Model files](#model-files). | --- | --- | | Krea 2 Raw (`krea2-raw`) | `diffusion_model`, `llm`, `vae`, `tae` | | Krea 2 Turbo (`krea2-turbo`) | `diffusion_model`, `llm`, `vae`, `tae` | +| Krea 2 Raw Edit (`krea2-raw-edit`) | `diffusion_model`, `llm`, `llm_vision`, `vae`, `tae` | +| Krea 2 Turbo Edit (`krea2-turbo-edit`) | `diffusion_model`, `llm`, `llm_vision`, `vae`, `tae` | Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +The Edit recipes require a matching Ostris-compatible community editing LoRA, +selected separately, and reference images. Each reference goes through both +the vision encoder and VAE. Select a vision projector in `llm_vision` when it +is not bundled in the text encoder. The recipe does not load the LoRA +automatically. + +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/krea2/krea2-raw-txt2img.dgl) | Krea2 Raw. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\krea2\krea2-raw-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/krea2/krea2-raw-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Krea2 diff --git a/docs/models/lcm.md b/docs/models/lcm.md index 90330d2a6e..30edcb4c24 100644 --- a/docs/models/lcm.md +++ b/docs/models/lcm.md @@ -12,8 +12,6 @@ The example below applies an LCM-LoRA to SD 1.5. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -33,7 +31,37 @@ Select optional components when required by your checkpoint or task. Select the matching LCM checkpoint or apply a compatible LCM-LoRA, then set the sampling method, CFG, and steps for that model. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [LCM-LoRA with SD 1.5](../dgl/lcm/lcm-lora-sd1-5.dgl) | Apply the acceleration LoRA before sampling. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\lcm\lcm-lora-sd1-5.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/lcm/lcm-lora-sd1-5.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### LCM-LoRA with SD 1.5 diff --git a/docs/models/lens.md b/docs/models/lens.md index 42708eb85a..b209118296 100644 --- a/docs/models/lens.md +++ b/docs/models/lens.md @@ -16,8 +16,6 @@ Lens and Lens Turbo require an external GPT-OSS `tokenizer.json` matching the te ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -34,7 +32,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Lens](../dgl/lens/lens-txt2img.dgl) | Text-to-image generation. | +| [Lens Turbo](../dgl/lens/lens-turbo-txt2img.dgl) | Distilled text-to-image generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\lens\lens-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/lens/lens-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Lens diff --git a/docs/models/lingbot_video.md b/docs/models/lingbot_video.md index a085c891b3..d94a19e38c 100644 --- a/docs/models/lingbot_video.md +++ b/docs/models/lingbot_video.md @@ -13,8 +13,6 @@ Lingbot Video uses a Lingbot diffusion transformer, the Wan2.1 VAE, and Qwen3-VL ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -31,7 +29,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to video](../dgl/lingbot_video/lingbot-video-dens-1-3b-txt2video.dgl) | LingBot-Video Dens 1.3B. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\lingbot_video\lingbot-video-dens-1-3b-txt2video.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/lingbot_video/lingbot-video-dens-1-3b-txt2video.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### LingBot-Video T2V diff --git a/docs/models/llada_image.md b/docs/models/llada_image.md index d627b7bd1b..05174378c8 100644 --- a/docs/models/llada_image.md +++ b/docs/models/llada_image.md @@ -123,8 +123,6 @@ save_file(merged, "llada_connectors.safetensors") ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -141,7 +139,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/llada_image/llada-image-turbo-txt2img.dgl) | LLaDA-Image Turbo. | +| [Image editing](../dgl/llada_image/llada-image-turbo-edit.dgl) | Edit a reference image. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\llada_image\llada-image-turbo-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/llada_image/llada-image-turbo-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text to image @@ -223,9 +252,9 @@ Select optional components when required by your checkpoint or task. LLaDA-Image edit example -See [edit.md](../guides/edit.md) for the shared reference-image options. LLaDA-Image uses the -`llada_image` preset by default, resizing the reference image to the output width and height -before VAE encoding. SigVQ uses bilinear resizing to half the output resolution and inputs +See [edit.md](../guides/edit.md) for the shared reference-image options. The CLI and C API +resize the reference image to the output width and height before VAE encoding. +SigVQ uses bilinear resizing to half the output resolution and inputs normalized to `[-1, 1]`. CFG keeps the source latent in both branches and uses SigVQ features only in the positive branch. Editing requires connectors that include the SigVQ weights. @@ -247,5 +276,7 @@ only in the positive branch. Editing requires connectors that include the SigVQ - `--scheduler` defaults to `llada_image`, which reproduces the reference Kumaraswamy sigma grid. `--extra-sample-args uniform=1` selects the uniform grid instead. - Prompt templating is handled automatically; pass a plain description. +- Image editing uses the same target-sized reference pixels for VAE encoding + and the text encoder's image components. - VQ-conditioned generation (`generation_mode="vq"`, where the text encoder decodes image tokens before diffusion) is not implemented. diff --git a/docs/models/longcat_image.md b/docs/models/longcat_image.md index ec2fae131c..77cd68edd8 100644 --- a/docs/models/longcat_image.md +++ b/docs/models/longcat_image.md @@ -13,8 +13,6 @@ LongCat-Image uses a LongCat diffusion transformer, the FLUX VAE, and Qwen2.5-VL ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -31,7 +29,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/longcat_image/longcat-image-txt2img.dgl) | LongCat Image generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\longcat_image\longcat-image-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/longcat_image/longcat-image-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). LongCat uses quoted text for character-level text rendering. Put target text inside single quotes, double quotes, or Chinese quotes. diff --git a/docs/models/lora.md b/docs/models/lora.md index 56cb60b7d3..08265ac7af 100644 --- a/docs/models/lora.md +++ b/docs/models/lora.md @@ -12,14 +12,42 @@ using `` in the prompt. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Load a compatible base model with its recipe, then select the LoRA for generation. See [Web UI guide](../../examples/server/README.md#web-ui) for the shared workflow. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [SD 1.5 with LoRA](../dgl/lora/sd1-5-lora.dgl) | Apply the same LoRA to the UNet and text encoder. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\lora\sd1-5-lora.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/lora/sd1-5-lora.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** @@ -48,12 +76,21 @@ The example loads `../models/loras/marblesh.safetensors` or There are two ways to apply LoRA: **immediately** and **at_runtime**. You can specify it using the `--lora-apply-mode` parameter. -By default, the mode is selected automatically: - -* If the model weights contain any quantized parameters, the **at_runtime** mode is used; -* Otherwise, the **immediately** mode is used. +The default **auto** mode chooses **immediately** for unquantized and INT8 +tensorwise weights on the compute backend without row splitting. It chooses +**at_runtime** for other quantized formats, offloaded weights, or row-split +weights. For scripts, see +[DGL LoRA combinations](../dgl.md#lora-combinations). The **immediately** mode may have precision and compatibility issues with quantized parameters, but it usually offers faster inference speed and, in some cases, lower memory usage. +For INT8 tensorwise and convrot weights, **immediately** merges and requantizes +the affected weights. Requantizing can round away updates smaller than half an INT8 +step, so adapters with small updates can lose most or all of their effect; use +**at_runtime** for them. See the [INT8 convrot guide](../guides/int8_convrot.md). +When the weights fill the `--max-vram` budget, **immediately** can merge a few +weights at a time. Merged weights that have to leave VRAM use temporary RAM, +including with `--params-backend disk`. If the merge cannot fit, increasing the +memory budget or choosing **at_runtime** can help. In contrast, the **at_runtime** mode provides better compatibility and higher precision, but inference may be slower and memory usage may be higher in some cases. ## Notes and limitations diff --git a/docs/models/ltx2.md b/docs/models/ltx2.md index 1785487224..2b8862f95e 100644 --- a/docs/models/ltx2.md +++ b/docs/models/ltx2.md @@ -58,8 +58,6 @@ To run the text encoder quantized, convert it once with sd-cli: ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -77,7 +75,69 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +#### LTX-2.3 + +| Example | Description | +| --- | --- | +| [Text to video](../dgl/ltx2/ltx-2-3-dev-txt2video.dgl) | LTX-2.3 dev with audio. | +| [Image to video](../dgl/ltx2/ltx-2-3-dev-img2video.dgl) | Condition the initial frame. | +| [First/last-frame conditioning](../dgl/ltx2/ltx-2-3-dev-first-last-frame.dgl) | Set both endpoint images. | +| [Spatial latent upscaling](../dgl/ltx2/ltx-2-3-spatial-upscale.dgl) | Refine a low-resolution draft with a learned upscaler. | + +#### LTX-2.5 + +| Example | Description | +| --- | --- | +| [Text to video](../dgl/ltx2/ltx-2-5-dev-txt2video.dgl) | LTX-2.5 dev with audio. | +| [Image to video](../dgl/ltx2/ltx-2-5-dev-img2video.dgl) | Condition the initial frame. | +| [Spatial latent upscaling](../dgl/ltx2/ltx-2-5-spatial-upscale.dgl) | Refine a low-resolution draft with a learned upscaler. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\ltx2\ltx-2-3-dev-txt2video.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/ltx2/ltx-2-3-dev-txt2video.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +To continue a clip from existing frames and sound in a custom script, pack the +video and audio masks in the same layout as the latents. Give all features of +each audio token the same mask value. Pass the clean reference as `base` and +use `denoise_mask` with `mask_input = true` in one `sample` call. Use `0` for +the region to preserve and `1` for the region to generate. + +#### Latent upscaling + +`load_latent_upscaler` loads the spatial or temporal checkpoint as an +independent resource. Convert the video part of the draft diffusion latent +with `dit_to_vae_latents`, run `upscale_latent`, then convert back +with `vae_to_dit_latents` before the refine pass. The checkpoint +determines the scale and which axis to upscale. Repack the audio in the +script when the refine pass uses both video and audio latents. +See the [Video Hires example](../dgl/ltx2/ltx-2-3-spatial-upscale.dgl). +The CLI/C API render the same stages for `--hires`. LTX-2.3 temporal +upscaling also adjusts the output frame count and audio latent duration; +spatial or temporal refinement re-encodes supplied keyframes at the output size. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### LTX-2.3 dev T2V @@ -463,8 +523,16 @@ pass its name without path or extension to `--hires-upscaler`. ## Notes and limitations +For DGL, pass the separate LTX-2.3 connector file to `load_text_encoder` with +`connectors_path`. Set `projection_path` to the diffusion checkpoint when it +contains additional static conditioning weights, including LTX-2.5 connectors. +The CLI/C API and DGL share this text conditioner. Connector computation +runs during prompt encoding. The text encoder caches the final video and audio conditions; +`load_dit` only loads the diffusion network. See the +[LTX DGL example](../dgl/ltx2/ltx-2-3-dev-txt2video.dgl). + Not implemented: - The diffusion video decoder (`ltx-2.5-video-vae-bf16.safetensors`). Use the conv VAE. -- The temporal latent upscaler and the duration head (`--auto-duration`); pass +- The duration head (`--auto-duration`); pass `--video-frames` explicitly. diff --git a/docs/models/mage_flow.md b/docs/models/mage_flow.md index eaccdcf80f..e1169f9bee 100644 --- a/docs/models/mage_flow.md +++ b/docs/models/mage_flow.md @@ -12,8 +12,6 @@ ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -31,7 +29,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/mage_flow/mage-flow-turbo-txt2img.dgl) | Mage-Flow Turbo. | +| [Image editing](../dgl/mage_flow/mage-flow-edit.dgl) | Mage-Flow Edit. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\mage_flow\mage-flow-turbo-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/mage_flow/mage-flow-turbo-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text-to-image @@ -69,7 +98,11 @@ Use 30 steps for Base models and 4 steps with `--cfg-scale 1` for Turbo models. #### Image editing -Mage-Flow-Edit accepts one or more reference images. The default `mage_flow` reference preset sends each image to both Qwen3-VL and the diffusion transformer, caps the VLM copy's longest edge at 384 pixels, and keeps the VAE copy at the requested output resolution. +Mage-Flow-Edit accepts one or more reference images. The CLI and C API send each +image to both Qwen3-VL and the diffusion transformer. The vision copy follows +the encoder's native preprocessing and patch alignment; the VAE copy is resized +to the requested output resolution. Use a [DGL script](../guides/edit.md#custom-reference-processing) +to customize these two inputs. For the Turbo edit checkpoint, use 4 steps and `--cfg-scale 1`. diff --git a/docs/models/ming_image.md b/docs/models/ming_image.md index 53dc7a96e6..0dfdabbd4f 100644 --- a/docs/models/ming_image.md +++ b/docs/models/ming_image.md @@ -15,8 +15,6 @@ The example below uses `ming_image_0.1_design_bf16.safetensors` for the DiT. You ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -32,7 +30,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/ming_image/ming-image-0-1-design-txt2img.dgl) | Ming-Image 0.1 Design. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\ming_image\ming-image-0-1-design-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/ming_image/ming-image-0-1-design-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text-to-image diff --git a/docs/models/minimax_h3.md b/docs/models/minimax_h3.md index 862b04d3e9..2c410ec32b 100644 --- a/docs/models/minimax_h3.md +++ b/docs/models/minimax_h3.md @@ -12,7 +12,7 @@ Pass the four MiniMax-H3 components separately: - `--diffusion-model`: MiniMax-H3 diffusion transformer - `--vae`: MiniMax-H3 video VAE - `--audio-vae`: MiniMax-H3 audio VAE -- `--llm`: the MiniMax-H3 Qwen3-VL-32B text encoder, or Qwen3-VL-4B with the P-H3 text connector +- `--llm`: the MiniMax-H3 Qwen3-VL-32B text encoder, Qwen3-VL-4B with the P-H3 text connector, or Qwen3-VL-4B/8B with the ClipProj projection For the 32B option, use the MiniMax-H3 variant: Qwen3-VL-32B truncated to 50 language layers and exported without the final language-model normalization. @@ -51,10 +51,44 @@ or: --embeddings-connectors ../models/text_encoders/p-h3-image_text_connector.safetensors ``` +or use a plain Qwen3-VL-4B or Qwen3-VL-8B with the +[ClipProj projection](https://huggingface.co/NicoLab28/ClipProj-MiniMax-H3), a +small learned matrix that replaces the 32B encoder: + +**Windows (PowerShell) arguments** + +```text +--llm ..\models\text_encoders\qwen3vl_4b.gguf ` + --embeddings-connectors ..\models\text_encoders\mmh3-4b-ClipProj-v3.1.safetensors +``` + +**Linux/macOS arguments** + +```text +--llm ../models/text_encoders/qwen3vl_4b.gguf \ + --embeddings-connectors ../models/text_encoders/mmh3-4b-ClipProj-v3.1.safetensors +``` + +The `mmh3-4b-*` matrices expect a Qwen3-VL-4B encoder and the `mmh3-8b-*` +matrices a Qwen3-VL-8B encoder; match the two. ClipProj is a community proof of +concept: outputs are close to, not identical to, the 32B encoder. See the +[model card](https://huggingface.co/NicoLab28/ClipProj-MiniMax-H3) for +measurements and limitations. + Reference-image and reference-video conditioning needs the matching encoder's -Qwen3-VL vision tower, including the three DeepStack mergers. If stored -separately, pass it with `--llm_vision`. Keep using the MiniMax-H3 video and audio -VAEs with either text encoder. +Qwen3-VL vision tower; the official 32B encoder includes the three DeepStack mergers. +If stored separately, pass it with `--llm_vision`. Keep using the MiniMax-H3 +video and audio VAEs with any text encoder. + +In DGL, use `load_text_encoder` with `family = "minimax_h3"`. For a separate +4B connector or vision projector, pass `connectors_path` or `vision_path` to +that loader. The native generation API trims decoded audio to the duration of +the output video. In scripts, save decoded frames and audio with +`video::save(path, {frames=frames, fps_num=24, fps_den=1}, audio=audio, trim_audio=true)` +to match the generated clip duration. +For video presentation, pass frame tensors to `encode_prompt` as +`presentation=[{video={frames=frames, fps_num=24, fps_den=1}, stride=12}]`. Frame rate and sampling +stride are explicit; VAE reference latents remain a separate input. Both the original time-embedder DiT and the smaller AdaLN curve-table variant are detected from their weights. @@ -66,13 +100,12 @@ are detected from their weights. | minimax_h3_fl2va/minimax_h3_ref2va | [Safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/diffusion_models)
[GGUF](https://huggingface.co/leejet/MiniMax-H3-GGUF/tree/main) | `--diffusion-model` | Required | | qwen3vl_32b_minimax_h3 | [Safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/text_encoders)
[GGUF](https://huggingface.co/leejet/MiniMax-H3-GGUF/tree/main) | `--llm` | Use matching text encoder | | P-H3-Image text encoder (Qwen3-VL-4B with the text connector) | [Safetensors](https://huggingface.co/PrunaAI/P-H3-Image-Comfy/tree/main/text_encoders) | `--llm` | Use matching text encoder | +| ClipProj projection (for a plain Qwen3-VL-4B or Qwen3-VL-8B) | [Safetensors](https://huggingface.co/NicoLab28/ClipProj-MiniMax-H3) | `--embeddings-connectors` | Pair with a matching Qwen3-VL-4B/8B `--llm` | | vae | [Safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/vae) | `--vae` | Use matching VAE | | audio vae | [Safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/vae) | `--audio-vae` | Required | ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -91,7 +124,81 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to audio/video](../dgl/minimax_h3/minimax-h3-text-to-av.dgl) | Generate video and its soundtrack together. | +| [pi-H3 text to audio/video](../dgl/minimax_h3/pi-h3-text-to-av.dgl) | Generate video and its soundtrack in four Euler steps with the native H3 VAEs. | +| [First/last-frame conditioning](../dgl/minimax_h3/minimax-h3-first-last-frame.dgl) | Guide the video with endpoint images. | +| [Reference to audio/video](../dgl/minimax_h3/minimax-h3-reference-to-av.dgl) | Use image, video and audio references. | +| [Interpolated latent hires](../dgl/minimax_h3/minimax-h3-latent-hires.dgl) | Resize the draft latent, then run a second sampling pass. | +| [Learned latent hires](../dgl/minimax_h3/minimax-h3-learned-hires.dgl) | Use a learned latent upscaler between sampling passes. | +| [Audio/video continuation](../dgl/minimax_h3/minimax-h3-av-continuation.dgl) | Generate and join two clips with shared audio and video context. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\minimax_h3\minimax-h3-text-to-av.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/minimax_h3/minimax-h3-text-to-av.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +#### pi-H3 four-step generation + +Use a pruned MiniMax-H3 FL2VA transformer such as `minimax_h3_fl2va_pruned-Q4_K_M.gguf`. +Save the [four-step pi-H3 adapter](https://huggingface.co/Lakonik/pi-H3/tree/main/pi_h3_4step_adapter) +as `pi_h3_4step_adapter.safetensors` under `models/loras/minimax/` or set +`adapter_path` in the script. Keep the MiniMax-H3 text encoder and both VAEs. +The script applies the adapter's full-weight replacements and its LoRA at +strength `1.0`. It uses the four-step pi-H3 schedule with video shift `12`, +audio shift `3`, maximum raw sigma `0.96`, and final step size scale `0.6`. +The adapter with `dwd` in its name requires a separate decoder head. + +#### Audio/video continuation + +The continuation example saves the finished video as `continuation-joined.avi` +at 24 fps. It also writes `continuation-part-a.avi`, +`continuation-part-b.avi` with its overlap removed, and `continuation-part-a.npy` +with A's latent. + +Set `overlap_frames` to the maximum overlap you want. The script rounds down +to a supported overlap and leaves at least half of B for new content. Set it +to zero to generate two independent clips and join them. + +The video and audio VAEs use the default device. Set `vae_backend` to a device +reported by `sd-cli --list-devices` to run both decoders on that device. + +#### Latent upscaling + +Use `load_latent_upscaler` to load the learned spatial upscaler. +`upscale_latent` takes the video part of the draft diffusion latent +and returns a diffusion latent for the refine pass. Pass the target width +and height in latent units. A resize target uses even dimensions +(multiples of 32 in pixel units). + +```dgl +upscaler = load_latent_upscaler("minimax_h3_latent_upscaler_3d_conv_v1_bf16.safetensors") +bigger = upscale_latent(upscaler, draft_av.video, width = 76, height = 42) +``` + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text-to-audio-video @@ -104,7 +211,7 @@ Select optional components when required by your checkpoint or task. --vae ..\models\vae\minimax_h3_video_vae_fp16.safetensors ` --audio-vae ..\models\vae\minimax_h3_audio_vae_fp32.safetensors ` --llm ..\models\text_encoders\qwen3vl_32b_minimax_h3-Q4_K_M.gguf ` - -p "A cute American Shorthair silver tabby kitten surfs on a tropical ocean wave, riding a white surfboard with the clear text 'sd.cpp' on it. Cinematic tracking shot, realistic water, bright sunlight, smooth motion, and consistent character appearance. Add upbeat tropical surf-rock background music with cheerful drums and guitar, synchronized with the kitten`’s energetic surfing." ` + -p "A cute American Shorthair silver tabby kitten surfs on a tropical ocean wave, riding a white surfboard with the clear text 'sd.cpp' on it. Cinematic tracking shot, realistic water, bright sunlight, smooth motion, and consistent character appearance. Add upbeat tropical surf-rock background music with cheerful drums and guitar, synchronized with the kitten`鈥檚 energetic surfing." ` --cfg-scale 1.0 ` -W 864 ` -H 480 ` @@ -124,7 +231,7 @@ Select optional components when required by your checkpoint or task. --vae ../models/vae/minimax_h3_video_vae_fp16.safetensors \ --audio-vae ../models/vae/minimax_h3_audio_vae_fp32.safetensors \ --llm ../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf \ - -p "A cute American Shorthair silver tabby kitten surfs on a tropical ocean wave, riding a white surfboard with the clear text 'sd.cpp' on it. Cinematic tracking shot, realistic water, bright sunlight, smooth motion, and consistent character appearance. Add upbeat tropical surf-rock background music with cheerful drums and guitar, synchronized with the kitten’s energetic surfing." \ + -p "A cute American Shorthair silver tabby kitten surfs on a tropical ocean wave, riding a white surfboard with the clear text 'sd.cpp' on it. Cinematic tracking shot, realistic water, bright sunlight, smooth motion, and consistent character appearance. Add upbeat tropical surf-rock background music with cheerful drums and guitar, synchronized with the kitten鈥檚 energetic surfing." \ --cfg-scale 1.0 \ -W 864 \ -H 480 \ @@ -202,7 +309,7 @@ video soundtracks, and standalone audio references: --vae ..\models\vae\minimax_h3_video_vae_fp16.safetensors ` --audio-vae ..\models\vae\minimax_h3_audio_vae_fp32.safetensors ` --llm ..\models\text_encoders\qwen3vl_32b_minimax_h3-Q4_K_M.gguf ` - -p "Use the cat from as the main character. Keep the cat`’s appearance, fur color, facial features, and identity consistent with the reference image. Create a 2-second cinematic video: start with an extreme close-up shot of the cat`’s face, focusing on its cute expression and detailed fur texture. The camera slowly rotates around the cat`’s head, creating a dynamic reveal. Then smoothly pull back and zoom out to reveal the full scene: the cat is standing confidently on a surfboard, riding ocean waves. Water splashes around the board, sea breeze gently moves the cat`’s fur, and the cat maintains a cute and fearless expression while surfing. Smooth camera movement, cinematic orbit shot, seamless zoom-out transition, low-angle wide shot, realistic ocean environment, golden sunlight, dynamic waves, high-quality realistic style, natural motion, no distortion, keep the cat`’s identity unchanged." ` + -p "Use the cat from as the main character. Keep the cat`鈥檚 appearance, fur color, facial features, and identity consistent with the reference image. Create a 2-second cinematic video: start with an extreme close-up shot of the cat`鈥檚 face, focusing on its cute expression and detailed fur texture. The camera slowly rotates around the cat`鈥檚 head, creating a dynamic reveal. Then smoothly pull back and zoom out to reveal the full scene: the cat is standing confidently on a surfboard, riding ocean waves. Water splashes around the board, sea breeze gently moves the cat`鈥檚 fur, and the cat maintains a cute and fearless expression while surfing. Smooth camera movement, cinematic orbit shot, seamless zoom-out transition, low-angle wide shot, realistic ocean environment, golden sunlight, dynamic waves, high-quality realistic style, natural motion, no distortion, keep the cat`鈥檚 identity unchanged." ` -r ..\inputs\ernie_image\turbo_example.png ` --cfg-scale 1.0 ` -W 864 ` @@ -223,7 +330,7 @@ video soundtracks, and standalone audio references: --vae ../models/vae/minimax_h3_video_vae_fp16.safetensors \ --audio-vae ../models/vae/minimax_h3_audio_vae_fp32.safetensors \ --llm ../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf \ - -p "Use the cat from as the main character. Keep the cat’s appearance, fur color, facial features, and identity consistent with the reference image. Create a 2-second cinematic video: start with an extreme close-up shot of the cat’s face, focusing on its cute expression and detailed fur texture. The camera slowly rotates around the cat’s head, creating a dynamic reveal. Then smoothly pull back and zoom out to reveal the full scene: the cat is standing confidently on a surfboard, riding ocean waves. Water splashes around the board, sea breeze gently moves the cat’s fur, and the cat maintains a cute and fearless expression while surfing. Smooth camera movement, cinematic orbit shot, seamless zoom-out transition, low-angle wide shot, realistic ocean environment, golden sunlight, dynamic waves, high-quality realistic style, natural motion, no distortion, keep the cat’s identity unchanged." \ + -p "Use the cat from as the main character. Keep the cat鈥檚 appearance, fur color, facial features, and identity consistent with the reference image. Create a 2-second cinematic video: start with an extreme close-up shot of the cat鈥檚 face, focusing on its cute expression and detailed fur texture. The camera slowly rotates around the cat鈥檚 head, creating a dynamic reveal. Then smoothly pull back and zoom out to reveal the full scene: the cat is standing confidently on a surfboard, riding ocean waves. Water splashes around the board, sea breeze gently moves the cat鈥檚 fur, and the cat maintains a cute and fearless expression while surfing. Smooth camera movement, cinematic orbit shot, seamless zoom-out transition, low-angle wide shot, realistic ocean environment, golden sunlight, dynamic waves, high-quality realistic style, natural motion, no distortion, keep the cat鈥檚 identity unchanged." \ -r ../inputs/ernie_image/turbo_example.png \ --cfg-scale 1.0 \ -W 864 \ @@ -238,11 +345,15 @@ video soundtracks, and standalone audio references: `--ref-image`, `--ref-video`, and `--ref-audio` can each be repeated. A -reference video is a directory of image frames sorted lexicographically and is -treated as 24 fps. Repeated `--ref-video-audio` WAV files are paired by index -with repeated `--ref-video` inputs. WAV PCM (8/16/24/32-bit) and 32/64-bit -floating-point samples are accepted; audio is converted to stereo 32 kHz by the -pipeline. +reference video can be a directory of image frames sorted lexicographically, +treated as 24 fps, or a file decoded and sampled at 24 fps. File inputs support +AVI, static/animated WebP and this project's independent-frame VP8 WebM; +see [DGL media I/O](../dgl.md) for codec and build requirements. +Reference files retain supported embedded audio by default. Repeated +`--ref-video-audio` WAV files are paired by index with repeated `--ref-video` +inputs and replace their embedded audio; the replaced track is not decoded. +WAV PCM (8/16/24/32-bit) and 32/64-bit floating-point samples are accepted; audio is converted to stereo 32 kHz during +generation. Reference inputs are presented to Qwen3-VL in image, video, then audio order. Videos are sampled at 2 fps for the Qwen presentation while their full 24 fps @@ -250,20 +361,11 @@ latents condition the diffusion transformer. Paired video and audio references share the same timeline. Ref2VA cannot be combined with `--init-img` or `--end-img` in one request. -Reference images keep their aspect ratio and are only downscaled when they -exceed the configured limit; neither mode scales a reference up. The limit is -selected by `ref_image_size`. The default, `match`, uses the pixel area of the -requested generation canvas. Pass `--ref-image-args "ref_image_size=max"` (or -`ref_image_size` in the `ref_image_args` video-option string) to use a 2048 px short -edge instead, which preserves more identity detail at a higher sampling cost: -reference latents are attended at every sampling step. - -Whichever limit applies, each axis is then snapped to the nearest 32-pixel -multiple. An axis of at least 16 pixels can therefore grow by up to 16 pixels -past the scaled size (a 48-pixel axis becomes 64), and references are never -narrower than 32 pixels. -`resize_before_vae=false` is not supported here; MiniMax-H3 keeps references on -the 32-pixel grid and reports a warning. +Reference images preserve their aspect ratio and are downscaled only when +their pixel area exceeds the generation canvas. Each axis is then snapped to +the nearest 32-pixel multiple, with a minimum of 32. An axis may grow by up to +16 pixels during alignment. Custom reference sizes and preprocessing require a +[DGL program](../guides/edit.md#custom-reference-processing). The C API exposes the same inputs through `ref_images`, `ref_videos`, and the `ref_audios` video-option key. Each `sd_video_t` supplies its own @@ -456,3 +558,5 @@ They already include video flow shift 12, so keep the default flow shift. block's working memory must also fit within the VRAM budget. - The default video flow shift is 12. The audio stream is mapped internally to its shift of 3, so the regular samplers can operate on the packed AV latent. + CLI and C API translation keep this mapping consistent when `--flow-shift` + is overridden, including hires refinement. diff --git a/docs/models/minimax_h3_image.md b/docs/models/minimax_h3_image.md index 6a06236d2e..86d36883c0 100644 --- a/docs/models/minimax_h3_image.md +++ b/docs/models/minimax_h3_image.md @@ -10,7 +10,7 @@ Pass the three MiniMax-H3-Image components separately: - `--diffusion-model`: MiniMax-H3-Image diffusion transformer - `--vae`: MiniMax-H3-Image VAE -- `--llm`: the MiniMax-H3 Qwen3-VL-32B text encoder checkpoint +- `--llm`: the MiniMax-H3 Qwen3-VL-32B text encoder checkpoint, or a Qwen3-VL-4B/8B with a text connector Use the MiniMax-H3 text encoder, including its Qwen3-VL vision tower and DeepStack mergers. An existing MiniMax-H3 text encoder can be reused. If the @@ -25,6 +25,18 @@ with `--llm` and the [separate text connector](https://huggingface.co/PrunaAI/P- with `--embeddings-connectors`. Reference-image editing needs the Qwen3-VL-4B vision tower in the text encoder or in `--llm_vision`. +A [ClipProj projection](https://huggingface.co/NicoLab28/ClipProj-MiniMax-H3) +can replace the 32B encoder with a plain Qwen3-VL-4B or Qwen3-VL-8B: pass the +small encoder with `--llm` and the matching matrix with +`--embeddings-connectors`. It needs much less memory (about 4.5 GB with a 4B +INT8 encoder, versus 18 GB for the 32B encoder in Q4_K_M). The `mmh3-4b-*` +matrices expect a Qwen3-VL-4B encoder and the `mmh3-8b-*` matrices a +Qwen3-VL-8B encoder; match the two. Reference-image editing needs the encoder's +vision tower in the text encoder or in `--llm_vision`. ClipProj is a community +proof of concept: outputs are close to, not identical to, the 32B encoder. See +the [model card](https://huggingface.co/NicoLab28/ClipProj-MiniMax-H3) for +measurements and limitations. + Use a single-file diffusion checkpoint with the six-step PDD output heads included, such as `minimax_h3_image_pruned_bf16.safetensors` or its INT8 ConvRot version. Use the MiniMax-H3-Image VAE; the MiniMax-H3 video VAE and P-H3-Image @@ -37,12 +49,11 @@ VAE are incompatible. No audio VAE is needed. | minimax_h3_image_pruned | [Safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3-Image/tree/main/diffusion_models) | `--diffusion-model` | Required | | qwen3vl_32b_minimax_h3 | [Safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3-Image/tree/main/text_encoders)
[GGUF](https://huggingface.co/leejet/MiniMax-H3-GGUF/tree/main) | `--llm` | Use matching text encoder | | P-H3-Image text encoder (Qwen3-VL-4B with the text connector) | [Safetensors](https://huggingface.co/PrunaAI/P-H3-Image-Comfy/tree/main/text_encoders) | `--llm` | Use matching text encoder | +| ClipProj projection (for a plain Qwen3-VL-4B or Qwen3-VL-8B) | [Safetensors](https://huggingface.co/NicoLab28/ClipProj-MiniMax-H3) | `--embeddings-connectors` | Pair with a matching Qwen3-VL-4B/8B `--llm` | | vae | [Safetensors](https://huggingface.co/Comfy-Org/MiniMax-H3-Image/tree/main/vae) | `--vae` | Use matching VAE | ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -58,7 +69,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/minimax_h3_image/minimax-h3-image-txt2img.dgl) | MiniMax-H3-Image generation. | +| [Image editing](../dgl/minimax_h3_image/minimax-h3-image-edit.dgl) | Edit a reference image. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\minimax_h3_image\minimax-h3-image-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/minimax_h3_image/minimax-h3-image-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text-to-image @@ -118,6 +160,23 @@ With the P-H3-Image text encoder, replace the `--llm` argument: --llm ../models/text_encoders/p-h3-image_text_encoder_int8_convrot.safetensors ``` +With a ClipProj projection, replace the `--llm` argument with the small +encoder plus the matching matrix: + +**Windows (PowerShell) arguments** + +```text +--llm ..\models\text_encoders\qwen3vl_4b_bf16.safetensors ` + --embeddings-connectors ..\models\text_encoders\mmh3-4b-ClipProj-v3.1.safetensors +``` + +**Linux/macOS arguments** + +```text +--llm ../models/text_encoders/qwen3vl_4b_bf16.safetensors \ + --embeddings-connectors ../models/text_encoders/mmh3-4b-ClipProj-v3.1.safetensors +``` + Use Euler, CFG 1, and `--sigmas minimax-h3-image` for the model's six-step schedule. The default discrete scheduler also produces this schedule with `--steps 6`. Prompt expansion is not included. diff --git a/docs/models/minit2i.md b/docs/models/minit2i.md index 3e09b759c6..c658a451f4 100644 --- a/docs/models/minit2i.md +++ b/docs/models/minit2i.md @@ -11,8 +11,6 @@ MiniT2I uses a MiniT2I diffusion transformer and `google/flan-t5-large` as the t ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -28,7 +26,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [CUDA](../dgl/minit2i/minit2i-cuda-txt2img.dgl) | Text-to-image generation on CUDA. | +| [Metal](../dgl/minit2i/minit2i-metal-txt2img.dgl) | Run with `--threads 8`. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\minit2i\minit2i-cuda-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/minit2i/minit2i-cuda-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### CUDA diff --git a/docs/models/moss_image.md b/docs/models/moss_image.md index 398b9193e6..f56442a3f4 100644 --- a/docs/models/moss_image.md +++ b/docs/models/moss_image.md @@ -1,6 +1,7 @@ # MOSS-Image MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as the LLM text encoder. Both Base and SFT are supported. Prompt enhancement is not included. +Image editing requires a matching LoRA. ## Model files @@ -10,12 +11,17 @@ MOSS-Image uses a 5B diffusion transformer, the FLUX.2 VAE, and Qwen3.5 9B as th | vae | [Safetensors](https://huggingface.co/Comfy-Org/MOSS-Image/tree/main/vae) | `--vae` | Use matching VAE | | Qwen3.5 9B | [GGUF](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF/tree/main) | `--llm` | Use matching text encoder | | `tokenizer.json` | [Download](https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base/tree/main/tokenizer) | `--tokenizer` | Required; match text encoder | +| Qwen3.5 9B vision projector | [GGUF](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF/blob/main/mmproj-BF16.gguf) | `--llm_vision` | Required for vision inputs when the encoder uses separate vision weights | +| MOSS-Image-Edit-HQ LoRA | [`armV5-moss-edit-lora.safetensors`](https://huggingface.co/akhaliq/MOSS-Image-Edit-HQ/blob/main/armV5-moss-edit-lora.safetensors) | `--lora-model-dir` | HQ editing with SFT | +| chinoll Moss-Image-Edit LoRA | [`adapter_model.safetensors`](https://huggingface.co/chinoll/Moss-Image-Edit/blob/main/adapter_model.safetensors) | — | Editing with Base or SFT in DGL | Pass the external `tokenizer.json` with `--tokenizer`; Qwen3.5 uses a different vocabulary from the embedded Qwen tokenizer. -## Usage +[Inline prompt images](../guides/prompt_images.md) require Qwen3.5 vision +weights. HQ editing also uses them when available. Pass a separate projector +with `--llm_vision` in the CLI or `vision_path` on `load_text_encoder` in DGL. -CLI examples use the [shared path and shell conventions](README.md#example-conventions). +## Usage ### Web UI @@ -33,7 +39,41 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Base: text to image](../dgl/moss_image/moss-image-base-txt2img.dgl) | MOSS-Image Base. | +| [SFT: text to image](../dgl/moss_image/moss-image-sft-txt2img.dgl) | MOSS-Image SFT. | +| [Inline images](../dgl/moss_image/moss-image-sft-inline-images.dgl) | Insert named images into the prompt. | +| [Image editing (HQ)](../dgl/moss_image/moss-image-edit.dgl) | SFT with the armV5 LoRA and a Qwen3.5 vision projector. | +| [Image editing (chinoll)](../dgl/moss_image/moss-image-edit-chinoll.dgl) | Base or SFT with the chinoll LoRA. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\moss_image\moss-image-base-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/moss_image/moss-image-base-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### MOSS-Image Base @@ -105,4 +145,50 @@ Select optional components when required by your checkpoint or task. -Use dimensions divisible by 16. The default discrete scheduler uses the upstream time shift of 5. Use `--flow-shift` to override it. The negative CFG branch skips DiT layer 22 (zero-based), matching the upstream pipeline. +#### MOSS-Image Edit + +The CLI uses the HQ workflow with SFT. Save the LoRA as +`models/loras/moss/armV5-moss-edit-lora.safetensors` or adjust the LoRA tag below. +Pass `-r` for each reference image. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe ` + --diffusion-model ..\models\diffusion_models\moss_image_sft_int8_convrot_attn.safetensors ` + --llm ..\models\text_encoders\Qwen3.5-9B-Q4_K_M.gguf ` + --llm_vision ..\models\text_encoders\Qwen3.5-9B-mmproj-BF16.gguf ` + --vae ..\models\vae\flux2_ae.safetensors ` + --tokenizer ..\models\tokenizers\tokenizer_qwen3.5.json ` + --lora-model-dir ..\models\loras ` + -r ..\assets\flux\flux1-dev-q8_0.png ` + -p "change 'flux.cpp' to 'moss.cpp'" ` + --cfg-scale 3.0 ` + -v +``` + +**Linux/macOS** + +```sh +./bin/sd-cli \ + --diffusion-model ../models/diffusion_models/moss_image_sft_int8_convrot_attn.safetensors \ + --llm ../models/text_encoders/Qwen3.5-9B-Q4_K_M.gguf \ + --llm_vision ../models/text_encoders/Qwen3.5-9B-mmproj-BF16.gguf \ + --vae ../models/vae/flux2_ae.safetensors \ + --tokenizer ../models/tokenizers/tokenizer_qwen3.5.json \ + --lora-model-dir ../models/loras \ + -r ../assets/flux/flux1-dev-q8_0.png \ + -p "change 'flux.cpp' to 'moss.cpp'" \ + --cfg-scale 3.0 \ + -v +``` + +## Notes and limitations + +Use output dimensions divisible by 16. The editing examples cap the reference +long edge at 1024 pixels. The discrete scheduler defaults to a flow shift of 5. +Use `--flow-shift` to override it. Prompt weights use `(phrase:1.2)` syntax. + +For text-to-image and HQ editing, the CLI and C API set `skip_layers = [22]` on +the negative predictor. The corresponding DGL examples set the same zero-based +layer index. diff --git a/docs/models/ovis_image.md b/docs/models/ovis_image.md index ddf6c21579..fb3396216a 100644 --- a/docs/models/ovis_image.md +++ b/docs/models/ovis_image.md @@ -12,8 +12,6 @@ Ovis-Image generates images from text using an Ovis 2.5 encoder and the FLUX VAE ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -29,7 +27,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/ovis_image/ovis-image-txt2img.dgl) | Ovis-Image generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\ovis_image\ovis-image-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/ovis_image/ovis-image-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/p_h3_image.md b/docs/models/p_h3_image.md index eed578416a..2de8088691 100644 --- a/docs/models/p_h3_image.md +++ b/docs/models/p_h3_image.md @@ -13,6 +13,9 @@ P-H3-Image supports text-to-image and reference-image editing. It uses a MiniMax Alternatively, reuse Qwen3-VL-4B, including its vision tower, with the [separate text connector](https://huggingface.co/PrunaAI/P-H3-Image/blob/main/text_connector/diffusion_pytorch_model.safetensors). Save the connector as `p-h3-image_text_connector.safetensors` and pass it with `--embeddings-connectors`. +In DGL, set `family = "p_h3_image"` on the separately loaded DiT, text encoder, +and VAE. Pass the connector to `load_text_encoder` with `connectors_path`. + The MiniMax-H3 Qwen3-VL-32B encoder does not need a text connector. To use it in either example below, omit `--embeddings-connectors` and replace `--llm` with: @@ -35,8 +38,6 @@ Use the P-H3 image VAE; the MiniMax-H3 video VAE is not compatible. No audio VAE ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -52,7 +53,38 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/p_h3_image/p-h3-image-txt2img.dgl) | P-H3-Image generation. | +| [Image editing](../dgl/p_h3_image/p-h3-image-edit.dgl) | Edit a reference image. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\p_h3_image\p-h3-image-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/p_h3_image/p-h3-image-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text-to-image diff --git a/docs/models/photo_maker.md b/docs/models/photo_maker.md index 1bc8ab3a2c..5c22a985a0 100644 --- a/docs/models/photo_maker.md +++ b/docs/models/photo_maker.md @@ -3,16 +3,18 @@ [PhotoMaker](https://github.com/TencentARC/PhotoMaker) personalizes image generation from identity images. It requires an SDXL base model. +**Currently supported only through dgl.** + ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL usage | Requirement | | --- | --- | --- | --- | -| SDXL checkpoint | [SDXL guide](sd.md) | `-m` / `--model` | Required; PhotoMaker is SDXL-only | -| SDXL VAE | VAE compatible with the selected SDXL checkpoint | `--vae` | Use an override when required | -| PhotoMaker v1 | [Safetensors weights](https://huggingface.co/bssrdf/PhotoMaker) | `--photo-maker` | For v1; the original .bin release is unsupported | -| PhotoMaker v2 | [Safetensors weights](https://huggingface.co/bssrdf/PhotoMakerV2) | `--photo-maker` | Alternative to v1; requires precomputed face embeddings | -| Identity images | A directory of portraits of the same person | `--pm-id-images-dir` | Required | -| PhotoMaker v2 embeddings | `id_embeds.bin` from the preparation below | `--pm-id-embed-path` | Required for v2 | +| SDXL checkpoint | [SDXL guide](sd.md) | `load_unet`, `load_text_encoder` | Required; PhotoMaker is SDXL-only | +| SDXL VAE | VAE compatible with the selected SDXL checkpoint | `load_vae` | Use an override when required | +| PhotoMaker v1 | [Safetensors weights](https://huggingface.co/bssrdf/PhotoMaker) | `photomaker::load` | For v1; the original .bin release is unsupported | +| PhotoMaker v2 | [Safetensors weights](https://huggingface.co/bssrdf/PhotoMakerV2) | `photomaker::load` | Alternative to v1; requires precomputed face embeddings | +| Identity images | A directory of portraits of the same person | `image::load_dir` | Required | +| PhotoMaker v2 embeddings | `id_embeds.npy` from the preparation below | `tensor::load` | Required for v2 | ### Prepare PhotoMaker v2 embeddings @@ -32,126 +34,69 @@ python scripts\face_detect.py .\inputs\photomaker_examples\scarletthead_woman python scripts/face_detect.py ./inputs/photomaker_examples/scarletthead_woman ``` -The script requires its Python dependencies, including PyTorch, NumPy, Diffusers, -and InsightFace. It writes `id_embeds.bin` inside the input directory. Compute it -once and reuse it for later generations. The image directory and `id_embeds.bin` stay under the repository's `inputs/` -directory. +The script uses NumPy, Diffusers, and InsightFace. It writes +`id_embeds.npy` with one float32 embedding per image, in filename order. +Reuse the file with the same reference images, in the same order. +These DGL examples use `.npy` embeddings. -## Usage +For DGL, read the file with `tensor::load` and pass it as +`photomaker::encode_images(id_embedding=...)` alongside the images in the same order. +See the [PhotoMaker v2 example](../dgl/photo_maker/photomaker-v2-sdxl.dgl). -CLI examples use the [shared path and shell conventions](README.md#example-conventions). +## Usage ### Web UI -Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the -server, then select the recipe matching your weights. Fill the component slots -below and click **Load models**. -Use the files and compatibility requirements in [Model files](#model-files). - -| Recipe | Component slots | -| --- | --- | -| SDXL PhotoMaker (`sdxl-photomaker`) | `model`, `photo_maker`, `vae`, `tae` | +Open the server's **DGL editor**, edit the same script, and submit it. +Model and input paths must satisfy the server's file-access policy; save outputs +inside its `output/` directory. See the [Web UI guide](../../examples/server/README.md#web-ui). -Slot IDs correspond to CLI component options: `diffusion_model` uses -`--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. -Select optional components when required by your checkpoint or task. +### DGL -Select the appropriate PhotoMaker weights and supply the identity images. -PhotoMaker v2 also needs the prepared identity embedding. +| Example | Description | +| --- | --- | +| [PhotoMaker v1](../dgl/photo_maker/photomaker-v1-sdxl.dgl) | Generate from reference identity images with SDXL. | +| [PhotoMaker v2](../dgl/photo_maker/photomaker-v2-sdxl.dgl) | Use reference images and prepared `.npy` identity embeddings. | -### CLI +#### Run a script -#### PhotoMaker Version 1 +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\sdxlUnstableDiffusers_v11.safetensors ` - --vae ..\models\vae\sdxl_vae.safetensors ` - --photo-maker ..\models\photomaker\photomaker-v1.safetensors ` - --pm-id-images-dir ..\inputs\photomaker_examples\scarletthead_woman ` - -p "a girl img, retro futurism, retro game art style but extremely beautiful, intricate details, masterpiece, best quality, space-themed, cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed" ` - -n "realistic, photo-realistic, worst quality, greyscale, bad anatomy, bad hands, error, text" ` - --cfg-scale 5.0 ` - --sampling-method euler ` - --steps 50 ` - -H 1024 ` - -W 1024 ` - --pm-style-strength 10 ` - --vae-on-cpu +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\photo_maker\photomaker-v1-sdxl.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - -m ../models/checkpoints/sdxlUnstableDiffusers_v11.safetensors \ - --vae ../models/vae/sdxl_vae.safetensors \ - --photo-maker ../models/photomaker/photomaker-v1.safetensors \ - --pm-id-images-dir ../inputs/photomaker_examples/scarletthead_woman \ - -p "a girl img, retro futurism, retro game art style but extremely beautiful, intricate details, masterpiece, best quality, space-themed, cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed" \ - -n "realistic, photo-realistic, worst quality, greyscale, bad anatomy, bad hands, error, text" \ - --cfg-scale 5.0 \ - --sampling-method euler \ - --steps 50 \ - -H 1024 \ - -W 1024 \ - --pm-style-strength 10 \ - --vae-on-cpu -``` - -#### PhotoMaker Version 2 - -From the build directory, use the prepared identity embedding: - -**Windows (PowerShell)** - -```powershell -.\bin\Release\sd-cli.exe ` - -m ..\models\checkpoints\sdxlUnstableDiffusers_v11.safetensors ` - --vae ..\models\vae\sdxl_vae.safetensors ` - --photo-maker ..\models\photomaker\photomaker-v2.safetensors ` - --pm-id-images-dir ..\inputs\photomaker_examples\scarletthead_woman ` - --pm-id-embed-path ..\inputs\photomaker_examples\scarletthead_woman\id_embeds.bin ` - -p "a girl img, retro futurism, retro game art style but extremely beautiful, intricate details, masterpiece, best quality, space-themed, cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed" ` - -n "realistic, photo-realistic, worst quality, greyscale, bad anatomy, bad hands, error, text" ` - --cfg-scale 5.0 ` - --sampling-method euler ` - --steps 50 ` - -H 1024 ` - -W 1024 ` - --pm-style-strength 10 ` - --vae-on-cpu +./bin/sd-cli -M dgl --script ../docs/dgl/photo_maker/photomaker-v1-sdxl.dgl ``` -**Linux/macOS** +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. -```sh -./bin/sd-cli \ - -m ../models/checkpoints/sdxlUnstableDiffusers_v11.safetensors \ - --vae ../models/vae/sdxl_vae.safetensors \ - --photo-maker ../models/photomaker/photomaker-v2.safetensors \ - --pm-id-images-dir ../inputs/photomaker_examples/scarletthead_woman \ - --pm-id-embed-path ../inputs/photomaker_examples/scarletthead_woman/id_embeds.bin \ - -p "a girl img, retro futurism, retro game art style but extremely beautiful, intricate details, masterpiece, best quality, space-themed, cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed" \ - -n "realistic, photo-realistic, worst quality, greyscale, bad anatomy, bad hands, error, text" \ - --cfg-scale 5.0 \ - --sampling-method euler \ - --steps 50 \ - -H 1024 \ - -W 1024 \ - --pm-style-strength 10 \ - --vae-on-cpu -``` +Load the identity encoder with `photomaker::load` and pass the reference +images to `photomaker::encode_images`. Save the resulting tensor with `tensor::save` +to reuse the same identity across prompts or programs. Place the `img` +trigger after the class word in each prompt. `photomaker::encode_prompt` +uses the token count to allocate identity slots and returns their mask. +`photomaker::apply` merges the tokens into those slots. Use +`switch_predictor` to select the activation step and `apply_lora` to load +the checkpoint's LoRA onto the denoiser. ## Options -The prompt must include a class word followed by the trigger word `img`, for -example `a girl img`. Class words include `man`, `woman`, `girl`, and `boy`. -For Asian identity images, the original workflow places `Asian` before the class word. +The prompt must contain a class word followed by the trigger word `img`, for +example `a woman img`. The scripts expose `style_strength` in the range 0–100 +and pass `floor(steps * style_strength / 100)` to `switch_predictor`. Before that +step sampling uses the plain text condition; afterward it uses the merged +identity tokens. The examples use CFG 5 and 1024 × 1024. -`--pm-style-strength` accepts 0-100 and defaults to 20. The original examples use -10-20; lower values follow the source identity more closely. Use CFG 5 and -1024 x 1024 as in the example. On GPUs with 8 GB or less, `--vae-on-cpu` can help -with VAE memory usage. +The VAE is explicitly placed on CPU with `load_vae(..., backend="cpu")`. +Change that loader to select another compute device; identity encoding, +LoRA application and prompt encoding remain separate operations. diff --git a/docs/models/pid.md b/docs/models/pid.md index 7f89f1b0b3..ff44b3c79a 100644 --- a/docs/models/pid.md +++ b/docs/models/pid.md @@ -20,8 +20,6 @@ PiD and PiD 1.5 require an external Gemma 2 `tokenizer.json` matching the text e ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -44,7 +42,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/pid/pid-flux1-512-to-2048-txt2img.dgl) | Four-step generation from 512 to 2048 pixels. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\pid\pid-flux1-512-to-2048-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/pid/pid-flux1-512-to-2048-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/pixart.md b/docs/models/pixart.md index 336e1ee272..f31d276f74 100644 --- a/docs/models/pixart.md +++ b/docs/models/pixart.md @@ -17,8 +17,6 @@ encoder and a 4-channel VAE: SDXL-style for PixArt-Σ and SD1.x-style for PixArt ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -36,7 +34,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/pixart/pixart-sigma-xl2-1024-ms-txt2img.dgl) | PixArt Sigma XL2 at 1024 pixels. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\pixart\pixart-sigma-xl2-1024-ms-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/pixart/pixart-sigma-xl2-1024-ms-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/pulid.md b/docs/models/pulid.md index 188fbb8477..7e5b6fe258 100644 --- a/docs/models/pulid.md +++ b/docs/models/pulid.md @@ -4,13 +4,15 @@ identity while generating new images with FLUX.1 dev or schnell. Compute the identity embedding once with the external Python tool, then reuse it. +**Currently supported only through dgl.** + ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL usage | Requirement | | --- | --- | --- | --- | -| FLUX.1 base components | [FLUX.1 guide](flux.md) | `--diffusion-model`, `--vae`, `--clip_l`, `--t5xxl` | Required; dev or schnell | -| PuLID v0.9.x weights | [guozinan/PuLID](https://huggingface.co/guozinan/PuLID) | `--pulid-weights` | v0.9.1 is the tested version; v1.1 is unsupported | -| Identity embedding | `source.pulidembd` from preparation below | `--pulid-id-embedding` | Required for identity preservation | +| FLUX.1 base components | [FLUX.1 guide](flux.md) | `load_dit`, `load_vae`, `load_text_encoder` | Required; dev or schnell | +| PuLID v0.9.x weights | [guozinan/PuLID](https://huggingface.co/guozinan/PuLID) | `pulid::load` | v0.9.1 is the tested version; v1.1 is unsupported | +| Identity embedding | `source.pulidembd` from preparation below | `pulid::load_embedding` | Required for identity preservation | ### Prepare the identity embedding @@ -48,152 +50,73 @@ The examples below read the same file from the build directory. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI -Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the -server, then select the recipe matching your weights. Fill the component slots -below and click **Load models**. -Use the files and compatibility requirements in [Model files](#model-files). +Open the server's **DGL editor**, edit the same script, and submit it. +Model and input paths must satisfy the server's file-access policy; save outputs +inside its `output/` directory. See the [Web UI guide](../../examples/server/README.md#web-ui). -| Recipe | Component slots | +### DGL + +| Example | Description | | --- | --- | -| FLUX.1 dev PuLID (`flux1-pulid`) | `diffusion_model`, `clip_l`, `t5xxl`, `pulid_weights`, `vae`, `tae` | +| [Identity-guided generation](../dgl/pulid/pulid-flux1-schnell.dgl) | Use a prepared identity embedding with FLUX.1 schnell. | -Slot IDs correspond to CLI component options: `diffusion_model` uses -`--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. -Select optional components when required by your checkpoint or task. +#### Run a script -### CLI +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - --diffusion-model ..\models\diffusion_models\flux1-schnell-Q4_K_S.gguf ` - --vae ..\models\vae\ae.safetensors ` - --clip_l ..\models\text_encoders\clip_l.safetensors ` - --t5xxl ..\models\text_encoders\t5xxl_fp16.safetensors ` - --pulid-weights ..\models\pulid\pulid_flux_v0.9.1.safetensors ` - --pulid-id-embedding ..\inputs\source.pulidembd ` - -p "candid photograph of a young woman on a beach at sunset" ` - --cfg-scale 1.0 ` - --sampling-method euler ` - --steps 4 ` - -W 512 ` - -H 512 ` - --pulid-id-weight 1.0 ` - --clip-on-cpu ` - --seed 42 ` - -o out.png +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\pulid\pulid-flux1-schnell.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - --diffusion-model ../models/diffusion_models/flux1-schnell-Q4_K_S.gguf \ - --vae ../models/vae/ae.safetensors \ - --clip_l ../models/text_encoders/clip_l.safetensors \ - --t5xxl ../models/text_encoders/t5xxl_fp16.safetensors \ - --pulid-weights ../models/pulid/pulid_flux_v0.9.1.safetensors \ - --pulid-id-embedding ../inputs/source.pulidembd \ - -p "candid photograph of a young woman on a beach at sunset" \ - --cfg-scale 1.0 \ - --sampling-method euler \ - --steps 4 \ - -W 512 \ - -H 512 \ - --pulid-id-weight 1.0 \ - --clip-on-cpu \ - --seed 42 \ - -o out.png +./bin/sd-cli -M dgl --script ../docs/dgl/pulid/pulid-flux1-schnell.dgl ``` -For Flux Dev (instead of Schnell), add `--guidance 3.5` and `--steps 20`. - -## Options - -| Flag | Purpose | -|----------------------------|-------------------------------------------------------------------| -| `--pulid-weights ` | Path to `pulid_flux_v0.9.x.safetensors`. Loaded with the model. | -| `--pulid-id-embedding

` | Path to a `.pulidembd` binary produced by the precompute tool. | -| `--pulid-id-weight ` | Identity-injection strength. Typical 0.7-1.2; default 1.0. | - -Supply both the PuLID weights and identity embedding to activate identity -conditioning. `--pulid-id-weight` defaults to 1.0; set it to 0 to disable identity -injection. Loading `--pulid-weights` without an embedding leaves identity -conditioning inactive. - -### Backend selection - -The standard `--backend` flag works as documented. Common patterns: - -**Windows (PowerShell) arguments** - -```text -# AMD Vulkan ---backend "diffusion=vulkan0,vae=cpu" - -# NVIDIA Vulkan ---backend "diffusion=vulkan1,vae=cpu" +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. -# CUDA ---backend "diffusion=cuda0,vae=cpu" -``` +Load PuLID weights separately with `pulid::load` on the same compute backend +as the FLUX.1 denoiser. Read the identity embedding with +`pulid::load_embedding` and bind it to a text condition with `pulid::apply` +before calling `predictor`. Each binding sets its own `strength` and can +set `start_sigma` and `end_sigma` to bound the contribution in sigma space. +Omitting both bounds enables the binding throughout sampling. -**Linux/macOS arguments** +For FLUX.1 dev, choose its checkpoint and set `steps = 20`. The predictor's +default guidance is 3.5. -```text -# AMD Vulkan ---backend diffusion=vulkan0,vae=cpu +## Options -# NVIDIA Vulkan ---backend diffusion=vulkan1,vae=cpu +Load weights with `pulid::load`, read the prepared `.pulidembd` file with +`pulid::load_embedding`, and attach it to the positive condition with +`pulid::apply(..., strength=1.0)`. Typical identity strengths are 0.7–1.2. +Optional `start_sigma` and `end_sigma` bound the active noise interval. -# CUDA ---backend diffusion=cuda0,vae=cpu -``` +### Backend selection -The PuLID cross-attention layers run on the same backend as the main -diffusion model. They have not yet been independently profiled on every -backend; only Vulkan and CPU have been tested by the original contributor. +DGL selects devices on individual loaders. Use the same compute backend for +`load_dit` and `pulid::load`; for example `backend="cuda0"`, `"vulkan0"` or +`"vulkan1"`, according to the available devices. To decode on CPU set +`load_vae(..., backend="cpu")`. `params_backend="cpu"` offloads weights while +leaving computation on the selected compute device. +See [backend selection](../guides/backend.md). ## Notes and limitations -PuLID v1.1 weights are unsupported. Use PuLID and skip-layer guidance -(`--skip-layers`) separately. One precomputed identity embedding is accepted per -request; prepare it using the external tool. Identity conditioning is applied -to the positive CFG branch. - -At 512x512, 4 steps (Schnell), the 20 cross-attention layers add roughly -10% to denoise time and almost nothing to peak VRAM. Tested on a 12 GB -consumer card alongside Flux Schnell Q4 GGUF + CPU-offloaded clip_l and -t5xxl + GPU-resident VAE. - -At 1024x1024 with Flux Dev Q4 + 20 steps + PuLID, the VAE decode compute -buffer doesn't fit on a 12 GB card even with `--vae-on-cpu`. Workaround: -explicitly route VAE to the CPU backend instead of the offload flag: - -**Windows (PowerShell) arguments** - -```text ---backend "diffusion=vulkan0,vae=cpu" -``` - -**Linux/macOS arguments** - -```text ---backend diffusion=vulkan0,vae=cpu -``` - -The `--vae-on-cpu` flag offloads VAE weights but leaves the compute graph -on the default backend; this is existing stable-diffusion.cpp behavior, -not a PuLID-specific issue. Documented here because anyone running PuLID -at 1024 will hit it. +PuLID v1.1 weights are unsupported. One precomputed identity embedding is +used by this script and attached to the positive condition. Prepare it with +the external tool before running the program. -The original contributor tested Vulkan and CPU. Other backends were not -validated in those tests. See [backend selection](../guides/backend.md) for -device placement. Internal format details and validation procedures are in the -[PuLID developer notes](../development/pulid.md). +Large VAE decode workspaces can exceed GPU memory at 1024 × 1024; explicitly +select `backend="cpu"` on `load_vae` when needed. The original contributor +validated PuLID on Vulkan and CPU; those results do not establish support or +performance on every backend. diff --git a/docs/models/qwen_image.md b/docs/models/qwen_image.md index 030f2f772f..c1379ac89f 100644 --- a/docs/models/qwen_image.md +++ b/docs/models/qwen_image.md @@ -12,8 +12,6 @@ Qwen Image generates images from text using Qwen2.5-VL and the Qwen Image VAE. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -29,7 +27,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/qwen_image/qwen-image-txt2img.dgl) | Qwen Image generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\qwen_image\qwen-image-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/qwen_image/qwen-image-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/qwen_image_2.1.md b/docs/models/qwen_image_2.1.md index 7ddfda5a2d..0953f97476 100644 --- a/docs/models/qwen_image_2.1.md +++ b/docs/models/qwen_image_2.1.md @@ -16,8 +16,6 @@ For faster encoding, decoding, or previews, see [TAEQI2.1](taesd.md#qwen-image-2 ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -34,7 +32,47 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/qwen_image_2.1/qwen-image-2-1-txt2img.dgl) | Generate an image from a prompt. | +| [Image editing](../dgl/qwen_image_2.1/qwen-image-2-1-edit.dgl) | Edit a reference image; inputs are aligned automatically. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\qwen_image_2.1\qwen-image-2-1-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/qwen_image_2.1/qwen-image-2-1-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +The [editing script](../dgl/qwen_image_2.1/qwen-image-2-1-edit.dgl) loads the reference +at its original size. `vae_encode` and `encode_prompt` each align their input +to multiples of 32, as required by the mapping between vision image slots and +reference latent tokens. The VAE still compresses by a factor of 16. +Already aligned inputs skip resizing. `latent_shape` creates a compatible output +canvas from the reference dimensions, without imposing a fixed resolution. +Use `tensor::interpolate` or `tensor::crop` first to choose a different size. +See [DGL media dimensions](../dgl.md#media-dimensions) for rounding and video rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). Use image dimensions divisible by 32. The resolution-dependent flow schedule is selected automatically. @@ -199,3 +237,12 @@ Disable caching with `--model-args qwen_image_2_1_prefix_cache=false`. Numerical results can differ slightly because caching changes computation sizes. See the [prefix cache developer notes](../development/qwen_image_prefix_cache.md) for storage compatibility and implementation details. + +### DGL system instructions + +`encode_prompt` uses the model's default system message when `system` is omitted. +`system="your instruction"` replaces its body; `system=""` removes the whole +system segment and adjusts the output crop accordingly. User/assistant formatting +and reference-image handling remain model-defined. `raw=true` accepts the complete +tokenizer input without adding template segments or cropping a template prefix. +Do not combine it with `system` or image bindings. See [DGL prompt formatting](../dgl.md#independent-generation-components). diff --git a/docs/models/qwen_image_edit.md b/docs/models/qwen_image_edit.md index adec6fff3d..fd701f23b1 100644 --- a/docs/models/qwen_image_edit.md +++ b/docs/models/qwen_image_edit.md @@ -12,8 +12,6 @@ Qwen Image Edit supports reference-image editing with the original, 2509, and 25 ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -31,7 +29,39 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Qwen Image Edit](../dgl/qwen_image_edit/qwen-image-edit.dgl) | Edit a reference image. | +| [Qwen Image Edit 2509](../dgl/qwen_image_edit/qwen-image-edit-2509.dgl) | Use the 2509 checkpoint. | +| [Qwen Image Edit 2511](../dgl/qwen_image_edit/qwen-image-edit-2511.dgl) | Use the 2511 checkpoint. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\qwen_image_edit\qwen-image-edit.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/qwen_image_edit/qwen-image-edit.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Qwen Image Edit @@ -148,3 +178,9 @@ To use the new Qwen Image Edit 2511 mode, `--model-args qwen_image_zero_cond_t=t ``` qwen_image_edit_2509 + +## Notes and limitations + +The vision encoder uses a target area of `384 × 384` pixels for each reference +image, preserving its aspect ratio up to the encoder's patch alignment. VAE +reference latents use a separate resize based on the output size. diff --git a/docs/models/relay_vsr.md b/docs/models/relay_vsr.md index 4900fa4fb8..ce6eeb6cb9 100644 --- a/docs/models/relay_vsr.md +++ b/docs/models/relay_vsr.md @@ -1,19 +1,21 @@ # RelayVSR [RelayVSR](https://github.com/kopperx/RelayVSR) upscales images and videos by -2x or 4x with `-M vid_upscale`. +2x or 4x through separately loaded diffusion and VAE components. + +**Currently supported only through dgl.** ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL usage | Requirement | | --- | --- | --- | --- | -| RelayVSR diffusion model | [ComfyUI RelayVSR](https://huggingface.co/Comfy-Org/RelayVSR) | `--diffusion-model` | Match the requested 2x or 4x scale | -| RelayVSR VAE | Matching scale-specific VAE from the same repository | `--vae` | Required; ordinary Wan VAE is incompatible | +| RelayVSR diffusion model | [ComfyUI RelayVSR](https://huggingface.co/Comfy-Org/RelayVSR) | `load_dit` | Match the requested 2x or 4x scale | +| RelayVSR VAE | Matching scale-specific VAE from the same repository | `load_vae` | Required; ordinary Wan VAE is incompatible | [ComfyUI safetensors weights](https://huggingface.co/Comfy-Org/RelayVSR) load directly. Select the matching pair for the requested scale: -| `--upscale-factor` | `--diffusion-model` | `--vae` | +| Scale | `load_dit` | `load_vae` | | --- | --- | --- | | 2 | `relayvsr_x2_lightx2v_int8_convrot.safetensors` | `relayvsr_flash_vae_x2_fp32.safetensors` | | 4 | `relayvsr_x4_int8_convrot.safetensors` | `relayvsr_flash_vae_x4_fp32.safetensors` | @@ -22,60 +24,54 @@ No separate text encoder or ordinary Wan VAE is needed. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). +### DGL + +| Example | Description | +| --- | --- | +| [Upscale a video](../dgl/relay_vsr/relayvsr-x2-video-upscale.dgl) | Process overlapping windows with the 2x model. | +| [Upscale an image](../dgl/relay_vsr/relayvsr-x2-image-upscale.dgl) | Run the same 2x model on one image. | -### CLI +#### Run a script -For a video, extract numbered frames into a directory, then run: +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - -M vid_upscale ` - --diffusion-model ..\models\diffusion_models\relayvsr_x2_lightx2v_int8_convrot.safetensors ` - --vae ..\models\vae\relayvsr_flash_vae_x2_fp32.safetensors ` - --input-frames input_frames ` - --upscale-factor 2 ` - --fps 24 ` - --vsr-window-size 16 ` - -s 42 ` - -o output.avi +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\relay_vsr\relayvsr-x2-video-upscale.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - -M vid_upscale \ - --diffusion-model ../models/diffusion_models/relayvsr_x2_lightx2v_int8_convrot.safetensors \ - --vae ../models/vae/relayvsr_flash_vae_x2_fp32.safetensors \ - --input-frames input_frames \ - --upscale-factor 2 \ - --fps 24 \ - --vsr-window-size 16 \ - -s 42 \ - -o output.avi +./bin/sd-cli -M dgl --script ../docs/dgl/relay_vsr/relayvsr-x2-video-upscale.dgl ``` -Frames are read in filename order. Set `--fps` to the source video's frame rate. -Video outputs support AVI, WebM, and animated WebP. To save individual frames, -use an output pattern such as `-o output/%04d.png`. +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +Set `input_path` to a numbered-frame directory or a video supported by +`video::load`. -For a single image, replace `--input-frames input_frames` with `-i input.png` -and use `-o output.png` (or JPEG/WebP). No FPS setting is needed for an image. -`-i` / `--init-img` and `--input-frames` are mutually exclusive. +Frame directories are read in filename order. Set the script's `fps` to the +desired output rate. `video::save` writes AVI and receives the original audio +separately. The [single-image script](../dgl/relay_vsr/relayvsr-x2-image-upscale.dgl) +uses `image::load` / `image::save` instead. ## Notes and limitations -- `--upscale-factor` is required. Use 2 or 4 with the corresponding weights. - Output width and height are exactly the input dimensions times the scale. -- `--vsr-window-size` sets the reference-frame window, including both endpoints. - The default 16 selects reference frames 0, 15, 30, and so on, and always - includes the final frame. Every input frame appears once in the output. -- `--flash-attn auto` and `--conv-direct auto` are enabled by default. See - [backend selection](../guides/backend.md) to choose a device or weight placement. -- Sampler, scheduler, and step settings do not configure RelayVSR. - `--vsr-temporal-chunk-size` is a SeedVR2 option. -- Long videos require enough system memory to hold the input and output frames. - Audio is not copied to the output. +- Choose matching 2× or 4× diffusion/VAE weights. Their architecture determines + the output scale; ordinary Wan VAE weights are incompatible. +- `window_size = 16` splits the input into windows with one overlapping frame. + The script samples endpoint keyframes for each window, decodes against the + source frames, then joins windows by dropping duplicate overlap frames. +- Sampling is an explicit one-step flow with `[1, 0]` sigmas and Euler. There + is no separate native video-upscale sampler configuration. +- Loader attention and convolution settings use their normal auto defaults. + See [backend selection](../guides/backend.md) for placement. +- `video::load` limits decoded input to 256 MiB. Window outputs use the general + 1 GiB tensor limit, and joined video may use up to 4 GiB. Long clips or large + frames need a more granular input/output program. diff --git a/docs/models/sd.md b/docs/models/sd.md index 2d1ab53e36..e453127c31 100644 --- a/docs/models/sd.md +++ b/docs/models/sd.md @@ -3,6 +3,8 @@ Stable Diffusion 1.x, 2.x, and SDXL support text-to-image and image-to-image generation from single-file checkpoints. +See [Textual Inversion Embeddings](../embeddings.md) for `--embd-dir` and `` usage with SD 1.x/2.x/SDXL. + ## Model files | Component | Weights and downloads | CLI option | Requirement | @@ -15,8 +17,6 @@ generation from single-file checkpoints. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -37,7 +37,43 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [SD 1.4](../dgl/sd/sd1-4-txt2img.dgl) | Text-to-image generation. | +| [SD 1.5](../dgl/sd/sd1-5-txt2img.dgl) | Text-to-image generation. | +| [SDXL](../dgl/sd/sdxl-txt2img.dgl) | Text-to-image generation. | +| [SD 1.4 image to image](../dgl/sd/sd1-4-img2img.dgl) | Start from an existing image. | +| [SD 1.5 ControlNet](../dgl/sd/sd1-5-controlnet.dgl) | Use a pose control image. | +| [SD 1.5 inpainting](../dgl/sd/sd1-5-inpainting.dgl) | Use an inpainting checkpoint and mask. | +| [NitroSD Realism / NitroFusion](../dgl/sd/nitrosd-realism-nitrofusion.dgl) | Explicit noise schedule and custom prediction transform. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\sd\sd1-4-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/sd/sd1-4-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### SD 1.4 diff --git a/docs/models/sd3.md b/docs/models/sd3.md index 12cab00039..335cbb21cd 100644 --- a/docs/models/sd3.md +++ b/docs/models/sd3.md @@ -13,8 +13,6 @@ Stable Diffusion 3 and 3.5 generate images from text. The example below uses SD3 ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -32,7 +30,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/sd3/sd3-5-large-txt2img.dgl) | Stable Diffusion 3.5 Large. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\sd3\sd3-5-large-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/sd3/sd3-5-large-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### SD3.5 Large diff --git a/docs/models/seedvr2.md b/docs/models/seedvr2.md index 0a48914bf2..60fb927167 100644 --- a/docs/models/seedvr2.md +++ b/docs/models/seedvr2.md @@ -1,18 +1,20 @@ # SeedVR2 -SeedVR2 upscales images and videos with `-M vid_upscale`. Support is experimental. +SeedVR2 upscales images and videos through dgl. Support is experimental. + +**Currently supported only through dgl.** ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL usage | Requirement | | --- | --- | --- | --- | -| Diffusion model | [ComfyUI SeedVR2](https://huggingface.co/Comfy-Org/SeedVR2) | `--diffusion-model` | Choose 3B or 7B Sharp below | -| SeedVR2 VAE | `seedvr2_ema_vae_fp16.safetensors` from the same repository | `--vae` | Required; shared by both variants | +| Diffusion model | [ComfyUI SeedVR2](https://huggingface.co/Comfy-Org/SeedVR2) | `load_dit` | Choose 3B or 7B Sharp below | +| SeedVR2 VAE | `seedvr2_ema_vae_fp16.safetensors` from the same repository | `load_vae` | Required; shared by both variants | These [ComfyUI safetensors weights](https://huggingface.co/Comfy-Org/SeedVR2) load directly, without conversion or a separate text encoder: -| Model | `--diffusion-model` | `--vae` | +| Model | `load_dit` | `load_vae` | | --- | --- | --- | | 3B | `seedvr2_3b_int8_convrot.safetensors` | `seedvr2_ema_vae_fp16.safetensors` | | 7B Sharp | `seedvr2_7b_sharp_int8_convrot.safetensors` | `seedvr2_ema_vae_fp16.safetensors` | @@ -21,103 +23,74 @@ Use the matching SeedVR2 VAE for either model. The 7B model requires more memory ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). +### DGL -### CLI +| Example | Description | +| --- | --- | +| [Upscale an image](../dgl/seedvr2/seedvr2-3b-image-upscale.dgl) | Use the 3B diffusion model and matching SeedVR2 VAE. | +| [Upscale a video](../dgl/seedvr2/seedvr2-3b-video-upscale.dgl) | Process frame windows and retain the source audio. | -#### Upscale an image +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. **Windows (PowerShell)** ```powershell -.\bin\Release\sd-cli.exe ` - -M vid_upscale ` - --diffusion-model ..\models\diffusion_models\seedvr2_3b_int8_convrot.safetensors ` - --vae ..\models\vae\seedvr2_ema_vae_fp16.safetensors ` - -i input.png ` - --upscale-factor 2 ` - -s 42 ` - -o restored.png +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\seedvr2\seedvr2-3b-image-upscale.dgl ``` **Linux/macOS** ```sh -./bin/sd-cli \ - -M vid_upscale \ - --diffusion-model ../models/diffusion_models/seedvr2_3b_int8_convrot.safetensors \ - --vae ../models/vae/seedvr2_ema_vae_fp16.safetensors \ - -i input.png \ - --upscale-factor 2 \ - -s 42 \ - -o restored.png +./bin/sd-cli -M dgl --script ../docs/dgl/seedvr2/seedvr2-3b-image-upscale.dgl ``` -`-i` / `--init-img` accepts a single image. Outputs can be PNG, JPEG, or WebP. -No FPS or temporal chunk setting is needed for an image. +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +The [SeedVR2 script](../dgl/seedvr2/seedvr2-3b-video-upscale.dgl) loads the DiT and +causal VAE independently. The script controls output resolution with +bicubic resizing and pads each window to dimensions divisible by 16 and +a frame count of `4n+1`. It uses the VAE posterior mode, the checkpoint's +positive embedding, and a one-step Euler sampler. The condition contains +the scaled VAE latent and a one-channel task mask. Each decoded window is +cropped to its original frame count and target dimensions before stitching. +The intermediate float tensors must fit the DGL tensor size limit of 256 MiB +per tensor. For large output resolutions, use shorter pixel windows. -#### Upscale a video - -Extract the video into numbered frames, then pass the frame directory: - -**Windows (PowerShell)** +CLI examples use the [shared path and shell conventions](README.md#example-conventions). -```powershell -mkdir frames -ffmpeg -i input.mp4 -fps_mode passthrough frames\%06d.png -.\bin\Release\sd-cli.exe ` - -M vid_upscale ` - --diffusion-model ..\models\diffusion_models\seedvr2_3b_int8_convrot.safetensors ` - --vae ..\models\vae\seedvr2_ema_vae_fp16.safetensors ` - --input-frames frames ` - --upscale-factor 2 ` - --fps 24 ` - --vsr-temporal-chunk-size 1 ` - -s 42 ` - -o restored.avi -``` +#### Upscale an image -**Linux/macOS** +The image script reads `input_path` and writes a PNG with `image::save`. -```sh -mkdir frames -ffmpeg -i input.mp4 -fps_mode passthrough frames/%06d.png -./bin/sd-cli \ - -M vid_upscale \ - --diffusion-model ../models/diffusion_models/seedvr2_3b_int8_convrot.safetensors \ - --vae ../models/vae/seedvr2_ema_vae_fp16.safetensors \ - --input-frames frames \ - --upscale-factor 2 \ - --fps 24 \ - --vsr-temporal-chunk-size 1 \ - -s 42 \ - -o restored.avi -``` +#### Upscale a video -Set `--fps` to the source video's frame rate; 24 is only the example above. -Frames are read in filename order. Use either `-i` or `--input-frames`, not both. +Set `input_path` to numbered frames or a video supported by `video::load`. -Video outputs support AVI, WebM, and animated WebP. To save individual frames, -use an output pattern such as `-o restored/%06d.png`. +Set `fps` to the desired frame rate; the example uses 24. Frame directories +are read in filename order. Video output is AVI, and the script passes the +source audio separately to `video::save`. ## Notes and limitations -- `--upscale-factor` is required and must be a positive integer. Output width - and height are exactly the input dimensions multiplied by this value. -- `--vsr-temporal-chunk-size` controls how many video frames are processed - together. Valid values are 1, 5, 9, 13, and so on; the default is 5. A value of - 1 processes each frame independently and uses less memory. Larger values use - neighboring frames but require more memory. Chunk boundaries may be visible. -- Frame count and order are preserved, including a shorter final chunk. Audio - is not copied to the output. -- If you run out of GPU memory, try `--vsr-temporal-chunk-size 1`. A five-frame - chunk at 1728x960 output resolution exceeded 24 GB of GPU memory in testing. -- `--flash-attn auto` and `--conv-direct auto` are enabled by default. See - [backend selection](../guides/backend.md) to choose a device or weight placement. -- SeedVR2 does not use sampler, scheduler, or step settings. - `--vsr-window-size` is a RelayVSR option and does not affect SeedVR2. - -3B has been tested on CUDA and CPU; 7B has been tested on CUDA with small inputs. -Other backends have not been tested with this integration. +- `factor` is a positive integer scale applied to pixel dimensions before + VAE encoding. Both 3B and 7B Sharp use the matching SeedVR2 VAE. +- `window_size` controls processing granularity. The video example uses 1 to + process each frame independently and reduce memory; 5, 9, 13, … include + temporal context at higher memory cost. Each window is padded to `4n+1` + frames and cropped after decoding. Chunk boundaries may be visible. +- Sampling uses the checkpoint's positive embedding and an explicit one-step + Euler flow; no text encoder is needed. +- Input/output order and frame count are preserved. Input, output and + intermediate tensors must fit the 256 MiB per-tensor limit. For larger + output frames, reduce window size; long clips need incremental I/O. +- The existing DGL workflow was tested with 3B and 7B Sharp on Vulkan. The + documentation examples in this collection are also statically checked; + this does not establish image quality or throughput on every backend. Model reference: [ByteDance-Seed/SeedVR](https://github.com/ByteDance-Seed/SeedVR). diff --git a/docs/models/sefi_image.md b/docs/models/sefi_image.md index 1d6ffbdb76..deb90ad870 100644 --- a/docs/models/sefi_image.md +++ b/docs/models/sefi_image.md @@ -34,8 +34,6 @@ python3 scripts/convert_qwen3_vl.py "/Qwen3-VL-XB-Instruct" " 1.0, otherwise 0.3). Override via `--extra-sample-args sefi_alpha=` or `sefi_delta_t=`. +Set `--extra-sample-args sefi_alpha=0.3` for Base and RL; turbo uses the default +alpha of 1. Override the second timeline offset with `sefi_delta_t=`. +CLI and C API translation forward both settings to the initial and hires +schedules. Image-to-image strength trims both timelines together. Custom sigmas +replace the texture schedule while the semantic schedule uses the same number +of steps. diff --git a/docs/models/sensenova_u1.md b/docs/models/sensenova_u1.md index e77ab39e6a..fa2cee3021 100644 --- a/docs/models/sensenova_u1.md +++ b/docs/models/sensenova_u1.md @@ -15,8 +15,6 @@ and the tokenizer files. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the server instructions for @@ -25,7 +23,51 @@ Pass the complete repository directory with `--model` when starting the server, using the same model path as the CLI examples below. The browser then uses **Command-line model (all features)** for that loaded checkpoint. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/sensenova_u1/sensenova-u1-cuda-txt2img.dgl) | SenseNova U1.5 on CUDA. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\sensenova_u1\sensenova-u1-cuda-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/sensenova_u1/sensenova-u1-cuda-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +#### Prompt formatting + +The [DGL example](../dgl/sensenova_u1/sensenova-u1-cuda-txt2img.dgl) +uses the default system message for its positive prompt and passes the complete +negative input with `raw=true`. Edit the user text inside that raw string to +change its negative prompt. An empty negative still includes the user/assistant +markers and ``, and omits the positive template's `` segment. +Native CLI/C API generation builds this input automatically. + +For custom positive instructions, pass `system="your instruction"` to +`encode_prompt`; `system=""` removes the system segment but keeps the positive +assistant template. For a completely custom tokenizer input use `raw=true` +without `system`. See [DGL prompt formatting](../dgl.md#independent-generation-components). + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### CUDA diff --git a/docs/models/taesd.md b/docs/models/taesd.md index 607c0b419c..b22b358c43 100644 --- a/docs/models/taesd.md +++ b/docs/models/taesd.md @@ -93,14 +93,43 @@ curl -L -o ../models/vae/taeqi2_1.safetensors https://huggingface.co/madebyollin ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Use a compatible base model recipe that offers the `tae` slot, and select the tiny autoencoder matching that model. See [Web UI guide](../../examples/server/README.md#web-ui). -### CLI +### DGL + +The [SD 1.5 example](../dgl/taesd/sd1-5-taesd-preview.dgl) uses TAESD to +decode the final image and passes the same decoder to `preview(decoder = vae)`. +Running it with `sd-cli -M dgl` writes the final PNG. To receive intermediate +images, run it in a host that registers a DGL preview callback in `"tae"` mode. +See [progress and previews](../dgl.md#progress-preview-and-cancellation). + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\taesd\sd1-5-taesd-preview.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/taesd/sd1-5-taesd-preview.dgl +``` + +Add `--check` to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). **Windows (PowerShell)** diff --git a/docs/models/wan.md b/docs/models/wan.md index 1b4695536e..1b4d4131de 100644 --- a/docs/models/wan.md +++ b/docs/models/wan.md @@ -32,8 +32,6 @@ file. For lower VAE memory use, see [tiny autoencoders](taesd.md). ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -56,7 +54,71 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +The Wan text encoder zeros UMT5 padding embeddings before returning the prompt +condition, matching the model's fixed-length text input. This also applies to +CLI and C API generation through dgl. + +#### Wan 2.1 + +| Example | Description | +| --- | --- | +| [Text to video, 1.3B](../dgl/wan/wan2-1-t2v-1-3b.dgl) | Wan 2.1 T2V. | +| [Text to video, 14B](../dgl/wan/wan2-1-t2v-14b.dgl) | Wan 2.1 T2V. | +| [Image to video, 14B](../dgl/wan/wan2-1-i2v-14b.dgl) | Wan 2.1 I2V, 480p. | +| [First/last-frame conditioning, 14B](../dgl/wan/wan2-1-first-last-frame-14b.dgl) | Wan 2.1 FLF2V, 720p. | + +#### Wan 2.2 + +| Example | Description | +| --- | --- | +| [Text to video, A14B](../dgl/wan/wan2-2-t2v-a14b.dgl) | Switch between high- and low-noise experts. | +| [Image to video, A14B](../dgl/wan/wan2-2-i2v-a14b.dgl) | Use the matching I2V experts. | +| [Speech to video, 14B](../dgl/wan/wan2-2-s2v-14b.dgl) | Condition a speaker image with audio features. | +| [Single-image generation, A14B](../dgl/wan/wan2-2-t2v-a14b-image.dgl) | Run T2V experts with one output frame. | +| [Text to video with LoRA](../dgl/wan/wan2-2-t2v-a14b-lora.dgl) | Patch the diffusion experts before sampling. | +| [TI2V 5B: text to video](../dgl/wan/wan2-2-ti2v-5b-txt2video.dgl) | Generate without an initial image. | +| [TI2V 5B: image to video](../dgl/wan/wan2-2-ti2v-5b-img2video.dgl) | Condition the initial frame. | +| [First/last-frame conditioning, A14B](../dgl/wan/wan2-2-first-last-frame-a14b.dgl) | Use the Wan 2.2 I2V experts. | + +#### VACE + +| Example | Description | +| --- | --- | +| [VACE 1.3B: text to video](../dgl/wan/wan2-1-vace-1-3b-txt2video.dgl) | Generate without control frames. | +| [VACE 1.3B: reference to video](../dgl/wan/wan2-1-vace-1-3b-ref2video.dgl) | Condition a reference image. | +| [VACE 1.3B: video to video](../dgl/wan/wan2-1-vace-1-3b-video2video.dgl) | Condition control frames. | +| [VACE 14B: text to video](../dgl/wan/wan2-1-vace-14b-txt2video.dgl) | Generate without control frames. | +| [VACE 14B: reference to video](../dgl/wan/wan2-1-vace-14b-ref2video.dgl) | Condition a reference image. | +| [VACE 14B: video to video](../dgl/wan/wan2-1-vace-14b-video2video.dgl) | Condition control frames. | +| [VACE Fun A14B: reference to video](../dgl/wan/wan2-2-vace-fun-a14b-ref2video.dgl) | Use Wan 2.2 VACE experts. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\wan\wan2-1-t2v-1-3b.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/wan/wan2-1-t2v-1-3b.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Wan2.1 T2V 1.3B @@ -208,8 +270,6 @@ Select optional components when required by your checkpoint or task. --cfg-scale 3.5 ` --sampling-method euler ` --steps 10 ` - --high-noise-cfg-scale 3.5 ` - --high-noise-sampling-method euler ` --high-noise-steps 8 ` --flow-shift 3.0 ` -W 832 ` @@ -233,8 +293,6 @@ Select optional components when required by your checkpoint or task. --cfg-scale 3.5 \ --sampling-method euler \ --steps 10 \ - --high-noise-cfg-scale 3.5 \ - --high-noise-sampling-method euler \ --high-noise-steps 8 \ --flow-shift 3.0 \ -W 832 \ @@ -263,8 +321,6 @@ Select optional components when required by your checkpoint or task. --cfg-scale 3.5 ` --sampling-method euler ` --steps 10 ` - --high-noise-cfg-scale 3.5 ` - --high-noise-sampling-method euler ` --high-noise-steps 8 ` --flow-shift 3.0 ` -W 832 ` @@ -290,8 +346,6 @@ Select optional components when required by your checkpoint or task. --cfg-scale 3.5 \ --sampling-method euler \ --steps 10 \ - --high-noise-cfg-scale 3.5 \ - --high-noise-sampling-method euler \ --high-noise-steps 8 \ --flow-shift 3.0 \ -W 832 \ @@ -420,8 +474,6 @@ Notes: --cfg-scale 3.5 ` --sampling-method euler ` --steps 10 ` - --high-noise-cfg-scale 3.5 ` - --high-noise-sampling-method euler ` --high-noise-steps 8 ` --flow-shift 3.0 ` -W 832 ` @@ -444,8 +496,6 @@ Notes: --cfg-scale 3.5 \ --sampling-method euler \ --steps 10 \ - --high-noise-cfg-scale 3.5 \ - --high-noise-sampling-method euler \ --high-noise-steps 8 \ --flow-shift 3.0 \ -W 832 \ @@ -473,8 +523,6 @@ Notes: --cfg-scale 3.5 ` --sampling-method euler ` --steps 4 ` - --high-noise-cfg-scale 3.5 ` - --high-noise-sampling-method euler ` --high-noise-steps 4 ` --flow-shift 3.0 ` -W 832 ` @@ -499,8 +547,6 @@ Notes: --cfg-scale 3.5 \ --sampling-method euler \ --steps 4 \ - --high-noise-cfg-scale 3.5 \ - --high-noise-sampling-method euler \ --high-noise-steps 4 \ --flow-shift 3.0 \ -W 832 \ @@ -674,8 +720,6 @@ TI2V 5B can decode multiple latent frames together when temporal tiling is enabl --cfg-scale 3.5 ` --sampling-method euler ` --steps 10 ` - --high-noise-cfg-scale 3.5 ` - --high-noise-sampling-method euler ` --high-noise-steps 8 ` --flow-shift 3.0 ` -W 480 ` @@ -701,8 +745,6 @@ TI2V 5B can decode multiple latent frames together when temporal tiling is enabl --cfg-scale 3.5 \ --sampling-method euler \ --steps 10 \ - --high-noise-cfg-scale 3.5 \ - --high-noise-sampling-method euler \ --high-noise-steps 8 \ --flow-shift 3.0 \ -W 480 \ @@ -804,6 +846,12 @@ TI2V 5B can decode multiple latent frames together when temporal tiling is enabl ##### V2V +`--control-video` accepts a frame directory or a video file (AVI, WebP or +this project's independent-frame VP8 WebM). Files are decoded at the requested +`--fps` (default 16), without audio; `--video-frames` limits decoded frames +after resampling. Missing frames are padded by the existing VACE workflow. +See [DGL media I/O](../dgl.md) for codec restrictions. + **Windows (PowerShell)** ```powershell @@ -1009,8 +1057,6 @@ for the reference image, same as Wan2.1 VACE. --cfg-scale 3.5 ` --sampling-method euler ` --steps 10 ` - --high-noise-cfg-scale 3.5 ` - --high-noise-sampling-method euler ` --high-noise-steps 8 ` -W 832 ` -H 480 ` @@ -1034,8 +1080,6 @@ for the reference image, same as Wan2.1 VACE. --cfg-scale 3.5 \ --sampling-method euler \ --steps 10 \ - --high-noise-cfg-scale 3.5 \ - --high-noise-sampling-method euler \ --high-noise-steps 8 \ -W 832 \ -H 480 \ @@ -1056,6 +1100,12 @@ video, like Wan2.1 VACE t2v). ## Notes and limitations +Dual experts share CFG, sampler, scheduler and flow shift. By default, +`--high-noise-steps -1` splits `--steps` at `--moe-boundary`. A nonnegative +`--high-noise-steps` instead adds that many high-noise steps before the +`--steps` low-noise steps; `0` runs only the low-noise model. +Use a DGL script for independently configured experts. + Wan models require `-M vid_gen`, including single-frame generation. `--video-frames` alone does not select video mode. Library callers must use `generate_video()` instead of `generate_image()`. Use the task-specific input and sampling settings in each example. VAE diff --git a/docs/models/z_image.md b/docs/models/z_image.md index 9b39e3d67d..ebd72cba07 100644 --- a/docs/models/z_image.md +++ b/docs/models/z_image.md @@ -12,11 +12,10 @@ You can run Z-Image with stable-diffusion.cpp on GPUs with 4GB of VRAM — or ev | Z-Image | [Safetensors](https://huggingface.co/Comfy-Org/z_image/tree/main/split_files/diffusion_models)
[GGUF](https://huggingface.co/unsloth/Z-Image-GGUF/tree/main) | `--diffusion-model` | Choose matching variant | | vae | [Safetensors](https://huggingface.co/black-forest-labs/FLUX.1-schnell/tree/main) | `--vae` | Use matching VAE | | Qwen3 4b | [Safetensors](https://huggingface.co/Comfy-Org/z_image_turbo/tree/main/split_files/text_encoders)
[GGUF](https://huggingface.co/unsloth/Qwen3-4B-Instruct-2507-GGUF/tree/main) | `--llm` | Use matching text encoder | +| ControlNet | Z-Image control checkpoint with `control_all_x_embedder.2-1.weight` | `--control-net` or DGL `controlnet::load` | Optional. Match the DiT architecture | ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -33,7 +32,51 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Turbo: text to image](../dgl/z_image/z-image-turbo-txt2img.dgl) | Distilled generation. | +| [Base: text to image](../dgl/z_image/z-image-base-txt2img.dgl) | Base checkpoint. | +| [Turbo with ControlNet](../dgl/z_image/z-image-turbo-controlnet.dgl) | Load and apply control weights separately. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\z_image\z-image-turbo-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/z_image/z-image-turbo-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +#### ControlNet + +The [Z-Image ControlNet script](../dgl/z_image/z-image-turbo-controlnet.dgl) +loads the diffusion and control weights as separate models. Set the four +checkpoint paths and the prepared control image path in the script. The script +encodes the image with the FLUX VAE in posterior mode, converts it to diffusion +latents and pads the channel axis to 33 before calling `controlnet::apply`. +Each control model shares the DiT's compute backend. Repeated +`controlnet::apply` calls combine the controls before sampling. In the current +Z-Image model, control conditions and reference latents require separate +predictions. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Z-Image-Turbo diff --git a/docs/models/z_image_l2p.md b/docs/models/z_image_l2p.md index c572af8ca2..c67ccab29d 100644 --- a/docs/models/z_image_l2p.md +++ b/docs/models/z_image_l2p.md @@ -12,8 +12,6 @@ directly in pixel space using Z-Image-Turbo and Qwen3 4B. No VAE is required. ## Usage -CLI examples use the [shared path and shell conventions](README.md#example-conventions). - ### Web UI Follow the [Web UI guide](../../examples/server/README.md#web-ui) to start the @@ -29,7 +27,37 @@ Slot IDs correspond to CLI component options: `diffusion_model` uses `--diffusion-model`, `llm` uses `--llm`, and `model` uses `-m` / `--model`. Select optional components when required by your checkpoint or task. -### CLI +### DGL + +| Example | Description | +| --- | --- | +| [Text to image](../dgl/z_image_l2p/z-image-l2p-txt2img.dgl) | Z-Image L2P generation. | + +#### Run a script + +Edit paths, prompts and settings in the script's `var` block, then run from +the build directory. Paths inside the script resolve from the working directory. + +**Windows (PowerShell)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\z_image_l2p\z-image-l2p-txt2img.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/z_image_l2p/z-image-l2p-txt2img.dgl +``` + +Choose another script from the table to run a different task. Add `--check` +to validate syntax and types without loading weights. See the +[shared run instructions](../dgl/README.md#run-an-example) for build paths +and the server's file-access rules. + +### Legacy CLI + +CLI examples use the [shared path and shell conventions](README.md#example-conventions). #### Text-to-image diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index c667cd4b89..c849ce107c 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -51,3 +51,32 @@ If the problem persists after trying the relevant steps above, [submit a bug report](https://github.com/leejet/stable-diffusion.cpp/issues/new?template=bug_report.yml). Include your full command, backend and hardware, model and weight format, logs, and the scale values you tried with their results. + +## Windows: process exits immediately with 0xC0000135 (STATUS_DLL_NOT_FOUND) + +`sd-cli.exe` / `sd-server.exe` from the Windows ROCm prebuilt may exit with +`0xC0000135` (`STATUS_DLL_NOT_FOUND`) and no output when the HIP runtime is +not on `PATH`. `stable-diffusion.dll` statically imports `hipblas.dll` and +`libhipblaslt.dll`, but the release archive only bundles `amd_comgr.dll`, +`amdhip64_7.dll` and `rocm_kpack.dll`. This is a loader failure, unrelated to +`--audio-vae` or other generation options; `0xC000001D` +(`STATUS_ILLEGAL_INSTRUCTION`) would instead indicate a CPU instruction issue. + +Fix: prepend the ROCm SDK `bin` directories to `PATH` — with the Python ROCm +wheels these are `\Lib\site-packages\_rocm_sdk_libraries\bin` and +`_rocm_sdk_core\bin`. Do not copy individual DLLs: `rocblas.dll` and +`libhipblaslt.dll` also need their sibling `rocblas\` and `hipblaslt\` data +directories. + +Verify: + +```powershell +.\sd-cli.exe --version +'0x{0:X8}' -f $LASTEXITCODE +``` + +Expect the version string and `0x00000000`. If it still fails, inspect the +whole DLL chain (`sd-cli.exe` -> `stable-diffusion.dll` -> ...): `dumpbin +/dependents` lists only one image's direct imports, so use +[Dependencies](https://github.com/lucasg/Dependencies) or also check +`stable-diffusion.dll` to find the missing module. diff --git a/examples/cli/CMakeLists.txt b/examples/cli/CMakeLists.txt index 36b9243e35..b93b3e7226 100644 --- a/examples/cli/CMakeLists.txt +++ b/examples/cli/CMakeLists.txt @@ -2,12 +2,12 @@ set(TARGET sd-cli) add_executable(${TARGET} ../common/common.cpp - ../common/generation_metadata.cpp ../common/log.cpp ../common/media_io.cpp ../common/media_metadata.cpp - image_metadata.cpp main.cpp + dgl.cpp + media_input.cpp ) if(APPLE) sd_set_macos_rpaths(${TARGET}) @@ -26,3 +26,13 @@ if(SD_WEBM) target_link_libraries(${TARGET} PRIVATE webm) endif() target_compile_features(${TARGET} PUBLIC c_std_11 cxx_std_17) + +set(SD_DGL_BUILTIN_CATALOG "${PROJECT_SOURCE_DIR}/docs/dgl-builtins.md") +add_custom_target(dgl-update-builtins + COMMAND $ -M dgl --write-builtins "${SD_DGL_BUILTIN_CATALOG}" + DEPENDS ${TARGET} + VERBATIM) +add_custom_target(dgl-check-builtins + COMMAND $ -M dgl --check-builtins "${SD_DGL_BUILTIN_CATALOG}" + DEPENDS ${TARGET} + VERBATIM) diff --git a/examples/cli/README.md b/examples/cli/README.md index 0316f7bd02..d8c5a0fc49 100644 --- a/examples/cli/README.md +++ b/examples/cli/README.md @@ -17,17 +17,43 @@ From the build directory, show the full list of command-line arguments: See [sampling methods and schedulers](../../docs/guides/sampling.md) for supported names, defaults, and custom sigma schedules. -Omitted inference options use the [library defaults](../../docs/guides/c_api.md#keys). -In particular, an omitted seed requests a random seed; use `--seed 42` for a -repeatable run. Video generation defaults to 6 requested frames before model -alignment. SLG layers remain unset unless `--skip-layers` is supplied, and the -conditioning cache uses the library default. Zero and false are explicit inputs; -invalid values are reported rather than treated as omitted. +The CLI defaults to seed 42 for repeatable runs. Pass `--seed -1` to request a +random seed. Other omitted inference options use the +[library defaults](../../docs/guides/c_api.md#keys). +Video generation defaults to 6 requested frames before model +alignment. The conditioning cache uses the library default. Zero and false are +explicit inputs; invalid values are reported rather than treated as omitted. + +IP-Adapter, PhotoMaker, PuLID, AnimateDiff, SLG, NitroFusion, ADetailer and video +upscaling use explicit DGL workflows. Their former native CLI options and the +`adetailer` / `vid_upscale` modes have been removed. See the +[model and component guides](../../docs/models/README.md) for scripts. + +`--ref-video` accepts a frame directory or a video file. Directories retain +filename order and 24 fps; files are decoded through DGL `video::load` at +24 fps. Supported embedded audio is retained unless a matching +`--ref-video-audio` WAV overrides it. `--control-video` accepts the same inputs; +files are sampled at the generation `--fps` (default 16), without audio, and +`--video-frames` limits decoding after resampling. Existing VACE frame padding +is unchanged. File formats are AVI, static/animated WebP, and this project's +independent-frame VP8 WebM. VP9 and Opus are unsupported; see +[DGL media I/O](../../docs/dgl.md) for codec and build requirements. Logging defaults to `info`. Use `--log-level ` to select `debug`, `verbose`, `info`, `warn`, or `error` (from most to least detailed). Each level includes messages at that level and all less detailed levels. `-v` and `--verbose` are equivalent to `--log-level verbose`. If repeated, the last logging option wins. +Native image/video generation and upscaling print the translated DGL program +before execution at debug level (`--log-level debug`). + +Run a [DGL program](../../docs/dgl.md) with `sd-cli -M dgl --script program.dgl`. +DGL mode accepts the same logging options and sends logs to stderr. +Weight loading displays a progress bar with transfer speed; sampling displays +its step progress. Context progress callbacks remain active during loading. +`--run-once on|off` controls model release after last use and defaults to `on`. +Image and video generation release each model after its last use as well, +except for image batches (`-b` greater than 1), which keep models loaded across +the batch. `--flash-attn on|off|auto` defaults to `auto`, selecting flash attention for each compute backend during context creation. See [Backend selection](../../docs/guides/backend.md#flash-attention---flash-attn-onoffauto) diff --git a/examples/cli/dgl.cpp b/examples/cli/dgl.cpp new file mode 100644 index 0000000000..21db339eb2 --- /dev/null +++ b/examples/cli/dgl.cpp @@ -0,0 +1,145 @@ +#include "dgl.h" + +#include +#include +#include +#include +#include +#include + +#include "common/common.h" +#include "stable-diffusion.h" + +ArgOptions DGLModeParams::get_options() { + ArgOptions options; + options.string_options = { + {"", "--script", "path to the .dgl program", 0, &script_path}, + {"", "--write-builtins", "write the DGL built-in catalog to a file", 0, &write_builtins_path}, + {"", "--check-builtins", "verify a file against the DGL built-in catalog", 0, &check_builtins_path}, + {"", "--max-ram", "limit DGL context weight residency in GiB", 0, &max_ram}, + }; + options.bool_options = { + {"", "--check", "check the DGL script without loading models", true, &check_only}, + {"", "--list-builtins", "print the DGL built-in catalog", true, &list_builtins}, + }; + options.manual_options = { + {"", "--run-once", "on|off (default: on). Release DGL models after their last use when on", + [this](int argc, const char** argv, int index) { + const std::string_view value = index + 1 < argc ? argv[index + 1] : ""; + if (value != "on" && value != "off") { + LOG_ERROR("--run-once requires on or off"); + return -1; + } + run_once = value == "on"; + return 1; + }}, + {"", "--tensor", "save a named result tensor as .npy (NAME FILE, repeatable)", + [this](int argc, const char** argv, int index) { + if (index + 2 >= argc) + return -1; + tensor_paths.emplace_back(argv_to_utf8(index + 1, argv), argv_to_utf8(index + 2, argv)); + return 2; + }}, + }; + return options; +} + +bool DGLModeParams::has_options() const { + return !script_path.empty() || !write_builtins_path.empty() || !check_builtins_path.empty() || + !tensor_paths.empty() || !max_ram.empty() || check_only || run_once.has_value() || list_builtins; +} + +bool DGLModeParams::validate() const { + const int actions = int(!script_path.empty()) + int(!write_builtins_path.empty()) + int(!check_builtins_path.empty()) + int(list_builtins); + if (actions != 1) { + LOG_ERROR("DGL mode requires exactly one of --script, --list-builtins, --write-builtins and --check-builtins"); + return false; + } + if (script_path.empty() && (check_only || run_once.has_value() || !tensor_paths.empty() || !max_ram.empty())) { + LOG_ERROR("--check, --run-once, --tensor and --max-ram require --script"); + return false; + } + return true; +} + +static void check_dgl(bool success) { + if (!success) + throw std::runtime_error(sd_dgl_error()); +} + +int DGLModeParams::run(const SDContextParams& options, bool embed_metadata) const { + try { + if (script_path.empty()) { + const auto* catalog = sd_dgl_builtin_catalog(); + check_dgl(catalog != nullptr); + if (list_builtins) { + std::cout << catalog; + } else if (!write_builtins_path.empty()) { + std::ofstream file(std::filesystem::u8path(write_builtins_path), std::ios::binary); + file << catalog; + file.close(); + if (!file) + throw std::runtime_error("cannot write the DGL built-in catalog"); + } else { + std::ifstream file(std::filesystem::u8path(check_builtins_path)); + const std::string existing{std::istreambuf_iterator(file), std::istreambuf_iterator()}; + if (!file || existing != catalog) + throw std::runtime_error("DGL built-in catalog is out of date. Run the dgl-update-builtins CMake target."); + std::cout << "DGL built-in catalog is current.\n"; + } + return 0; + } + + const auto path = std::filesystem::u8path(script_path); + if (path.extension() != ".dgl") + throw std::runtime_error("expected a .dgl file"); + std::ifstream file(path, std::ios::binary); + if (!file) + throw std::runtime_error("cannot open program file"); + const std::string source{std::istreambuf_iterator(file), std::istreambuf_iterator()}; + if (check_only) { + check_dgl(sd_dgl_check(source.c_str(), false) == SD_STATUS_OK); + std::cout << "DGL syntax and types are valid. Models were not loaded.\n"; + return 0; + } + if (!options.register_rpc_devices()) + return 1; + auto* raw_context = run_once.value_or(true) ? sd_dgl_ctx_create_once() : sd_dgl_ctx_create(); + check_dgl(raw_context != nullptr); + std::unique_ptr context(raw_context, sd_dgl_ctx_free); + check_dgl(options.configure_dgl(context.get())); + check_dgl(sd_dgl_ctx_set(context.get(), "embed_metadata", embed_metadata ? "on" : "off")); + if (!max_ram.empty()) + check_dgl(sd_dgl_ctx_set(context.get(), "max_ram", max_ram.c_str())); + sd_dgl_result_t* raw_result = nullptr; + check_dgl(sd_dgl_run(context.get(), source.c_str(), nullptr, 0, &raw_result) == SD_STATUS_OK); + std::unique_ptr result(raw_result, sd_dgl_result_free); + for (const auto& [name, output_path] : tensor_paths) { + auto tensor = sd_dgl_result_tensor(result.get(), name.c_str()); + if (!tensor) + throw std::runtime_error("unknown output tensor '" + name + "'"); + check_dgl(sd_tensor_save(tensor, output_path.c_str())); + } + const std::string type = sd_dgl_result_type(result.get()); + if (type == "string") { + const auto* tensor = sd_dgl_result_tensor(result.get(), "result"); + const auto* data = static_cast(sd_tensor_data(tensor)); + const auto size = sd_tensor_byte_size(tensor); + if (size) { + std::cout.write(data, size); + if (data[size - 1] != '\n') + std::cout << '\n'; + } + return 0; + } + const size_t count = sd_dgl_result_count(result.get()); + LOG_VERBOSE("Result: %s, tensors: %zu", type.c_str(), count); + for (size_t i = 0; i < count; ++i) { + LOG_VERBOSE(" %s", sd_dgl_result_name(result.get(), i)); + } + return 0; + } catch (const std::exception& error) { + LOG_ERROR("%s", error.what()); + return 1; + } +} diff --git a/examples/cli/dgl.h b/examples/cli/dgl.h new file mode 100644 index 0000000000..9bee4d5208 --- /dev/null +++ b/examples/cli/dgl.h @@ -0,0 +1,28 @@ +#ifndef __EXAMPLES_CLI_DGL_H__ +#define __EXAMPLES_CLI_DGL_H__ + +#include +#include +#include +#include + +struct ArgOptions; +struct SDContextParams; + +struct DGLModeParams { + std::string script_path; + std::string write_builtins_path; + std::string check_builtins_path; + std::string max_ram; + std::vector> tensor_paths; + bool check_only = false; + std::optional run_once; + bool list_builtins = false; + + ArgOptions get_options(); + bool has_options() const; + bool validate() const; + int run(const SDContextParams& options, bool embed_metadata) const; +}; + +#endif // __EXAMPLES_CLI_DGL_H__ diff --git a/examples/cli/image_metadata.h b/examples/cli/image_metadata.h deleted file mode 100644 index 9538167f4f..0000000000 --- a/examples/cli/image_metadata.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include - -enum class MetadataOutputFormat { - TEXT, - JSON, -}; - -struct MetadataReadOptions { - MetadataOutputFormat output_format = MetadataOutputFormat::TEXT; - bool include_raw = false; - bool brief = false; - bool include_structural = false; -}; - -bool print_image_metadata(const std::string& image_path, - const MetadataReadOptions& options, - std::ostream& out, - std::string& error); diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index a29fd70b60..a40c9fc7e1 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -20,7 +20,8 @@ #include "common/common.h" #include "common/media_io.h" #include "common/resource_owners.hpp" -#include "image_metadata.h" +#include "dgl.h" +#include "media_input.h" namespace fs = std::filesystem; @@ -34,16 +35,13 @@ const char* previews_str[] = { std::regex format_specifier_regex("(?:[^%]|^)(?:%%)*(%\\d{0,3}d)"); struct SDCliParams { - std::string input_frames; - int video_upscale_factor = 0; - std::optional vsr_window_size; - std::optional vsr_temporal_chunk_size; SDMode mode = IMG_GEN; std::string output_path = "output.png"; int output_begin_idx = -1; int compression_quality = 90; std::string image_path; std::string metadata_format = "text"; + DGLModeParams dgl; sd_log_level_t log_level = SD_LOG_INFO; bool convert_name = false; @@ -67,7 +65,6 @@ struct SDCliParams { ArgOptions options; options.string_options = { - {"", "--input-frames", "directory of ordered RGB frames for vid_upscale (use -i for a single image)", 0, &input_frames}, {"-o", "--output", "path to write result image to. you can use printf-style %d format specifiers for image sequences (default: ./output.png) (eg. output_%03d.png). Single-file video outputs support .avi, .webm, and animated .webp", @@ -96,9 +93,6 @@ struct SDCliParams { }; options.int_options = { - {"", "--upscale-factor", "required positive video upscale factor (RelayVSR: 2 or 4; SeedVR2: integer)", &video_upscale_factor}, - {"", "--vsr-window-size", "RelayVSR window including both endpoints (default: 16)", &vsr_window_size}, - {"", "--vsr-temporal-chunk-size", "SeedVR2 input frames per independent chunk: 1 or 4n+1 (default: 5)", &vsr_temporal_chunk_size}, {"", "--preview-interval", "preview interval: in each sampling pass, positive N updates every Nth denoiser step and -N previews only completed logical step N; 0 previews the final completed step of the first pass (base-resolution or high-noise). Default: 1", @@ -188,7 +182,7 @@ struct SDCliParams { options.manual_options = { {"-M", "--mode", - "run mode, one of [img_gen, adetailer, vid_gen, vid_upscale, upscale, convert, metadata], default: img_gen", + "run mode, one of [" SD_ALL_MODES_STR "], default: img_gen", on_mode_arg}, {"", "--preview", @@ -218,8 +212,11 @@ struct SDCliParams { } bool validate() { - if (mode == VID_UPSCALE && video_upscale_factor <= 0) { - LOG_ERROR("vid_upscale requires a positive --upscale-factor"); + if (mode == DGL) { + return dgl.validate(); + } + if (dgl.has_options()) { + LOG_ERROR("DGL options require --mode dgl"); return false; } if (mode != METADATA) { @@ -284,25 +281,28 @@ void print_usage(int argc, const char* argv[], const std::vector& op options_list[1].print(); std::cout << "\nGeneration Options:\n"; options_list[2].print(); + std::cout << "\nDGL Options:\n"; + options_list[3].print(); } void parse_args(int argc, const char** argv, SDCliParams& cli_params, SDContextParams& ctx_params, SDGenerationParams& gen_params) { - std::vector options_vec = {cli_params.get_options(), ctx_params.get_options(), gen_params.get_options()}; + std::vector options_vec = {cli_params.get_options(), ctx_params.get_options(), gen_params.get_options(), cli_params.dgl.get_options()}; if (!parse_options(argc, argv, options_vec)) { print_usage(argc, argv, options_vec); exit(cli_params.normal_exit ? 0 : 1); } - log_level = cli_params.log_level; - log_color = cli_params.color; + log_level = cli_params.log_level; + log_color = cli_params.color; + log_stream = cli_params.mode == DGL ? stderr : nullptr; if (ctx_params.list_devices) { exit(ctx_params.print_devices() ? 0 : 1); } bool valid = cli_params.resolve_and_validate(); - if (valid && cli_params.mode != METADATA) { + if (valid && cli_params.mode != METADATA && cli_params.mode != DGL) { valid = ctx_params.resolve_and_validate(cli_params.mode) && gen_params.resolve_and_validate(cli_params.mode, ctx_params.lora_model_dir, @@ -317,57 +317,7 @@ void parse_args(int argc, const char** argv, SDCliParams& cli_params, SDContextP void sd_log_cb(enum sd_log_level_t level, const char* log, void* data) { SDCliParams* cli_params = (SDCliParams*)data; - log_print(level, log, cli_params->log_level, cli_params->color); -} - -bool load_images_from_dir(const std::string dir, - std::vector& images, - int max_image_num = 0) { - const fs::path dir_path = fs::u8path(dir); - if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) { - LOG_ERROR("'%s' is not a valid directory\n", dir.c_str()); - return false; - } - - std::vector entries; - for (const auto& entry : fs::directory_iterator(dir_path)) { - if (entry.is_regular_file()) { - entries.push_back(entry); - } - } - - std::sort(entries.begin(), entries.end(), - [](const fs::directory_entry& a, const fs::directory_entry& b) { - return a.path().filename().u8string() < b.path().filename().u8string(); - }); - - for (const auto& entry : entries) { - std::string path = entry.path().u8string(); - std::string ext = entry.path().extension().u8string(); - std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - - if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".webp") { - LOG_VERBOSE("load image %zu from '%s'", images.size(), path.c_str()); - int width = 0; - int height = 0; - int loaded_channel = 0; - uint8_t* image_buffer = load_image_from_file(path.c_str(), width, height, loaded_channel, 0, 0); - if (image_buffer == nullptr) { - LOG_ERROR("load image from '%s' failed", path.c_str()); - return false; - } - - images.emplace_back(SDImage{(uint32_t)width, - (uint32_t)height, - (uint32_t)loaded_channel, - image_buffer}); - - if (max_image_num > 0 && static_cast(images.size()) >= max_image_num) { - break; - } - } - } - return true; + log_print(level, log, cli_params->log_level, cli_params->color, log_stream); } std::string format_frame_idx(std::string pattern, int frame_idx) { @@ -535,9 +485,7 @@ bool save_results(const SDCliParams& cli_params, return sucessful_reults != 0; } - const bool video_upscale_output = cli_params.mode == VID_UPSCALE && - (gen_params.init_image_path.empty() || ext_lower == ".avi" || ext_lower == ".webm"); - if ((cli_params.mode == VID_GEN && num_results > 1) || video_upscale_output) { + if (cli_params.mode == VID_GEN && num_results > 1) { if (ext_lower != ".avi" && ext_lower != ".webp" && ext_lower != ".webm") ext = ".avi"; std::string params = gen_params.embed_image_metadata @@ -583,56 +531,6 @@ bool save_results(const SDCliParams& cli_params, return sucessful_reults != 0; } -static bool apply_adetailer(sd_ctx_t* sd_ctx, - const SDContextParams& ctx_params, - SDGenerationParams& gen_params, - SDMode mode, - SDImageVec& results, - int num_results) { - if (gen_params.ad_model_path.empty()) { - return true; - } - - ADetailerCtxPtr ad_ctx(create_sd_adetailer(gen_params.ad_model_path.c_str(), - ctx_params.n_threads, - ctx_params.effective_backend.c_str(), - ctx_params.effective_params_backend.c_str())); - if (ad_ctx == nullptr) { - LOG_ERROR("sd_adetailer_create failed"); - return false; - } - - for (int i = 0; i < num_results; ++i) { - if (results[i].data == nullptr) { - continue; - } - SDOptBuilder ad_options(gen_params.to_image_opt(true).release()); - ad_options.set_int("seed", generation_seed(results.generation_info(i), gen_params.seed.value_or(-1))); - if (mode == IMG_GEN) { - ad_options.unset("width"); - ad_options.unset("height"); - ad_options.unset("strength"); - } - sd_result_t* detailed = nullptr; - if (!adetail_sd_image(ad_ctx.get(), - sd_ctx, - results[i], - ad_options.finish(), - &detailed) || - detailed == nullptr || sd_result_get_image_count(detailed) <= 0 || sd_tensor_data(sd_result_get_image(detailed, 0)) == nullptr) { - sd_result_free(detailed); - LOG_ERROR("ADetailer failed for image %d", i + 1); - return false; - } - results.append_generation_info(i, sd_result_get_generation_info(detailed, 0), ctx_params.lora_model_dir); - sd_image_free(&results[i]); - results[i] = take_result_image(detailed, 0); - - sd_result_free(detailed); - } - return true; -} - int main(int argc, const char* argv[]) { if (argc > 1 && std::string(argv[1]) == "--version") { std::cout << version_string() << "\n"; @@ -642,92 +540,36 @@ int main(int argc, const char* argv[]) { SDCliParams cli_params; SDContextParams ctx_params; SDGenerationParams gen_params; + gen_params.seed = 42; sd_set_log_callback(sd_log_cb, (void*)&cli_params); parse_args(argc, argv, cli_params, ctx_params, gen_params); - if (cli_params.mode == METADATA) { - MetadataReadOptions options; - options.output_format = cli_params.metadata_format == "json" - ? MetadataOutputFormat::JSON - : MetadataOutputFormat::TEXT; - options.include_raw = cli_params.metadata_raw; - options.brief = cli_params.metadata_brief; - options.include_structural = cli_params.metadata_all; - - std::string error; - if (!print_image_metadata(cli_params.image_path, options, std::cout, error)) { - LOG_ERROR("%s", error.c_str()); - return 1; - } - return 0; + if (cli_params.mode == DGL) { + return cli_params.dgl.run(ctx_params, gen_params.embed_image_metadata); } - if (cli_params.mode == VID_UPSCALE) { - if (cli_params.input_frames.empty() == gen_params.init_image_path.empty()) { - LOG_ERROR("vid_upscale requires exactly one input: -i/--init-img or --input-frames"); - return 1; - } - ctx_params.prepare_backend_assignments(); - std::vector owned_frames; - if (!gen_params.init_image_path.empty()) { - owned_frames.emplace_back(); - if (!load_sd_image_from_file(owned_frames.back().put(), gen_params.init_image_path.c_str(), 0, 0, 3)) { - LOG_ERROR("load image from '%s' failed", gen_params.init_image_path.c_str()); - return 1; - } - } else if (!load_images_from_dir(cli_params.input_frames, owned_frames) || owned_frames.empty()) { - LOG_ERROR("vid_upscale input contains no readable frames"); - return 1; - } - if (owned_frames.size() > size_t(INT_MAX)) + if (cli_params.mode == METADATA) { + uint32_t flags = 0; + if (cli_params.metadata_format == "json") + flags |= SD_METADATA_READ_JSON; + if (cli_params.metadata_raw) + flags |= SD_METADATA_READ_RAW; + if (cli_params.metadata_brief) + flags |= SD_METADATA_READ_BRIEF; + if (cli_params.metadata_all) + flags |= SD_METADATA_READ_STRUCTURAL; + const auto* output = sd_read_metadata(cli_params.image_path.c_str(), flags); + if (!output) { + LOG_ERROR("%s", sd_get_last_error()); return 1; - std::vector frames; - for (const auto& frame : owned_frames) - frames.push_back(frame.get()); - SDVideoUpscalerParams params; - - params.diffusion_model_path = ctx_params.diffusion_model_path.c_str(); - params.vae_path = ctx_params.vae_path.c_str(); - params.upscale_factor = cli_params.video_upscale_factor; - params.n_threads = ctx_params.n_threads; - params.backend = ctx_params.effective_backend.c_str(); - params.params_backend = ctx_params.effective_params_backend.c_str(); - params.flash_attn_mode = ctx_params.flash_attn_mode ? ctx_params.flash_attn_mode->c_str() : nullptr; - std::string conv_direct_mode = ctx_params.conv_direct_mode.value_or(""); - if (conv_direct_mode.empty()) { - conv_direct_mode = "auto"; - if (ctx_params.diffusion_conv_direct.value_or(false)) - conv_direct_mode += ",diffusion=on"; - if (ctx_params.vae_conv_direct.value_or(false)) - conv_direct_mode += ",vae=on"; } - params.conv_direct_mode = conv_direct_mode.c_str(); - std::unique_ptr upscaler( - create_sd_vid_upscaler(params), - sd_vid_upscaler_free); - if (!upscaler) - return 1; - sd_result_t* output = nullptr; - SDVideoUpscaleParams upscale_params; - - upscale_params.frames = frames.data(); - upscale_params.frame_count = int(frames.size()); - upscale_params.fps = gen_params.fps; - upscale_params.window_size = cli_params.vsr_window_size; - upscale_params.temporal_chunk_size = cli_params.vsr_temporal_chunk_size; - upscale_params.seed = gen_params.seed; - if (!upscale_sd_video(upscaler.get(), upscale_params, &output)) - return 1; - std::string video_info = sd_result_get_generation_info(output, 0); - gen_params.fps = sd_result_get_fps(output); - SDImageVec results; - results.adopt_video(output); - return save_results(cli_params, ctx_params, gen_params, results, int(results.size()), nullptr, video_info) ? 0 : 1; + print_utf8(stdout, output); + return 0; } - if (!gen_params.ad_model_path.empty() && cli_params.mode != IMG_GEN && cli_params.mode != ADETAILER) { - LOG_ERROR("--ad-model is only supported in image generation and adetailer modes"); + if (!ctx_params.esrgan_path.empty() && cli_params.mode != UPSCALE) { + LOG_ERROR("generation followed by automatic upscaling requires DGL; use -M dgl --script FILE"); return 1; } @@ -841,7 +683,7 @@ int main(int argc, const char* argv[]) { }; if (gen_params.init_image_path.size() > 0) { - const bool native_init = cli_params.mode == IMG_GEN || cli_params.mode == ADETAILER; + const bool native_init = cli_params.mode == IMG_GEN; if (!load_image_and_update_size(gen_params.init_image_path, gen_params.init_image, native_init ? 0 : 3)) { return 1; } @@ -866,24 +708,11 @@ int main(int argc, const char* argv[]) { if (!gen_params.ref_video_paths.empty()) { gen_params.ref_videos.clear(); - gen_params.ref_videos.reserve(gen_params.ref_video_paths.size()); - for (const auto& path : gen_params.ref_video_paths) { - std::vector frames; - if (!load_images_from_dir(path, frames) || frames.empty()) { - LOG_ERROR("load reference video frames from '%s' failed", path.c_str()); - return 1; - } - gen_params.ref_videos.push_back(std::move(frames)); - } - gen_params.ref_video_audios.clear(); - gen_params.ref_video_audios.resize(gen_params.ref_videos.size()); - for (size_t i = 0; i < gen_params.ref_video_audio_paths.size(); ++i) { - if (!load_audio(gen_params.ref_video_audio_paths[i], gen_params.ref_video_audios[i])) { - return 1; - } - } } + std::vector reference_video_inputs; + if (!load_reference_video_inputs(gen_params.ref_video_paths, gen_params.ref_video_audio_paths, reference_video_inputs)) + return 1; if (!gen_params.ref_audio_paths.empty()) { gen_params.ref_audios.clear(); @@ -916,33 +745,23 @@ int main(int argc, const char* argv[]) { } } - if (gen_params.ip_adapter_image_path.size() > 0) { - if (!load_sd_image_from_file(gen_params.ip_adapter_image.put(), - gen_params.ip_adapter_image_path.c_str(), - 0, - 0)) { - LOG_ERROR("load image from '%s' failed", gen_params.ip_adapter_image_path.c_str()); - return 1; - } - } - + VideoInput control_video_input; if (!gen_params.control_video_path.empty()) { gen_params.control_frames.clear(); - if (!load_images_from_dir(gen_params.control_video_path, - gen_params.control_frames, - gen_params.video_frames.value_or(0))) { - return 1; - } - } - - if (!gen_params.pm_id_images_dir.empty()) { - gen_params.pm_id_images.clear(); - if (!load_images_from_dir(gen_params.pm_id_images_dir, - gen_params.pm_id_images)) { + if (fs::is_directory(fs::u8path(gen_params.control_video_path))) { + if (!load_images_from_dir(gen_params.control_video_path, + gen_params.control_frames, + gen_params.video_frames.value_or(0))) + return 1; + } else if (!load_video_input(gen_params.control_video_path, gen_params.fps.value_or(16), + gen_params.video_frames.value_or(0), false, control_video_input)) { return 1; } } + // A single generation run needs no component cache; each model is released after its last use. + if (cli_params.mode == VID_GEN || (cli_params.mode == IMG_GEN && gen_params.batch_count.value_or(1) <= 1)) + ctx_params.run_once = true; SDOptPtr sd_ctx_params = ctx_params.to_context_opt(); SDImageVec results; @@ -975,40 +794,28 @@ int main(int argc, const char* argv[]) { }, &prompt_image); - const bool use_img_gen_params = cli_params.mode == IMG_GEN || cli_params.mode == ADETAILER; if (cli_params.mode == IMG_GEN) { sd_result_t* generated = nullptr; generate_sd_image(sd_ctx.get(), gen_params.to_image_opt(), &generated); - results.adopt(generated, ctx_params.lora_model_dir); + results.adopt(generated); num_results = results.count(); - } else if (cli_params.mode == ADETAILER) { - num_results = 1; - results.push_back(gen_params.init_image.release()); } else if (cli_params.mode == VID_GEN) { SDOptPtr vid_gen_params = gen_params.to_video_opt(); - sd_result_t* generated = nullptr; + if (!vid_gen_params || !set_video_inputs(vid_gen_params.get(), reference_video_inputs, control_video_input.frames.get())) + return 1; + sd_result_t* generated = nullptr; if (generate_sd_video(sd_ctx.get(), vid_gen_params, &generated)) { gen_params.fps = cli_params.preview_fps = sd_result_get_fps(generated); generated_audio = retain_result_audio(generated); num_results = sd_result_get_image_count(generated); - results.adopt_video(generated, ctx_params.lora_model_dir); + results.adopt_video(generated); video_info = results.generation_info(0); } } if (!results) { - LOG_ERROR("generate failed"); - return 1; - } - - if (use_img_gen_params && - !apply_adetailer(sd_ctx.get(), - ctx_params, - gen_params, - cli_params.mode, - results, - num_results)) { + LOG_ERROR("generate failed: %s", sd_get_last_error()); return 1; } } @@ -1019,7 +826,8 @@ int main(int argc, const char* argv[]) { ctx_params.n_threads, gen_params.upscale_tile_size, ctx_params.effective_backend.c_str(), - ctx_params.effective_params_backend.c_str())); + ctx_params.effective_params_backend.c_str(), + ctx_params.linear_type)); if (upscaler_ctx == nullptr) { LOG_ERROR("sd_upscaler_create failed"); @@ -1029,21 +837,17 @@ int main(int argc, const char* argv[]) { continue; } SDImageOwner current_image(results[i]); - results[i] = {0, 0, 0, nullptr}; - for (int u = 0; u < gen_params.upscale_repeats; ++u) { - sd_result_t* upscaled = nullptr; - bool upscale_ok = upscale_sd_image(upscaler_ctx.get(), current_image.get(), &upscaled); - if (!upscale_ok || !upscaled || sd_result_get_image_count(upscaled) <= 0 || sd_tensor_data(sd_result_get_image(upscaled, 0)) == nullptr) { - sd_result_free(upscaled); - LOG_ERROR("upscale failed"); - break; - } - results.append_generation_info(i, sd_result_get_generation_info(upscaled, 0)); - SDImage upscaled_image = take_result_image(upscaled, 0); - + results[i] = {0, 0, 0, nullptr}; + sd_result_t* upscaled = nullptr; + if (!upscale_sd_image(upscaler_ctx.get(), current_image.get(), &upscaled, gen_params.upscale_repeats) || !upscaled) { + LOG_ERROR("upscale failed: %s", sd_get_last_error()); sd_result_free(upscaled); - current_image.reset(upscaled_image); + return 1; } + const std::string source = sd_result_get_generation_info(upscaled, 0); + current_image.reset(take_result_image(upscaled, 0)); + results.set_generation_info(i, source); + sd_result_free(upscaled); results[i] = current_image.release(); // Set the final upscaled image as the result } } diff --git a/examples/cli/media_input.cpp b/examples/cli/media_input.cpp new file mode 100644 index 0000000000..ce9d073955 --- /dev/null +++ b/examples/cli/media_input.cpp @@ -0,0 +1,149 @@ +#include "media_input.h" + +#include +#include +#include +#include + +#include "common/media_io.h" +#include "json.hpp" + +bool load_images_from_dir(const std::string& dir, + std::vector& images, + int max_image_num) { + const std::filesystem::path dir_path = std::filesystem::u8path(dir); + if (!std::filesystem::exists(dir_path) || !std::filesystem::is_directory(dir_path)) { + LOG_ERROR("'%s' is not a valid directory\n", dir.c_str()); + return false; + } + + std::vector entries; + for (const auto& entry : std::filesystem::directory_iterator(dir_path)) { + if (entry.is_regular_file()) { + entries.push_back(entry); + } + } + + std::sort(entries.begin(), entries.end(), + [](const std::filesystem::directory_entry& a, const std::filesystem::directory_entry& b) { + return a.path().filename().u8string() < b.path().filename().u8string(); + }); + + for (const auto& entry : entries) { + std::string path = entry.path().u8string(); + std::string ext = entry.path().extension().u8string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + + if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".webp") { + LOG_VERBOSE("load image %zu from '%s'", images.size(), path.c_str()); + int width = 0; + int height = 0; + int loaded_channel = 0; + uint8_t* image_buffer = load_image_from_file(path.c_str(), width, height, loaded_channel, 0, 0); + if (image_buffer == nullptr) { + LOG_ERROR("load image from '%s' failed", path.c_str()); + return false; + } + + images.emplace_back(SDImage{(uint32_t)width, + (uint32_t)height, + (uint32_t)loaded_channel, + image_buffer}); + + if (max_image_num > 0 && static_cast(images.size()) >= max_image_num) { + break; + } + } + } + return true; +} + +bool load_video_input(const std::string& path, int fps, size_t max_frames, bool audio, VideoInput& result) { + std::ostringstream source; + source << "fn main() { return video::load(" << nlohmann::json(path).dump() + << ", fps_num = " << fps << ", max_frames = " << max_frames + << ", audio = " << (audio ? "true" : "false") << ") }"; + std::unique_ptr context(sd_dgl_ctx_create_once(), sd_dgl_ctx_free); + if (!context) { + LOG_ERROR("cannot prepare video input '%s': %s", path.c_str(), sd_dgl_error()); + return false; + } + sd_dgl_result_t* raw_result = nullptr; + if (sd_dgl_run(context.get(), source.str().c_str(), nullptr, 0, &raw_result) != SD_STATUS_OK) { + LOG_ERROR("cannot read video input '%s': %s", path.c_str(), sd_dgl_error()); + return false; + } + std::unique_ptr loaded(raw_result, sd_dgl_result_free); + const auto* root = sd_dgl_result_root(loaded.get()); + const auto* sound = sd_dgl_value_field(root, "audio"); + int64_t sample_rate = 0; + if (sd_dgl_value_get_int(sd_dgl_value_field(sound, "sample_rate"), &sample_rate) != SD_STATUS_OK) { + LOG_ERROR("video input has no audio sample rate: %s", sd_dgl_error()); + return false; + } + VideoInput input; + input.frames.reset(sd_tensor_retain(sd_dgl_result_tensor(loaded.get(), "video.frames"))); + input.samples.reset(sd_tensor_retain(sd_dgl_result_tensor(loaded.get(), "audio.samples"))); + input.sample_rate = uint32_t(sample_rate); + input.fps = fps; + if (!input.frames || !input.samples) { + LOG_ERROR("video input is missing frame or audio tensors: %s", sd_dgl_error()); + return false; + } + result = std::move(input); + return true; +} + +bool load_reference_video_inputs(const std::vector& paths, const std::vector& audio_paths, std::vector& result) { + std::vector inputs; + inputs.reserve(paths.size()); + for (size_t i = 0; i < paths.size(); ++i) { + VideoInput input; + const bool external_audio = i < audio_paths.size(); + if (std::filesystem::is_directory(std::filesystem::u8path(paths[i]))) { + std::vector frames; + if (!load_images_from_dir(paths[i], frames) || frames.empty()) { + LOG_ERROR("load reference video frames from '%s' failed", paths[i].c_str()); + return false; + } + std::vector views; + views.reserve(frames.size()); + for (const auto& frame : frames) + views.push_back(frame.get()); + input.frames = frames_tensor(views.data(), views.size()); + if (!input.frames) + return false; + } else if (!load_video_input(paths[i], 24, 0, !external_audio, input)) { + return false; + } + if (external_audio) { + std::vector samples; + uint32_t rate = 0, channels = 0; + if (!load_wav_from_file(audio_paths[i], samples, rate, channels)) { + LOG_ERROR("load WAV audio from '%s' failed", audio_paths[i].c_str()); + return false; + } + const int64_t shape[] = {channels, int64_t(samples.size() / channels)}; + input.samples.reset(sd_tensor_create(SD_TENSOR_F32, 2, shape, samples.data(), samples.size() * sizeof(float))); + input.sample_rate = rate; + if (!input.samples) + return false; + } + inputs.push_back(std::move(input)); + } + result = std::move(inputs); + return true; +} + +bool set_video_inputs(sd_opt_t* options, const std::vector& references, const sd_tensor_t* control) { + std::vector views; + views.reserve(references.size()); + for (const auto& video : references) + views.push_back(video.view()); + if ((!views.empty() && sd_opt_set_videos(options, "ref_videos", views.data(), views.size()) != SD_STATUS_OK) || + (control && sd_opt_set_tensor(options, "control_frames", control) != SD_STATUS_OK)) { + LOG_ERROR("cannot set video inputs: %s", sd_get_last_error()); + return false; + } + return true; +} diff --git a/examples/cli/media_input.h b/examples/cli/media_input.h new file mode 100644 index 0000000000..aff5a9d213 --- /dev/null +++ b/examples/cli/media_input.h @@ -0,0 +1,20 @@ +#ifndef __SD_EXAMPLES_CLI_MEDIA_INPUT_H__ +#define __SD_EXAMPLES_CLI_MEDIA_INPUT_H__ + +#include "common/resource_owners.hpp" + +struct VideoInput { + SDTensorPtr frames; + SDTensorPtr samples; + uint32_t sample_rate = 0; + int fps = 24; + + sd_video_t view() const { return {frames.get(), fps, {sample_rate, sample_rate ? samples.get() : nullptr}}; } +}; + +bool load_images_from_dir(const std::string& path, std::vector& images, int max_image_num = 0); +bool load_video_input(const std::string& path, int fps, size_t max_frames, bool audio, VideoInput& result); +bool load_reference_video_inputs(const std::vector& paths, const std::vector& audio_paths, std::vector& result); +bool set_video_inputs(sd_opt_t* options, const std::vector& references, const sd_tensor_t* control); + +#endif // __SD_EXAMPLES_CLI_MEDIA_INPUT_H__ diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 0c155c1b89..9d9ad70882 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -30,12 +30,11 @@ namespace fs = std::filesystem; const char* const modes_str[] = { "img_gen", - "adetailer", "vid_gen", "convert", "upscale", "metadata", - "vid_upscale", + "dgl", }; static void prepend_backend_assignment(std::string& spec, const char* assignment) { @@ -484,19 +483,9 @@ ArgOptions SDContextParams::get_options() { "path to control net model", 0, &control_net_path}, - {"", - "--ip-adapter", - "path to IP-Adapter model (requires --clip_vision)", - 0, - &ip_adapter_path}, - {"", - "--motion-module", - "path to AnimateDiff motion module (SD 1.5); enables video generation on --video-frames > 1", - 0, - &motion_module_path}, {"", "--embd-dir", - "embeddings directory", + "textual inversion embeddings directory (SD 1.x/2.x/SDXL only, see docs/embeddings.md)", 0, &embedding_dir}, {"", @@ -521,16 +510,6 @@ ArgOptions SDContextParams::get_options() { "qwen_image_2_1_prefix_cache_type (auto or a type name from --type)", (int)',', &model_args}, - {"", - "--photo-maker", - "path to PHOTOMAKER model", - 0, - &photo_maker_path}, - {"", - "--pulid-weights", - "path to PuLID Flux weights", - 0, - &pulid_weights_path}, {"", "--upscale-model", "path to esrgan model.", @@ -560,7 +539,7 @@ ArgOptions SDContextParams::get_options() { &rpc_servers}, {"", "--max-vram", - "optional per-device budget in GiB for managed weights and runner buffers during automatic graph-cut execution. Accepts a single value or assignments by backend/device, e.g. 6 or cuda0=6,vulkan0=4. 0 uses live free VRAM without an explicit budget; a negative value reserves that much free VRAM", + "optional per-device budget in GiB for managed weights, runner buffers, and idle backend buffers. Accepts a single value or assignments by backend/device, e.g. 6 or cuda0=6,vulkan0=4. 0 uses live free VRAM without an explicit budget; a negative value reserves that much free VRAM", 0, &max_vram}, }; @@ -592,7 +571,7 @@ ArgOptions SDContextParams::get_options() { true, &disable_segmented_compute}, {"", "--eager-load", - "load all params into the params backend at model-load time instead of lazily on first use (defaults to false)", + "read params at model-load time into the highest residency location with free capacity instead of on first use (defaults to false)", true, &eager_load}, {"", "--force-sdxl-vae-conv-scale", @@ -707,6 +686,22 @@ ArgOptions SDContextParams::get_options() { vae_conv_direct = true; return 0; }}, + {"", + "--linear-type", + "auto|i8|raw or module assignments, e.g. dit=i8 or i8,te=raw. Default: auto (currently equivalent to raw)", + [this](int argc, const char** argv, int index) { + if (++index >= argc || argv[index][0] == '\0') { + LOG_ERROR("--linear-type requires auto, i8, raw, or module assignments"); + return -1; + } + SDOptPtr validation(sd_ctx_opt_create()); + if (sd_opt_set_string(validation.get(), "linear_type", argv[index]) != SD_STATUS_OK) { + LOG_ERROR("--linear-type: %s", sd_get_last_error()); + return -1; + } + linear_type = argv[index]; + return 1; + }}, {"", "--conv-direct", "on|off|auto or diffusion/vae/controlnet assignments (default: auto), e.g. auto,vae=off. Overrides legacy convolution flags", @@ -752,8 +747,8 @@ ArgOptions SDContextParams::get_options() { }}, {"", "--auto-fit", - "on|off (default: on). Preserve --backend (otherwise select one GPU) and place weights on the compute GPU, " - "RAM, another GPU, or disk in that order, according to available memory (--max-vram limits GPU budgets). " + "on|off (default: on). Preserve --backend (otherwise select one GPU) and move components to another GPU " + "when the weights do not fit the main GPU and RAM (--max-vram limits GPU budgets). " "Disabled by explicit --params-backend; uses automatic graph segmentation when needed", [this](int argc, const char** argv, int index) { return parse_on_off_arg(argc, argv, index, "--auto-fit", auto_fit); @@ -779,23 +774,25 @@ ArgOptions SDContextParams::get_options() { on_sampler_rng_arg}, {"", "--prediction", - "prediction type override, one of [eps, v, edm_v, sd3_flow, flux_flow, sefi_flow, minit2i_flow, sensenova_u1_flow, flux3_flow, h3_av_flow, ming_image_flow]", + "prediction type override, one of [eps, v, edm_v, flow, flux_flow, sefi_flow, minit2i_flow, sensenova_u1_flow, flux3_flow, h3_av_flow, ming_image_flow]", on_prediction_arg}, {"", "--lora-apply-mode", - "the way to apply LoRA, one of [auto, immediately, at_runtime], default is auto. " - "In auto mode, if the model weights contain any quantized parameters, the at_runtime mode will be used; otherwise, immediately will be used." - "The immediately mode may have precision and compatibility issues with quantized parameters, " - "but it usually offers faster inference speed and, in some cases, lower memory usage. " - "The at_runtime mode, on the other hand, is exactly the opposite.", + "Select auto (default), immediately, or at_runtime for LoRA application. " + "Auto merges unquantized weights on the compute backend when row splitting is off. " + "It applies LoRA at runtime for quantized, offloaded, or row-split weights.", on_lora_apply_mode_arg}, }; return options; } +bool SDContextParams::register_rpc_devices() const { + return !rpc_servers || sd_add_rpc_servers(rpc_servers->c_str()); +} + bool SDContextParams::print_devices() const { - if (!sd_add_rpc_servers(rpc_servers ? rpc_servers->c_str() : nullptr)) { + if (!register_rpc_devices()) { return false; } size_t device_list_size = sd_list_devices(nullptr, 0); @@ -967,6 +964,7 @@ std::string SDContextParams::to_string() const { << " flash_attn_mode: " << flash_attn_mode << ",\n" << " conv_direct_mode: " << conv_direct_mode << ",\n" << " sage_attn: " << sage_attn << ",\n" + << " linear_type: " << linear_type.value_or("auto") << ",\n" << " linear_scale: " << linear_scale << ",\n" << " attn_scale: " << attn_scale << ",\n" << " diffusion_conv_direct: " << diffusion_conv_direct << ",\n" @@ -979,6 +977,22 @@ std::string SDContextParams::to_string() const { return oss.str(); } +bool SDContextParams::configure_dgl(sd_dgl_ctx_t* ctx) const { + auto set = [ctx](const char* key, const auto& option) { + return !option || sd_dgl_ctx_set(ctx, key, std::to_string(*option).c_str()); + }; + return (!max_vram || sd_dgl_ctx_set(ctx, "max_vram", max_vram->c_str())) && + (!linear_type || sd_dgl_ctx_set(ctx, "linear_type", linear_type->c_str())) && + set("auto_fit", auto_fit) && + set("conditioning_cache_size", conditioning_cache_size) && + set("batched_cfg", batched_cfg) && + set("n_threads", n_threads) && + set("enable_mmap", enable_mmap) && + set("eager_load", eager_load) && + set("disable_prefetch", disable_prefetch) && + set("disable_segmented_compute", disable_segmented_compute); +} + SDOptPtr SDContextParams::to_context_opt() { prepare_backend_assignments(); embedding_vec.clear(); @@ -1008,10 +1022,14 @@ SDOptPtr SDContextParams::to_context_opt() { opt.set_string("audio_encoder_path", audio_encoder_path); opt.set_string("taesd_path", taesd_path); opt.set_string("control_net_path", control_net_path); - opt.set_string("ip_adapter_path", ip_adapter_path); - opt.set_string("motion_module_path", motion_module_path); - opt.set_string("photo_maker_path", photo_maker_path); - opt.set_string("pulid_weights_path", pulid_weights_path); + if (!ip_adapter_path.empty()) + opt.set_string("ip_adapter_path", ip_adapter_path); + if (!motion_module_path.empty()) + opt.set_string("motion_module_path", motion_module_path); + if (!photo_maker_path.empty()) + opt.set_string("photo_maker_path", photo_maker_path); + if (!pulid_weights_path.empty()) + opt.set_string("pulid_weights_path", pulid_weights_path); opt.set_string("tensor_type_rules", tensor_type_rules); opt.set_int("n_threads", n_threads); opt.set_int("conditioning_cache_size", conditioning_cache_size); @@ -1025,6 +1043,7 @@ SDOptPtr SDContextParams::to_context_opt() { opt.set_string("flash_attn_mode", flash_attn_mode); opt.set_string("conv_direct_mode", conv_direct_mode); opt.set_bool("sage_attn", sage_attn); + opt.set_string("linear_type", linear_type); opt.set_float("linear_scale", linear_scale); opt.set_float("attn_scale", attn_scale); opt.set_bool("tae_preview_only", taesd_preview_only); @@ -1037,6 +1056,7 @@ SDOptPtr SDContextParams::to_context_opt() { opt.set_bool("disable_segmented_compute", disable_segmented_compute); opt.set_bool("batched_cfg", batched_cfg); opt.set_bool("eager_load", eager_load); + opt.set_bool("run_once", run_once); if (backend || !effective_backend.empty()) opt.set_string("backend", effective_backend); if (params_backend || !effective_params_backend.empty()) @@ -1065,29 +1085,9 @@ ArgOptions SDGenerationParams::get_options() { "the negative prompt (default: \"\")", 0, &negative_prompt}, - {"", - "--ad-model", - "path to a converted YOLOv8 detection model for ADetailer", - 0, - &ad_model_path}, - {"", - "--ad-prompt", - "ADetailer prompt; empty inherits the main prompt, supports [PROMPT], [SEP], and [SKIP]", - 0, - &ad_prompt}, - {"", - "--ad-negative-prompt", - "ADetailer negative prompt; empty inherits the main negative prompt, supports [PROMPT] and [SEP]", - 0, - &ad_negative_prompt}, - {"", - "--extra-ad-args", - "extra ADetailer args, key=value list. Supports input_size, confidence, nms, max_detections, mask_k_largest, mask_min_ratio, mask_max_ratio, dilate_erode, x_offset, y_offset, mask_mode, merge_masks, invert_mask, mask_blur, inpaint_padding, inpaint_width, inpaint_height, denoising_strength, steps, cfg_scale, sample_method, scheduler, sort_by", - (int)',', - &extra_ad_args}, {"-i", "--init-img", - "path to the init image, or a single input image for vid_upscale", + "path to the init image", 0, &init_image_path}, {"", @@ -1105,33 +1105,12 @@ ArgOptions SDGenerationParams::get_options() { "path to control image, control net", 0, &control_image_path}, - {"", - "--ip-adapter-image", - "path to the IP-Adapter reference image", - 0, - &ip_adapter_image_path}, {"", "--control-video", - "path to control video frames, It must be a directory path. The video frames inside should be stored as images in " - "lexicographical (character) order. For example, if the control video path is `frames`, the directory contain images " - "such as 00.png, 01.png, ... etc.", + "control video file (AVI, WebP or independent-frame VP8 WebM) or frame directory in filename order; " + "files are sampled at the output FPS without audio", 0, &control_video_path}, - {"", - "--pm-id-images-dir", - "path to PHOTOMAKER input id images dir", - 0, - &pm_id_images_dir}, - {"", - "--pm-id-embed-path", - "path to PHOTOMAKER v2 id embed", - 0, - &pm_id_embed_path}, - {"", - "--pulid-id-embedding", - "path to PuLID id embedding", - 0, - &pulid_id_embedding_path}, {"", "--hires-upscaler", "highres fix upscaler, Lanczos, Nearest, Latent, Latent (nearest), Latent (nearest-exact), " @@ -1148,7 +1127,7 @@ ArgOptions SDGenerationParams::get_options() { &control_type}, {"", "--extra-sample-args", - "extra sampler/scheduler/guidance args, key=value list. CFG supports guidance_schedule; APG supports apg_eta, apg_momentum, apg_norm_threshold, apg_norm_threshold_smoothing; SLG supports slg_uncond; lcm supports noise_clip_std, noise_scale_start, noise_scale_end; flux supports base_shift, max_shift; ltx2 supports max_shift, base_shift, stretch, terminal; euler_ge supports gamma; beta scheduler supports alpha, beta; logit_normal supports mu, std, logsnr_min, logsnr_max, resolution_aware; llada_image supports uniform; lms supports lms_max_order, lms_shift, lms_divisions; noise-injecting samplers support noise_sampler with value iid (default except for dpm++2m_sde_bt) or brownian_tree; brownian_tree_rng supports cpu (default), cuda, std_default or sampler_rng", + "extra sampler/scheduler/guidance args, key=value list. CFG supports guidance_schedule; APG supports apg_eta, apg_momentum, apg_norm_threshold, apg_norm_threshold_smoothing; lcm supports noise_clip_std, noise_scale_start, noise_scale_end; flux supports base_shift, max_shift; ltx2 supports max_shift, base_shift, stretch, terminal; euler_ge supports gamma; beta scheduler supports alpha, beta; logit_normal supports mu, std, logsnr_min, logsnr_max, resolution_aware; llada_image supports uniform; lms supports lms_max_order, lms_shift, lms_divisions; noise-injecting samplers support noise_sampler with value iid (default except for dpm++2m_sde_bt) or brownian_tree; brownian_tree_rng supports cpu (default), cuda, std_default or sampler_rng", (int)',', &extra_sample_args}, {"", @@ -1156,14 +1135,6 @@ ArgOptions SDGenerationParams::get_options() { "extra VAE tiling args, key=value list. Supported video VAEs accept temporal_tile_frames/temporal_tile_size (default: 4), temporal_tile_overlap (default: 1); Wan2.2 TI2V 5B accepts temporal_decode_frames (default: 1)", (int)',', &extra_tiling_args}, - {"", - "--ref-image-args", - "Key-value list to set up the way the reference images are processed (empty = auto-detect from model weigths)", - (int)',', - &ref_image_args}, - {"", "--image-preprocess", - "Image preprocessing rule: target=init|end|mask|control|ref|ip-adapter|id|control-frame,index=N,mode=auto|none|stretch|crop|crop-resize|fit-pad,filter=auto|nearest|nearest-exact|bilinear|bicubic|lanczos,antialias=auto|true|false,width=W,height=H,anchor=center|top|bottom|left|right,pad_color=#RRGGBB[AA],canny=true|false. Repeat for multiple rules.", - (int)';', &image_preprocess}, }; options.int_options = { @@ -1181,7 +1152,7 @@ ArgOptions SDGenerationParams::get_options() { &sample_params.sample_steps}, {"", "--high-noise-steps", - "(high noise) number of sample steps (default: -1 = auto)", + "high-noise steps; >= 0 adds to --steps, -1 splits --steps at --moe-boundary (default: -1)", &high_noise_sample_params.sample_steps}, {"", "--clip-skip", @@ -1204,11 +1175,6 @@ ArgOptions SDGenerationParams::get_options() { "--fps", "fps (default: 24)", &fps}, - {"", - "--timestep-shift", - "shift timestep for NitroFusion models (default: 0). " - "recommended N for NitroSD-Realism around 250 and 500 for NitroSD-Vibrant", - &sample_params.shifted_timestep}, {"", "--upscale-repeats", "Run the ESRGAN upscaler this many times (default: 1)", @@ -1248,18 +1214,6 @@ ArgOptions SDGenerationParams::get_options() { "--guidance", "distilled guidance scale for models with guidance input (default: 3.5)", &sample_params.guidance.distilled_guidance}, - {"", - "--slg-scale", - "skip layer guidance (SLG) scale, only for DiT models: (default: 0). 0 means disabled, a value of 2.5 is nice for sd3.5 medium", - &sample_params.guidance.slg.scale}, - {"", - "--skip-layer-start", - "SLG enabling point (default: 0.01)", - &sample_params.guidance.slg.layer_start}, - {"", - "--skip-layer-end", - "SLG disabling point (default: 0.2)", - &sample_params.guidance.slg.layer_end}, {"", "--eta", "noise multiplier (default: 0 for ddim_trailing, tcd, res_multistep and res_2s; 1 for euler_a, er_sde, dpm++2s_a, dpm++2m_sde and dpm++2m_sde_bt)", @@ -1268,54 +1222,14 @@ ArgOptions SDGenerationParams::get_options() { "--flow-shift", "shift value for Flow models like SD3.x or WAN (default: auto)", &sample_params.flow_shift}, - {"", - "--high-noise-cfg-scale", - "(high noise) unconditional guidance scale: (default: 7.0)", - &high_noise_sample_params.guidance.txt_cfg}, - {"", - "--high-noise-img-cfg-scale", - "(high noise) image guidance scale for inpaint or image edit models (default: same as --cfg-scale)", - &high_noise_sample_params.guidance.img_cfg}, - {"", - "--high-noise-guidance", - "(high noise) distilled guidance scale for models with guidance input (default: 3.5)", - &high_noise_sample_params.guidance.distilled_guidance}, - {"", - "--high-noise-slg-scale", - "(high noise) skip layer guidance (SLG) scale, only for DiT models: (default: 0)", - &high_noise_sample_params.guidance.slg.scale}, - {"", - "--high-noise-skip-layer-start", - "(high noise) SLG enabling point (default: 0.01)", - &high_noise_sample_params.guidance.slg.layer_start}, - {"", - "--high-noise-skip-layer-end", - "(high noise) SLG disabling point (default: 0.2)", - &high_noise_sample_params.guidance.slg.layer_end}, - {"", - "--high-noise-eta", - "(high noise) noise multiplier (default: 0 for ddim_trailing, tcd, res_multistep and res_2s; 1 for euler_a, er_sde, dpm++2s_a, dpm++2m_sde and dpm++2m_sde_bt)", - &high_noise_sample_params.eta}, {"", "--strength", "strength for noising/unnoising (default: 0.75)", &strength}, - {"", - "--pm-style-strength", - "", - &pm_style_strength}, - {"", - "--pulid-id-weight", - "strength of PuLID identity injection", - &pulid_id_weight}, {"", "--control-strength", "strength to apply Control Net (default: 0.9). 1.0 corresponds to full destruction of information in init image", &control_strength}, - {"", - "--ip-adapter-strength", - "strength to apply IP-Adapter (default: 1.0)", - &ip_adapter_strength}, {"", "--moe-boundary", "timestep boundary for Wan2.2 MoE model. (default: 0.875). Only enabled if `--high-noise-steps` is set to -1", @@ -1339,11 +1253,6 @@ ArgOptions SDGenerationParams::get_options() { }; options.bool_options = { - {"", - "--increase-ref-index", - "automatically increase the indices of references images based on the order they are listed (starting with 1).", - true, - &increase_ref_index}, {"", "--circular", "enable circular padding on both axes for tileable output", @@ -1358,7 +1267,7 @@ ArgOptions SDGenerationParams::get_options() { true, &circular_y}, {"", "--disable-image-metadata", - "do not embed generation metadata on image files", + "do not embed generation metadata in image or video files (including DGL saves)", false, &embed_image_metadata}, {"", @@ -1395,15 +1304,6 @@ ArgOptions SDGenerationParams::get_options() { return 1; }; - auto on_high_noise_sample_method_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - high_noise_sample_params.sample_method = arg; - return 1; - }; - auto on_scheduler_arg = [&](int argc, const char** argv, int index) { if (++index >= argc) { return -1; @@ -1413,68 +1313,6 @@ ArgOptions SDGenerationParams::get_options() { return 1; }; - auto on_skip_layers_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - std::string layers_str = argv[index]; - if (layers_str.size() < 2 || layers_str.front() != '[' || layers_str.back() != ']') { - return -1; - } - - layers_str = layers_str.substr(1, layers_str.size() - 2); - - std::regex regex("[, ]+"); - std::sregex_token_iterator iter(layers_str.begin(), layers_str.end(), regex, -1); - std::sregex_token_iterator end; - std::vector tokens(iter, end); - std::vector layers; - for (const auto& token : tokens) { - try { - size_t used = 0; - const int layer = std::stoi(token, &used); - if (used != token.size()) - return -1; - layers.push_back(layer); - } catch (const std::exception&) { - return -1; - } - } - skip_layers = layers; - return 1; - }; - - auto on_high_noise_skip_layers_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - std::string layers_str = argv[index]; - if (layers_str.size() < 2 || layers_str.front() != '[' || layers_str.back() != ']') { - return -1; - } - - layers_str = layers_str.substr(1, layers_str.size() - 2); - - std::regex regex("[, ]+"); - std::sregex_token_iterator iter(layers_str.begin(), layers_str.end(), regex, -1); - std::sregex_token_iterator end; - std::vector tokens(iter, end); - std::vector layers; - for (const auto& token : tokens) { - try { - size_t used = 0; - const int layer = std::stoi(token, &used); - if (used != token.size()) - return -1; - layers.push_back(layer); - } catch (const std::exception&) { - return -1; - } - } - high_noise_skip_layers = layers; - return 1; - }; - auto parse_sigmas_arg = [&](const char* value, std::optional>* target, const char* option_name) { if (target == nullptr || value == nullptr) { return -1; @@ -1724,18 +1562,13 @@ ArgOptions SDGenerationParams::get_options() { options.manual_options = { {"-s", "--seed", - "RNG seed; unset or a negative value requests a random seed", + "RNG seed (default: " + (seed ? std::to_string(*seed) : "random") + "); a negative value requests a random seed", on_seed_arg}, {"", "--sampling-method", "sampling method, one of [" + sample_methods + "], " "default: euler for Flux/SD3/Wan, euler_a otherwise", on_sample_method_arg}, - {"", - "--high-noise-sampling-method", - "(high noise) sampling method, one of [" + sample_methods + "], " - "default: euler for Flux/SD3/Wan, euler_a otherwise", - on_high_noise_sample_method_arg}, {"", "--scheduler", "denoiser sigma scheduler, one of [" + schedulers + "], " @@ -1749,25 +1582,17 @@ ArgOptions SDGenerationParams::get_options() { "--hires-sigmas", "custom sigma values for the highres fix second pass, comma-separated (e.g., \"0.85,0.725,0.421875,0.0\") or preset: qwen-image-2.1-turbo, p-h3-image, minimax-h3-image, hyperflow-h3-flash-4, hyperflow-h3-flash-6, hyperflow-h3-flash-8.", on_hires_sigmas_arg}, - {"", - "--skip-layers", - "layers to skip for SLG steps; unset uses the library default", - on_skip_layers_arg}, - {"", - "--high-noise-skip-layers", - "(high noise) layers to skip for SLG steps; unset uses the library default", - on_high_noise_skip_layers_arg}, {"-r", "--ref-image", "reference image for Flux Kontext or MiniMax-H3 Ref2VA (can be used multiple times)", on_ref_image_arg}, {"", "--ref-video", - "MiniMax-H3 Ref2VA reference video frame directory at 24 fps (can be used multiple times)", + "MiniMax-H3 Ref2VA reference video file or frame directory, sampled at 24 fps (can be used multiple times)", on_ref_video_arg}, {"", "--ref-video-audio", - "WAV soundtrack paired by index with --ref-video (can be used multiple times)", + "WAV soundtrack overriding embedded audio, paired by index with --ref-video (can be used multiple times)", on_ref_video_audio_arg}, {"", "--ref-audio", @@ -1779,11 +1604,11 @@ ArgOptions SDGenerationParams::get_options() { on_audio_arg}, {"", "--cache-mode", - "caching method: 'easycache' (DiT), 'ucache' (UNET), 'dbcache'/'taylorseer'/'cache-dit' (DiT block-level), 'spectrum' (UNET/DiT Chebyshev+Taylor forecasting)", + "caching method: 'easycache' (DiT), 'ucache' (UNET), 'dbcache'/'taylorseer'/'cache-dit' (DiT condition-level), 'spectrum' (UNET/DiT Chebyshev+Taylor forecasting)", on_cache_mode_arg}, {"", "--cache-option", - "named cache params (key=value format, comma-separated). easycache/ucache: threshold=,start=,end=,decay=,relative=,reset=; dbcache/taylorseer/cache-dit: Fn=,Bn=,threshold=,warmup=; spectrum: w=,m=,lam=,window=,flex=,warmup=,stop=. Examples: \"threshold=0.25\" or \"threshold=1.5,reset=0\"", + "named cache params (key=value format, comma-separated). easycache/ucache: threshold=,start=,end=,decay=,relative=,reset=; dbcache/taylorseer/cache-dit: threshold=,warmup= (Fn/Bn are ignored with a warning); spectrum: w=,m=,lam=,window=,flex=,warmup=,stop=. Examples: \"threshold=0.25\" or \"threshold=1.5,reset=0\"", on_cache_option_arg}, {"", "--scm-mask", @@ -2124,29 +1949,6 @@ static bool resolve_model_file_from_dir(const std::string& model_name, return false; } -bool SDGenerationParams::parse_image_preprocess_json(const std::string& json_str) { - const auto value = json::parse(json_str, nullptr, false); - std::string rules; - if (value.is_string()) { - rules = value.get(); - } else if (value.is_array()) { - for (const auto& item : value) { - if (!item.is_string()) { - LOG_ERROR("image_preprocess must contain rule strings"); - return false; - } - if (!rules.empty()) - rules += ";"; - rules += item.get(); - } - } else { - LOG_ERROR("image_preprocess must be a string or array of strings"); - return false; - } - image_preprocess = std::move(rules); - return true; -} - bool SDGenerationParams::parse_prompt_images_json(const std::string& json_str) { auto images = json::parse(json_str, nullptr, false); if (!images.is_object()) { @@ -2213,11 +2015,14 @@ bool SDGenerationParams::from_json_str( return false; } - if (j.contains("image_preprocess") && !parse_image_preprocess_json(j["image_preprocess"].dump())) - return false; + if (j.contains("image_preprocess")) + throw std::invalid_argument("image_preprocess requires a DGL script"); if (j.contains("prompt_images") && !parse_prompt_images_json(j["prompt_images"].dump())) return false; + if ((j.contains("ref_image_args") && j["ref_image_args"] != "") || + (j.contains("increase_ref_index") && j["increase_ref_index"] != false)) + throw std::invalid_argument("reference overrides require a DGL script"); auto load_if_exists = [&](const char* key, auto& out) { load_json_input(j, key, out); }; load_if_exists("prompt", prompt); @@ -2229,7 +2034,6 @@ bool SDGenerationParams::from_json_str( load_if_exists("cache_mode", cache_mode); load_if_exists("cache_option", cache_option); load_if_exists("scm_mask", scm_mask); - load_if_exists("ref_image_args", ref_image_args); load_if_exists("clip_skip", clip_skip); load_if_exists("width", width); @@ -2248,7 +2052,6 @@ bool SDGenerationParams::from_json_str( load_if_exists("moe_boundary", moe_boundary); load_if_exists("vace_strength", vace_strength); - load_if_exists("increase_ref_index", increase_ref_index); load_if_exists("embed_image_metadata", embed_image_metadata); if (j.contains("hires") && j["hires"].is_object()) { @@ -2479,10 +2282,10 @@ bool SDGenerationParams::initialize_cache_params() { cache_params.use_relative_threshold = (std::stof(val) != 0.0f); } else if (key == "reset") { cache_params.reset_error_on_compute = (std::stof(val) != 0.0f); - } else if (key == "Fn" || key == "fn") { - cache_params.Fn_compute_blocks = std::stoi(val); - } else if (key == "Bn" || key == "bn") { - cache_params.Bn_compute_blocks = std::stoi(val); + } else if (key == "Fn" || key == "fn" || key == "Bn" || key == "bn") { + if (std::stoi(val) < 0) + throw std::out_of_range("block count must be nonnegative"); + LOG_WARN("cache option '%s' is ignored: condition-level caching does not support front/back block counts", key.c_str()); } else if (key == "warmup") { if (cache_mode == "spectrum") { cache_params.spectrum_warmup_steps = std::stoi(val); @@ -2592,10 +2395,6 @@ bool SDGenerationParams::resolve(const std::string& lora_model_dir, const std::s /** Validates params for a generation mode; enforces mode-specific input rules. */ bool SDGenerationParams::validate(SDMode mode) { - if (!image_preprocess.empty() && mode != IMG_GEN && mode != VID_GEN) { - LOG_ERROR("--image-preprocess requires img_gen or vid_gen mode"); - return false; - } if (ref_video_audio_paths.size() + ref_video_audios.size() > ref_video_paths.size() + ref_videos.size()) { LOG_ERROR("error: each --ref-video-audio needs a corresponding --ref-video"); return false; @@ -2611,21 +2410,15 @@ bool SDGenerationParams::validate(SDMode mode) { return false; } - if (mode == UPSCALE || mode == ADETAILER) { + if (mode == UPSCALE) { if (init_image_path.length() == 0) { - LOG_ERROR("error: %s mode needs an init image (--init-img)\n", - mode == UPSCALE ? "upscale" : "adetailer"); + LOG_ERROR("error: upscale mode needs an init image (--init-img)"); return false; } } - if (mode == ADETAILER && ad_model_path.empty()) { - LOG_ERROR("error: adetailer mode needs a detector model (--ad-model)\n"); - return false; - } - - if (mode == IMG_GEN || mode == ADETAILER || mode == VID_GEN) { - auto opt = mode == VID_GEN ? to_video_opt() : to_image_opt(mode == ADETAILER); + if (mode == IMG_GEN || mode == VID_GEN) { + auto opt = mode == VID_GEN ? to_video_opt() : to_image_opt(); if (!opt) { LOG_ERROR("%s", sd_get_last_error()); return false; @@ -2671,10 +2464,13 @@ static void set_sample_options(SDOptBuilder& opt, const std::string& prefix, con } static void set_cache_options(SDOptBuilder& opt, const SDCacheParams& params) { - opt.set_int("cache.bn_compute_blocks", params.Bn_compute_blocks); + const SDCacheParams defaults; + if (params.Bn_compute_blocks != defaults.Bn_compute_blocks) + opt.set_int("cache.bn_compute_blocks", params.Bn_compute_blocks); opt.set_float("cache.end_percent", params.end_percent); opt.set_float("cache.error_decay_rate", params.error_decay_rate); - opt.set_int("cache.fn_compute_blocks", params.Fn_compute_blocks); + if (params.Fn_compute_blocks != defaults.Fn_compute_blocks) + opt.set_int("cache.fn_compute_blocks", params.Fn_compute_blocks); opt.set_int("cache.max_cached_steps", params.max_cached_steps); opt.set_int("cache.max_continuous_cached_steps", params.max_continuous_cached_steps); opt.set_int("cache.max_warmup_steps", params.max_warmup_steps); @@ -2708,7 +2504,7 @@ static void set_tiling_options(SDOptBuilder& opt, const SDTilingParams& params) opt.set_int("vae_tiling.tile_size_w", params.tile_size_w); } -SDOptPtr SDGenerationParams::to_image_opt(bool adetail) { +SDOptPtr SDGenerationParams::to_image_opt() { lora_vec.clear(); lora_vec.reserve(lora_map.size() + high_noise_lora_map.size()); for (const auto& kv : lora_map) { @@ -2724,68 +2520,37 @@ SDOptPtr SDGenerationParams::to_image_opt(bool adetail) { ref_image_views.push_back(ref_image.get()); } - pm_id_image_views.clear(); - pm_id_image_views.reserve(pm_id_images.size()); - for (auto& image : pm_id_images) { - pm_id_image_views.push_back(image.get()); - } - vae_tiling_params.extra_tiling_args = extra_tiling_args.empty() ? nullptr : extra_tiling_args.c_str(); cache_params.scm_mask = scm_mask.empty() ? nullptr : scm_mask.c_str(); - std::string effective_ref_image_args = ref_image_args; - if (!adetail && increase_ref_index) { - if (!effective_ref_image_args.empty()) - effective_ref_image_args += ","; - effective_ref_image_args += "ref_index_mode=increase"; - } - - SDOptBuilder opt(adetail ? sd_adetail_opt_create() : sd_img_gen_opt_create()); + SDOptBuilder opt(sd_img_gen_opt_create()); opt.set_string("prompt", prompt); opt.set_string("negative_prompt", negative_prompt); opt.set_int("clip_skip", clip_skip); - if (!adetail) - opt.set_image("init_image", init_image.get()); - if (!adetail) - opt.set_string("ref_image_args", effective_ref_image_args); - if (!adetail) - opt.set_image("mask_image", mask_image.get()); + opt.set_image("init_image", init_image.get()); + opt.set_image("mask_image", mask_image.get()); opt.set_int("width", width); opt.set_int("height", height); opt.set_float("strength", strength); opt.set_int("seed", seed); - if (!adetail) - opt.set_int("batch_count", batch_count); - if (!adetail) - opt.set_int("qwen_image_layers", qwen_image_layers); - if (!adetail) - opt.set_image("control_image", control_image.get()); - if (!adetail) - opt.set_float("control_strength", control_strength); - if (!adetail) - opt.set_string("control_type", control_type); - if (!adetail) - opt.set_image("ip_adapter_image", ip_adapter_image.get()); - if (!adetail) - opt.set_float("ip_adapter_strength", ip_adapter_strength); - if (!adetail) + opt.set_int("batch_count", batch_count); + opt.set_int("qwen_image_layers", qwen_image_layers); + opt.set_image("control_image", control_image.get()); + opt.set_float("control_strength", control_strength); + opt.set_string("control_type", control_type); + opt.set_image("ip_adapter_image", ip_adapter_image.get()); + opt.set_float("ip_adapter_strength", ip_adapter_strength); + if (hires_enabled.value_or(false)) opt.set_bool("hires.enabled", hires_enabled); - if (!adetail) - opt.set_string("hires.upscaler", resolved_hires_upscaler.empty() ? hires_upscaler : std::optional(resolved_hires_upscaler)); - if (!adetail) + opt.set_string("hires.upscaler", resolved_hires_upscaler.empty() ? hires_upscaler : std::optional(resolved_hires_upscaler)); + if (!hires_upscaler_model_path.empty()) opt.set_string("hires.model_path", hires_upscaler_model_path); - if (!adetail) - opt.set_float("hires.scale", hires_scale); - if (!adetail) - opt.set_int("hires.target_width", hires_width); - if (!adetail) - opt.set_int("hires.target_height", hires_height); - if (!adetail) - opt.set_int("hires.steps", hires_steps); - if (!adetail) - opt.set_float("hires.denoising_strength", hires_denoising_strength); - if (!adetail) - opt.set_int("hires.upscale_tile_size", hires_upscale_tile_size); + opt.set_float("hires.scale", hires_scale); + opt.set_int("hires.target_width", hires_width); + opt.set_int("hires.target_height", hires_height); + opt.set_int("hires.steps", hires_steps); + opt.set_float("hires.denoising_strength", hires_denoising_strength); + opt.set_int("hires.upscale_tile_size", hires_upscale_tile_size); if (circular) opt.set_bool("circular_x", true); else @@ -2795,32 +2560,11 @@ SDOptPtr SDGenerationParams::to_image_opt(bool adetail) { else opt.set_bool("circular_y", circular_y); opt.set_loras("loras", lora_vec.data(), lora_vec.size()); - if (!adetail) - opt.set_images("ref_images", ref_image_views.data(), ref_image_views.size()); - if (!adetail) - opt.set_images("photomaker.id_images", pm_id_image_views.data(), pm_id_image_views.size()); - if (!adetail) - opt.set_string("photomaker.id_embed_path", pm_id_embed_path); - if (!adetail) - opt.set_float("photomaker.style_strength", pm_style_strength); - if (!adetail) - opt.set_string("pulid.id_embedding_path", pulid_id_embedding_path); - if (!adetail) - opt.set_float("pulid.id_weight", pulid_id_weight); - if (!adetail) - opt.set_floats("hires.sigmas", hires_custom_sigmas); - if (!adetail) - opt.set_string("image_preprocess.rules", image_preprocess); + opt.set_images("ref_images", ref_image_views.data(), ref_image_views.size()); + opt.set_floats("hires.sigmas", hires_custom_sigmas); set_sample_options(opt, "sample.", sample_params, skip_layers, custom_sigmas, extra_sample_args); set_cache_options(opt, cache_params); set_tiling_options(opt, vae_tiling_params); - if (adetail) { - if (!ad_prompt.empty()) - opt.set_string("adetail.prompt", ad_prompt); - if (!ad_negative_prompt.empty()) - opt.set_string("adetail.negative_prompt", ad_negative_prompt); - opt.set_string("adetail.args", extra_ad_args); - } return opt.finish(); } @@ -2886,9 +2630,11 @@ SDOptPtr SDGenerationParams::to_video_opt() { opt.set_int("video_frames", video_frames); opt.set_int("fps", fps); opt.set_float("vace_strength", vace_strength); - opt.set_bool("hires.enabled", hires_enabled); + if (hires_enabled.value_or(false)) + opt.set_bool("hires.enabled", hires_enabled); opt.set_string("hires.upscaler", resolved_hires_upscaler.empty() ? hires_upscaler : std::optional(resolved_hires_upscaler)); - opt.set_string("hires.model_path", hires_upscaler_model_path); + if (!hires_upscaler_model_path.empty()) + opt.set_string("hires.model_path", hires_upscaler_model_path); opt.set_float("hires.scale", hires_scale); opt.set_int("hires.target_width", hires_width); opt.set_int("hires.target_height", hires_height); @@ -2903,19 +2649,18 @@ SDOptPtr SDGenerationParams::to_video_opt() { opt.set_bool("circular_y", true); else opt.set_bool("circular_y", circular_y); - opt.set_string("ref_image_args", ref_image_args); opt.set_loras("loras", lora_vec.data(), lora_vec.size()); opt.set_images("ref_images", ref_image_views.data(), ref_image_views.size()); opt.set_videos("ref_videos", ref_video_views.data(), ref_video_views.size()); opt.set_audios("ref_audios", ref_audio_views.data(), ref_audio_views.size()); opt.set_frames("control_frames", control_frame_views.data(), control_frame_views.size()); opt.set_floats("hires.sigmas", hires_custom_sigmas); - opt.set_string("image_preprocess.rules", image_preprocess); opt.set_string("sample.scheduler", high_noise_sample_params.scheduler); opt.set_float("sample.flow_shift", high_noise_sample_params.flow_shift); opt.set_int("sample.shifted_timestep", high_noise_sample_params.shifted_timestep); set_sample_options(opt, "sample.", sample_params, skip_layers, custom_sigmas, extra_sample_args); - set_sample_options(opt, "high_noise_sample.", high_noise_sample_params, high_noise_skip_layers, {}, high_noise_extra_sample_args); + // Native video workflows share the sampler and guidance between stages. + opt.set_int("high_noise_sample.steps", high_noise_sample_params.sample_steps); set_cache_options(opt, cache_params); set_tiling_options(opt, vae_tiling_params); return opt.finish(); @@ -2974,12 +2719,6 @@ std::string SDGenerationParams::to_string() const { << " ref_video_audio_paths: " << vec_str_to_string(ref_video_audio_paths) << ",\n" << " ref_audio_paths: " << vec_str_to_string(ref_audio_paths) << ",\n" << " control_video_path: \"" << control_video_path << "\",\n" - << " image_preprocess: " << image_preprocess << ",\n" - << " ref_image_args: " << ref_image_args << ",\n" - << " increase_ref_index: " << (increase_ref_index ? "true" : "false") << ",\n" - << " pm_id_images_dir: \"" << pm_id_images_dir << "\",\n" - << " pm_id_embed_path: \"" << pm_id_embed_path << "\",\n" - << " pm_style_strength: " << pm_style_strength << ",\n" << " skip_layers: " << (skip_layers ? vec_to_string(*skip_layers) : "unset") << ",\n" << " sample_params: " << SAFE_STR(sample_params_str.c_str()) << ",\n" << " high_noise_skip_layers: " << (high_noise_skip_layers ? vec_to_string(*high_noise_skip_layers) : "unset") << ",\n" diff --git a/examples/common/common.h b/examples/common/common.h index eb4a043a7f..509f6734ba 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -1,7 +1,6 @@ #ifndef __EXAMPLES_COMMON_COMMON_H__ #define __EXAMPLES_COMMON_COMMON_H__ -#include "generation_metadata.h" #include "options.h" #include @@ -23,16 +22,15 @@ std::string argv_to_utf8(int index, const char** argv); #define BOOL_STR(b) ((b) ? "true" : "false") extern const char* const modes_str[]; -#define SD_ALL_MODES_STR "img_gen, adetailer, vid_gen, convert, upscale, metadata, vid_upscale" +#define SD_ALL_MODES_STR "img_gen, vid_gen, convert, upscale, metadata, dgl" enum SDMode { IMG_GEN, - ADETAILER, VID_GEN, CONVERT, UPSCALE, METADATA, - VID_UPSCALE, + DGL, MODE_COUNT }; @@ -165,6 +163,7 @@ struct SDContextParams { std::optional disable_prefetch; std::optional disable_segmented_compute; std::optional eager_load; + std::optional run_once; std::optional batched_cfg; std::optional backend; std::optional params_backend; @@ -182,6 +181,7 @@ struct SDContextParams { std::optional flash_attn_mode; std::optional conv_direct_mode; std::optional sage_attn; + std::optional linear_type; std::optional diffusion_conv_direct; std::optional vae_conv_direct; std::optional taesd_preview_only; @@ -202,6 +202,8 @@ struct SDContextParams { bool resolve_and_validate(SDMode mode); std::string to_string() const; SDOptPtr to_context_opt(); + bool configure_dgl(sd_dgl_ctx_t* ctx) const; + bool register_rpc_devices() const; }; struct SDGenerationParams { @@ -221,7 +223,6 @@ struct SDGenerationParams { std::optional strength; std::optional control_strength; std::optional ip_adapter_strength; - bool increase_ref_index = false; bool embed_image_metadata = true; std::string init_image_path; @@ -229,7 +230,6 @@ struct SDGenerationParams { std::string mask_image_path; std::string control_image_path; std::optional control_type; - std::string ip_adapter_image_path; std::vector ref_image_paths; std::vector ref_video_paths; std::vector ref_video_audio_paths; @@ -258,16 +258,6 @@ struct SDGenerationParams { SDTilingParams vae_tiling_params; std::string extra_tiling_args; - std::string ref_image_args; - std::string image_preprocess; - - std::string pm_id_images_dir; - std::string pm_id_embed_path; - std::optional pm_style_strength; - - std::string pulid_id_embedding_path; - std::optional pulid_id_weight; - int upscale_repeats = 1; std::optional upscale_tile_size; @@ -305,7 +295,6 @@ struct SDGenerationParams { SDImageOwner mask_image; SDImageOwner control_image; SDImageOwner ip_adapter_image; - std::vector pm_id_images; std::vector control_frames; // Media views used while populating the opaque options. @@ -313,7 +302,6 @@ struct SDGenerationParams { std::vector> ref_video_frame_views; std::vector ref_video_views; std::vector ref_audio_views; - std::vector pm_id_image_views; std::vector control_frame_views; SDGenerationParams(); @@ -324,7 +312,6 @@ struct SDGenerationParams { ArgOptions get_options(); bool from_json_str(const std::string& json_str, const std::function& lora_path_resolver = {}); - bool parse_image_preprocess_json(const std::string& json_str); bool parse_prompt_images_json(const std::string& json_str); bool initialize_cache_params(); bool extract_and_remove_lora(const std::string& lora_model_dir); @@ -338,7 +325,7 @@ struct SDGenerationParams { const std::string& lora_model_dir, const std::string& hires_upscalers_dir, bool strict = false); - SDOptPtr to_image_opt(bool adetail = false); + SDOptPtr to_image_opt(); SDOptPtr to_video_opt(); std::string to_string() const; }; diff --git a/examples/common/generation_metadata.cpp b/examples/common/generation_metadata.cpp deleted file mode 100644 index 05205fffdb..0000000000 --- a/examples/common/generation_metadata.cpp +++ /dev/null @@ -1,164 +0,0 @@ -#include "generation_metadata.h" - -#include -#include -#include - -#include "json.hpp" - -static void relativize_lora_paths(nlohmann::json& info, const std::filesystem::path& root) { - if (info.contains("loras")) { - for (auto& lora : info["loras"]) { - const auto path = lora.value("path", ""); - if (path.empty()) - continue; - std::error_code error; - const auto absolute = std::filesystem::absolute(std::filesystem::u8path(path), error); - if (error) - continue; - const auto relative = absolute.lexically_normal().lexically_relative(root); - if (!relative.empty()) - lora["path"] = relative.generic_u8string(); - } - } - if (info.contains("inpaint_params")) - relativize_lora_paths(info["inpaint_params"], root); - if (info.contains("postprocess")) { - for (auto& operation : info["postprocess"]) - relativize_lora_paths(operation, root); - } -} - -std::string generation_info_with_relative_lora_paths(const std::string& info, const std::string& lora_model_dir) { - if (info.empty() || lora_model_dir.empty()) - return info; - std::error_code error; - const auto root = std::filesystem::absolute(std::filesystem::u8path(lora_model_dir), error); - if (error) - return info; - auto result = nlohmann::json::parse(info); - relativize_lora_paths(result, root.lexically_normal()); - return result.dump(); -} - -std::string merge_generation_info(const std::string& source, const std::string& operation) { - if (source.empty()) - return operation; - auto result = nlohmann::json::parse(source); - const auto next = nlohmann::json::parse(operation); - result["postprocess"].push_back(next); - return result.dump(); -} - -int64_t generation_seed(const std::string& info, int64_t fallback) { - if (info.empty()) - return fallback; - const auto value = nlohmann::json::parse(info); - const auto& params = value.contains("inpaint_params") ? value.at("inpaint_params") : value; - return params.contains("seed") ? std::stoll(params.at("seed").get()) : fallback; -} - -std::string generation_info_to_webui(const std::string& text) { - using nlohmann::json; - if (text.empty()) - return ""; - const auto info = json::parse(text); - if (info.value("schema", "") != "sdcpp.generation/v1") - return ""; - // Standalone postprocessing has no source diffusion settings to import. - if (!info.contains("sample_params")) - return ""; - const auto& sampling = info.at("sample_params"); - std::string result = info.value("prompt", ""); - if (info.contains("loras")) { - bool prompt_trimmed = false; - for (const auto& lora : info.at("loras")) { - // WebUI tags cannot restrict a LoRA to the high-noise model. - if (lora.value("is_high_noise", false)) - continue; - auto name = lora.at("path").get(); - const auto separator = name.find_last_of("/\\"); - if (separator != std::string::npos) - name.erase(0, separator + 1); - const auto extension = name.find_last_of('.'); - if (extension != std::string::npos && extension > 0) - name.erase(extension); - if (name.empty() || name.find_first_of(":<>\r\n") != std::string::npos) - continue; - if (!result.empty()) { - if (!prompt_trimmed) { - while (!result.empty() && std::isspace(static_cast(result.back()))) - result.pop_back(); - prompt_trimmed = true; - } - if (!result.empty()) - result += " "; - } - result += ""; - } - } - const auto negative = info.value("negative_prompt", ""); - if (!negative.empty()) - result += "\nNegative prompt: " + negative; - result += "\n"; - bool first = true; - const auto field = [&](const char* key, const json& value) { - std::string v = value.is_string() ? value.get() : value.dump(); - if (v.find_first_of(",\n\r:\"") != std::string::npos) - v = json(v).dump(-1, ' ', false); - if (!first) - result += ", "; - first = false; - result += std::string(key) + ": " + v; - }; - field("Steps", sampling.contains("custom_sigmas") ? json(sampling.at("custom_sigmas").size() - 1) : sampling.at("sample_steps")); - static const std::map samplers = { - {"euler", "Euler"}, {"euler_a", "Euler a"}, {"heun", "Heun"}, {"dpm2", "DPM2"}, {"dpm++2s_a", "DPM++ 2S a"}, {"dpm++2m", "DPM++ 2M"}, {"dpm++2m_sde", "DPM++ 2M SDE"}, {"lcm", "LCM"}}; - const auto method = sampling.at("sample_method").get(); - auto mapped = samplers.find(method); - field(mapped != samplers.end() ? "Sampler" : "SDCPP Sampler", mapped != samplers.end() ? mapped->second : method); - static const std::map schedules = { - {"discrete", "Normal"}, {"karras", "Karras"}, {"exponential", "Exponential"}, {"sgm_uniform", "SGM Uniform"}, {"simple", "Simple"}, {"ddim_uniform", "DDIM"}, {"beta", "Beta"}}; - if (sampling.contains("scheduler")) { - const auto scheduler = sampling.at("scheduler").get(); - auto mapped_schedule = schedules.find(scheduler); - field(mapped_schedule != schedules.end() ? "Schedule type" : "SDCPP Schedule", mapped_schedule != schedules.end() ? mapped_schedule->second : scheduler); - } - field("CFG scale", sampling.at("guidance").at("txt_cfg")); - field("Seed", info.at("seed")); - field("Size", std::to_string(info.at("width").get()) + "x" + std::to_string(info.at("height").get())); - if (info.contains("models")) { - const auto& models = info.at("models"); - auto model = models.value("diffusion_model", models.value("model", "")); - const auto extension = model.find_last_of('.'); - if (extension != std::string::npos && extension > 0) - model.erase(extension); - if (!model.empty()) - field("Model", model); - if (models.contains("vae")) - field("VAE", models.at("vae")); - } - if (sampling.contains("eta")) - field("Eta", sampling.at("eta")); - if (info.value("clip_skip", 0) > 0) - field("Clip skip", info.at("clip_skip")); - if (info.contains("strength")) - field("Denoising strength", info.at("strength")); - if (info.contains("hires") && info.at("hires").value("enabled", false)) { - const auto& hires = info.at("hires"); - field("Hires resize", std::to_string(hires.at("target_width").get()) + "x" + std::to_string(hires.at("target_height").get())); - if (hires.value("steps", 0) > 0) - field("Hires steps", hires.at("steps")); - field("Denoising strength", hires.at("denoising_strength")); - field("Hires upscaler", hires.at("upscaler")); - } - field("Version", "stable-diffusion.cpp"); - return result; -} - -std::string generation_info_to_image_metadata(const std::string& info) { - if (info.empty()) - return ""; - const auto parameters = generation_info_to_webui(info); - return parameters.empty() ? info : parameters + ", SDCPP: " + info; -} diff --git a/examples/common/generation_metadata.h b/examples/common/generation_metadata.h deleted file mode 100644 index 7c9e9ffd45..0000000000 --- a/examples/common/generation_metadata.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __EXAMPLES_COMMON_GENERATION_METADATA_H__ -#define __EXAMPLES_COMMON_GENERATION_METADATA_H__ - -#include -#include - -std::string merge_generation_info(const std::string& source, const std::string& operation); -std::string generation_info_with_relative_lora_paths(const std::string& info, const std::string& lora_model_dir); -int64_t generation_seed(const std::string& info, int64_t fallback = -1); -std::string generation_info_to_webui(const std::string& text); -std::string generation_info_to_image_metadata(const std::string& info); - -#endif // __EXAMPLES_COMMON_GENERATION_METADATA_H__ diff --git a/examples/common/log.cpp b/examples/common/log.cpp index 12d0683274..5a656d04b2 100644 --- a/examples/common/log.cpp +++ b/examples/common/log.cpp @@ -4,6 +4,7 @@ sd_log_level_t log_level = SD_LOG_INFO; bool log_color = false; +FILE* log_stream = nullptr; std::string sd_basename(const std::string& path) { size_t pos = path.find_last_of('/'); @@ -79,10 +80,10 @@ bool parse_log_level(const std::string& name, sd_log_level_t& level) { return false; } -void log_print(enum sd_log_level_t level, const char* log, sd_log_level_t min_level, bool color) { +void log_print(enum sd_log_level_t level, const char* log, sd_log_level_t min_level, bool color, FILE* stream) { int tag_color; const char* level_str; - FILE* out_stream = (level == SD_LOG_ERROR) ? stderr : stdout; + FILE* out_stream = stream ? stream : ((level == SD_LOG_ERROR) ? stderr : stdout); if (!log || level < min_level) { return; @@ -141,5 +142,5 @@ void example_log_printf(sd_log_level_t level, const char* file, int line, const } message += " --- " + sd_basename(file) + ":" + std::to_string(line) + '\n'; - log_print(level, message.c_str(), log_level, log_color); + log_print(level, message.c_str(), log_level, log_color, log_stream); } diff --git a/examples/common/log.h b/examples/common/log.h index f623b0eadd..fd5bd4cff8 100644 --- a/examples/common/log.h +++ b/examples/common/log.h @@ -18,12 +18,13 @@ extern sd_log_level_t log_level; extern bool log_color; +extern FILE* log_stream; std::string sd_basename(const std::string& path); void print_utf8(FILE* stream, const char* utf8); const char* log_level_name(sd_log_level_t level); bool parse_log_level(const std::string& name, sd_log_level_t& level); -void log_print(sd_log_level_t level, const char* log, sd_log_level_t min_level, bool color); +void log_print(sd_log_level_t level, const char* log, sd_log_level_t min_level, bool color, FILE* stream = nullptr); void example_log_printf(sd_log_level_t level, const char* file, int line, const char* format, ...); #define LOG_DEBUG(format, ...) example_log_printf(SD_LOG_DEBUG, __FILE__, __LINE__, format, ##__VA_ARGS__) diff --git a/examples/common/media_io.cpp b/examples/common/media_io.cpp index 4159e46695..941c70bfc4 100644 --- a/examples/common/media_io.cpp +++ b/examples/common/media_io.cpp @@ -1,5 +1,4 @@ #include "media_io.h" -#include "generation_metadata.h" #include "log.h" #include "media_metadata.h" #include "resource_owners.hpp" @@ -377,7 +376,7 @@ bool encode_webp_image_to_vector(const uint8_t* image, out.assign(encoded.get(), encoded.get() + encoded_size); - return embed_webp_metadata(out, generation_info_to_image_metadata(parameters)); + return embed_webp_metadata(out, parameters); } #ifdef SD_USE_WEBM @@ -710,7 +709,6 @@ std::vector encode_image_to_vector(EncodedImageFormat format, const std::string& parameters, int quality) { std::vector buffer; - const auto metadata = format == EncodedImageFormat::WEBP ? std::string() : generation_info_to_image_metadata(parameters); auto write_func = [&buffer](void* context, void* data, int size) { (void)context; @@ -733,7 +731,7 @@ std::vector encode_image_to_vector(EncodedImageFormat format, result = stbi_write_jpg_to_func(c_func, &ctx, width, height, channels, image, quality); break; case EncodedImageFormat::PNG: - result = stbi_ext_write_png_to_func(c_func, &ctx, width, height, channels, image, width * channels, metadata.empty() ? nullptr : metadata.c_str()); + result = stbi_ext_write_png_to_func(c_func, &ctx, width, height, channels, image, width * channels, nullptr); break; case EncodedImageFormat::WEBP: #ifdef SD_USE_WEBP @@ -751,7 +749,8 @@ std::vector encode_image_to_vector(EncodedImageFormat format, break; } - if (result && format == EncodedImageFormat::JPEG && !embed_jpeg_metadata(buffer, metadata)) { + if (result && ((format == EncodedImageFormat::JPEG && !embed_jpeg_metadata(buffer, parameters)) || + (format == EncodedImageFormat::PNG && !embed_png_metadata(buffer, parameters)))) { LOG_ERROR("generation metadata exceeds the container capacity or the encoded image is invalid"); result = 0; } @@ -813,27 +812,13 @@ uint8_t* load_image_from_memory(const char* image_bytes, } static void append_avi_metadata(std::vector& data, const std::string& parameters) { - if (parameters.empty()) { - return; - } - - std::vector info_content; - - write_fourcc(info_content, "INFO"); - - const size_t comment_size = parameters.size() + 1; - write_fourcc(info_content, "ICMT"); - write_u32_le(info_content, static_cast(comment_size)); - info_content.insert(info_content.end(), parameters.begin(), parameters.end()); - info_content.push_back(0); - if (comment_size & 1u) { - info_content.push_back(0); - } - - write_fourcc(data, "LIST"); - write_u32_le(data, static_cast(info_content.size())); - data.insert(data.end(), info_content.begin(), info_content.end()); - size_t start_pos = data.size(); + const void* info = nullptr; + size_t size = 0; + if (sd_get_metadata_chunk(parameters.c_str(), SD_METADATA_AVI, &info, &size) != SD_STATUS_OK) + throw std::runtime_error(sd_get_last_error()); + const auto* bytes = static_cast(info); + if (size) + data.insert(data.end(), bytes, bytes + size); } std::vector create_mjpg_avi_from_sd_images_to_vector(SDImage* images, int num_images, int fps, int quality, const SDAudio* audio, const std::string& parameters) { diff --git a/examples/common/media_io.h b/examples/common/media_io.h index d765db7fcc..5951f39a0a 100644 --- a/examples/common/media_io.h +++ b/examples/common/media_io.h @@ -16,7 +16,7 @@ enum class EncodedImageFormat { EncodedImageFormat encoded_image_format_from_path(const std::string& path); -// parameters is the core sdcpp.generation/v1 JSON; empty disables both metadata formats. +// parameters is the executed DGL source; empty disables generation metadata. std::vector encode_image_to_vector(EncodedImageFormat format, const uint8_t* image, int width, diff --git a/examples/common/media_metadata.cpp b/examples/common/media_metadata.cpp index d5e9af3fa3..d665c28fb7 100644 --- a/examples/common/media_metadata.cpp +++ b/examples/common/media_metadata.cpp @@ -1,47 +1,43 @@ #include "media_metadata.h" -std::string generation_xmp(const std::string& info) { - std::string escaped; - for (char c : info) { - switch (c) { - case '&': - escaped += "&"; - break; - case '<': - escaped += "<"; - break; - case '>': - escaped += ">"; - break; - case '"': - escaped += """; - break; - case '\'': - escaped += "'"; - break; - default: - escaped += c; - break; - } - } - return "" - "" - "" + - escaped + ""; +#include + +#include "stable-diffusion.h" + +std::string generation_xmp(const std::string& source) { + const void* data = nullptr; + size_t size = 0; + if (sd_get_metadata_chunk(source.c_str(), SD_METADATA_XMP, &data, &size) != SD_STATUS_OK || !size) + return ""; + return std::string(static_cast(data), size); } -bool embed_jpeg_metadata(std::vector& image, const std::string& parameters) { - if (parameters.empty()) +bool embed_jpeg_metadata(std::vector& image, const std::string& source) { + if (source.empty()) return true; - const char label[] = "parameters"; - const size_t overhead = sizeof(label) + 1; - if (image.size() < 2 || parameters.size() > 65533 - overhead) + if (image.size() < 2) + return false; + const void* data = nullptr; + size_t size = 0; + if (sd_get_metadata_chunk(source.c_str(), SD_METADATA_JPEG, &data, &size) != SD_STATUS_OK) + return false; + const auto* bytes = static_cast(data); + if (size) + image.insert(image.begin() + 2, bytes, bytes + size); + return true; +} + +bool embed_png_metadata(std::vector& image, const std::string& source) { + if (source.empty()) + return true; + if (image.size() < 33 || std::memcmp(image.data() + 12, "IHDR", 4)) + return false; + const void* data = nullptr; + size_t size = 0; + if (sd_get_metadata_chunk(source.c_str(), SD_METADATA_PNG, &data, &size) != SD_STATUS_OK) return false; - const size_t length = overhead + parameters.size() + 2; - std::vector segment = {0xff, 0xfe, static_cast(length >> 8), static_cast(length)}; - segment.insert(segment.end(), label, label + sizeof(label)); - segment.insert(segment.end(), parameters.begin(), parameters.end()); - segment.push_back(0); - image.insert(image.begin() + 2, segment.begin(), segment.end()); + const auto* bytes = static_cast(data); + if (size) + image.insert(image.begin() + 33, bytes, bytes + size); return true; } diff --git a/examples/common/media_metadata.h b/examples/common/media_metadata.h index 1843dee19d..1ca49dc4f1 100644 --- a/examples/common/media_metadata.h +++ b/examples/common/media_metadata.h @@ -6,6 +6,7 @@ #include std::string generation_xmp(const std::string& parameters); +bool embed_png_metadata(std::vector& image, const std::string& source); bool embed_jpeg_metadata(std::vector& image, const std::string& parameters); #endif // __EXAMPLES_COMMON_MEDIA_METADATA_H__ diff --git a/examples/common/resource_owners.hpp b/examples/common/resource_owners.hpp index 8ba69e7a9c..83f2dca503 100644 --- a/examples/common/resource_owners.hpp +++ b/examples/common/resource_owners.hpp @@ -12,7 +12,6 @@ #include #include -#include "generation_metadata.h" #include "log.h" #include "stable-diffusion.h" @@ -123,17 +122,6 @@ static inline SDAudio* retain_result_audio(const sd_result_t* result) { return view; } -static inline bool preprocess_canny(SDImage& image, float high, float low, float weak, float strong, bool inverse) { - auto input = image_tensor(image); - sd_tensor_t* output = nullptr; - if (!input || sd_preprocess_canny(input.get(), high, low, weak, strong, inverse, &output) != SD_STATUS_OK) - return false; - sd_image_free(&image); - image = tensor_image_view(output); - image.storage = output; - return true; -} - struct FreeDeleter { void operator()(void* ptr) const { free(ptr); @@ -164,21 +152,12 @@ struct UpscalerCtxDeleter { } }; -struct ADetailerCtxDeleter { - void operator()(sd_adetailer_t* ctx) const { - if (ctx != nullptr) { - sd_adetailer_free(ctx); - } - } -}; - template using FreeUniquePtr = std::unique_ptr; -using FilePtr = std::unique_ptr; -using SDCtxPtr = std::unique_ptr; -using UpscalerCtxPtr = std::unique_ptr; -using ADetailerCtxPtr = std::unique_ptr; +using FilePtr = std::unique_ptr; +using SDCtxPtr = std::unique_ptr; +using UpscalerCtxPtr = std::unique_ptr; struct SDOptDeleter { void operator()(sd_opt_t* opt) const { sd_opt_free(opt); } @@ -345,100 +324,28 @@ static inline bool generate_sd_video(sd_ctx_t* ctx, const SDOptPtr& opt, sd_resu return opt && sd_generate_video(ctx, opt.get(), result) == SD_STATUS_OK; } -static inline sd_upscaler_t* create_sd_upscaler(const char* path, std::optional direct, std::optional threads, std::optional tile, const char* backend, const char* params_backend) { +static inline sd_upscaler_t* create_sd_upscaler(const char* path, std::optional direct, std::optional threads, std::optional tile, const char* backend, const char* params_backend, const std::optional& linear_type) { SDOptPtr opt(sd_upscaler_opt_create()); if (!opt || sd_opt_set_string(opt.get(), "model_path", path) != SD_STATUS_OK || (direct && sd_opt_set_bool(opt.get(), "conv_direct", *direct) != SD_STATUS_OK) || (tile && sd_opt_set_int(opt.get(), "tile_size", *tile) != SD_STATUS_OK) || (threads && sd_opt_set_int(opt.get(), "n_threads", *threads) != SD_STATUS_OK) || (backend && sd_opt_set_string(opt.get(), "backend", backend) != SD_STATUS_OK) || - (params_backend && sd_opt_set_string(opt.get(), "params_backend", params_backend) != SD_STATUS_OK)) + (params_backend && sd_opt_set_string(opt.get(), "params_backend", params_backend) != SD_STATUS_OK) || + (linear_type && sd_opt_set_string(opt.get(), "linear_type", linear_type->c_str()) != SD_STATUS_OK)) return nullptr; sd_upscaler_t* result = nullptr; sd_upscaler_create(opt.get(), &result); return result; } -static inline bool upscale_sd_image(sd_upscaler_t* ctx, SDImage image, sd_result_t** result) { +static inline bool upscale_sd_image(sd_upscaler_t* ctx, SDImage image, sd_result_t** result, int repeats = 1) { if (result) *result = nullptr; SDOptPtr opt(sd_upscale_opt_create()); auto tensor = image_tensor(image); return opt && tensor && sd_opt_set_tensor(opt.get(), "image", tensor.get()) == SD_STATUS_OK && - sd_upscale(ctx, opt.get(), result) == SD_STATUS_OK; -} - -static inline sd_adetailer_t* create_sd_adetailer(const char* path, std::optional threads, const char* backend, const char* params_backend) { - SDOptPtr opt(sd_adetailer_opt_create()); - if (!opt || sd_opt_set_string(opt.get(), "model_path", path) != SD_STATUS_OK || - (threads && sd_opt_set_int(opt.get(), "n_threads", *threads) != SD_STATUS_OK) || - (backend && sd_opt_set_string(opt.get(), "backend", backend) != SD_STATUS_OK) || - (params_backend && sd_opt_set_string(opt.get(), "params_backend", params_backend) != SD_STATUS_OK)) - return nullptr; - sd_adetailer_t* result = nullptr; - sd_adetailer_create(opt.get(), &result); - return result; -} - -static inline bool adetail_sd_image(sd_adetailer_t* detector, sd_ctx_t* ctx, SDImage image, SDOptPtr opt, sd_result_t** result) { - if (result) - *result = nullptr; - auto tensor = image_tensor(image); - return opt && tensor && sd_opt_set_tensor(opt.get(), "image", tensor.get()) == SD_STATUS_OK && - sd_adetail(detector, ctx, opt.get(), result) == SD_STATUS_OK; -} - -struct SDVideoUpscalerParams { - const char* diffusion_model_path{}; - const char* vae_path{}; - // Explicit output scale; RelayVSR requires 2 or 4 matching both checkpoints. - int upscale_factor{}; - std::optional n_threads; - const char* backend{}; - const char* params_backend{}; - // auto/on/off or diffusion/vae assignments; null selects auto. - const char* flash_attn_mode{}; - const char* conv_direct_mode{}; -}; - -struct SDVideoUpscaleParams { - const SDImage* frames{}; - int frame_count{}; - std::optional fps; - std::optional seed; - // RelayVSR reference window, including both endpoints; defaults to 16. - std::optional window_size; - // SeedVR2 independent temporal chunks in input frames (1 or 4n+1); defaults to 5. - std::optional temporal_chunk_size; -}; - -static inline sd_vid_upscaler_t* create_sd_vid_upscaler(const SDVideoUpscalerParams& config) { - SDOptPtr opt(sd_vid_upscaler_opt_create()); - if (!opt || sd_opt_set_string(opt.get(), "diffusion_model_path", config.diffusion_model_path) != SD_STATUS_OK || - sd_opt_set_string(opt.get(), "vae_path", config.vae_path) != SD_STATUS_OK || - sd_opt_set_int(opt.get(), "upscale_factor", config.upscale_factor) != SD_STATUS_OK || - (config.n_threads && sd_opt_set_int(opt.get(), "n_threads", *config.n_threads) != SD_STATUS_OK) || - (config.backend && sd_opt_set_string(opt.get(), "backend", config.backend) != SD_STATUS_OK) || - (config.params_backend && sd_opt_set_string(opt.get(), "params_backend", config.params_backend) != SD_STATUS_OK) || - (config.flash_attn_mode && sd_opt_set_string(opt.get(), "flash_attn_mode", config.flash_attn_mode) != SD_STATUS_OK) || - (config.conv_direct_mode && sd_opt_set_string(opt.get(), "conv_direct_mode", config.conv_direct_mode) != SD_STATUS_OK)) - return nullptr; - sd_vid_upscaler_t* result = nullptr; - sd_vid_upscaler_create(opt.get(), &result); - return result; -} - -static inline bool upscale_sd_video(sd_vid_upscaler_t* ctx, const SDVideoUpscaleParams& config, sd_result_t** result) { - if (result) - *result = nullptr; - SDOptBuilder opt(sd_vid_upscale_opt_create()); - opt.set_frames("frames", config.frames, config.frame_count); - opt.set_int("fps", config.fps); - opt.set_int("seed", config.seed); - opt.set_int("window_size", config.window_size); - opt.set_int("temporal_chunk_size", config.temporal_chunk_size); - auto params = opt.finish(); - return params && sd_upscale_video(ctx, params.get(), result) == SD_STATUS_OK; + sd_opt_set_int(opt.get(), "repeats", repeats) == SD_STATUS_OK && sd_upscale(ctx, opt.get(), result) == SD_STATUS_OK; } static inline SDImage take_result_image(sd_result_t* result, size_t index) { @@ -615,12 +522,12 @@ class SDImageVec { return index < generation_infos_.size() ? generation_infos_[index] : empty; } - void append_generation_info(size_t index, const std::string& info, const std::string& lora_model_dir = {}) { + void set_generation_info(size_t index, const std::string& source) { generation_infos_.resize(images_.size()); - generation_infos_.at(index) = merge_generation_info(generation_infos_.at(index), generation_info_with_relative_lora_paths(info, lora_model_dir)); + generation_infos_.at(index) = source; } - void adopt(sd_result_t* result, const std::string& lora_model_dir = {}) { + void adopt(sd_result_t* result) { clear(); SDResultPtr owner(result); if (!result) @@ -629,13 +536,14 @@ class SDImageVec { images_.reserve(count); generation_infos_.reserve(count); for (size_t i = 0; i < count; ++i) { - generation_infos_.push_back(generation_info_with_relative_lora_paths(sd_result_get_generation_info(result, i), lora_model_dir)); + const auto* source = sd_result_get_generation_info(result, i); + generation_infos_.emplace_back(source ? source : ""); images_.push_back(take_result_image(result, i)); } } - void adopt_video(sd_result_t* result, const std::string& lora_model_dir = {}) { - adopt(result, lora_model_dir); + void adopt_video(sd_result_t* result) { + adopt(result); } void adopt(SDImage* images, int count) { diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt index d01f7a7e20..ccf290a116 100644 --- a/examples/server/CMakeLists.txt +++ b/examples/server/CMakeLists.txt @@ -64,11 +64,11 @@ endif() add_executable(${TARGET} ../common/common.cpp - ../common/generation_metadata.cpp ../common/log.cpp ../common/media_io.cpp ../common/media_metadata.cpp main.cpp + server_access.cpp runtime.cpp model_catalog.cpp routes_models.cpp @@ -77,6 +77,8 @@ add_executable(${TARGET} routes_openai.cpp routes_sdapi.cpp routes_sdcpp.cpp + routes_dgl.cpp + routes_media.cpp ) if(APPLE) sd_set_macos_rpaths(${TARGET}) diff --git a/examples/server/README.md b/examples/server/README.md index 8673eb80c4..4a80b0683b 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -4,7 +4,7 @@ and HTTP APIs. Download or build the server before starting; see the [build guide](../../docs/build.md) and [frontend build instructions](#build-with-frontend). -- [Web UI](#web-ui): start the server, load a model, and generate. +- [Web UI](#web-ui): start the server, select a model, and generate. - [Model management](#model-management): model directories, recipes, and startup models. - [Server configuration](#server-configuration): launcher settings, network, logging, and help. - [API](#api): native and compatibility endpoints. @@ -61,7 +61,7 @@ for another build configuration or an extracted release archive. Open after the server starts, and keep the server running while using the browser. -### Load a model +### Select a model 1. Download the weights and required components listed in the matching [model guide](../../docs/models/README.md). Put them in the category folders @@ -76,8 +76,6 @@ while using the browser. to the chosen checkpoint and variant, as described in its model guide. 5. If a file is missing from a dropdown, check its category folder and click **Refresh files & recipes**. Selectors support searching by name or path. -6. Click **Load models** and wait for loading to finish. Selecting a recipe or - file alone does not reload the model. Recipe and component selectors support searching by name or relative file ID. Use the arrow keys and Enter to select, or Escape to cancel a search. With @@ -85,13 +83,10 @@ Use the arrow keys and Enter to select, or Escape to cancel a search. With declared generation defaults while preserving prompts, input images and fields not specified by the recipe. Disable it to keep your current parameters when switching recipes. This preference defaults to enabled and is saved locally. -Model loading and server-info refreshes do not reapply defaults or reset the form. Recipes declaring `video_frames` also switch the form to Video Generation; -other recipes switch to Image Generation. Generation is enabled after the -selected recipe is loaded. - -The model button shows elapsed loading time and keeps the final time after -success or failure, including after a page refresh. +other recipes switch to Image Generation. Select the required components to +enable **Generate**. The job loads any needed components and reports the +loading progress alongside sampling and output encoding. ### Generate an image or video @@ -99,6 +94,8 @@ success or failure, including after a page refresh. 2. Open **Sample & Guidance** to set **Method**, **Scheduler**, **Steps**, and **CFG Scale** when the model guide specifies values different from the recipe defaults. Set the output dimensions in **Aspect Ratio & Resolution**. + For image generation, **Preset sigmas** displays the step count defined by + the preset. Select another scheduler to set your own step count. 3. Supply inputs for the chosen task. Editing recipes use **Reference Images**; IP-Adapter uses **IP-Adapter Image**. For image-to-video, use video generation and upload a **Start Frame**; add an **End Frame** only for a compatible @@ -114,6 +111,14 @@ total work is unknown. The canvas keeps the submitted output aspect ratio, and stage changes keep the same layout. Editing the next request's resolution does not resize the current preview or result. +Settings will offer **Notify me when generation finishes** (upcoming; requires +a frontend update). When enabled, the UI requests browser notification +permission and shows a notification when a generation job completes, fails, or +is cancelled, so you do not need to watch the tab while waiting. The +preference is saved locally. Notifications require granting browser +notification permission; if permission was previously denied, reset it in the +browser's site settings for this site before turning the setting on. + ### LoRAs To apply a LoRA, open **LoRA**, select a compatible file, and set its @@ -121,6 +126,66 @@ To apply a LoRA, open **LoRA**, select a compatible file, and set its requests use this selector; prompt tags such as `` are CLI syntax and are not parsed by the native server API. +### DGL editor + +Open the Web UI and select **DGL** in the header. The workspace follows the +server's `--listen-ip` setting. The default `127.0.0.1` limits access to the +server machine. When the server listens on a LAN interface, open the Web UI +using the server's LAN IP and port to use the workspace from another device. +Use **Search scripts** to filter the script list, then select a saved script or +choose **New**. **Save** updates the current file or asks for a name for a new +script. Use **Save as…** to save a copy. The editor reopens the last saved script +used in that browser when it is still available. **Run** submits the current +editor text to the generation queue, including unsaved edits. The status bar +below the editor shows progress and keeps the final status and elapsed time. +The server terminal displays weight-loading throughput and sampling speed. + +When a script returns values, **View result** appears in the status bar. Open it +to inspect text, scalars, tensor metadata, and encoded media. PNG appears as an +image, WebM as a video player, and AVI as a download. WebM encoding is silent. +Use AVI for a PCM16 soundtrack. + +Use `image::encode` or `video::encode` and return their `{data, mime_type}` +dicts, either directly or as named fields of the root dict. To save the same +encoded output, call `media::save("output/cover.png", cover)` before returning +it. Saving is optional. The job result contains the same encoded bytes, and +polling returns them without re-encoding. + +The editor underlines supported media paths and shows compact previews below +their lines. Previews align with the code indentation, and files on the same +line appear side by side when space permits. Media loads near the visible area +of the editor. An output path without a file stays collapsed, and a completed +run refreshes its preview when the file becomes available. Drag the handle in +a preview's lower-right corner to resize it, or double-click the handle to reset it. +Click an image or video preview to open it at a larger size. Expanded videos +open at the current playback position. Click the picture to play or pause, or +drag the timeline below it to seek. AVI path previews support MJPEG and +uncompressed 24-bit RGB video with up to 64 MiB of PCM or 32-bit float audio. +The speaker button mutes the preview. To adjust volume in an inline preview, +hover or focus the speaker button to open the volume slider. +The editor previews files under `input/`, `assets/`, and the configured output +directory (`output/` by default). For example, use `assets/reference.png` or +`output/clip.webm` with the default configuration. Turn off **Media view** in +the editor toolbar to hide previews. Start the server with `--no-media-view` +to disable file previews at the server. + +DGL jobs share an execution context for the lifetime of the server. Compatible +scripts can reuse loaded model components across runs. The context can release +idle weights under memory pressure. + +Scripts are listed and saved in the server's working directory under +`dgl/` by default. Use `--dgl-dir` to select another directory. Script paths +are relative to the server's working directory. Model files and their +dependencies must reside under one of the configured `--model-dir` roots. +Write results under `output/` by default. For example, +`image::save("output/result.png", image)` saves a PNG. Use `--output-dir` to +choose a dedicated directory for DGL writes and previews. For example, start +the server with `--model-dir ../models --output-dir renders` and use +`image::save("renders/result.png", image)` to save and preview the PNG. +Relative paths still resolve from the server's working directory. Absolute +paths under the configured output directory also work. Writes outside that +directory are denied. + ## Model management ### Model directories @@ -243,6 +308,10 @@ Image 2.1 uses the same recipe for its full VAE and TAEQI2.1 alternatives. ### Models loaded at startup You can pass the same model-loading arguments used by `sd-cli` to `sd-server`. +Explicit model paths can be outside `--model-dir`. A startup model directory +includes the dependencies inside that directory. A startup shard index also +permits the shards it names within the index directory. Native generation accepts +LoRAs from `--lora-model-dir` and upscalers from `--hires-upscalers-dir`. For example, run this Z-Image Turbo configuration from the build directory: **Windows (PowerShell)** @@ -275,54 +344,34 @@ For example, run this Z-Image Turbo configuration from the build directory: `--offload-to-cpu` keeps weights in RAM when possible to reduce VRAM pressure, `-v` enables verbose logging, and `--cfg-scale 1.0` sets the default CFG scale. -API clients can use the model loaded at startup without selecting a recipe. -The UI automatically selects **Command-line model (all features)** and uses the -startup generation defaults. This runtime-only recipe exposes all controls for the supported -image/video mode. Selecting another recipe previews a model switch; selecting -the command-line entry again restores its generation defaults. The entry is -removed when the command-line context is unloaded or replaced. +The model specified on the command line is the initial model for API clients. +Its components load when needed. The UI offers **Current server model** with +generation defaults and controls for the active configuration. Generating with +a catalog recipe makes that selection the current model. #### Identity inputs -The browser currently has no PhotoMaker identity-image or PuLID identity-embedding -upload control. Prepare the inputs using the +PhotoMaker and PuLID use the **DGL editor**. Prepare the inputs using the [PhotoMaker](../../docs/models/photo_maker.md) or [PuLID](../../docs/models/pulid.md) -guide, then supply them when starting the server. From the build directory, for example: - -**Windows (PowerShell)** - -```powershell -.\bin\Release\sd-server.exe --model-dir ..\models --pm-id-images-dir ..\inputs\identity -``` - -**Linux/macOS** - -```sh -./bin/sd-server --model-dir ../models --pm-id-images-dir ../inputs/identity -``` - -Select the PhotoMaker recipe and weights in the browser. For PhotoMaker v2, also -pass `--pm-id-embed-path` with the prepared embedding file. For PuLID, use -`--pulid-id-embedding` instead of the PhotoMaker input argument, then select the -PuLID recipe and weights. These startup inputs are inherited by generation requests. +guide, then set model and identity-input paths in the corresponding script. +The former identity-input startup arguments have been removed. Scripts read +their own inputs under the server's file-access rules. #### Sharded checkpoints For a checkpoint loaded from a complete repository directory, pass its model loading arguments when starting `sd-server`, as in the model's CLI example. Keep the index, tokenizer, and all shards together. The browser then uses -**Command-line model (all features)** for the model loaded at startup; selecting -an individual shard in a recipe dropdown does not load the whole repository. +**Current server model** for that repository. Select the repository +using the startup option so the model loader can resolve all its shards. ### Switching models -The server keeps one model context loaded. Loading or unloading is rejected -while generation requests or queued jobs are pending. A switch validates the -selection before unloading the old context, then loads the replacement. -If loading fails, the service stays online with no active model and reports -the error. Backend and memory options supplied at startup apply to subsequent -loads. Recipe defaults apply to new loads; explicitly supplied generation -request parameters take precedence. +Choose a recipe and component files for the next generation. A queued job that +specifies a recipe makes it the current model when it starts. Later requests +without a recipe use the current model. The server shares one execution context +with the DGL editor and reuses matching model components within its startup +memory budgets. A load failure is reported on the job that requested the model. See [the API reference](api.md#model-management) for recipe fields, supported slots, management endpoints, and compatibility behavior. @@ -336,7 +385,7 @@ steps/CFG for the chosen weights. Metadata inspection, conversion, standalone upscaling and ADetailer are CLI workflows rather than model-loading recipes. ESRGAN and LTX latent upscalers are selected through generation upscaling settings with `--hires-upscalers-dir`; -textual inversion uses the startup `--embd-dir` option. +textual inversion uses the startup `--embd-dir` option (see `../../docs/embeddings.md` for trigger words and `` tags). SVD is not available through the current server pipeline. @@ -417,9 +466,58 @@ configured defaults. | --- | --- | --- | | `--listen-ip ` | `127.0.0.1` | Server listen address | | `--listen-port ` | `1234` | Server listen port | +| `--dgl-dir ` | `dgl` | Script directory for the DGL editor | +| `--output-dir ` | `output` | Directory for DGL writes and output previews | +| `--no-media-view` | Off | Disable the media view endpoint | | `--max-pending-jobs ` | `64` | Maximum async jobs queued or generating | | `--completed-ttl-seconds ` | `600` | Retention time for completed async jobs | +### Access + +The default listener accepts connections from the server machine. A listener +bound to a LAN interface also accepts connections from devices that can reach +it. You can open the Web UI from a link on another site. Browser API requests +are same-origin by default. Use an IP address, `localhost`, or the hostname +configured as the listen address when connecting directly. + +| Option | Default | Purpose | +| --- | --- | --- | +| `--api-key ` | none | Key clients must send as `Authorization: Bearer ` or `X-Api-Key: `. Separate multiple keys with commas. | +| `--api-key-file ` | none | The same, one key per line, so keys don't show in the process list | +| `--cors-origins ` | none | Additional browser origins allowed to make cross-origin requests, comma-separated | + +With a key, the page at `/` still loads. Enter the key in **Settings → Server API Key** +and select **Apply**. The Web UI saves it for that server in the current browser tab. +Leave **Base URL** blank when connecting to the server that serves the Web UI. +DGL scripts and media previews use the server that serves the Web UI. +Authentication failures return `401` with a `WWW-Authenticate` Bearer challenge. +Protected responses include `Cache-Control: no-store`. + +The server rejects requests from other browser origins with `403` unless their +origin is listed in `--cors-origins`. For a reverse proxy that preserves the +public Host header, include its full public origin in that list, such as +`https://sd.example.com`. The origin policy applies to DGL and media requests +as well as the generation APIs. + +Startup fails if an access option is missing its value, a list is empty +(such as `--api-key ,`), or the key file contains no keys. + +### Idle weight release + +| Option | Default | Memory released when idle | +| --- | --- | --- | +| `--weight-residency-ttl ` | `-1` | Cached model components, including RAM weights, GPU weights, staging copies, and component caches. The next request loads the needed components from their files. | + +The option also clears idle reusable buffers on supported backends after +releasing weights. GPU copies of weights stored in RAM, on another GPU, or on +disk are released when each component finishes, so they need no idle timer. + +`-1` disables release, `0` releases as soon as the shared +context is idle, and a positive integer sets the idle time in seconds. The +timer starts when the last job finishes. Running and queued generation or DGL +jobs defer release. Status and progress requests do not reset the timer. +The configured model and the model catalog remain available after unloading. + ### Logging Logging defaults to `info`. Use `--log-level ` to select `debug`, `verbose`, diff --git a/examples/server/api.md b/examples/server/api.md index 9f48e247f8..77cb807782 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -65,47 +65,50 @@ Current endpoints include: - `GET /sdcpp/v1/jobs/{id}` - `POST /sdcpp/v1/jobs/{id}/cancel` - `POST /sdcpp/v1/vid_gen` -- `POST /sdcpp/v1/upscale` ## Model management -Model management is additive: existing generation request bodies, successful -responses, job polling and cancellation remain unchanged. All three API families -use the current loaded context. Starting with the existing model arguments -preserves command-line preloading and its generation defaults; it does not -require a recipe. +All three API families share the server's execution context and its component +cache. The command-line model supplies the initial configuration. Native image +and video jobs can select a recipe and component files in the request. Video +requests with an explicit recipe require that recipe to declare +`defaults.video_frames`. The worker probes the selected model family and checks +that it supports the requested mode before applying the selection. A probe or +mode check failure is reported on the job and preserves the current model. +An applied selection remains the +current model for later requests that omit `model`, including A1111 and OpenAI +requests. Each native job reports loading and generation progress through the job API. Recipe defaults apply when a generation request omits the corresponding parameters. Image editing endpoints retain their existing input-image size inference when dimensions are omitted. -Without a loaded model, generation endpoints return HTTP 503 with -`{"error":"No model is loaded","code":"model_not_loaded"}`. -While loading/unloading, endpoints that access the context return HTTP 503 -with `code: "model_loading"`. These errors retain the existing string-valued -`error` field. Job polling/cancellation, catalog queries and model status remain -available during loading. Model lists are empty when no model is loaded; -`/v1/models` retains the `sd-cpp-local` ID when ready. +Requests that use the current model return HTTP 503 with +`{"error":"No current model is configured","code":"model_not_loaded"}` until +the server has a model configuration. `/v1/models` lists `sd-cpp-local` when a +model is configured. An accepted native job that omits `model` uses the current +model and its defaults when the job starts. | Method | Endpoint | Response / behavior | | --- | --- | --- | | GET | `/sdcpp/v1/recipes` | `{recipes: [...], errors: [...]}` | | GET | `/sdcpp/v1/model-files` | `{files: [{id, name, category, root, relative_path}], errors: [...]}` | | POST | `/sdcpp/v1/models/refresh` | Rescan recipes and files; return `{errors: [...]}` | -| GET | `/sdcpp/v1/models/status` | Current state, recipe, selection, error, loading time and optional revision | -| POST | `/sdcpp/v1/models/load` | Load the submitted recipe and selection; return status after completion. A load is a no-op returning the current status with `already_loaded: true` only when the state is ready and the fully resolved selection, the complete recipe object, and the resolved component paths all match the active model; a catalog refresh with modified recipe metadata or a retargeted model path therefore reloads even with an unchanged recipe ID and selection | -| POST | `/sdcpp/v1/models/unload` | Release the active context; return empty status | +| GET | `/sdcpp/v1/models/status` | Current model configuration (`configured` or `empty`), recipe, components and revision | -Load request: +Example `POST /sdcpp/v1/img_gen` request with a model selection. ```json { - "recipe": "flux1-dev", - "models": { - "diffusion_model": "diffusion_models/flux1-dev.gguf", - "clip_l": "text_encoders/clip_l.safetensors", - "t5xxl": "text_encoders/t5xxl.safetensors", - "vae": "vae/ae.safetensors" + "prompt": "a photograph of a cat", + "model": { + "recipe": "flux1-dev", + "models": { + "diffusion_model": "diffusion_models/flux1-dev.gguf", + "clip_l": "text_encoders/clip_l.safetensors", + "t5xxl": "text_encoders/t5xxl.safetensors", + "vae": "vae/ae.safetensors" + } } } ``` @@ -115,7 +118,7 @@ retains the existing relative IDs, such as `checkpoints/nested/model.gguf`. Additional roots use `@/` so identical paths in different roots remain selectable. Root qualifiers derive from the canonical root path; adding unrelated roots or refreshing the catalog does not change them. Moving -a root changes its qualifier. Do not construct IDs or use display names in load +a root changes its qualifier. Use the returned IDs to select files in generation requests. The display `name` omits the physical category directory (including aliases such @@ -137,31 +140,17 @@ relative path, or the full absolute file path when needed to distinguish duplica Continue sending `path` in structured LoRA requests. `--lora-model-dir` overrides automatic discovery across all model roots. Absolute paths, unknown files, wrong categories and -paths escaping the configured root are rejected. Optional slots can be omitted -or set to an empty string. Load/unload returns HTTP 409 (`model_busy`) while -requests or queued jobs are pending. Invalid configurations return HTTP 400 -(`invalid_model_config`) before unloading the current context. An initialization -failure returns HTTP 422 (`model_load_failed`) and leaves no active context. -The load HTTP request waits for completion; a separate client can poll status -while it runs. Refreshing the catalog never modifies an already loaded context. - -Status uses `state: empty | loading | ready | error`, `recipe` (ID or null), -`models` (slot-to-file-ID mapping), and `error` (string or null). A monotonically -increasing `revision` identifies runtime transitions within this server process. -Command-line preloading keeps `origin: command_line` and `recipe: null` for -compatibility, and adds `runtime_recipe`: a read-only `@command-line` recipe -with all feature declarations enabled. It is only available while that context -is loaded and cannot be submitted to `models/load`. The UI selects it by default -and uses command-line generation defaults, not defaults from a catalog recipe. -Capabilities also include this status as an additive `runtime` field. - -`load_elapsed_seconds` is the server-measured duration in seconds (a number or -null). It updates while a model is loading and freezes on success or failure. -Timing starts after selection validation and includes releasing the previous -model. It resets for each load and is null before any load and during/after -unloading. Command-line preloading reports its completed initialization time. -Poll `/sdcpp/v1/models/status` to display elapsed time, including while loading; -timer updates alone do not change `revision`. +paths escaping the configured root are rejected. An invalid selection returns +HTTP 400 with `code: "invalid_model_config"`. A component that fails to load +after submission reports its error in the job result. Catalog refreshes apply +to later submissions. + +The initial command-line selection has `origin: command_line`. Once a catalog +recipe is selected, status reports its ID and component files. The read-only +`runtime_recipe` with ID `@current` represents whichever model is configured at +the time of the query. Omit `model` from the request to use the current model. +Capabilities include the same model information in `runtime` and advertise +`generation_model_selection: true`. ### Recipe feature declarations @@ -206,9 +195,8 @@ Default-enabled features are `img2img`, `mask_image`, `lora`, `vae_tiling`, A `control_net` slot enables `controlnet`, `ip_adapter` enables `ip_adapter`, `high_noise_diffusion_model` enables `high_noise`, and `tae`/`taesd` enables `preview_tae`, unless explicitly disabled. -ControlNet controls are shown when previewing a supporting recipe, even before -a model file is selected. High-noise and TAE controls additionally require their -component to be selected. Runtime capabilities require the component to be loaded. +ControlNet, IP-Adapter, high-noise, TAE preview and audio reference controls +also depend on the selected component files. PuLID disables SLG while selected. Image-only and video-only inputs are filtered by the active generation mode. Eta depends on the selected sampler; SCM fields only apply to DBCache, @@ -219,18 +207,14 @@ each recipe. This is response-only metadata, like `source` and slot `categories` omit it when writing a user recipe file. The defaults are maintained by the server, not duplicated by the frontend. -`GET /sdcpp/v1/capabilities` adds `generation_features` for the loaded context, -derived from the active recipe and component availability without inferring -features from model-family names. When no model is loaded, every feature is -present and false. The UI can still preview a selected recipe using its -`effective_features` before loading. -Existing `features` / `features_by_mode` keys are retained and their model-specific -values reflect these declarations. A loaded recipe is snapshotted: refreshing -recipe files does not change the active context's capabilities until reloading. -Command-line preloading uses the runtime-only all-features recipe instead of model-family inference -and component paths; variant-specific recipe declarations are more precise. -Known high-noise sampling settings and `moe_boundary` are ignored when no -high-noise stage is loaded, and `vace_strength` is ignored by non-VACE models. +`GET /sdcpp/v1/capabilities` reports `generation_features` for the current model, +along with its generation mode and defaults. With no configured model, those +features are false. +The UI uses the selected catalog recipe's `effective_features` and component +selection for requests that specify `model`. +High-noise steps and `moe_boundary` apply only when a high-noise stage is loaded. +The shared scheduler and flow-shift aliases still apply to single-stage models. +`vace_strength` applies only to VACE models. Actual control-frame inputs still require VACE. These declarations govern the Web UI and advertised capabilities, not API @@ -281,12 +265,9 @@ supported directories; they cannot redefine or restrict its search directories. At least one required `model` or `diffusion_model` slot is necessary. An optional top-level `models` object maps slot IDs to file IDs, providing -recipe-local defaults for component selection. A load request may omit -`models` entirely and load with the recipe's defaults. Selections sent in the -request always override recipe defaults, slot by slot. An empty string -disables a slot's recipe default (omitting the slot selects it); the empty -key is then normalized out of the reported selection, so for slots without a -recipe default an empty selection loads identically to an omitted one. +recipe-local defaults for component selection. Omitting `model.models` uses +the recipe's defaults. Explicit selections override recipe defaults slot by +slot. An empty string disables the default for an optional slot. `size_multiple` is a positive integer from 1 to 4096 that declares the width and height increment used by the web UI. It defaults to `8` when omitted; the UI also @@ -396,7 +377,7 @@ Supported defaults: Other generation parameters continue to use startup defaults unless explicitly supplied by the generation request. Built-in Wan recipes provide video defaults; -use `/sdcpp/v1/vid_gen` after loading a video model. +use `/sdcpp/v1/vid_gen` with a video model. LoRAs are merged from `loras/` and `Lora/` in every model root unless `--lora-model-dir` is supplied. @@ -507,16 +488,10 @@ Native extension fields: Uploaded images are decoded at their original dimensions. The first decoded image establishes the generation dimensions if `size` is omitted. Input -geometry follows `image_preprocess`: references preserve their dimensions by -default, while init and mask use the generation canvas preset. +geometry follows the selected model's default input rules. -Reference encoding then follows model presets and `ref_image_args`. To skip -input geometry for references and disable resizing before VAE encoding, include -this in `prompt`: - -```text -edit this image {"image_preprocess":"target=ref,mode=none","ref_image_args":"resize_before_vae=false"} -``` +Reference encoding follows the model defaults. Custom resizing, cropping and +reference conditioning require a DGL program. Response fields: @@ -794,8 +769,8 @@ Field types: the elapsed generation time in seconds, including output encoding and excluding queue time. -`progress` is available independently of the preview setting, for both image -and video jobs. Continue polling until `status` is terminal: a sampling pass +`progress` is available independently of the preview setting for image, video, +and local DGL jobs. Continue polling until `status` is terminal: a sampling pass can finish before decoding, ADetailer, or output encoding finishes. | Field | Type | Notes | @@ -883,8 +858,9 @@ Top-level fields: | `schedulers` | `array` | Available schedulers | | `loras` | `array` | Available LoRA entries | | `upscalers` | `array` | Available highres upscalers, built-in and model-backed | -| `upscale` | `boolean` | Whether a compatible RGB ESRGAN model is available for `POST /sdcpp/v1/upscale` | | `preview_modes` | `array` | Available preview modes, e.g. `["none", "proj", "tae", "vae"]` | +| `media_view` | `boolean` | Whether the media view endpoint is enabled | +| `media_output` | `object`, optional | Configured output directory spellings in `paths` for matching DGL paths in the editor. `case_insensitive` is `true` on Windows. Omitted for the default directory or when media view is disabled. | | `limits` | `object` | Shared queue and size limits | `model` @@ -928,7 +904,6 @@ Shared nested fields: | --- | --- | --- | | `upscalers[].name` | `string` | Built-in name or model stem; use this value in `hires.upscaler` | | `upscalers[].model` | `boolean` | True for a model-backed upscaler, false for a built-in scaling filter | -| `upscalers[].image_upscale` | `boolean` | Whether this model can be selected by `POST /sdcpp/v1/upscale`; false for latent upscalers and built-in filters | Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, and `Latent (bicubic antialiased)`. Model-backed entries are scanned from the top level of `--hires-upscalers-dir`; subdirectories are not scanned. @@ -942,8 +917,6 @@ Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (neares | `limits.max_height` | `integer` | | `limits.max_batch_count` | `integer` | | `limits.max_queue_size` | `integer` | -| `limits.max_upscale_width` | `integer` | -| `limits.max_upscale_height` | `integer` | Shared default fields used by both `img_gen` and `vid_gen`: @@ -996,8 +969,6 @@ LTX and Wan preserve causal state between temporal tiles. Hunyuan Video and TAEH | Field | Type | | --- | --- | | `batch_count` | `integer` | -| `ref_image_args` | `string` | -| `increase_ref_index` | `boolean` | | `control_strength` | `number` | | `control_type` | `string` | | `ip_adapter_strength` | `number` | @@ -1014,27 +985,18 @@ LTX and Wan preserve causal state between temporal tiles. Hunyuan Video and TAEH `vid_gen`-specific default fields: +High-noise defaults are included when the configured model has a high-noise stage. + | Field | Type | | --- | --- | | `video_frames` | `integer` | | `fps` | `integer` | -| `ref_image_args` | `string` | | `moe_boundary` | `number` | | `vace_strength` | `number` | | `high_noise_sample_params` | `object` | -| `high_noise_sample_params.scheduler` | `string` | -| `high_noise_sample_params.sample_method` | `string` | -| `high_noise_sample_params.sample_steps` | `integer` | -| `high_noise_sample_params.eta` | `number \| null` | -| `high_noise_sample_params.shifted_timestep` | `integer` | +| `high_noise_sample_params.scheduler` | `string \| null` | +| `high_noise_sample_params.sample_steps` | `integer \| null` | | `high_noise_sample_params.flow_shift` | `number \| null` | -| `high_noise_sample_params.guidance.txt_cfg` | `number` | -| `high_noise_sample_params.guidance.img_cfg` | `number \| null` | -| `high_noise_sample_params.guidance.distilled_guidance` | `number` | -| `high_noise_sample_params.guidance.slg.layers` | `array` | -| `high_noise_sample_params.guidance.slg.layer_start` | `number` | -| `high_noise_sample_params.guidance.slg.layer_end` | `number` | -| `high_noise_sample_params.guidance.slg.scale` | `number` | Fields returned in `features_by_mode.img_gen`: @@ -1102,59 +1064,14 @@ Typical status codes: - `404 Not Found` - `410 Gone` -#### `POST /sdcpp/v1/upscale` - -Runs one RGB ESRGAN upscaler over an image, with no generation involved. Latent upscaler models remain available for hires generation but cannot be used here. - -This is the HTTP equivalent of `sd-cli -M upscale`: no diffusion model, text -encoder or sampling is used, so it is fast enough to answer synchronously and -does not create a job. - -Request fields: - -| Field | Type | Notes | -| --- | --- | --- | -| `image` | `string` | Required. Base64 or data URL image | -| `upscaler` | `string` | A name from `upscalers` with `image_upscale: true`; the first compatible entry when omitted | -| `repeats` | `integer` | Run the upscaler this many times, 1 to 4 (default `1`) | -| `tile_size` | `integer` | Tile size, defaulting to the server's `--upscale-tile-size` | -| `output_format` | `string` | `png`, `jpeg`, or `webp` when built with WebP support (default `png`); unsupported formats return 400 | -| `output_compression` | `integer` | Range is clamped to `0..100` | - -Response fields: - -| Field | Type | Notes | -| --- | --- | --- | -| `images` | `array` | One image | -| `images[].index` | `integer` | | -| `images[].b64_json` | `string` | Base64-encoded image bytes | -| `upscaler` | `string` | The upscaler actually used | -| `scale` | `integer` | The model's scale factor | -| `repeats` | `integer` | How many times it was run | -| `width` | `integer` | Result width | -| `height` | `integer` | Result height | -| `output_format` | `string` | Final encoded image format | - -Typical status codes: - -- `200 OK` -- `400 Bad Request` (invalid request, unsupported output format, unreadable image, incompatible upscaler, or output dimensions exceeding the limit) -- `500 Internal Server Error` - -Notes: - -- Final output dimensions, including all repeats, must not exceed 8192 pixels on either axis (`limits.max_upscale_width` and `limits.max_upscale_height`). Requests exceeding this bound are rejected before upscaling. -- The upscaler models are three-channel; alpha is not preserved. -- The request holds the generation context lock, so an upscale and a - generation never run on the device at the same time. - #### `POST /sdcpp/v1/jobs/{id}/cancel` -Cancels a queued job immediately, or requests interruption of a generating image or -video job. A generating job returns `200 OK` with `cancel_requested: true` and -remains `generating` until execution stops at a cancellation checkpoint. Continue -polling until its status becomes `cancelled`. Cancelled jobs have no result. -Repeated cancellation requests are safe; terminal jobs are returned unchanged. +Cancels a queued image, video, or DGL job immediately, or requests interruption +if it is already running. No request body is required. A running job returns +`200 OK` with `cancel_requested: true` and remains `generating` until it reaches +a cancellation checkpoint. Poll `GET /sdcpp/v1/jobs/{id}` for the final status. +Cancelled jobs have no result. Repeated cancellation requests are safe and +return the current status of terminal jobs. Typical status codes: @@ -1177,8 +1094,6 @@ Example: "strength": 0.75, "seed": -1, "batch_count": 1, - "ref_image_args": "", - "increase_ref_index": false, "control_strength": 0.9, "control_type": "", "ip_adapter_strength": 1.0, @@ -1256,16 +1171,13 @@ Example: ### Image Encoding Rules -Native image/video requests and SDAPI accept `image_preprocess` as a rule string -or array of rule strings. OpenAI-compatible requests can supply it in -`sd_cpp_extra_args`. See [Image preprocessing](../../docs/guides/image_preprocessing.md) -for one-time input geometry, native-resolution decoding, mask alignment, and -`canny=true` for edge detection on any supported image input. +Native generation follows model defaults. Custom input geometry and reference +conditioning use DGL tensor operations. See +[Image preprocessing](../../docs/guides/image_preprocessing.md) and +[Image editing](../../docs/guides/edit.md). -Image generation also accepts `ref_image_args` as a string (for example, -`"resize_before_vae=false"`) in native and SDAPI requests, or through -`sd_cpp_extra_args` in OpenAI-compatible requests. It controls downstream -reference encoding and is independent of input geometry rules. +The former `image_preprocess` rule field is rejected. Use the DGL execution +endpoint for custom preprocessing. Any image field accepts: @@ -1302,9 +1214,6 @@ Top-level scalar fields: | `strength` | `number` | | `seed` | `integer` | | `batch_count` | `integer` | -| `ref_image_args` | `string` | -| `image_preprocess` | `string \| array` | -| `increase_ref_index` | `boolean` | | `control_strength` | `number` | | `control_type` | `string` | | `ip_adapter_strength` | `number` | @@ -1336,7 +1245,7 @@ Sampling fields: | --- | --- | | `sample_params.scheduler` | `string` | | `sample_params.sample_method` | `string` | -| `sample_params.sample_steps` | `integer` | +| `sample_params.sample_steps` | `integer \| null` | | `sample_params.eta` | `number` | | `sample_params.shifted_timestep` | `integer` | | `sample_params.custom_sigmas` | `array` | @@ -1349,6 +1258,10 @@ Sampling fields: | `sample_params.guidance.slg.layer_end` | `number` | | `sample_params.guidance.slg.scale` | `number` | +An explicit `null` for `sample_params.sample_steps` clears the inherited step +setting. When custom sigmas are active, their count minus one sets the number of +steps in the schedule. + Other native fields: | Field | Type | @@ -1475,7 +1388,8 @@ Example cancelled job: `POST /sdcpp/v1/img_gen` may return: - `202 Accepted` when the job is created -- `400 Bad Request` for an empty body, unsupported model mode, invalid JSON, or invalid generation parameters +- `400 Bad Request` for an invalid model selection, an unsupported current model mode, or invalid request parameters +- `503 Service Unavailable` when the request uses the current model and the server has none configured - `429 Too Many Requests` when the job queue is full - `500 Internal Server Error` for unexpected server exceptions during submission @@ -1518,7 +1432,7 @@ Compared with `img_gen`, the `vid_gen` request body: - `vid_gen` is a single video sequence job, so `batch_count` is not part of the request schema - `mask_image`, `control_image`, `control_strength`, `ip_adapter_image`, `ip_adapter_strength`, and `embed_image_metadata` are not part of the request schema - `ref_images` is accepted for MiniMax-H3 Ref2VA conditioning; other video model families currently ignore it -- `vid_gen` adds `end_image`, `control_frames`, `high_noise_sample_params`, `video_frames`, `fps`, `ref_image_args`, `moe_boundary`, and `vace_strength` +- `vid_gen` adds `end_image`, `control_frames`, `high_noise_sample_params`, `video_frames`, `fps`, `moe_boundary`, and `vace_strength` Example: @@ -1533,7 +1447,6 @@ Example: "seed": -1, "video_frames": 33, "fps": 16, - "ref_image_args": "", "moe_boundary": 0.875, "vace_strength": 1.0, @@ -1547,40 +1460,17 @@ Example: "sample_method": "euler", "sample_steps": 28, "eta": 1.0, - "shifted_timestep": 0, "custom_sigmas": [], "flow_shift": 0.0, "guidance": { "txt_cfg": 7.0, "img_cfg": 7.0, - "distilled_guidance": 3.5, - "slg": { - "layers": [7, 8, 9], - "layer_start": 0.01, - "layer_end": 0.2, - "scale": 0.0 - } + "distilled_guidance": 3.5 } }, "high_noise_sample_params": { - "scheduler": "discrete", - "sample_method": "euler", - "sample_steps": -1, - "eta": 1.0, - "shifted_timestep": 0, - "flow_shift": 0.0, - "guidance": { - "txt_cfg": 7.0, - "img_cfg": 7.0, - "distilled_guidance": 3.5, - "slg": { - "layers": [7, 8, 9], - "layer_start": 0.01, - "layer_end": 0.2, - "scale": 0.0 - } - } + "sample_steps": -1 }, "lora": [], @@ -1615,7 +1505,6 @@ Example: - Images retain request order and correspond to ``, ``, and so on in the prompt. - For MiniMax-H3, non-empty `ref_images` cannot be combined with `init_image` or `end_image`. A conflicting API request fails during generation; the WebUI checks this before submission. - MiniMax-H3 does not support `control_frames`; leave that array empty. -- `ref_image_args` applies to `vid_gen`; MiniMax-H3 honors `ref_image_size` there (`match` default, `max` for a 2048 px short edge). Only references above the limit are downscaled; each axis is then snapped to the nearest 32 px multiple. - Other video model families currently ignore `ref_images`. - `features_by_mode.vid_gen` does not currently advertise `ref_images`; its absence is not an indication that MiniMax-H3 reference images are unsupported. @@ -1666,7 +1555,6 @@ Top-level scalar fields: | `seed` | `integer` | | `video_frames` | `integer` | | `fps` | `integer` | -| `ref_image_args` | `string` | | `moe_boundary` | `number` | | `vace_strength` | `number` | | `preview` | `string` | @@ -1697,41 +1585,29 @@ Sampling fields: | `sample_params.sample_method` | `string` | | `sample_params.sample_steps` | `integer` | | `sample_params.eta` | `number` | -| `sample_params.shifted_timestep` | `integer` | | `sample_params.custom_sigmas` | `array` | | `sample_params.flow_shift` | `number` | | `sample_params.guidance.txt_cfg` | `number` | | `sample_params.guidance.img_cfg` | `number` | | `sample_params.guidance.distilled_guidance` | `number` | -| `sample_params.guidance.slg.layers` | `array` | -| `sample_params.guidance.slg.layer_start` | `number` | -| `sample_params.guidance.slg.layer_end` | `number` | -| `sample_params.guidance.slg.scale` | `number` | High-noise sampling fields: -The two video stages share the scheduler, flow shift and timestep shifting. -`high_noise_sample_params.scheduler`, `.flow_shift` and `.shifted_timestep` -are accepted as aliases for those shared settings in video requests. Image -requests ignore these high-noise fields. Within one video request, a -corresponding `sample_params` field takes precedence. Request aliases override -inherited startup and recipe values; `null` clears the inherited shared setting. +The two native video stages share the scheduler, flow shift, sampler, eta and +guidance. `high_noise_sample_params.scheduler` and `.flow_shift` are accepted +as aliases for the shared settings. A corresponding `sample_params` field takes +precedence. Request aliases override inherited startup and recipe values, and +`null` clears the inherited shared setting. + +The server accepts legacy `high_noise_sample_params.sample_method`, `.eta` and +`.guidance` fields for compatibility. Set these shared values in `sample_params`. +Independent stage settings and timestep shifting require an explicit DGL workflow. | Field | Type | | --- | --- | | `high_noise_sample_params.scheduler` | `string` | -| `high_noise_sample_params.sample_method` | `string` | | `high_noise_sample_params.sample_steps` | `integer` | -| `high_noise_sample_params.eta` | `number` | -| `high_noise_sample_params.shifted_timestep` | `integer` | | `high_noise_sample_params.flow_shift` | `number` | -| `high_noise_sample_params.guidance.txt_cfg` | `number` | -| `high_noise_sample_params.guidance.img_cfg` | `number` | -| `high_noise_sample_params.guidance.distilled_guidance` | `number` | -| `high_noise_sample_params.guidance.slg.layers` | `array` | -| `high_noise_sample_params.guidance.slg.layer_start` | `number` | -| `high_noise_sample_params.guidance.slg.layer_end` | `number` | -| `high_noise_sample_params.guidance.slg.scale` | `number` | Other native fields: @@ -1806,10 +1682,7 @@ When omitted, backend defaults apply to these fields: - `sample_params.flow_shift` - `sample_params.guidance.img_cfg` - `high_noise_sample_params.scheduler` -- `high_noise_sample_params.sample_method` -- `high_noise_sample_params.eta` - `high_noise_sample_params.flow_shift` -- `high_noise_sample_params.guidance.img_cfg` `high_noise_sample_params` may also be omitted entirely. @@ -1820,19 +1693,21 @@ to the loaded model: | Model family | Frame alignment | Fixed FPS | | --- | --- | --- | -| Wan, HunyuanVideo, LingBot | `4n + 1`, round down | Wan 2.2 S2V: 16 | -| LTX | `8n + 1`, round down | None | +| Wan, HunyuanVideo, LingBot | `4n + 1`, round up | Wan 2.2 S2V: 16 | +| LTX | `8n + 1`, round up | None | | MiniMax-H3 | `17n + 5`, round up, minimum 5 | 24 | -| AnimateDiff | Whole frames, maximum 32 | None | + +AnimateDiff requires an explicit DGL workflow rather than the native video +generation API. Wan examples: - `video_frames = 33` stays `33` -- `video_frames = 34` becomes `33` -- `video_frames = 32` becomes `29` +- `video_frames = 34` becomes `37` +- `video_frames = 32` becomes `33` -At 16 FPS, a 5-second target requests 80 frames and aligns to 77 frames for Wan, -or approximately 4.813 seconds. Audio-driven generation and temporal upscaling +At 16 FPS, a 5-second target requests 80 frames and aligns to 81 frames for Wan, +or approximately 5.063 seconds. Audio-driven generation and temporal upscaling can change the final length. Use the completed job's actual decoded `frame_count` and `fps` for the final playback duration. @@ -1909,17 +1784,92 @@ Example cancelled job: `POST /sdcpp/v1/vid_gen` may return: - `202 Accepted` when the job is created -- `400 Bad Request` for an empty body, unsupported model mode, invalid JSON, invalid generation parameters, or an unsupported output format +- `400 Bad Request` for an invalid model selection, an unsupported current model mode, invalid request parameters, or an unsupported output format +- `503 Service Unavailable` when the request uses the current model and the server has none configured - `429 Too Many Requests` when the job queue is full - `500 Internal Server Error` for unexpected server exceptions during submission +## Media view + +`GET /sdcpp/v1/view?root=assets&path=reference.png` serves an image or video +over the configured listener. `root` selects `input` or `assets` in the +server's working directory, or `output` for the directory selected by +`--output-dir` (`output/` in the working directory by default). `path` is a +slash-separated relative path within the selected directory. Supported formats +are PNG, JPEG, GIF, WebP, WebM, MP4, and AVI. The endpoint supports HTTP byte +ranges and sends `Cache-Control: no-store`. + +The server returns `403` when access is denied or the server was started with +`--no-media-view`. Unavailable paths, links, and unsupported files return +`404`. + +## DGL editor API + +These endpoints follow the server's access rules and `--listen-ip`. The server +uses `./dgl` in the working directory unless `--dgl-dir` is set. + +| Method and path | Request or response | +| --- | --- | +| GET /sdcpp/v1/dgl/scripts | Returns directory and a list of scripts | +| GET /sdcpp/v1/dgl/script?name=example.dgl | Returns the script as source | +| POST /sdcpp/v1/dgl/script | Saves UTF-8 source with the given name. Pass previous_source to update an existing script. A conflict returns HTTP 409. | +| POST /sdcpp/v1/dgl/jobs | Queues the source string and returns a job ID and `poll_url` with HTTP 202 | +| GET /sdcpp/v1/jobs/{id} | Returns job status and progress, plus any error or result with tensor descriptions and inline encoded media | +| POST /sdcpp/v1/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job | + +Failed jobs report `error.code` and `error.message`. When execution reports +`out_of_memory`, the message includes the memory failure details available +from the runtime. + +Scripts share the component cache and execution settings used for generation. +Model reads are restricted to the configured model directories. Script writes +are restricted to `--output-dir`, which defaults to `output/` in the server's +working directory. + +Cancellation returns the current job status with HTTP 200. A queued job +becomes `cancelled` immediately. A running job sets the `cancel_requested` +flag. Poll the status endpoint until it reports `cancelled`. Execution stops +at a DGL cancellation check, so an operation currently running may have to +finish first. A terminal job returns its current status. + +### Encoded DGL results + +The existing job result has `type`, `outputs` and `media`. `outputs` retains +the flat tensor descriptions. `media` recognizes a root `{data, mime_type}` +dict or such dicts in the root's named fields. `data` must be DGL `bytes`, and +the supported MIME types are `image/png`, `video/webm` and `video/x-msvideo`. +Bare bytes, U8 tensors and more deeply nested dicts are not inferred as media. +The name of a root media dict is `result`. + +```json +{ + "type": "dict", + "outputs": [], + "media": [ + {"name": "cover", "mime_type": "image/png", "b64_json": "..."}, + {"name": "clip", "mime_type": "video/webm", "b64_json": "..."} + ] +} +``` + +The script encodes media once. After execution releases the generation lock, +the server converts returned bytes to Base64 once, before publishing +`completed`. Polling returns the stored metadata and inline Base64 media. + +Inline media share a 64 MiB raw-byte budget per job. An item that exceeds the +remaining budget has no `b64_json`; it instead contains +`error: {code: "inline_too_large", message: "..."}`. Other media and tensor +outputs remain available, and any file already written by `media::save` +remains intact. Encoder failures fail the script through the ordinary DGL +execution error path. WebM encoding rejects nonempty audio instead of silently +removing it. Use AVI encoding for a PCM16 soundtrack. + ## Actual generation parameters -Generation responses expose the core `sdcpp.generation/v1` record as -`generation_info`, independently of `embed_image_metadata`. Native async image -result items and OpenAI image items contain the parameter snapshot with each -image's actual seed and without `batch_count`. Native video -results contain the video request snapshot. SD API `info.generation_info` is an array +Generation responses expose the executed DGL source as `generation_info`, +independently of `embed_image_metadata`. Native async image result items and +OpenAI image items contain each image's source with its resolved seed. Native +video results contain the sequence-wide source. SD API `info.generation_info` is an array aligned with `info.infotexts` and `info.all_seeds`; the outer `parameters` field remains the request echo. See [generation metadata](../../docs/guides/generation_metadata.md) -for field semantics, postprocessing and container storage. +for source semantics and container storage. diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index bb88fb6aa5..329cf29e8d 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -4,13 +4,18 @@ #include #include +#include #include +#include #include +#include #include +#include #include "common/log.h" #include "common/media_io.h" #include "common/resource_owners.hpp" +#include "model_catalog.h" class JobCancellationMonitor { std::mutex mutex_; @@ -21,18 +26,24 @@ class JobCancellationMonitor { public: // The caller holds sd_ctx_mutex until this monitor has joined, keeping the // context alive and preventing cancellation from reaching another request. - JobCancellationMonitor(sd_ctx_t* ctx, const AsyncGenerationJob& job) - : thread_([this, ctx, &job]() { + template + JobCancellationMonitor(const AsyncGenerationJob& job, Cancel cancel) + : thread_([this, &job, cancel = std::move(cancel)]() { std::unique_lock lock(mutex_); while (!done_) { if (job.cancel_requested.load()) { - // Each generation pass resets the library flag, including ADetailer. - sd_cancel_generation(ctx, SD_CANCEL_ALL); + cancel(); } cv_.wait_for(lock, std::chrono::milliseconds(10), [this]() { return done_; }); } }) {} + JobCancellationMonitor(sd_ctx_t* ctx, const AsyncGenerationJob& job) + : JobCancellationMonitor(job, [ctx]() { + // Each generation pass resets the library flag, including ADetailer. + sd_cancel_generation(ctx, SD_CANCEL_ALL); + }) {} + ~JobCancellationMonitor() { { std::lock_guard lock(mutex_); @@ -115,24 +126,25 @@ static void finish_job_progress(AsyncGenerationJob& job) { job.progress.finished = std::chrono::steady_clock::now(); } -class JobCallbacksGuard { - sd_ctx_t* ctx_; - AsyncGenerationJob& job_; - bool detailing_ = false; - - static void progress_callback(const sd_generation_progress_t* progress, void* data) { - auto& guard = *static_cast(data); - update_job_progress(guard.job_, guard.detailing_ ? "adetailer" : progress->stage, - guard.detailing_ ? progress->stage : progress->detail, +static void job_progress_callback(const sd_generation_progress_t* progress, void* data) noexcept { + try { + auto& job = *static_cast(data); + update_job_progress(job, progress->stage, progress->detail, progress->sample_pass, progress->completed, progress->total, progress->unit); + } catch (...) { + // Progress callbacks must not unwind into the generation context. } +} + +class JobCallbacksGuard { + sd_ctx_t* ctx_; public: JobCallbacksGuard(sd_ctx_t* ctx, AsyncGenerationJob& job) - : ctx_(ctx), job_(job) { + : ctx_(ctx) { clear_preview_callback(); set_preview_callback(job); - sd_set_generation_progress_callback(ctx_, progress_callback, this); + sd_set_generation_progress_callback(ctx_, job_progress_callback, &job); } ~JobCallbacksGuard() { @@ -140,22 +152,36 @@ class JobCallbacksGuard { clear_preview_callback(); } - void begin_detailing() { - clear_preview_callback(); - detailing_ = true; - update_job_progress(job_, "adetailer"); - } - JobCallbacksGuard(const JobCallbacksGuard&) = delete; JobCallbacksGuard& operator=(const JobCallbacksGuard&) = delete; }; +class DglJobProgressGuard { + sd_dgl_ctx_t* ctx_; + +public: + DglJobProgressGuard(sd_dgl_ctx_t* ctx, AsyncGenerationJob& job) : ctx_(ctx) { + if (sd_dgl_ctx_set_progress_callback(ctx_, job_progress_callback, &job) != SD_STATUS_OK) + throw std::runtime_error(sd_dgl_error()); + } + + ~DglJobProgressGuard() { + if (sd_dgl_ctx_set_progress_callback(ctx_, nullptr, nullptr) != SD_STATUS_OK) + LOG_WARN("could not clear DGL job progress callback: %s", sd_dgl_error()); + } + + DglJobProgressGuard(const DglJobProgressGuard&) = delete; + DglJobProgressGuard& operator=(const DglJobProgressGuard&) = delete; +}; + const char* async_job_kind_name(AsyncJobKind kind) { switch (kind) { case AsyncJobKind::ImgGen: return "img_gen"; case AsyncJobKind::VidGen: return "vid_gen"; + case AsyncJobKind::Dgl: + return "dgl"; default: return "img_gen"; } @@ -233,6 +259,9 @@ bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job) { } manager.queue.erase(new_end, manager.queue.end()); + job.model.reset(); + job.request_body = nullptr; + job.dgl_source.clear(); job.cancel_requested.store(true); job.status = AsyncJobStatus::Cancelled; job.completed_at = unix_timestamp_now_ms(); @@ -289,7 +318,9 @@ json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJo } if (job.status == AsyncJobStatus::Completed) { - if (job.kind == AsyncJobKind::VidGen) { + if (job.kind == AsyncJobKind::Dgl) { + result["result"] = job.dgl_result_info; + } else if (job.kind == AsyncJobKind::VidGen) { result["result"] = { {"output_format", job.vid_gen.output_format}, {"mime_type", job.result_media_mime_type}, @@ -339,37 +370,48 @@ json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJo return result; } +static bool prepare_native_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message) { + if (job.cancel_requested.load()) + return false; + const SDMode mode = job.kind == AsyncJobKind::VidGen ? VID_GEN : IMG_GEN; + if (job.model) { + auto model = std::move(job.model); + return set_current_model(runtime, std::move(*model), mode, error_message); + } + auto body = std::move(job.request_body); + if (job.model_revision == runtime.models->revision) + return true; + // An earlier queued job can change the model and its defaults before this job starts. + if (!runtime_supports_generation_mode(runtime, mode)) { + error_message = unsupported_generation_mode_error(mode); + return false; + } + try { + return parse_native_job_request(body, runtime, job, error_message); + } catch (const std::exception& error) { + error_message = error.what(); + return false; + } +} + bool execute_img_gen_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::vector& output_images, json& output_info, std::string& error_message) { - output_info = json::array(); - SDOptPtr params = job.img_gen.to_image_opt(); - + output_info = json::array(); SDImageVec results; { std::lock_guard lock(*runtime.sd_ctx_mutex); - if (job.cancel_requested.load()) { + if (!prepare_native_job(runtime, job, error_message)) { return false; } JobCancellationMonitor cancellation(runtime.sd_ctx, job); JobCallbacksGuard callbacks(runtime.sd_ctx, job); - PromptImageCallbackGuard prompt_images(runtime.sd_ctx, job.img_gen.gen_params); - sd_result_t* generated = nullptr; - generate_sd_image(runtime.sd_ctx, params, &generated); - results.adopt(generated, runtime.ctx_params->lora_model_dir); - if (job.cancel_requested.load()) { + if (!generate_server_images(runtime.sd_ctx, job.img_gen, results, error_message) || job.cancel_requested.load()) { return false; } - if (!results.empty() && job.img_gen.adetailer_enabled && !runtime.default_gen_params->ad_model_path.empty()) { - callbacks.begin_detailing(); - if (!apply_server_adetailer(runtime, job.img_gen, results)) { - error_message = "ADetailer failed"; - return false; - } - } } const int num_results = results.count(); @@ -405,7 +447,7 @@ bool execute_img_gen_job(ServerRuntime& runtime, continue; } output_images.push_back(base64_encode(image_bytes)); - output_info.push_back(json::parse(results.generation_info(i))); + output_info.push_back(results.generation_info(i)); update_job_progress(job, "encoding", "image", -1, i + 1, num_results, "images"); } @@ -425,7 +467,6 @@ bool execute_vid_gen_job(ServerRuntime& runtime, int& output_fps, json& output_info, std::string& error_message) { - SDOptPtr params = job.vid_gen.to_video_opt(); std::string str_params; SDImageVec results; @@ -434,9 +475,10 @@ bool execute_vid_gen_job(ServerRuntime& runtime, { std::lock_guard lock(*runtime.sd_ctx_mutex); - if (job.cancel_requested.load()) { + if (!prepare_native_job(runtime, job, error_message)) { return false; } + auto params = job.vid_gen.to_video_opt(); JobCancellationMonitor cancellation(runtime.sd_ctx, job); JobCallbacksGuard callbacks(runtime.sd_ctx, job); PromptImageCallbackGuard prompt_images(runtime.sd_ctx, job.vid_gen.gen_params); @@ -445,17 +487,20 @@ bool execute_vid_gen_job(ServerRuntime& runtime, output_fps = sd_result_get_fps(generated); generated_audio = retain_result_audio(generated); - results.adopt_video(generated, runtime.ctx_params->lora_model_dir); - output_info = json::parse(results.generation_info(0)); + results.adopt_video(generated); + output_info = results.generation_info(0); if (job.vid_gen.gen_params.embed_image_metadata) str_params = results.generation_info(0); + } else { + error_message = sd_get_last_error(); } } num_results = results.count(); if (job.cancel_requested.load() || num_results <= 0) { free_sd_audio(generated_audio); - error_message = "generate_video returned no results"; + if (error_message.empty()) + error_message = "generate_video returned no results"; return false; } @@ -479,6 +524,284 @@ bool execute_vid_gen_job(ServerRuntime& runtime, return true; } +static int64_t dgl_image_frame_count(const sd_tensor_t* tensor) { + if (!tensor || sd_tensor_type(tensor) != SD_TENSOR_U8) + return 0; + const auto rank = sd_tensor_rank(tensor); + if (rank != 3 && rank != 4) + return 0; + const auto channels = sd_tensor_dim(tensor, 0); + const auto width = sd_tensor_dim(tensor, 1); + const auto height = sd_tensor_dim(tensor, 2); + if (channels < 1 || channels > 4 || width <= 0 || height <= 0 || + sd_tensor_byte_size(tensor) == 0 || sd_tensor_byte_size(tensor) > std::numeric_limits::max()) + return 0; + return rank == 3 ? 1 : sd_tensor_dim(tensor, 3); +} + +static json describe_dgl_media(const sd_dgl_result_t* result) { + json media = json::array(); + size_t remaining = 64 * 1024 * 1024; + auto append = [&](const sd_dgl_value_t* value, const std::string& name) { + if (sd_dgl_value_kind(value) != SD_DGL_VALUE_DICT) + return; + const auto* data = sd_dgl_value_field(value, "data"); + const auto* mime = sd_dgl_value_field(value, "mime_type"); + if (sd_dgl_value_kind(data) != SD_DGL_VALUE_BYTES || sd_dgl_value_kind(mime) != SD_DGL_VALUE_STRING) + return; + const char* mime_text = nullptr; + size_t mime_size = 0; + const void* bytes = nullptr; + size_t size = 0; + if (sd_dgl_value_get_string(mime, &mime_text, &mime_size) != SD_STATUS_OK || + sd_dgl_value_get_bytes(data, &bytes, &size) != SD_STATUS_OK) + throw std::runtime_error(sd_get_last_error()); + const std::string mime_type(mime_text, mime_size); + if (mime_type != "image/png" && mime_type != "video/webm" && mime_type != "video/x-msvideo") + return; + json item = {{"name", name}, {"mime_type", mime_type}}; + if (size > remaining) { + item["error"] = {{"code", "inline_too_large"}, {"message", "DGL media exceeds the 64 MiB inline result budget; use media::save"}}; + } else { + item["b64_json"] = base64_encode(bytes, size); + remaining -= size; + } + media.push_back(std::move(item)); + }; + const auto* root = sd_dgl_result_root(result); + if (sd_dgl_value_kind(root) == SD_DGL_VALUE_DICT) { + append(root, "result"); + if (media.empty()) + for (size_t i = 0; i < sd_dgl_value_count(root); ++i) { + const auto* value = sd_dgl_value_at(root, i); + if (const auto* name = sd_dgl_value_name(value)) + append(value, name); + } + } + return media; +} + +static json describe_dgl_result(const sd_dgl_result_t* result) { + const std::string type = sd_dgl_result_type(result); + json outputs = json::array(); + for (size_t i = 0; i < sd_dgl_result_count(result); ++i) { + const auto* name = sd_dgl_result_name(result, i); + const auto* tensor = sd_dgl_result_tensor(result, name); + const auto dtype = sd_tensor_type(tensor); + const auto bytes = sd_tensor_byte_size(tensor); + std::vector shape; + for (size_t axis = 0; axis < sd_tensor_rank(tensor); ++axis) + shape.push_back(sd_tensor_dim(tensor, axis)); + json output = {{"name", name}, {"dtype", dtype}, {"shape", shape}, {"bytes", bytes}, {"frames", dgl_image_frame_count(tensor)}}; + const auto* data = sd_tensor_data(tensor); + if (type == "string" && std::string_view(name) == "result") { + output["value"] = bytes ? std::string(static_cast(data), bytes) : ""; + } else if (shape.empty() && bytes != 0) { + switch (dtype) { + case SD_TENSOR_U8: + output["value"] = *static_cast(data); + break; + case SD_TENSOR_I32: + output["value"] = *static_cast(data); + break; + case SD_TENSOR_I64: + output["value"] = std::to_string(*static_cast(data)); + break; + case SD_TENSOR_F32: + output["value"] = *static_cast(data); + break; + case SD_TENSOR_F64: + output["value"] = *static_cast(data); + break; + } + } + outputs.push_back(std::move(output)); + } + return {{"type", type}, {"outputs", std::move(outputs)}, {"media", describe_dgl_media(result)}}; +} + +namespace { + namespace fs = std::filesystem; + + bool has_resolved_model_parent(const fs::path& path) { + std::error_code error; + for (auto part = path; !part.empty(); part = part.parent_path()) { + const auto status = fs::symlink_status(part, error); + if (status.type() != fs::file_type::not_found) { + if (error || !fs::is_directory(status)) + return false; + // A dangling link or junction must not be treated as a missing dependency. + const auto canonical = fs::canonical(part, error); + return !error && model_path_key(canonical) == model_path_key(part); + } + if (part == part.root_path()) + break; + } + return false; + } + + bool allowed_dgl_path(const char* path, sd_dgl_file_access_t access, void* userdata) try { + const auto& policy = *static_cast(userdata); + std::error_code error; + const auto file = fs::u8path(path); + if (file.empty()) + return false; +#ifdef _WIN32 + if (file.native().compare(0, 4, L"\\\\?\\") == 0 || file.native().compare(0, 4, L"\\\\.\\") == 0) + return false; + for (const auto& part : file.relative_path()) { + const auto name = part.native(); + if (name.empty() || name == L"." || name == L"..") + continue; + if (name.back() == L'.' || name.back() == L' ' || name.find(L':') != std::wstring::npos) + return false; + auto device = name.substr(0, name.find(L'.')); + while (!device.empty() && device.back() == L' ') + device.pop_back(); + std::transform(device.begin(), device.end(), device.begin(), [](wchar_t ch) { return std::towupper(ch); }); + if (device == L"CON" || device == L"PRN" || device == L"AUX" || device == L"NUL" || + device == L"CONIN$" || device == L"CONOUT$" || + (device.size() == 4 && (device.compare(0, 3, L"COM") == 0 || device.compare(0, 3, L"LPT") == 0) && + std::wstring_view(L"123456789\u00b9\u00b2\u00b3").find(device.back()) != std::wstring_view::npos)) + return false; + } +#endif + const auto absolute = fs::absolute(file, error); + if (error) + return false; + const auto resolved = fs::weakly_canonical(absolute, error); + if (error) + return false; + if (access == SD_DGL_FILE_WRITE) { + if (!model_path_inside(policy.output, resolved)) + return false; + for (auto part = absolute; part != part.root_path(); part = part.parent_path()) { + const auto status = fs::symlink_status(part, error); + if (fs::is_symlink(status) || (error && status.type() != fs::file_type::not_found)) + return false; + error.clear(); + } + const auto status = fs::symlink_status(resolved, error); + if (status.type() != fs::file_type::not_found) { + return !error && fs::is_regular_file(status) && fs::hard_link_count(resolved, error) == 1 && !error; + } + error.clear(); + fs::create_directories(resolved.parent_path(), error); + return !error; + } + const auto status = fs::status(resolved, error); + const bool readable = !error && (fs::is_regular_file(status) || fs::is_directory(status)); + if (access == SD_DGL_FILE_READ) + return readable; + if (!readable && status.type() != fs::file_type::not_found) + return false; + + const auto key = model_path_key(resolved); + const bool allowed = policy.configured_files.count(key) || + std::any_of(policy.model_bundles.begin(), policy.model_bundles.end(), [&](const fs::path& root) { + return model_path_inside(root, resolved); + }) || + std::any_of(policy.models.begin(), policy.models.end(), [&](const ModelRoot& root) { + return model_path_key(root.path) == key || model_path_inside(root.path, resolved); + }); + return allowed && (readable || has_resolved_model_parent(resolved)); + } catch (const std::exception&) { + return false; + } +} + +void configure_server_file_access(ServerModels& models, const SDSvrParams& params, const SDContextParams& config) { + auto& policy = models.file_access; + fs::path output_root = + params.output_dir.empty() + ? fs::weakly_canonical(fs::current_path()) / "output" + : fs::weakly_canonical(fs::absolute(fs::u8path(params.output_dir))); + if (output_root.has_relative_path() && !output_root.has_filename()) + output_root = output_root.parent_path(); + policy = {get_model_roots(params), output_root, {}, {}}; + for (const auto* directory : {&config.lora_model_dir, &config.hires_upscalers_dir}) + if (!directory->empty()) + policy.models.push_back(make_model_root(fs::u8path(*directory), false)); + for (const auto& entry : config.embedding_map) + policy.configured_files.insert(model_path_key(fs::weakly_canonical(fs::absolute(fs::u8path(entry.second))))); + add_startup_model_sources(policy, config); + // The DGL context gets a copy of the policy: take the snapshot after the + // enrichment, or graphs cannot read from --lora-model-dir / --hires-upscalers-dir. + models.workspace_file_access = policy; + + if (sd_ctx_set_file_access_callback(models.context.get(), allowed_dgl_path, &policy) != SD_STATUS_OK) + throw std::runtime_error(sd_get_last_error()); + if (!sd_dgl_ctx_set_file_access_callback(sd_ctx_get_dgl_ctx(models.context.get()), allowed_dgl_path, &models.workspace_file_access)) + throw std::runtime_error(sd_get_last_error()); +} + +static sd_status_t execute_dgl_job(ServerRuntime& runtime, + AsyncGenerationJob& job, + json& result_info, + std::string& error_message) { + try { + auto source = std::move(job.dgl_source); + sd_dgl_result_t* raw_result = nullptr; + { + std::lock_guard lock(*runtime.sd_ctx_mutex); + if (job.cancel_requested.load()) + return SD_STATUS_CANCELLED; + auto* ctx = sd_ctx_get_dgl_ctx(runtime.sd_ctx); + DglJobProgressGuard progress(ctx, job); + JobCancellationMonitor cancellation(job, [ctx]() { + sd_dgl_ctx_cancel(ctx); + }); + update_job_progress(job, "executing", "dgl"); + const auto status = sd_dgl_run(ctx, source.c_str(), nullptr, 0, &raw_result); + if (status != SD_STATUS_OK) { + error_message = sd_dgl_error(); + return status; + } + } + std::unique_ptr result(raw_result, sd_dgl_result_free); + result_info = describe_dgl_result(result.get()); + return SD_STATUS_OK; + } catch (const std::exception& error) { + error_message = error.what(); + return SD_STATUS_GENERATION_FAILED; + } +} + +void AsyncJobManager::record_context_job_completion(const SDSvrParams& params) { + const auto now = std::chrono::steady_clock::now(); + if (params.weight_residency_ttl >= 0) + residency_deadline = now + std::chrono::seconds(params.weight_residency_ttl); +} + +static void wait_for_job(ServerRuntime& runtime, std::unique_lock& lock) { + auto& manager = *runtime.async_job_manager; + using Clock = std::chrono::steady_clock; + const auto disabled = Clock::time_point::max(); + while (!manager.stop && manager.queue.empty()) { + const auto deadline = manager.residency_deadline; + if (deadline == disabled || manager.synchronous_jobs != 0) { + manager.cv.wait(lock); + continue; + } + const auto now = Clock::now(); + if (now < deadline) { + manager.cv.wait_until(lock, deadline); + continue; + } + + // Keep job admission serialized with the idle check and the DGL release. + auto* ctx = sd_ctx_get_dgl_ctx(runtime.sd_ctx); + const auto status = sd_dgl_ctx_unload_models(ctx); + if (status == SD_STATUS_BUSY) { + manager.cv.wait_for(lock, std::chrono::milliseconds(100)); + continue; + } + if (status != SD_STATUS_OK) + LOG_WARN("idle weight release failed: %s", sd_dgl_error()); + manager.residency_deadline = disabled; + } +} + void async_job_worker(ServerRuntime& runtime) { AsyncJobManager& manager = *runtime.async_job_manager; @@ -486,7 +809,7 @@ void async_job_worker(ServerRuntime& runtime) { std::shared_ptr job; { std::unique_lock lock(manager.mutex); - manager.cv.wait(lock, [&]() { return manager.stop || !manager.queue.empty(); }); + wait_for_job(runtime, lock); if (manager.stop && manager.queue.empty()) { break; @@ -517,8 +840,10 @@ void async_job_worker(ServerRuntime& runtime) { std::string output_media_mime_type; int output_frame_count = 0; int output_fps = 0; + json dgl_result_info; std::string error_message; - bool ok = false; + const char* error_code = "generation_failed"; + bool ok = false; if (job->kind == AsyncJobKind::ImgGen) { ok = execute_img_gen_job(runtime, *job, output_images, output_info, error_message); @@ -531,12 +856,19 @@ void async_job_worker(ServerRuntime& runtime) { output_fps, output_info, error_message); + } else if (job->kind == AsyncJobKind::Dgl) { + const auto status = execute_dgl_job(runtime, *job, dgl_result_info, error_message); + ok = status == SD_STATUS_OK; + if (status == SD_STATUS_OUT_OF_MEMORY) { + error_code = "out_of_memory"; + } } else { error_message = "unsupported job kind"; } { std::lock_guard lock(manager.mutex); + manager.record_context_job_completion(*runtime.svr_params); auto it = manager.jobs.find(job->id); if (it == manager.jobs.end()) { continue; @@ -556,11 +888,12 @@ void async_job_worker(ServerRuntime& runtime) { job->result_media_mime_type = std::move(output_media_mime_type); job->result_frame_count = output_frame_count; job->result_fps = output_fps; + job->dgl_result_info = std::move(dgl_result_info); job->error_code.clear(); job->error_message.clear(); } else { job->status = AsyncJobStatus::Failed; - job->error_code = "generation_failed"; + job->error_code = error_code; job->error_message = error_message.empty() ? "unknown generation error" : error_message; job->result_images_b64.clear(); job->result_generation_info = nullptr; diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h index a442305606..0f8b932315 100644 --- a/examples/server/async_jobs.h +++ b/examples/server/async_jobs.h @@ -12,11 +12,12 @@ #include -#include "runtime.h" +#include "model_catalog.h" enum class AsyncJobKind { ImgGen, VidGen, + Dgl, }; enum class AsyncJobStatus { @@ -49,8 +50,13 @@ struct AsyncGenerationJob { int64_t created_at = unix_timestamp_now_ms(); int64_t started_at = 0; int64_t completed_at = 0; + std::unique_ptr model; + json request_body; + uint64_t model_revision = 0; ImgGenJobRequest img_gen; VidGenJobRequest vid_gen; + std::string dgl_source; + json dgl_result_info; std::vector result_images_b64; json result_generation_info; std::string result_media_b64; @@ -79,6 +85,11 @@ struct AsyncJobManager { size_t max_pending_jobs = 64; int64_t completed_ttl_seconds = 600; int64_t failed_ttl_seconds = 600; + + size_t synchronous_jobs = 0; + std::chrono::steady_clock::time_point residency_deadline = std::chrono::steady_clock::time_point::max(); + + void record_context_job_completion(const SDSvrParams& params); }; void purge_expired_jobs(AsyncJobManager& manager); @@ -86,6 +97,7 @@ size_t count_pending_jobs(const AsyncJobManager& manager); std::string make_async_job_id(AsyncJobManager& manager); bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job); json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job); +bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message); bool execute_img_gen_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::vector& output_images, diff --git a/examples/server/frontend b/examples/server/frontend index b07665f893..0c27f95a38 160000 --- a/examples/server/frontend +++ b/examples/server/frontend @@ -1 +1 @@ -Subproject commit b07665f893047e7b633bbdb69d97c3a9c594076e +Subproject commit 0c27f95a38c89bb601d6b1f0d70717a63c48a71e diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 391a1ec9ad..432d0cd65a 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -1,11 +1,13 @@ #include #include #include +#include #include #include #include -#include "httplib.h" +// cpp-httplib must include Winsock2 before other headers include windows.h. +#include "server_access.h" #include "async_jobs.h" #include "common/common.h" @@ -39,6 +41,7 @@ static void parse_args(int argc, ctx_params.get_options(), default_gen_params.get_options(), }; + svr_params.add_access_options(options_vec[0], options_vec); if (!parse_options(argc, argv, options_vec)) { print_usage(argv[0], options_vec); @@ -87,16 +90,24 @@ int main(int argc, const char** argv) { LOG_DEBUG("%s", ctx_params.to_string().c_str()); LOG_DEBUG("%s", default_gen_params.to_string().c_str()); + if (!ctx_params.register_rpc_devices()) { + return 1; + } + ctx_params.rpc_servers.reset(); + SDOptPtr sd_ctx_params = ctx_params.to_context_opt(); ServerModels models; - if (!ctx_params.model_path.empty() || !ctx_params.diffusion_model_path.empty()) { - const auto started = std::chrono::steady_clock::now(); - models.context.reset(create_sd_context(sd_ctx_params)); - models.status["load_elapsed_seconds"] = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); + models.context.reset(create_sd_context(sd_ctx_params)); + if (!models.context) { + LOG_ERROR("sd_ctx_create failed: %s", sd_get_last_error()); + return 1; } - - if ((!ctx_params.model_path.empty() || !ctx_params.diffusion_model_path.empty()) && !models.context) { - LOG_ERROR("sd_ctx_create failed"); + try { + configure_server_file_access(models, svr_params, ctx_params); + if (!sd_dgl_ctx_set(sd_ctx_get_dgl_ctx(models.context.get()), "console_progress", "on")) + throw std::runtime_error(sd_dgl_error()); + } catch (const std::exception& error) { + LOG_ERROR("Context setup failed: %s", error.what()); return 1; } @@ -134,24 +145,7 @@ int main(int argc, const char** argv) { std::thread async_worker(async_job_worker, std::ref(runtime)); - httplib::Server svr; - - svr.set_pre_routing_handler([](const httplib::Request& req, httplib::Response& res) { - std::string origin = req.get_header_value("Origin"); - if (origin.empty()) { - origin = "*"; - } - res.set_header("Access-Control-Allow-Origin", origin); - res.set_header("Access-Control-Allow-Credentials", "true"); - res.set_header("Access-Control-Allow-Methods", "*"); - res.set_header("Access-Control-Allow-Headers", "*"); - - if (req.method == "OPTIONS") { - res.status = 204; - return httplib::Server::HandlerResponse::Handled; - } - return httplib::Server::HandlerResponse::Unhandled; - }); + SDHttpServer svr(svr_params); std::string index_html; #ifdef HAVE_INDEX_HTML @@ -160,9 +154,11 @@ int main(int argc, const char** argv) { index_html = "Stable Diffusion Server is running"; #endif register_index_endpoints(svr, svr_params, index_html); + register_media_view_endpoint(svr, svr_params.media_view, models.workspace_file_access.output); register_openai_api_endpoints(svr, runtime); register_sdapi_endpoints(svr, runtime); register_sdcpp_api_endpoints(svr, runtime); + register_dgl_endpoints(svr, runtime); register_model_endpoints(svr, runtime); LOG_INFO("listening on: http://%s:%d\n", svr_params.listen_ip.c_str(), svr_params.listen_port); diff --git a/examples/server/model_catalog.cpp b/examples/server/model_catalog.cpp index 5a538fd529..3697502208 100644 --- a/examples/server/model_catalog.cpp +++ b/examples/server/model_catalog.cpp @@ -66,14 +66,6 @@ static void clear_model_paths(SDContextParams& params) { } } -bool component_paths_match(const SDContextParams& a, const SDContextParams& b) { - for (const auto& slot : k_model_slots) { - if ((a.*slot.field) != (b.*slot.field)) - return false; - } - return true; -} - std::string model_path_key(const fs::path& path) { #ifdef _WIN32 const auto value = path.generic_wstring(); @@ -132,6 +124,56 @@ std::vector get_model_roots(const SDSvrParams& params) { return roots; } +static void add_startup_index_shards(ServerFileAccess& policy, const fs::path& index_path) { + std::error_code error; + if (!fs::is_regular_file(index_path, error) || error) + return; + std::ifstream file(index_path); + const auto index = json::parse(file, nullptr, false); + const auto shards = index.find("weight_map"); + if (shards == index.end() || !shards->is_object()) + return; + const auto root = fs::weakly_canonical(index_path.parent_path()); + for (const auto& entry : *shards) { + if (!entry.is_string()) + continue; + const auto path = fs::weakly_canonical((index_path.parent_path() / fs::u8path(entry.get_ref())).lexically_normal(), error); + if (!error && model_path_inside(root, path)) + policy.configured_files.insert(model_path_key(path)); + } +} + +void add_startup_model_sources(ServerFileAccess& policy, const SDContextParams& config) { + for (const auto& slot : k_model_slots) { + const auto& source = config.*slot.field; + if (source.empty() || slot.field == &SDContextParams::tokenizer) + continue; + const auto path = fs::absolute(fs::u8path(source)); + const auto resolved = fs::weakly_canonical(path); + policy.configured_files.insert(model_path_key(resolved)); + if (fs::is_directory(resolved)) + policy.model_bundles.push_back(resolved); + else if (path.extension() == ".json") + add_startup_index_shards(policy, path); + } + + auto add_tokenizer = [&](const std::string& path) { + if (!path.empty()) + policy.configured_files.insert(model_path_key(fs::weakly_canonical(fs::absolute(fs::u8path(path))))); + }; + if (config.tokenizer.find('=') == std::string::npos) { + add_tokenizer(config.tokenizer); + } else { + std::istringstream assignments(config.tokenizer); + std::string assignment; + while (std::getline(assignments, assignment, ',')) { + const auto equal = assignment.find('='); + if (equal != std::string::npos) + add_tokenizer(assignment.substr(equal + 1)); + } + } +} + std::vector model_category_directories(const ModelRoot& root, const std::string& category) { std::vector directories; if (!fs::exists(root.path)) @@ -370,29 +412,28 @@ json resolve_recipe_features(const json& recipe) { features[name.get()] = true; for (const auto& name : recipe.value("disabled_features", json::array())) features[name.get()] = false; + for (const char* name : {"ip_adapter", "slg", "shifted_timestep"}) + features[name] = false; return features; } json model_generation_features(const ServerRuntime& runtime) { - if (!runtime.sd_ctx || runtime.models->active_recipe.is_null()) { - json features = k_recipe_features; - for (auto& feature : features) - feature = false; + const auto& recipe = runtime.models->current_recipe; + if (!recipe.is_null()) { + auto features = recipe.at("effective_features"); + const auto& context = *runtime.ctx_params; + features["high_noise"] = features.at("high_noise").get() && !context.high_noise_diffusion_model_path.empty(); + if (recipe.value("source", "") != "command_line") { + features["controlnet"] = features.at("controlnet").get() && !context.control_net_path.empty(); + features["preview_tae"] = features.at("preview_tae").get() && !context.taesd_path.empty(); + features["ref_audios"] = features.at("ref_audios").get() && (!context.audio_vae_path.empty() || !context.audio_encoder_path.empty()); + features["ref_video_audios"] = features.at("ref_video_audios").get() && !context.audio_vae_path.empty(); + } return features; } - json features = resolve_recipe_features(runtime.models->active_recipe); - if (runtime.models->active_recipe.value("source", "") == "command_line") - return features; - // Optional components only become usable once selected and loaded. - features["ip_adapter"] = features.value("ip_adapter", false) && !runtime.ctx_params->ip_adapter_path.empty(); - features["controlnet"] = features.value("controlnet", false) && !runtime.ctx_params->control_net_path.empty(); - features["high_noise"] = features.value("high_noise", false) && !runtime.ctx_params->high_noise_diffusion_model_path.empty(); - features["preview_tae"] = features.value("preview_tae", false) && !runtime.ctx_params->taesd_path.empty(); - features["ref_audios"] = features.value("ref_audios", false) && - (!runtime.ctx_params->audio_vae_path.empty() || !runtime.ctx_params->audio_encoder_path.empty()); - features["ref_video_audios"] = features.value("ref_video_audios", false) && !runtime.ctx_params->audio_vae_path.empty(); - if (!runtime.ctx_params->pulid_weights_path.empty()) - features["slg"] = false; + json features = k_recipe_features; + for (auto& feature : features) + feature = false; return features; } @@ -637,12 +678,21 @@ void refresh_model_catalog(ServerRuntime& runtime) { models.catalog_errors = std::move(errors); } -json model_status(ServerRuntime& runtime) { - std::lock_guard lock(runtime.models->status_mutex); - auto& models = *runtime.models; - json status = models.status; - if (status["state"] == "loading" && !status["load_elapsed_seconds"].is_null()) { - status["load_elapsed_seconds"] = std::chrono::duration(std::chrono::steady_clock::now() - models.load_started_at).count(); +json model_status(const ServerRuntime& runtime) { + const auto& models = *runtime.models; + const auto& recipe = models.current_recipe; + const bool startup = !recipe.is_null() && recipe.value("source", "") == "command_line"; + json status = {{"state", recipe.is_null() ? "empty" : "configured"}, + {"recipe", recipe.is_null() || startup ? json(nullptr) : recipe.at("id")}, + {"models", models.current_files}, + {"error", nullptr}, + {"revision", models.revision}}; + if (startup) + status["origin"] = "command_line"; + if (!recipe.is_null()) { + status["runtime_recipe"] = {{"id", "@current"}, {"name", "Current server model"}, {"source", "current"}, {"size_multiple", recipe.value("size_multiple", 8)}, {"slots", json::array()}}; + if (recipe.contains("video_constraints")) + status["runtime_recipe"]["video_constraints"] = recipe.at("video_constraints"); } return status; } @@ -652,29 +702,26 @@ void initialize_server_models(ServerRuntime& runtime) { models.base_context = *runtime.ctx_params; clear_model_paths(models.base_context); models.base_defaults = *runtime.default_gen_params; - if (runtime.sd_ctx) { - models.status["state"] = "ready"; - models.status["origin"] = "command_line"; - json features = json::array(); + if (has_current_model(runtime)) { + json features = json::array(); for (const auto& feature : k_recipe_features) features.push_back(feature.first); - models.active_recipe = { + models.current_recipe = { {"id", "@command-line"}, {"name", "Command-line model (all features)"}, {"source", "command_line"}, - {"description", "Uses the loaded command-line model and its generation defaults."}, + {"description", "Uses the model and generation defaults specified on the command line."}, {"slots", json::array()}, {"defaults", json::object()}, {"size_multiple", 8}, {"features", features}, }; - models.active_recipe["effective_features"] = resolve_recipe_features(models.active_recipe); - models.status["runtime_recipe"] = models.active_recipe; + models.current_recipe["effective_features"] = resolve_recipe_features(models.current_recipe); } refresh_model_catalog(runtime); } -void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& context, SDGenerationParams& defaults, json* loaded_recipe) { +ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body, SDMode mode) { check_keys(body, {"recipe", "models"}); const auto recipe_id = body.at("recipe").get(); // `models` is optional; unselected slots may fall back to recipe defaults below. @@ -686,13 +733,14 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con const auto found = models.recipes.find(recipe_id); if (found == models.recipes.end()) throw std::runtime_error("unknown recipe"); - const auto& recipe = found->second; - if (loaded_recipe) - *loaded_recipe = recipe; - context = models.base_context; - defaults = models.base_defaults; + const auto& recipe = found->second; + const auto recipe_defaults = recipe.value("defaults", json::object()); + if (mode == VID_GEN && !recipe_defaults.contains("video_frames")) + throw std::runtime_error("selected recipe does not support vid_gen: " + recipe_id); + auto context = models.base_context; + auto defaults = models.base_defaults; apply_recipe_context(recipe.value("context", json::object()), context); - apply_recipe_defaults(recipe.value("defaults", json::object()), defaults); + apply_recipe_defaults(recipe_defaults, defaults); // Recipe-provided default models fill any slot the request did not select. // An explicit selection blocks the default for that slot, including an // empty string (a deliberate opt-out of the default). The tae/taesd pair @@ -718,8 +766,7 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con if (selection.contains(id)) throw std::runtime_error("specify only one of tae and taesd"); selection[id] = selection.at(alias); - // Keep only the declared spelling: equivalent loads must resolve - // to an identical selection for the idempotent-load comparison. + // Normalize the alias so the same selection reuses the current configuration. selection.erase(alias); } } @@ -744,20 +791,6 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con if (!allowed.count(it.key())) throw std::runtime_error("unknown model slot: " + it.key()); } - // Omitting an optional slot and sending it as an empty string resolve to - // the same context; drop the empty key so equivalent loads compare - // identically instead of rebuilding the context. The explicit empty - // string already overrode any recipe default during the merge, so its - // intent is preserved. - for (auto it = selection.begin(); it != selection.end();) { - if (!it->is_string() || !it->get().empty()) { - ++it; - continue; - } - it = selection.erase(it); - } - // Echo the fully resolved selection (recipe defaults merged in) for status reporting. - body["models"] = selection; for (const auto& group : recipe.value("required_any", json::array())) { if (std::none_of(group.begin(), group.end(), [&](const json& value) { return !selection.value(value.get(), std::string()).empty(); @@ -765,6 +798,41 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con throw std::runtime_error("select at least one model from: " + group.dump()); } } - if (!context.resolve_and_validate(IMG_GEN)) + if (!context.resolve(IMG_GEN)) throw std::runtime_error("invalid model context parameters"); + auto options = context.to_context_opt(); + if (!options) + throw std::runtime_error(sd_get_last_error()); + for (auto it = selection.begin(); it != selection.end();) { + if (it.value() == "") + it = selection.erase(it); + else + ++it; + } + return {std::move(context), std::move(defaults), recipe, std::move(selection), std::move(options)}; +} + +bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, SDMode mode, std::string& error_message) { + auto& models = *runtime.models; + std::unique_lock lock(models.model_mutex); + if (models.current_recipe == selection.recipe && models.current_files == selection.files && + std::all_of(std::begin(k_model_slots), std::end(k_model_slots), [&](const ModelSlot& slot) { + return runtime.ctx_params->*slot.field == selection.context.*slot.field; + })) { + if (runtime_supports_generation_mode(runtime, mode)) + return true; + error_message = unsupported_generation_mode_error(mode); + return false; + } + const auto kind = mode == VID_GEN ? SD_RESULT_VIDEO : SD_RESULT_IMAGE; + if (sd_ctx_set_model_options_for_generation(runtime.sd_ctx, selection.options.get(), kind) != SD_STATUS_OK) { + error_message = sd_get_last_error(); + return false; + } + *runtime.ctx_params = std::move(selection.context); + *runtime.default_gen_params = std::move(selection.defaults); + models.current_recipe = std::move(selection.recipe); + models.current_files = std::move(selection.files); + ++models.revision; + return true; } diff --git a/examples/server/model_catalog.h b/examples/server/model_catalog.h index 2e45fd183f..934b246796 100644 --- a/examples/server/model_catalog.h +++ b/examples/server/model_catalog.h @@ -1,9 +1,9 @@ #ifndef __SD_EXAMPLES_SERVER_MODEL_CATALOG_H__ #define __SD_EXAMPLES_SERVER_MODEL_CATALOG_H__ -#include #include #include +#include #include #include @@ -29,36 +29,47 @@ ModelRoot make_model_root(const std::filesystem::path& path, bool primary); std::vector get_model_roots(const SDSvrParams& params); std::vector model_category_directories(const ModelRoot& root, const std::string& category); +struct ServerFileAccess { + std::vector models; + std::filesystem::path output; + std::vector model_bundles; + std::set configured_files; +}; + struct ServerModels { - std::shared_mutex runtime_mutex; + std::shared_mutex model_mutex; std::mutex catalog_mutex; - std::mutex status_mutex; + ServerFileAccess file_access; + ServerFileAccess workspace_file_access; SDCtxPtr context; SDContextParams base_context; SDGenerationParams base_defaults; std::map recipes; std::map files; - std::chrono::steady_clock::time_point load_started_at; - json active_recipe = nullptr; + json current_recipe = nullptr; + json current_files = json::object(); + uint64_t revision = 0; json catalog_errors = json::array(); - json status = {{"state", "empty"}, {"recipe", nullptr}, {"models", json::object()}, {"error", nullptr}, {"load_elapsed_seconds", nullptr}}; +}; + +struct ServerModelSelection { + SDContextParams context; + SDGenerationParams defaults; + json recipe; + json files; + SDOptPtr options; }; void refresh_model_catalog(ServerRuntime& runtime); -json model_status(ServerRuntime& runtime); +json model_status(const ServerRuntime& runtime); void initialize_server_models(ServerRuntime& runtime); json resolve_recipe_features(const json& recipe); json model_generation_features(const ServerRuntime& runtime); -// Resolves the load request into context/generation params. `body` is updated -// so `models` reflects the fully resolved selection (recipe defaults merged in), -// letting the caller report exactly which components got loaded. -void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& context, SDGenerationParams& defaults, json* loaded_recipe = nullptr); - -// True when both parameter sets resolve to the same component files. File IDs -// stay stable if a model directory symlink is retargeted inside the configured -// root, so the idempotent-load check compares the resolved paths too. -bool component_paths_match(const SDContextParams& a, const SDContextParams& b); +ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body, SDMode mode); +// The caller holds the generation mutex across the switch and generation. +bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, SDMode mode, std::string& error_message); +void add_startup_model_sources(ServerFileAccess& policy, const SDContextParams& config); #endif diff --git a/examples/server/recipes/README.md b/examples/server/recipes/README.md index 9405fdb357..6f2c744e6d 100644 --- a/examples/server/recipes/README.md +++ b/examples/server/recipes/README.md @@ -81,11 +81,11 @@ for supported fields. ## Output dimension alignment Set `size_multiple` when the runtime's output dimension alignment differs from -the default of `8`. Match `GenerationRequest::align_image_size` in -[`src/pipeline/request.cpp`](../../../src/pipeline/request.cpp): the VAE scale +the default of `8`. Match the aligned dimensions in +[`generation_program.cpp`](../../../src/api/generation_program.cpp): the VAE scale factor multiplied by the model definition's `diffusion_down_factor`. The scale comes from [`VAE::get_scale_factor`](../../../src/model/vae/vae.hpp), with the -PiD override in [`diffusion_engine.cpp`](../../../src/pipeline/diffusion_engine.cpp); +PiD override in [`geometry.hpp`](../../../src/model/vae/geometry.hpp); model geometry is defined under [`src/model/integrations`](../../../src/model/integrations/). Use the runtime's output alignment, not the nominal patch size: some models pad @@ -96,13 +96,12 @@ applies. Reference-image preprocessing constraints are independent of this field ## Video length constraints -Video recipes declare `video_constraints` to match `align_video_frames` in -[`diffusion_engine.cpp`](../../../src/pipeline/diffusion_engine.cpp) and the FPS -and AnimateDiff overrides in -[`request.cpp`](../../../src/pipeline/request.cpp). Wan, HunyuanVideo and LingBot -round down to `4n + 1`; LTX rounds down to `8n + 1`. MiniMax-H3 rounds up to -`17n + 5`, with at least 5 frames and fixed 24 FPS. AnimateDiff accepts whole -frames up to 32. Wan 2.2 S2V fixes FPS at 16. +Video recipes declare `video_constraints` to match `aligned_frames` in +[`geometry.hpp`](../../../src/model/vae/geometry.hpp) and the FPS policy in +[`generation_program.cpp`](../../../src/api/generation_program.cpp). Wan, HunyuanVideo and LingBot +round up to `4n + 1`; LTX rounds up to `8n + 1`. MiniMax-H3 rounds up to +`17n + 5`, with at least 5 frames and fixed 24 FPS. AnimateDiff requires an +explicit DGL workflow. Wan 2.2 S2V fixes FPS at 16. Declare fixed FPS only where the runtime enforces it; recommended FPS belongs in `defaults.fps`. These constraints guide UI conversion and estimates, not diff --git a/examples/server/recipes/anima-edit.json b/examples/server/recipes/anima-edit.json index f22c1b6ccc..6918b972be 100644 --- a/examples/server/recipes/anima-edit.json +++ b/examples/server/recipes/anima-edit.json @@ -2,7 +2,7 @@ "schema_version": 1, "id": "anima-edit", "name": "Anima Edit (LoRA)", - "description": "Requires a matching community editing LoRA. Apply it after loading and supply reference images; uses the cosmos_reference preset.", + "description": "Select a matching community editing LoRA separately and supply reference images. References are VAE-encoded for diffusion conditioning; the recipe does not load the LoRA automatically.", "model_url": "https://huggingface.co/circlestone-labs/Anima", "slots": [ { diff --git a/examples/server/recipes/animatediff-sd15.json b/examples/server/recipes/animatediff-sd15.json deleted file mode 100644 index e7bf07d3a8..0000000000 --- a/examples/server/recipes/animatediff-sd15.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "schema_version": 1, - "id": "animatediff-sd15", - "name": "AnimateDiff SD 1.5", - "size_multiple": 64, - "description": "Use Video Generation with an SD 1.5 checkpoint and compatible motion module.", - "model_url": "https://huggingface.co/guoyww/animatediff", - "slots": [ - { - "id": "model", - "required": true - }, - { - "id": "motion_module", - "required": true - }, - { - "id": "vae", - "required": false - }, - { - "id": "tae", - "required": false - } - ], - "video_constraints": { - "frame_step": 1, - "frame_offset": 0, - "frame_rounding": "floor", - "min_frames": 1, - "max_frames": 32 - }, - "defaults": { - "sampling_method": "euler", - "video_frames": 8, - "fps": 8, - "cfg_scale": 7.5, - "steps": 20, - "width": 512, - "height": 512 - }, - "features": [ - "cache_unet", - "clip_skip", - "init_image" - ], - "disabled_features": [ - "cache_dit", - "img2img", - "mask_image" - ] -} diff --git a/examples/server/recipes/defaults.md b/examples/server/recipes/defaults.md index fdccc96a9c..47434e6aa3 100644 --- a/examples/server/recipes/defaults.md +++ b/examples/server/recipes/defaults.md @@ -75,7 +75,6 @@ For community edit adapters and other optional extensions, these are the base-mo | `moss-image-base` | 3 | 20 | 1024 × 1024 | [Source](https://huggingface.co/OpenMOSS-Team/MOSS-Image-Base) | | `moss-image-sft` | 3 | 20 | 1024 × 1024 | [Source](https://huggingface.co/OpenMOSS-Team/MOSS-Image-SFT) | | `p-h3-image` | 1 | 8 | 1024 × 1024 | [Runtime guide](../../../docs/models/p_h3_image.md) Fixed P-H3 sigma schedule; upstream 2912 × 2912 reduced to the catalog default. | -| `nitrosd-realism` | 1 | 1 | 1024 × 1024 | [Source](https://huggingface.co/ChenDY/NitroFusion) | | `ovis-image` | 5 | 20 | 1024 × 1024 | [Source](https://huggingface.co/ATH-MaaS/Ovis-Image-7B) | | `pid` | 1 | 4 | 2048 × 2048 | [Source](https://huggingface.co/nvidia/PiD) Standalone PiD decoding at 2K; guidance is handled by the upstream generator. | | `pid-15` | 1 | 4 | 2048 × 2048 | [Source](https://huggingface.co/nvidia/PiD) Standalone PiD decoding at 2K; guidance is handled by the upstream generator. | diff --git a/examples/server/recipes/flux1-pulid.json b/examples/server/recipes/flux1-pulid.json deleted file mode 100644 index 8203dd1b53..0000000000 --- a/examples/server/recipes/flux1-pulid.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "schema_version": 1, - "id": "flux1-pulid", - "name": "FLUX.1 dev PuLID", - "description": "Supply a precomputed PuLID identity embedding with the generation request.", - "model_url": "https://huggingface.co/guozinan/PuLID", - "slots": [ - { - "id": "diffusion_model", - "required": true - }, - { - "id": "clip_l", - "required": true - }, - { - "id": "t5xxl", - "required": true - }, - { - "id": "pulid_weights", - "required": true - }, - { - "id": "vae", - "required": false - }, - { - "id": "tae", - "required": false - } - ], - "required_any": [ - [ - "vae", - "tae" - ] - ], - "defaults": { - "sampling_method": "euler", - "cfg_scale": 1, - "steps": 20, - "width": 1024, - "height": 1024, - "distilled_guidance": 3.5 - }, - "features": [ - "clip_skip", - "distilled_guidance", - "flow_shift", - "slg" - ], - "disabled_features": [ - "slg" - ] -} diff --git a/examples/server/recipes/hunyuan-video-15-i2v.json b/examples/server/recipes/hunyuan-video-15-i2v.json index 5dc0509f91..8fd1e34dad 100644 --- a/examples/server/recipes/hunyuan-video-15-i2v.json +++ b/examples/server/recipes/hunyuan-video-15-i2v.json @@ -40,7 +40,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/hunyuan-video-15-t2v.json b/examples/server/recipes/hunyuan-video-15-t2v.json index 81aaceee64..d7a69f735c 100644 --- a/examples/server/recipes/hunyuan-video-15-t2v.json +++ b/examples/server/recipes/hunyuan-video-15-t2v.json @@ -40,7 +40,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/krea2-raw-edit.json b/examples/server/recipes/krea2-raw-edit.json index 8d3eb9c7b8..80a61cb724 100644 --- a/examples/server/recipes/krea2-raw-edit.json +++ b/examples/server/recipes/krea2-raw-edit.json @@ -2,7 +2,7 @@ "schema_version": 1, "id": "krea2-raw-edit", "name": "Krea 2 Raw Edit (LoRA)", - "description": "Requires a matching Ostris-compatible community editing LoRA. Apply it after loading and supply reference images; uses the krea2_ostris_edit preset. Select a separate vision projector when it is not bundled in the text encoder.", + "description": "Select a matching Ostris-compatible community editing LoRA separately and supply reference images. References go through both the vision encoder and VAE; the recipe does not load the LoRA automatically. Select a separate vision projector when it is not bundled in the text encoder.", "model_url": "https://huggingface.co/krea/Krea-2-Raw", "slots": [ { diff --git a/examples/server/recipes/krea2-turbo-edit.json b/examples/server/recipes/krea2-turbo-edit.json index e8c521d354..f26eb97f37 100644 --- a/examples/server/recipes/krea2-turbo-edit.json +++ b/examples/server/recipes/krea2-turbo-edit.json @@ -2,7 +2,7 @@ "schema_version": 1, "id": "krea2-turbo-edit", "name": "Krea 2 Turbo Edit (LoRA)", - "description": "Requires a matching Ostris-compatible community editing LoRA. Apply it after loading and supply reference images; uses the krea2_ostris_edit preset. Select a separate vision projector when it is not bundled in the text encoder.", + "description": "Select a matching Ostris-compatible community editing LoRA separately and supply reference images. References go through both the vision encoder and VAE; the recipe does not load the LoRA automatically. Select a separate vision projector when it is not bundled in the text encoder.", "model_url": "https://huggingface.co/krea/Krea-2-Turbo", "slots": [ { diff --git a/examples/server/recipes/lingbot-video-dense.json b/examples/server/recipes/lingbot-video-dense.json index 3affb48516..5fbb208dd8 100644 --- a/examples/server/recipes/lingbot-video-dense.json +++ b/examples/server/recipes/lingbot-video-dense.json @@ -34,7 +34,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/lingbot-video-moe.json b/examples/server/recipes/lingbot-video-moe.json index 55bf59f0e3..10f65d8a73 100644 --- a/examples/server/recipes/lingbot-video-moe.json +++ b/examples/server/recipes/lingbot-video-moe.json @@ -34,7 +34,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/ltx23-dev.json b/examples/server/recipes/ltx23-dev.json index f0bf3f2883..d18854a62f 100644 --- a/examples/server/recipes/ltx23-dev.json +++ b/examples/server/recipes/ltx23-dev.json @@ -43,7 +43,7 @@ "video_constraints": { "frame_step": 8, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/ltx23-distilled.json b/examples/server/recipes/ltx23-distilled.json index 3e4d08e9db..d512a1cdbc 100644 --- a/examples/server/recipes/ltx23-distilled.json +++ b/examples/server/recipes/ltx23-distilled.json @@ -43,7 +43,7 @@ "video_constraints": { "frame_step": 8, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/ltx25-dev.json b/examples/server/recipes/ltx25-dev.json index 011a49edaa..ce14efc047 100644 --- a/examples/server/recipes/ltx25-dev.json +++ b/examples/server/recipes/ltx25-dev.json @@ -39,7 +39,7 @@ "video_constraints": { "frame_step": 8, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/nitrosd-realism.json b/examples/server/recipes/nitrosd-realism.json deleted file mode 100644 index ae7345db72..0000000000 --- a/examples/server/recipes/nitrosd-realism.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "schema_version": 1, - "id": "nitrosd-realism", - "name": "NitroSD Realism", - "size_multiple": 64, - "model_url": "https://huggingface.co/ChenDY/NitroFusion", - "slots": [ - { - "id": "model", - "required": true - }, - { - "id": "vae", - "required": false - }, - { - "id": "tae", - "required": false - } - ], - "defaults": { - "scheduler": "sgm_uniform", - "shifted_timestep": 250, - "cfg_scale": 1, - "steps": 1, - "width": 1024, - "height": 1024 - }, - "features": [ - "cache_unet", - "clip_skip", - "shifted_timestep" - ], - "disabled_features": [ - "cache_dit" - ] -} diff --git a/examples/server/recipes/sd1-ip-adapter.json b/examples/server/recipes/sd1-ip-adapter.json deleted file mode 100644 index 7e14c15668..0000000000 --- a/examples/server/recipes/sd1-ip-adapter.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "schema_version": 1, - "id": "sd1-ip-adapter", - "name": "SD 1.5 IP-Adapter / Plus", - "size_multiple": 64, - "description": "Select matching SD 1.5 IP-Adapter or Plus weights and CLIP Vision H, then supply an IP-Adapter image.", - "model_url": "https://huggingface.co/h94/IP-Adapter", - "slots": [ - { - "id": "model", - "required": true - }, - { - "id": "clip_vision", - "required": true, - "label": "CLIP Vision H" - }, - { - "id": "ip_adapter", - "required": true - }, - { - "id": "vae", - "required": false - }, - { - "id": "tae", - "required": false - } - ], - "defaults": { - "cfg_scale": 7.5, - "steps": 20, - "width": 512, - "height": 512 - }, - "features": [ - "cache_unet", - "clip_skip" - ], - "disabled_features": [ - "cache_dit" - ] -} diff --git a/examples/server/recipes/sdxl-ip-adapter.json b/examples/server/recipes/sdxl-ip-adapter.json deleted file mode 100644 index f0bc8cdafb..0000000000 --- a/examples/server/recipes/sdxl-ip-adapter.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "schema_version": 1, - "id": "sdxl-ip-adapter", - "name": "SDXL IP-Adapter / Plus", - "size_multiple": 64, - "description": "Select matching SDXL ViT-H IP-Adapter or Plus weights and CLIP Vision H, then supply an IP-Adapter image.", - "model_url": "https://huggingface.co/h94/IP-Adapter", - "slots": [ - { - "id": "model", - "required": true - }, - { - "id": "clip_vision", - "required": true, - "label": "CLIP Vision H" - }, - { - "id": "ip_adapter", - "required": true - }, - { - "id": "vae", - "required": false - }, - { - "id": "tae", - "required": false - } - ], - "defaults": { - "scheduler": "discrete", - "sampling_method": "dpm++2m", - "cfg_scale": 5, - "steps": 20, - "width": 1024, - "height": 1024 - }, - "features": [ - "cache_unet", - "clip_skip", - "shifted_timestep" - ], - "disabled_features": [ - "cache_dit" - ] -} diff --git a/examples/server/recipes/sdxl-photomaker.json b/examples/server/recipes/sdxl-photomaker.json deleted file mode 100644 index c8b5790256..0000000000 --- a/examples/server/recipes/sdxl-photomaker.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "schema_version": 1, - "id": "sdxl-photomaker", - "name": "SDXL PhotoMaker", - "size_multiple": 64, - "description": "Select PhotoMaker v1 and supply identity images. Include the img trigger in the prompt.", - "model_url": "https://huggingface.co/TencentARC/PhotoMaker", - "slots": [ - { - "id": "model", - "required": true - }, - { - "id": "photo_maker", - "required": true - }, - { - "id": "vae", - "required": false - }, - { - "id": "tae", - "required": false - } - ], - "defaults": { - "width": 1024, - "height": 1024 - }, - "features": [ - "cache_unet", - "clip_skip", - "shifted_timestep" - ], - "disabled_features": [ - "cache_dit" - ] -} diff --git a/examples/server/recipes/wan21-flf2v.json b/examples/server/recipes/wan21-flf2v.json index 6bb4c33d62..23c4201db0 100644 --- a/examples/server/recipes/wan21-flf2v.json +++ b/examples/server/recipes/wan21-flf2v.json @@ -39,7 +39,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/wan21-i2v.json b/examples/server/recipes/wan21-i2v.json index 32d5fc7ace..88b3597356 100644 --- a/examples/server/recipes/wan21-i2v.json +++ b/examples/server/recipes/wan21-i2v.json @@ -39,7 +39,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/wan21-t2v.json b/examples/server/recipes/wan21-t2v.json index 998078cb07..81a487a205 100644 --- a/examples/server/recipes/wan21-t2v.json +++ b/examples/server/recipes/wan21-t2v.json @@ -34,7 +34,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/wan21-vace.json b/examples/server/recipes/wan21-vace.json index d7f834380b..3321752ed8 100644 --- a/examples/server/recipes/wan21-vace.json +++ b/examples/server/recipes/wan21-vace.json @@ -34,7 +34,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/recipes/wan22-i2v.json b/examples/server/recipes/wan22-i2v.json index c7ab2ed8db..82ab7e8f0c 100644 --- a/examples/server/recipes/wan22-i2v.json +++ b/examples/server/recipes/wan22-i2v.json @@ -39,7 +39,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { @@ -48,9 +48,6 @@ "fps": 16, "flow_shift": 5, "high_noise_steps": -1, - "high_noise_cfg_scale": 3.5, - "high_noise_sampling_method": "euler", - "high_noise_flow_shift": 5, "cfg_scale": 3.5, "steps": 20, "width": 1280, diff --git a/examples/server/recipes/wan22-s2v.json b/examples/server/recipes/wan22-s2v.json index 641ed6e59c..fd43061be5 100644 --- a/examples/server/recipes/wan22-s2v.json +++ b/examples/server/recipes/wan22-s2v.json @@ -39,7 +39,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1, "fixed_fps": 16 }, diff --git a/examples/server/recipes/wan22-t2v.json b/examples/server/recipes/wan22-t2v.json index fba962fcb2..9f7fc956f3 100644 --- a/examples/server/recipes/wan22-t2v.json +++ b/examples/server/recipes/wan22-t2v.json @@ -39,7 +39,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { @@ -48,9 +48,6 @@ "fps": 16, "flow_shift": 12, "high_noise_steps": -1, - "high_noise_cfg_scale": 4, - "high_noise_sampling_method": "euler", - "high_noise_flow_shift": 12, "cfg_scale": 3, "steps": 20, "width": 1280, diff --git a/examples/server/recipes/wan22-ti2v-5b.json b/examples/server/recipes/wan22-ti2v-5b.json index bc433611a6..4bcd9f0ac8 100644 --- a/examples/server/recipes/wan22-ti2v-5b.json +++ b/examples/server/recipes/wan22-ti2v-5b.json @@ -34,7 +34,7 @@ "video_constraints": { "frame_step": 4, "frame_offset": 1, - "frame_rounding": "floor", + "frame_rounding": "ceil", "min_frames": 1 }, "defaults": { diff --git a/examples/server/routes.h b/examples/server/routes.h index f77939184e..01c8de18ec 100644 --- a/examples/server/routes.h +++ b/examples/server/routes.h @@ -6,9 +6,11 @@ #include "runtime.h" void register_index_endpoints(httplib::Server& svr, const SDSvrParams& svr_params, const std::string& index_html); +void register_media_view_endpoint(httplib::Server& svr, bool enabled, const std::filesystem::path& output_root); void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt); void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt); void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt); +void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& rt); void register_model_endpoints(httplib::Server& svr, ServerRuntime& rt); class RuntimeRoutes { diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp new file mode 100644 index 0000000000..1b7e1d6f8a --- /dev/null +++ b/examples/server/routes_dgl.cpp @@ -0,0 +1,188 @@ +#include "routes.h" + +#include +#include +#include +#include + +#include "async_jobs.h" + +namespace { + namespace fs = std::filesystem; + using Request = httplib::Request; + using Response = httplib::Response; + + struct DglWorkspace { + fs::path directory; + std::mutex mutex; + + explicit DglWorkspace(const std::string& path) : directory(fs::u8path(path)) {} + }; + + void send_json(Response& res, int status, const json& body) { + res.status = status; + res.set_content(body.dump(), "application/json"); + } + + void send_error(Response& res, int status, const std::string& message) { + res.status = status; + res.set_content(json({{"error", message}}).dump(-1, ' ', false, json::error_handler_t::replace), "application/json"); + } + + httplib::Server::Handler with_dgl_errors(httplib::Server::Handler handler) { + return [handler = std::move(handler)](const Request& req, Response& res) { + res.set_header("Cache-Control", "no-store"); + if (req.method == "POST") { + const auto content_type = req.get_header_value("Content-Type"); + if (content_type.substr(0, content_type.find(';')) != "application/json") { + send_error(res, 415, "DGL requests require application/json"); + return; + } + } + try { + handler(req, res); + } catch (const json::exception&) { + send_error(res, 400, "Expected valid UTF-8 JSON or script text"); + } catch (const std::exception& error) { + send_error(res, 500, error.what()); + } + }; + } + + bool valid_script_name(const std::string& name) { + return name.size() > std::string_view(".dgl").size() && name.find_first_of("/\\:*?\"<>|") == std::string::npos && + std::none_of(name.begin(), name.end(), [](unsigned char c) { return c < 32; }) && + fs::u8path(name).extension() == ".dgl"; + } + + bool valid_source(const std::string& source) { + return source.find('\0') == std::string::npos; + } + + std::string read_script(const fs::path& path) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + const auto length = file.tellg(); + if (length < 0) + throw std::runtime_error("Could not open script"); + if (static_cast(length) > std::string{}.max_size()) + throw std::runtime_error("Script is too large to read"); + std::string source(static_cast(length), '\0'); + file.seekg(0); + if (!file.read(source.data(), length) || file.peek() != std::char_traits::eof()) + throw std::runtime_error("Script changed while reading"); + if (!valid_source(source)) + throw std::runtime_error("Script must contain UTF-8 text"); + return source; + } + + void save_script(const fs::path& path, const std::string& source) { + const auto prefix = ".dgl-save-" + std::to_string(unix_timestamp_now_ms()) + "-"; + fs::path staging; + for (size_t i = 0; staging.empty(); ++i) { + auto candidate = path.parent_path() / (prefix + std::to_string(i)); + if (fs::create_directory(candidate)) + staging = std::move(candidate); + } + const auto temporary = staging / "script"; + try { + std::ofstream file(temporary, std::ios::binary); + file.write(source.data(), static_cast(source.size())); + file.close(); + if (!file) + throw std::runtime_error("Could not write script"); + fs::rename(temporary, path); + } catch (...) { + std::error_code ignored; + fs::remove(temporary, ignored); + fs::remove(staging, ignored); + throw; + } + std::error_code ignored; + fs::remove(staging, ignored); + } +} + +void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { + auto workspace = std::make_shared(runtime.svr_params->dgl_dir); + svr.Get("/sdcpp/v1/dgl/scripts", with_dgl_errors([workspace](const Request&, Response& res) { + std::lock_guard lock(workspace->mutex); + std::vector names; + if (fs::exists(workspace->directory)) { + for (const auto& entry : fs::directory_iterator(workspace->directory)) { + auto name = entry.path().filename().u8string(); + if (valid_script_name(name) && fs::is_regular_file(entry.symlink_status())) + names.push_back(std::move(name)); + } + } + std::sort(names.begin(), names.end()); + send_json(res, 200, {{"directory", workspace->directory.generic_u8string()}, {"scripts", names}}); + })); + + svr.Get("/sdcpp/v1/dgl/script", with_dgl_errors([workspace](const Request& req, Response& res) { + const auto name = req.get_param_value("name"); + if (!valid_script_name(name)) { + send_error(res, 400, "Expected a .dgl file name"); + return; + } + std::lock_guard lock(workspace->mutex); + const auto path = workspace->directory / fs::u8path(name); + if (!fs::is_regular_file(fs::symlink_status(path))) { + send_error(res, 404, "Script not found"); + return; + } + send_json(res, 200, {{"source", read_script(path)}}); + })); + + svr.Post("/sdcpp/v1/dgl/script", with_dgl_errors([workspace](const Request& req, Response& res) { + const auto body = json::parse(req.body); + const auto name = body.at("name").get(); + const auto source = body.at("source").get(); + if (!valid_script_name(name) || !valid_source(source)) { + send_error(res, 400, "Expected a .dgl file name and UTF-8 source"); + return; + } + const bool updating = body.contains("previous_source"); + std::lock_guard lock(workspace->mutex); + const auto path = workspace->directory / fs::u8path(name); + const auto status = fs::symlink_status(path); + if (updating) { + if (!fs::is_regular_file(status) || read_script(path) != body.at("previous_source").get()) { + send_error(res, 409, "The script changed on disk. Reopen it or save with a new name."); + return; + } + } else if (fs::exists(status)) { + send_error(res, 409, "A file with that name already exists"); + return; + } + fs::create_directories(workspace->directory); + save_script(path, source); + send_json(res, updating ? 200 : 201, {{"name", name}}); + })); + + svr.Post("/sdcpp/v1/dgl/jobs", with_dgl_errors([&runtime](const Request& req, Response& res) { + auto source = json::parse(req.body).at("source").get(); + if (source.empty() || !valid_source(source)) { + send_error(res, 400, "Expected non-empty UTF-8 source"); + return; + } + auto job = std::make_shared(); + job->kind = AsyncJobKind::Dgl; + job->dgl_source = std::move(source); + auto& manager = *runtime.async_job_manager; + { + std::lock_guard lock(manager.mutex); + purge_expired_jobs(manager); + if (count_pending_jobs(manager) >= manager.max_pending_jobs) { + send_error(res, 429, "Job queue is full"); + return; + } + job->id = make_async_job_id(manager); + manager.jobs.emplace(job->id, job); + manager.queue.push_back(job->id); + auto response = make_async_job_json(manager, *job); + response["poll_url"] = "/sdcpp/v1/jobs/" + job->id; + send_json(res, 202, response); + } + manager.cv.notify_one(); + })); +} diff --git a/examples/server/routes_media.cpp b/examples/server/routes_media.cpp new file mode 100644 index 0000000000..6f04678b07 --- /dev/null +++ b/examples/server/routes_media.cpp @@ -0,0 +1,300 @@ +#include "routes.h" + +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#include +#include +#endif + +namespace media_view { + namespace fs = std::filesystem; + +#ifdef _WIN32 + class FileHandle { + HANDLE handle_; + + public: + explicit FileHandle(HANDLE handle = INVALID_HANDLE_VALUE) : handle_(handle) {} + ~FileHandle() { + if (*this) + CloseHandle(handle_); + } + FileHandle(FileHandle&& other) noexcept : handle_(std::exchange(other.handle_, INVALID_HANDLE_VALUE)) {} + FileHandle& operator=(FileHandle&& other) noexcept { + std::swap(handle_, other.handle_); + return *this; + } + explicit operator bool() const { return handle_ != INVALID_HANDLE_VALUE; } + HANDLE get() const { return handle_; } + }; + + static FileHandle open_directory(const fs::path& path) { + return FileHandle(CreateFileW(path.c_str(), FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr)); + } + + static FileHandle open_child(const FileHandle& parent, const fs::path& part, bool directory) { + static const auto open_file = reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtOpenFile")); + if (!open_file) + return FileHandle(); + auto name = part.native(); + const auto bytes = static_cast(name.size() * sizeof(wchar_t)); + UNICODE_STRING relative{bytes, bytes, name.data()}; + OBJECT_ATTRIBUTES object; + InitializeObjectAttributes(&object, &relative, OBJ_CASE_INSENSITIVE, parent.get(), nullptr); + IO_STATUS_BLOCK status{}; + HANDLE handle = INVALID_HANDLE_VALUE; + const auto access = (directory ? FILE_TRAVERSE : FILE_READ_DATA) | FILE_READ_ATTRIBUTES | SYNCHRONIZE; + // A handle-relative open keeps every component under the directory already checked. + if (open_file(&handle, access, &object, &status, FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT) < 0) + return FileHandle(); + FileHandle file(handle); + BY_HANDLE_FILE_INFORMATION info{}; + if (GetFileType(handle) != FILE_TYPE_DISK || !GetFileInformationByHandle(handle, &info) || + (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || + static_cast(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != directory || + (!directory && info.nNumberOfLinks != 1)) + return FileHandle(); + return file; + } + + static uint64_t file_size(const FileHandle& file) { + LARGE_INTEGER size{}; + return GetFileSizeEx(file.get(), &size) && size.QuadPart > 0 ? static_cast(size.QuadPart) : 0; + } + + static size_t read_at(const FileHandle& file, size_t offset, char* buffer, size_t length) { + LARGE_INTEGER position{}; + position.QuadPart = static_cast(offset); + DWORD count = 0; + if (!SetFilePointerEx(file.get(), position, nullptr, FILE_BEGIN) || + !ReadFile(file.get(), buffer, static_cast(length), &count, nullptr)) + return 0; + return count; + } +#else + class FileHandle { + int fd_; + + public: + explicit FileHandle(int fd = -1) : fd_(fd) {} + ~FileHandle() { + if (*this) + close(fd_); + } + FileHandle(FileHandle&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {} + FileHandle& operator=(FileHandle&& other) noexcept { + std::swap(fd_, other.fd_); + return *this; + } + explicit operator bool() const { return fd_ >= 0; } + int get() const { return fd_; } + }; + + static FileHandle open_directory(const fs::path& path) { + return FileHandle(open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)); + } + + static FileHandle open_child(const FileHandle& parent, const fs::path& part, bool directory) { + const auto flags = O_RDONLY | O_NOFOLLOW | O_CLOEXEC | (directory ? O_DIRECTORY : O_NONBLOCK); + return FileHandle(openat(parent.get(), part.c_str(), flags)); + } + + static uint64_t file_size(const FileHandle& file) { + struct stat info{}; + if (fstat(file.get(), &info) != 0 || !S_ISREG(info.st_mode) || info.st_nlink != 1 || info.st_size <= 0) + return 0; + return static_cast(info.st_size); + } + + static size_t read_at(const FileHandle& file, size_t offset, char* buffer, size_t length) { + ssize_t count; + do { + count = pread(file.get(), buffer, length, static_cast(offset)); + } while (count < 0 && errno == EINTR); + return count > 0 ? static_cast(count) : 0; + } +#endif + + static bool valid_component(std::string_view part) { + return !part.empty() && part.size() <= 1020 && part != "." && part != ".." && + part.back() != '.' && part.back() != ' ' && part.find_first_of("\\:*?\"<>|") == std::string_view::npos && + std::none_of(part.begin(), part.end(), [](unsigned char c) { return c < 32 || c == 127; }); + } + + static FileHandle open_output_root(const fs::path& path) { + auto root = path.root_path(); + const auto relative = path.relative_path(); + auto part = relative.begin(); +#ifdef _WIN32 + // A UNC path needs the share name before it can be opened as a directory. + if (path.root_name().native().compare(0, 2, L"\\\\") == 0 && part != relative.end()) { + root /= *part; + ++part; + } +#endif + auto directory = open_directory(root); + for (; directory && part != relative.end(); ++part) + directory = open_child(directory, *part, true); + return directory; + } + + static FileHandle open_media(const fs::path& output_root, const std::string& root, std::string_view path) { + FileHandle parent; + if (root == "output") { + parent = open_output_root(output_root); + } else if (root == "input" || root == "assets") { + const auto cwd = open_directory("."); + if (cwd) + parent = open_child(cwd, root, true); + } + while (parent) { + const auto slash = path.find('/'); + const auto part = path.substr(0, slash); + if (!valid_component(part)) + break; + const bool directory = slash != std::string_view::npos; + auto child = open_child(parent, fs::u8path(part), directory); + if (!directory) + return child; + parent = std::move(child); + path.remove_prefix(slash + 1); + } + return FileHandle(); + } + + static size_t ebml_vint_width(std::string_view bytes, size_t max_width) { + if (bytes.empty()) + return 0; + const auto first = static_cast(bytes.front()); + for (size_t width = 1; width <= std::min(max_width, bytes.size()); ++width) { + if (first & (0x80u >> (width - 1))) + return width; + } + return 0; + } + + static bool read_ebml_size(std::string_view& bytes, uint64_t& size) { + const auto width = ebml_vint_width(bytes, 8); + if (width == 0) + return false; + size = static_cast(bytes.front()) & (0xffu >> width); + for (size_t i = 1; i < width; ++i) + size = (size << 8) | static_cast(bytes[i]); + bytes.remove_prefix(width); + return size != (uint64_t{1} << (7 * width)) - 1; + } + + static bool has_webm_doctype(std::string_view header, uint64_t file_size) { + constexpr std::string_view ebml_id = "\x1a\x45\xdf\xa3"; + if (header.substr(0, ebml_id.size()) != ebml_id) + return false; + const auto probe_size = header.size(); + header.remove_prefix(ebml_id.size()); + uint64_t size; + if (!read_ebml_size(header, size)) + return false; + const auto prefix_size = probe_size - header.size(); + if (prefix_size > file_size || size > file_size - prefix_size) + return false; + header = header.substr(0, static_cast(size)); + while (!header.empty()) { + const auto width = ebml_vint_width(header, 4); + if (width == 0) + return false; + const bool is_doctype = header.substr(0, width) == "\x42\x82"; + header.remove_prefix(width); + if (!read_ebml_size(header, size) || size > header.size()) + return false; + if (is_doctype) + return header.substr(0, static_cast(size)) == "webm"; + header.remove_prefix(static_cast(size)); + } + return false; + } + + static const char* media_type(std::string extension, std::string_view header, uint64_t size) { + for (auto& ch : extension) { + if (ch >= 'A' && ch <= 'Z') + ch += 'a' - 'A'; + } + if (extension == ".png" && header.substr(0, 8) == "\x89PNG\r\n\x1a\n") + return "image/png"; + if ((extension == ".jpg" || extension == ".jpeg") && header.substr(0, 3) == "\xff\xd8\xff") + return "image/jpeg"; + if (extension == ".gif" && (header.substr(0, 6) == "GIF87a" || header.substr(0, 6) == "GIF89a")) + return "image/gif"; + if (extension == ".webp" && header.size() >= 16 && header.substr(0, 4) == "RIFF" && header.substr(8, 7) == "WEBPVP8" && + (header[15] == ' ' || header[15] == 'L' || header[15] == 'X')) + return "image/webp"; + if (extension == ".webm" && has_webm_doctype(header, size)) + return "video/webm"; + if (extension == ".avi" && header.size() >= 12 && header.substr(0, 4) == "RIFF" && header.substr(8, 4) == "AVI ") + return "video/x-msvideo"; + if (extension == ".mp4" && header.size() >= 16 && header.substr(4, 4) == "ftyp") { + uint32_t box_size = 0; + for (size_t i = 0; i < 4; ++i) + box_size = (box_size << 8) | static_cast(header[i]); + if (box_size >= 16 && box_size <= size) + return "video/mp4"; + } + return nullptr; + } + + static bool set_media_content(const fs::path& output_root, + const std::string& root, + const std::string& path, + httplib::Response& res) { + auto file = open_media(output_root, root, path); + if (!file) + return false; + const auto size = file_size(file); + if (size == 0 || size > std::numeric_limits::max()) + return false; + std::array header; + const auto count = read_at(file, 0, header.data(), header.size()); + const auto extension = path.find_last_of('.'); + if (extension == std::string::npos) + return false; + const auto* type = media_type(path.substr(extension), {header.data(), count}, size); + if (!type) + return false; + res.set_header("Accept-Ranges", "bytes"); + res.set_content_provider(static_cast(size), type, + [file = std::make_shared(std::move(file))](size_t offset, size_t length, httplib::DataSink& sink) { + std::array buffer; + const auto count = read_at(*file, offset, buffer.data(), std::min(length, buffer.size())); + return count != 0 && sink.write(buffer.data(), count); + }); + return true; + } +} + +void register_media_view_endpoint(httplib::Server& svr, bool enabled, const std::filesystem::path& output_root) { + svr.Get("/sdcpp/v1/view", [enabled, output_root](const httplib::Request& req, httplib::Response& res) { + res.set_header("Cache-Control", "no-store"); + res.set_header("X-Content-Type-Options", "nosniff"); + if (!enabled) { + res.status = 403; + return; + } + try { + if (req.get_param_value_count("root") == 1 && req.get_param_value_count("path") == 1 && + media_view::set_media_content(output_root, req.get_param_value("root"), req.get_param_value("path"), res)) + return; + } catch (const std::system_error&) { + // Invalid path encodings are treated like unavailable files. + } + res.status = 404; + }); +} diff --git a/examples/server/routes_models.cpp b/examples/server/routes_models.cpp index 9dbd6ed761..adb2b5c2f4 100644 --- a/examples/server/routes_models.cpp +++ b/examples/server/routes_models.cpp @@ -3,6 +3,30 @@ #include "async_jobs.h" #include "model_catalog.h" +class SynchronousContextJob { + AsyncJobManager& manager_; + const SDSvrParams& params_; + +public: + explicit SynchronousContextJob(const ServerRuntime& runtime) + : manager_(*runtime.async_job_manager), params_(*runtime.svr_params) { + std::lock_guard lock(manager_.mutex); + ++manager_.synchronous_jobs; + } + + SynchronousContextJob(const SynchronousContextJob&) = delete; + SynchronousContextJob& operator=(const SynchronousContextJob&) = delete; + + ~SynchronousContextJob() { + { + std::lock_guard lock(manager_.mutex); + --manager_.synchronous_jobs; + manager_.record_context_job_completion(params_); + } + manager_.cv.notify_one(); + } +}; + static void model_error(httplib::Response& res, int status, const std::string& code, const std::string& message) { res.status = status; res.set_content(json({{"error", message}, {"code", code}}).dump(), "application/json"); @@ -11,126 +35,36 @@ static void model_error(httplib::Response& res, int status, const std::string& c httplib::Server::Handler RuntimeRoutes::protect(httplib::Server::Handler handler) { ServerRuntime* runtime = &runtime_; return [runtime, handler](const httplib::Request& req, httplib::Response& res) { - std::shared_lock lock(runtime->models->runtime_mutex, std::try_to_lock); - if (!lock.owns_lock()) { - model_error(res, 503, "model_loading", "Model is loading or unloading"); - return; - } - const bool generation = req.path == "/sdcpp/v1/img_gen" || req.path == "/sdcpp/v1/vid_gen" || - req.path == "/sdapi/v1/txt2img" || req.path == "/sdapi/v1/img2img" || + const bool generation = req.path == "/sdapi/v1/txt2img" || req.path == "/sdapi/v1/img2img" || req.path == "/v1/images/generations" || req.path == "/v1/images/edits"; - if (generation && !runtime->sd_ctx) { - model_error(res, 503, "model_not_loaded", "No model is loaded"); - return; + if (generation) { + SynchronousContextJob job(*runtime); + std::lock_guard lock(*runtime->sd_ctx_mutex); + if (!has_current_model(*runtime)) { + model_error(res, 503, "model_not_loaded", "No current model is configured"); + return; + } + handler(req, res); + } else { + handler(req, res); } - handler(req, res); }; } void RuntimeRoutes::get(const std::string& pattern, httplib::Server::Handler handler) { - // Job polling and cancellation only access the job manager, even during a model transition. - server_.Get(pattern, pattern.find("/sdcpp/v1/jobs/") != std::string::npos ? handler : protect(handler)); -} - -void RuntimeRoutes::post(const std::string& pattern, httplib::Server::Handler handler) { - server_.Post(pattern, pattern.find("/sdcpp/v1/jobs/") != std::string::npos ? handler : protect(handler)); -} - -static void set_model_status(ServerRuntime& runtime, const char* state, const json& recipe, const json& selection, const json& error = nullptr) { - std::lock_guard lock(runtime.models->status_mutex); - auto& models = *runtime.models; - const uint64_t revision = models.status.value("revision", uint64_t(0)) + 1; - json elapsed = nullptr; - if (!recipe.is_null()) { - const auto now = std::chrono::steady_clock::now(); - if (std::string(state) == "loading") { - models.load_started_at = now; - elapsed = 0.0; - } else { - elapsed = std::chrono::duration(now - models.load_started_at).count(); - } - } - models.status = {{"state", state}, {"recipe", recipe}, {"models", selection}, {"error", error}, {"revision", revision}, {"load_elapsed_seconds", elapsed}}; -} - -static void change_model(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, bool unload) { - auto& models = *runtime.models; - std::unique_lock lock(models.runtime_mutex, std::try_to_lock); - if (!lock.owns_lock()) { - model_error(res, 409, "model_busy", "Model is in use or another model operation is running"); + if (pattern.find("/sdcpp/v1/jobs/") != std::string::npos) { + server_.Get(pattern, handler); return; } - { - // Admission holds runtime_mutex through enqueue. Jobs stay pending until - // generation and metadata encoding finish, so no worker can retain this context here. - std::lock_guard jobs_lock(runtime.async_job_manager->mutex); - if (count_pending_jobs(*runtime.async_job_manager) != 0) { - model_error(res, 409, "model_busy", "Finish or cancel pending generation jobs before switching models"); - return; - } - } - - json body; - json loaded_recipe; - SDContextParams context; - SDGenerationParams defaults; - if (!unload) { - try { - body = json::parse(req.body); - prepare_model_load(runtime, body, context, defaults, &loaded_recipe); - } catch (const std::exception& e) { - model_error(res, 400, "invalid_model_config", e.what()); - return; - } - } - - // Idempotent load: if this exact recipe and resolved selection are already - // active, report the current status instead of tearing down the context. - // Comparing full recipe objects (not just the id) also reloads when the - // catalog was refreshed with modified recipe metadata for the same id. - // Comparing resolved component paths catches the same file IDs resolving - // to different files (e.g. a model directory symlink retargeted inside - // the configured root since the catalog was last scanned). - if (!unload) { - json current = model_status(runtime); - if (current.value("state", "") == "ready" && current.value("recipe", json(nullptr)) == body.at("recipe") && - current.value("models", json::object()) == body.at("models") && models.active_recipe == loaded_recipe && - component_paths_match(*runtime.ctx_params, context)) { - current["already_loaded"] = true; - res.set_content(current.dump(), "application/json"); - return; - } - } + ServerModels* models = runtime_.models; + server_.Get(pattern, [models, handler](const httplib::Request& req, httplib::Response& res) { + std::shared_lock lock(models->model_mutex); + handler(req, res); + }); +} - const json recipe = unload ? json(nullptr) : body.at("recipe"); - const json selection = unload ? json::object() : body.value("models", json::object()); - set_model_status(runtime, "loading", recipe, selection); - try { - runtime.sd_ctx = nullptr; - models.context.reset(); - models.active_recipe = nullptr; - *runtime.ctx_params = unload ? models.base_context : std::move(context); - *runtime.default_gen_params = unload ? models.base_defaults : std::move(defaults); - if (!unload) { - auto params = runtime.ctx_params->to_context_opt(); - models.context.reset(create_sd_context(params)); - if (!models.context) { - throw std::runtime_error("Model initialization failed; check the server log for component compatibility and memory errors"); - } - runtime.sd_ctx = models.context.get(); - models.active_recipe = std::move(loaded_recipe); - } - set_model_status(runtime, unload ? "empty" : "ready", recipe, selection); - res.set_content(model_status(runtime).dump(), "application/json"); - } catch (const std::exception& e) { - runtime.sd_ctx = nullptr; - models.context.reset(); - models.active_recipe = nullptr; - *runtime.ctx_params = models.base_context; - *runtime.default_gen_params = models.base_defaults; - set_model_status(runtime, "error", recipe, selection, e.what()); - model_error(res, 422, "model_load_failed", e.what()); - } +void RuntimeRoutes::post(const std::string& pattern, httplib::Server::Handler handler) { + server_.Post(pattern, protect(handler)); } void register_model_endpoints(httplib::Server& svr, ServerRuntime& runtime) { @@ -157,12 +91,7 @@ void register_model_endpoints(httplib::Server& svr, ServerRuntime& runtime) { res.set_content(json({{"errors", runtime.models->catalog_errors}}).dump(), "application/json"); }); svr.Get("/sdcpp/v1/models/status", [&runtime](const httplib::Request&, httplib::Response& res) { + std::shared_lock lock(runtime.models->model_mutex); res.set_content(model_status(runtime).dump(), "application/json"); }); - svr.Post("/sdcpp/v1/models/load", [&runtime](const httplib::Request& req, httplib::Response& res) { - change_model(runtime, req, res, false); - }); - svr.Post("/sdcpp/v1/models/unload", [&runtime](const httplib::Request& req, httplib::Response& res) { - change_model(runtime, req, res, true); - }); } diff --git a/examples/server/routes_openai.cpp b/examples/server/routes_openai.cpp index e67bd20159..0fe6537524 100644 --- a/examples/server/routes_openai.cpp +++ b/examples/server/routes_openai.cpp @@ -218,27 +218,7 @@ static bool execute_sync_img_gen_request(ServerRuntime& runtime, ImgGenJobRequest& request, SDImageVec& results, std::string& error_message) { - SDOptPtr img_gen_params = request.to_image_opt(); - int num_results = 0; - - { - std::lock_guard lock(*runtime.sd_ctx_mutex); - PromptImageCallbackGuard prompt_images(runtime.sd_ctx, request.gen_params); - sd_result_t* generated = nullptr; - generate_sd_image(runtime.sd_ctx, img_gen_params, &generated); - results.adopt(generated, runtime.ctx_params->lora_model_dir); - num_results = results.count(); - if (!results.empty() && !apply_server_adetailer(runtime, request, results)) { - error_message = "ADetailer failed"; - return false; - } - } - - if (results.empty()) { - error_message = "generate_image returned no results"; - return false; - } - return true; + return generate_server_images(runtime.sd_ctx, request, results, error_message); } void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { @@ -248,7 +228,7 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { routes.get("/v1/models", [runtime](const httplib::Request&, httplib::Response& res) { json r; r["data"] = json::array(); - if (runtime->sd_ctx) { + if (has_current_model(*runtime)) { r["data"].push_back({{"id", "sd-cpp-local"}, {"object", "model"}, {"owned_by", "local"}}); } res.set_content(r.dump(), "application/json"); @@ -311,7 +291,7 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { json item; item["b64_json"] = base64_encode(image_bytes); - item["generation_info"] = json::parse(results.generation_info(i)); + item["generation_info"] = results.generation_info(i); out["data"].push_back(item); } @@ -375,7 +355,7 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { request.output_compression); json item; item["b64_json"] = base64_encode(image_bytes); - item["generation_info"] = json::parse(results.generation_info(i)); + item["generation_info"] = results.generation_info(i); out["data"].push_back(item); } diff --git a/examples/server/routes_sdapi.cpp b/examples/server/routes_sdapi.cpp index e9f60c7555..a725174f9e 100644 --- a/examples/server/routes_sdapi.cpp +++ b/examples/server/routes_sdapi.cpp @@ -375,16 +375,13 @@ static bool build_sdapi_img_gen_request(const json& j, } } - if (j.contains("ref_image_args")) { - if (!j["ref_image_args"].is_string()) { - error_message = "ref_image_args must be a string"; - return false; - } - request.gen_params.ref_image_args = j["ref_image_args"].get(); + if (j.contains("ref_image_args") && j["ref_image_args"] != "") { + error_message = "reference overrides require a DGL script"; + return false; } - if (j.contains("image_preprocess") && !request.gen_params.parse_image_preprocess_json(j["image_preprocess"].dump())) { - error_message = "invalid image_preprocess"; + if (j.contains("image_preprocess")) { + error_message = "image_preprocess requires a DGL script"; return false; } @@ -453,26 +450,22 @@ static bool build_sdapi_img_gen_request(const json& j, validate_server_img_gen_request(runtime, request, error_message); } -static nlohmann::json prepare_info_field(const std::string& generation_info) { - const auto info = nlohmann::json::parse(generation_info); - const auto& sampling = info.at("sample_params"); - nlohmann::json result = {{"prompt", info.at("prompt")}, - {"negative_prompt", info.at("negative_prompt")}, - {"seed", generation_seed(generation_info)}, - {"cfg_scale", sampling.at("guidance").at("txt_cfg")}, - {"width", info.at("width")}, - {"height", info.at("height")}, - {"steps", sampling.contains("custom_sigmas") ? json(sampling.at("custom_sigmas").size() - 1) : sampling.at("sample_steps")}, - {"sampler_name", sampling.at("sample_method")}, - {"version", "stable-diffusion.cpp"}}; - if (info.contains("clip_skip")) - result["clip_skip"] = info.at("clip_skip"); - if (info.contains("strength")) - result["denoising_strength"] = info.at("strength"); - if (sampling.contains("scheduler")) - result["extra_generation_params"]["Schedule type"] = sampling.at("scheduler"); +static json generation_metadata(const std::string& source) { + const auto* metadata = sd_get_generation_metadata(source.c_str()); + return metadata ? json::parse(metadata) : json::object(); +} + +static nlohmann::json prepare_info_field(const json& info) { + auto result = json::object(); + const std::map names{{"prompt", "prompt"}, {"negative_prompt", "negative_prompt"}, {"seed", "seed"}, {"cfg_scale", "cfg_scale"}, {"width", "width"}, {"height", "height"}, {"steps", "steps"}, {"method", "sampler_name"}, {"clip_skip", "clip_skip"}, {"strength", "denoising_strength"}}; + for (const auto& [key, output] : names) + if (info.contains(key)) + result[output] = info.at(key); + if (info.contains("scheduler")) + result["extra_generation_params"]["Schedule type"] = info.at("scheduler"); + result["version"] = "stable-diffusion.cpp"; for (const auto* key : {"infotexts", "all_prompts", "all_negative_prompts", "all_seeds", "generation_info"}) - result[key] = nlohmann::json::array(); + result[key] = json::array(); return result; } @@ -589,38 +582,29 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { LOG_DEBUG("%s\n", request.gen_params.to_string().c_str()); - SDOptPtr img_gen_params = request.to_image_opt(); SDImageVec results; int num_results = 0; { - std::lock_guard lock(*runtime->sd_ctx_mutex); - PromptImageCallbackGuard prompt_images(runtime->sd_ctx, request.gen_params); const bool detailing = request.adetailer_enabled && !runtime->default_gen_params->ad_model_path.empty(); SDAPIPreviewGuard preview_guard(id_task, request.gen_params, img2img ? "img2img" : "txt2img", detailing); - sd_result_t* generated = nullptr; - generate_sd_image(runtime->sd_ctx, img_gen_params, &generated); - results.adopt(generated, runtime->ctx_params->lora_model_dir); + generate_server_images(runtime->sd_ctx, request, results, error_message); num_results = results.count(); if (detailing && !results.empty()) preview_guard.begin_detailing(); - if (!results.empty() && !apply_server_adetailer(*runtime, request, results)) { - res.status = 500; - res.set_content(R"({"error":"ADetailer failed"})", "application/json"); - return; - } } if (results.empty()) { res.status = 500; - res.set_content(R"({"error":"generate_image returned no results"})", "application/json"); + res.set_content(json({{"error", error_message}}).dump(), "application/json"); return; } json out; out["images"] = json::array(); out["parameters"] = j; - json jsoninfo = prepare_info_field(results.generation_info(0)); + auto metadata = generation_metadata(results.generation_info(0)); + json jsoninfo = prepare_info_field(metadata); for (int i = 0; i < num_results; ++i) { if (results[i].data == nullptr) { @@ -629,7 +613,9 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { bool embed_meta = request.gen_params.embed_image_metadata; - std::string params = generation_info_to_webui(results.generation_info(i)); + if (i != 0) + metadata = generation_metadata(results.generation_info(i)); + const auto params = metadata.value("infotext", ""); auto image_bytes = encode_image_to_vector(EncodedImageFormat::PNG, results[i].data, @@ -645,12 +631,12 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { out["images"].push_back(base64_encode(image_bytes)); - const auto actual = json::parse(results.generation_info(i)); jsoninfo["infotexts"].push_back(params); - jsoninfo["all_seeds"].push_back(generation_seed(results.generation_info(i))); - jsoninfo["generation_info"].push_back(actual); - jsoninfo["all_prompts"].push_back(actual["prompt"]); - jsoninfo["all_negative_prompts"].push_back(actual["negative_prompt"]); + const auto seed = metadata.find("seed"); + jsoninfo["all_seeds"].push_back(seed != metadata.end() && seed->is_number_integer() ? seed->get() : -1); + jsoninfo["generation_info"].push_back(results.generation_info(i)); + jsoninfo["all_prompts"].push_back(metadata.value("prompt", "")); + jsoninfo["all_negative_prompts"].push_back(metadata.value("negative_prompt", "")); } // not a mistake: it is supposed to be a string in json format @@ -786,7 +772,7 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { entry["sha256"] = "8888888888888888888888888888888888888888888888888888888888888888"; entry["config"] = nullptr; json r = json::array(); - if (runtime->sd_ctx) { + if (has_current_model(*runtime)) { r.push_back(entry); } res.set_content(r.dump(), "application/json"); @@ -800,6 +786,50 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(r.dump(), "application/json"); }); + // A1111 clients (e.g. SDAI) fetch these during setup and abort on 404. sd-server has no + // equivalent concept, so they report "nothing available" in A1111's response shapes. + routes.get("/sdapi/v1/embeddings", [](const httplib::Request&, httplib::Response& res) { + json r; + r["loaded"] = json::object(); + r["skipped"] = json::object(); + res.set_content(r.dump(), "application/json"); + }); + + for (const char* path : {"/sdapi/v1/hypernetworks", + "/sdapi/v1/sd-modules", + "/sdapi/v1/extensions", + "/sdapi/v1/script-info"}) { + routes.get(path, [](const httplib::Request&, httplib::Response& res) { + res.set_content(json::array().dump(), "application/json"); + }); + } + + routes.get("/sdapi/v1/scripts", [](const httplib::Request&, httplib::Response& res) { + json r; + r["txt2img"] = json::array(); + r["img2img"] = json::array(); + res.set_content(r.dump(), "application/json"); + }); + + // Server options are fixed at launch; accept and ignore updates so clients that save + // settings before generating keep working. + routes.post("/sdapi/v1/options", [](const httplib::Request&, httplib::Response& res) { + res.set_content(json::object().dump(), "application/json"); + }); + + routes.post("/sdapi/v1/interrupt", [runtime](const httplib::Request&, httplib::Response& res) { + // Hold the preview lock through the cancel: the generation's preview guard clears + // `active` under this lock before sd_ctx_mutex is released, so the next queued + // generation cannot start (and be cancelled by mistake) between check and cancel. + // protect() holds runtime_mutex (shared) for this handler, so sd_ctx cannot be + // unloaded underneath us. sd_cancel_generation only stores an atomic flag. + std::lock_guard lock(g_preview.mutex); + if (g_preview.active && runtime->sd_ctx) { + sd_cancel_generation(runtime->sd_ctx, SD_CANCEL_ALL); + } + res.set_content(json::object().dump(), "application/json"); + }); + routes.get("/sdapi/v1/progress", [](const httplib::Request& req, httplib::Response& res) { bool skip_current_image = false; bool has_id_param = req.has_param("id_task"); diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index c6e49710b1..6dbb1e2e09 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -1,36 +1,16 @@ #include "routes.h" -#include #include #include -#include +#include #include "async_jobs.h" #include "common/common.h" -#include "common/media_io.h" #include "common/resource_owners.hpp" #include "model_catalog.h" namespace fs = std::filesystem; -static constexpr uint32_t k_max_upscale_dimension = 8192; - -static bool valid_upscale_dimensions(const SDImage& image, int factor, int repeats) { - if (image.width == 0 || image.height == 0 || factor < 1 || repeats < 1 || repeats > 4) { - return false; - } - uint32_t width = image.width; - uint32_t height = image.height; - for (int i = 0; i < repeats; ++i) { - if (width > k_max_upscale_dimension / factor || height > k_max_upscale_dimension / factor) { - return false; - } - width *= factor; - height *= factor; - } - return true; -} - static bool parse_cache_mode(const std::string& value, std::string& mode) { const std::string canonical = value == "cache-dit" ? "cache_dit" : value; SDOptPtr opt(sd_img_gen_opt_create()); @@ -68,7 +48,7 @@ static fs::path resolve_display_model_path(const ServerRuntime& runtime) { return {}; } -static json make_sample_params_json(const SDSampleParams& sample_params, const std::optional>& skip_layers, const std::optional>& custom_sigmas = {}) { +static json make_sample_params_json(const SDSampleParams& sample_params, const std::optional>& skip_layers, const std::optional>& custom_sigmas) { const auto& guidance = sample_params.guidance; return { {"scheduler", sample_params.scheduler}, @@ -119,9 +99,6 @@ static json make_img_gen_defaults_json(const SDGenerationParams& defaults, const {"seed", defaults.seed}, {"batch_count", defaults.batch_count}, {"qwen_image_layers", defaults.qwen_image_layers}, - {"ref_image_args", defaults.ref_image_args}, - {"image_preprocess", defaults.image_preprocess}, - {"increase_ref_index", defaults.increase_ref_index}, {"control_strength", defaults.control_strength}, {"control_type", defaults.control_type}, {"ip_adapter_strength", defaults.ip_adapter_strength}, @@ -137,8 +114,8 @@ static json make_img_gen_defaults_json(const SDGenerationParams& defaults, const }; } -static json make_vid_gen_defaults_json(const SDGenerationParams& defaults, const std::string& output_format) { - return { +static json make_vid_gen_defaults_json(const SDGenerationParams& defaults, const std::string& output_format, bool high_noise) { + json result = { {"prompt", defaults.prompt}, {"negative_prompt", defaults.negative_prompt}, {"clip_skip", defaults.clip_skip}, @@ -147,13 +124,9 @@ static json make_vid_gen_defaults_json(const SDGenerationParams& defaults, const {"strength", defaults.strength}, {"seed", defaults.seed}, {"video_frames", defaults.video_frames}, - {"image_preprocess", defaults.image_preprocess}, - {"ref_image_args", defaults.ref_image_args}, {"fps", defaults.fps}, - {"moe_boundary", defaults.moe_boundary}, {"vace_strength", defaults.vace_strength}, {"sample_params", make_sample_params_json(defaults.sample_params, defaults.skip_layers, defaults.custom_sigmas)}, - {"high_noise_sample_params", make_sample_params_json(defaults.high_noise_sample_params, defaults.high_noise_skip_layers)}, {"hires", make_hires_json(defaults)}, {"vae_tiling_params", make_vae_tiling_json(defaults.vae_tiling_params)}, {"cache_mode", defaults.cache_mode}, @@ -163,6 +136,15 @@ static json make_vid_gen_defaults_json(const SDGenerationParams& defaults, const {"output_format", output_format}, {"output_compression", 100}, }; + if (high_noise) { + result["moe_boundary"] = defaults.moe_boundary; + result["high_noise_sample_params"] = { + {"scheduler", defaults.high_noise_sample_params.scheduler}, + {"sample_steps", defaults.high_noise_sample_params.sample_steps}, + {"flow_shift", finite_number_or_null(defaults.high_noise_sample_params.flow_shift)}, + }; + } + return result; } static json make_img_gen_features_json() { @@ -170,7 +152,7 @@ static json make_img_gen_features_json() { {"init_image", true}, {"mask_image", true}, {"control_image", true}, - {"ip_adapter_image", true}, + {"ip_adapter_image", false}, {"ref_images", true}, {"lora", true}, {"vae_tiling", true}, @@ -183,7 +165,7 @@ static json make_img_gen_features_json() { } /** Builds the default feature set advertised for vid_gen requests. */ -static json make_vid_gen_features_json() { +static json make_vid_gen_features_json(bool high_noise) { return { {"init_image", true}, {"end_image", true}, @@ -191,7 +173,7 @@ static json make_vid_gen_features_json() { {"ref_videos", true}, {"ref_audios", true}, {"ref_video_audios", true}, - {"high_noise_sample_params", true}, + {"high_noise_sample_params", high_noise}, {"lora", true}, {"vae_tiling", true}, {"cache", true}, @@ -252,58 +234,46 @@ static json make_capabilities_json(ServerRuntime& runtime) { available_upscalers.push_back({ {"name", "None"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Lanczos"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Nearest"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (nearest)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (nearest-exact)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (antialiased)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (bicubic)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (bicubic antialiased)"}, {"model", false}, - {"image_upscale", false}, }); - bool have_upscaler_models = false; { std::lock_guard lock(*runtime.upscaler_mutex); for (const auto& entry : *runtime.upscaler_cache) { available_upscalers.push_back({ {"name", entry.name}, {"model", true}, - {"image_upscale", entry.image_upscale_factor > 0}, }); - have_upscaler_models = have_upscaler_models || entry.image_upscale_factor > 0; } } @@ -332,9 +302,7 @@ static json make_capabilities_json(ServerRuntime& runtime) { std::string(key) == "ref_video_audios"))) features[key] = generation_features.at(key); } - if (video) - features["high_noise_sample_params"] = generation_features.at("high_noise"); - else { + if (!video) { features["mask_image"] = generation_features.at("mask_image").get() && generation_features.at("img2img").get(); features["control_image"] = generation_features.at("controlnet").get() || generation_features.at("control_image").get(); features["ip_adapter_image"] = generation_features.at("ip_adapter"); @@ -342,17 +310,16 @@ static json make_capabilities_json(ServerRuntime& runtime) { return features; }; json defaults_by_mode = json::object(); - json output_formats_by_mode = json::object(); + json output_formats_by_mode = {{"img_gen", image_output_formats}, {"vid_gen", video_output_formats}}; json features_by_mode = json::object(); if (supports_img) { - defaults_by_mode["img_gen"] = make_img_gen_defaults_json(defaults, default_img_output_format); - output_formats_by_mode["img_gen"] = image_output_formats; - features_by_mode["img_gen"] = recipe_features(make_img_gen_features_json(), false); + defaults_by_mode["img_gen"] = make_img_gen_defaults_json(defaults, default_img_output_format); + features_by_mode["img_gen"] = recipe_features(make_img_gen_features_json(), false); } if (supports_vid) { - defaults_by_mode["vid_gen"] = make_vid_gen_defaults_json(defaults, default_vid_output_format); - output_formats_by_mode["vid_gen"] = video_output_formats; - features_by_mode["vid_gen"] = recipe_features(make_vid_gen_features_json(), true); + const bool high_noise = generation_features.at("high_noise").get(); + defaults_by_mode["vid_gen"] = make_vid_gen_defaults_json(defaults, default_vid_output_format, high_noise); + features_by_mode["vid_gen"] = recipe_features(make_vid_gen_features_json(high_noise), true); } json top_level_defaults = json::object(); @@ -380,21 +347,32 @@ static json make_capabilities_json(ServerRuntime& runtime) { {"stem", model_path.stem().u8string()}, {"path", model_path.u8string()}, }; - result["generation_features"] = generation_features; - result["runtime"] = model_status(runtime); - result["current_mode"] = current_mode; - result["supported_modes"] = supported_modes; - result["defaults"] = top_level_defaults; - result["defaults_by_mode"] = defaults_by_mode; - result["limits"] = { + result["generation_features"] = generation_features; + result["generation_model_selection"] = true; + result["media_view"] = runtime.svr_params->media_view; + if (runtime.svr_params->media_view && !runtime.svr_params->output_dir.empty()) { + const auto& output = runtime.models->workspace_file_access.output; + auto paths = json::array({output.generic_u8string()}); + const auto relative = output.lexically_relative(fs::weakly_canonical(fs::current_path())); + if (!relative.empty()) + paths.push_back(relative.generic_u8string()); + result["media_output"] = {{"paths", std::move(paths)}}; +#ifdef _WIN32 + result["media_output"]["case_insensitive"] = true; +#endif + } + result["runtime"] = model_status(runtime); + result["current_mode"] = current_mode; + result["supported_modes"] = supported_modes; + result["defaults"] = top_level_defaults; + result["defaults_by_mode"] = defaults_by_mode; + result["limits"] = { {"min_width", 64}, {"max_width", k_max_generation_dimension}, {"min_height", 64}, {"max_height", k_max_generation_dimension}, {"max_batch_count", 8}, {"max_queue_size", manager.max_pending_jobs}, - {"max_upscale_width", k_max_upscale_dimension}, - {"max_upscale_height", k_max_upscale_dimension}, }; result["samplers"] = samplers; result["schedulers"] = schedulers; @@ -404,7 +382,6 @@ static json make_capabilities_json(ServerRuntime& runtime) { result["features_by_mode"] = features_by_mode; result["loras"] = available_loras; result["upscalers"] = available_upscalers; - result["upscale"] = have_upscaler_models; result["preview_modes"] = make_preview_modes_json(); return result; } @@ -467,7 +444,7 @@ static bool parse_vid_gen_request(const json& body, merge_shared_sample_input("flow_shift", &SDSampleParams::flow_shift); merge_shared_sample_input("shifted_timestep", &SDSampleParams::shifted_timestep); - std::string output_format = body.value("output_format", "webm"); + std::string output_format = body.value("output_format", supported_vid_output_formats().front()); int output_compression = body.value("output_compression", 100); if (!assign_output_options(request, output_format, output_compression, error_message)) { return false; @@ -482,312 +459,117 @@ static bool parse_vid_gen_request(const json& body, return true; } -void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { - ServerRuntime* runtime = &rt; - RuntimeRoutes routes(svr, rt); - - routes.get("/sdcpp/v1/capabilities", [runtime](const httplib::Request&, httplib::Response& res) { - res.status = 200; - res.set_content(make_capabilities_json(*runtime).dump(), "application/json"); - }); - - routes.post("/sdcpp/v1/upscale", [runtime](const httplib::Request& req, httplib::Response& res) { - try { - if (req.body.empty()) { - res.status = 400; - res.set_content(R"({"error":"empty body"})", "application/json"); - return; - } - json body = json::parse(req.body); - if (!body.is_object()) { - res.status = 400; - res.set_content(R"({"error":"body must be an object"})", "application/json"); - return; - } - for (const char* key : {"repeats", "tile_size", "output_compression"}) { - if (!body.contains(key)) { - continue; - } - const auto& value = body[key]; - const bool valid = value.is_number_unsigned() - ? value.get() <= static_cast(std::numeric_limits::max()) - : value.is_number_integer() && value.get() >= std::numeric_limits::min() && - value.get() <= std::numeric_limits::max(); - if (!valid) { - res.status = 400; - res.set_content(json({{"error", std::string(key) + " must be a 32-bit integer"}}).dump(), "application/json"); - return; - } - } - ImgGenJobRequest output_options; - std::string error_message; - if (!assign_output_options(output_options, - body.value("output_format", std::string("png")), - body.value("output_compression", 100), - true, - error_message)) { - res.status = 400; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); - return; - } - const auto tile_size = body.value("tile_size", runtime->default_gen_params->upscale_tile_size); - if (tile_size && *tile_size < 32) { - res.status = 400; - res.set_content(json({{"error", "tile_size must be at least 32"}}).dump(), "application/json"); - return; - } - const int repeats = std::clamp(body.value("repeats", 1), 1, 4); - const std::string wanted = body.value("upscaler", std::string()); - - const std::string encoded = body.value("image", std::string()); - if (encoded.empty()) { - res.status = 400; - res.set_content(R"({"error":"image is required"})", "application/json"); - return; - } - SDImageOwner input; - if (!decode_base64_image(encoded, 3, 0, 0, input) || input.get().data == nullptr) { - res.status = 400; - res.set_content(R"({"error":"image could not be read"})", "application/json"); - return; - } - - refresh_upscaler_cache(*runtime); - int model_scale = 0; - std::string model_path; - std::string used_name; - { - std::lock_guard lock(*runtime->upscaler_mutex); - for (const auto& entry : *runtime->upscaler_cache) { - if (entry.image_upscale_factor > 0 && (wanted.empty() || entry.name == wanted)) { - model_path = entry.fullpath; - used_name = entry.name; - model_scale = entry.image_upscale_factor; - break; - } - } - } - if (model_path.empty()) { - res.status = 400; - res.set_content(json({{"error", wanted.empty() - ? std::string("no RGB ESRGAN upscaler models are available; " - "start the server with --hires-upscalers-dir") - : "no compatible image upscaler called " + wanted}}) - .dump(), - "application/json"); - return; - } - - if (!valid_upscale_dimensions(input.get(), model_scale, repeats)) { - res.status = 400; - res.set_content(R"({"error":"upscaled dimensions must not exceed 8192 x 8192"})", "application/json"); - return; - } - - // One GPU: an upscale must not run while a generation is using it. - std::lock_guard ctx_lock(*runtime->sd_ctx_mutex); - UpscalerCtxPtr upscaler_ctx(create_sd_upscaler(model_path.c_str(), - runtime->ctx_params->diffusion_conv_direct, - runtime->ctx_params->n_threads, - tile_size, - runtime->ctx_params->backend ? runtime->ctx_params->backend->c_str() : nullptr, - runtime->ctx_params->params_backend ? runtime->ctx_params->params_backend->c_str() : nullptr)); - if (upscaler_ctx == nullptr) { - res.status = 500; - res.set_content(R"({"error":"the upscaler model could not be loaded"})", "application/json"); - return; - } - const int factor = sd_upscaler_get_scale(upscaler_ctx.get()); - // The model file may have changed since its metadata was cached. - if (!valid_upscale_dimensions(input.get(), factor, repeats)) { - res.status = 400; - res.set_content(R"({"error":"upscaled dimensions must not exceed 8192 x 8192"})", "application/json"); - return; - } - - SDImageOwner current(input.release()); - std::string generation_info; - for (int i = 0; i < repeats; ++i) { - sd_result_t* generated = nullptr; - if (!upscale_sd_image(upscaler_ctx.get(), current.get(), &generated) || - !generated || sd_result_get_image_count(generated) <= 0 || sd_tensor_data(sd_result_get_image(generated, 0)) == nullptr) { - sd_result_free(generated); - res.status = 500; - res.set_content(R"({"error":"upscale failed"})", "application/json"); - return; - } - generation_info = merge_generation_info(generation_info, sd_result_get_generation_info(generated, 0)); - SDImage produced = take_result_image(generated, 0); - - sd_result_free(generated); - current.reset(produced); - } - - const std::string& format = output_options.output_format; - const int compression = output_options.output_compression; - const SDImage result = current.get(); - auto image_bytes = encode_image_to_vector(format == "jpeg" ? EncodedImageFormat::JPEG - : format == "webp" ? EncodedImageFormat::WEBP - : EncodedImageFormat::PNG, - result.data, - result.width, - result.height, - result.channel, - generation_info, - compression); - if (image_bytes.empty()) { - res.status = 500; - res.set_content(R"({"error":"the result could not be encoded"})", "application/json"); - return; - } +bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message) { + return job.kind == AsyncJobKind::VidGen ? parse_vid_gen_request(body, runtime, job.vid_gen, error_message) + : parse_img_gen_request(body, runtime, job.img_gen, error_message); +} - json out; - out["generation_info"] = json::parse(generation_info); - out["upscaler"] = used_name; - out["scale"] = factor; - out["repeats"] = repeats; - out["width"] = result.width; - out["height"] = result.height; - out["output_format"] = format; - json images = json::array(); - images.push_back({{"index", 0}, {"b64_json", base64_encode(image_bytes)}}); - out["images"] = std::move(images); - res.set_content(out.dump(), "application/json"); - res.status = 200; - } catch (const json::exception& e) { +static void submit_generation_job(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, SDMode mode) { + try { + if (req.body.empty()) { res.status = 400; - res.set_content(json({{"error", "invalid request"}, {"message", e.what()}}).dump(), "application/json"); - } catch (const std::exception& e) { - res.status = 500; - res.set_content(json({{"error", std::string("server_error: ") + e.what()}}).dump(), "application/json"); + res.set_content(R"({"error":"empty body"})", "application/json"); + return; + } + auto body = json::parse(req.body); + if (!body.is_object()) { + res.status = 400; + res.set_content(R"({"error":"generation request must be an object"})", "application/json"); + return; } - }); - routes.post("/sdcpp/v1/img_gen", [runtime](const httplib::Request& req, httplib::Response& res) { - try { - if (req.body.empty()) { + auto job = std::make_shared(); + job->kind = mode == VID_GEN ? AsyncJobKind::VidGen : AsyncJobKind::ImgGen; + ServerRuntime request_runtime = runtime; + std::shared_lock model_lock(runtime.models->model_mutex, std::defer_lock); + if (auto model = body.find("model"); model != body.end()) { + try { + job->model = std::make_unique(resolve_model_selection(runtime, *model, mode)); + } catch (const std::exception& error) { res.status = 400; - res.set_content(R"({"error":"empty body"})", "application/json"); + res.set_content(json({{"error", error.what()}, {"code", "invalid_model_config"}}).dump(), "application/json"); return; } - if (!runtime_supports_generation_mode(*runtime, IMG_GEN)) { - res.status = 400; - res.set_content(json({{"error", unsupported_generation_mode_error(IMG_GEN)}}).dump(), "application/json"); + body.erase(model); + request_runtime.ctx_params = &job->model->context; + request_runtime.default_gen_params = &job->model->defaults; + } else { + model_lock.lock(); + if (!has_current_model(runtime)) { + res.status = 503; + res.set_content(R"({"error":"No current model is configured","code":"model_not_loaded"})", "application/json"); return; } - - json body = json::parse(req.body); - ImgGenJobRequest request; - std::string error_message; - if (!parse_img_gen_request(body, *runtime, request, error_message)) { + if (!runtime_supports_generation_mode(runtime, mode)) { res.status = 400; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); + res.set_content(json({{"error", unsupported_generation_mode_error(mode)}}).dump(), "application/json"); return; } + } - AsyncJobManager& manager = *runtime->async_job_manager; - std::shared_ptr job = std::make_shared(); - job->kind = AsyncJobKind::ImgGen; - job->status = AsyncJobStatus::Queued; - job->created_at = unix_timestamp_now_ms(); - job->img_gen = std::move(request); - - { - std::lock_guard lock(manager.mutex); - purge_expired_jobs(manager); - if (count_pending_jobs(manager) >= manager.max_pending_jobs) { - res.status = 429; - res.set_content(R"({"error":"job queue is full"})", "application/json"); - return; - } - job->id = make_async_job_id(manager); - manager.jobs[job->id] = job; - manager.queue.push_back(job->id); - } - - manager.cv.notify_one(); - - json out; - out["id"] = job->id; - out["kind"] = async_job_kind_name(job->kind); - out["status"] = async_job_status_name(job->status); - out["created"] = job->created_at; - out["poll_url"] = "/sdcpp/v1/jobs/" + job->id; - - res.status = 202; - res.set_content(out.dump(), "application/json"); - } catch (const json::parse_error& e) { + std::string error_message; + if (!parse_native_job_request(body, request_runtime, *job, error_message)) { res.status = 400; - res.set_content(json({{"error", "invalid json"}, {"message", e.what()}}).dump(), "application/json"); - } catch (const std::exception& e) { - res.status = 500; - res.set_content(json({{"error", "server_error"}, {"message", e.what()}}).dump(), "application/json"); + res.set_content(json({{"error", error_message}}).dump(), "application/json"); + return; + } + if (model_lock.owns_lock()) { + job->model_revision = runtime.models->revision; + job->request_body = std::move(body); + model_lock.unlock(); } - }); - - routes.post("/sdcpp/v1/vid_gen", [runtime](const httplib::Request& req, httplib::Response& res) { - try { - if (req.body.empty()) { - res.status = 400; - res.set_content(R"({"error":"empty body"})", "application/json"); - return; - } - if (!runtime_supports_generation_mode(*runtime, VID_GEN)) { - res.status = 400; - res.set_content(json({{"error", unsupported_generation_mode_error(VID_GEN)}}).dump(), "application/json"); - return; - } - json body = json::parse(req.body); - VidGenJobRequest request; - std::string error_message; - if (!parse_vid_gen_request(body, *runtime, request, error_message)) { - res.status = 400; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); + auto& manager = *runtime.async_job_manager; + { + std::lock_guard lock(manager.mutex); + purge_expired_jobs(manager); + if (count_pending_jobs(manager) >= manager.max_pending_jobs) { + res.status = 429; + res.set_content(R"({"error":"job queue is full"})", "application/json"); return; } + job->id = make_async_job_id(manager); + manager.jobs[job->id] = job; + manager.queue.push_back(job->id); + } + manager.cv.notify_one(); + + json out; + out["id"] = job->id; + out["kind"] = async_job_kind_name(job->kind); + out["status"] = async_job_status_name(AsyncJobStatus::Queued); + out["created"] = job->created_at; + out["poll_url"] = "/sdcpp/v1/jobs/" + job->id; + res.status = 202; + res.set_content(out.dump(), "application/json"); + } catch (const json::parse_error& error) { + res.status = 400; + res.set_content(json({{"error", "invalid json"}, {"message", error.what()}}).dump(), "application/json"); + } catch (const std::exception& error) { + res.status = 500; + res.set_content(json({{"error", "server_error"}, {"message", error.what()}}).dump(), "application/json"); + } +} - AsyncJobManager& manager = *runtime->async_job_manager; - std::shared_ptr job = std::make_shared(); - job->kind = AsyncJobKind::VidGen; - job->status = AsyncJobStatus::Queued; - job->created_at = unix_timestamp_now_ms(); - job->vid_gen = std::move(request); - - { - std::lock_guard lock(manager.mutex); - purge_expired_jobs(manager); - if (count_pending_jobs(manager) >= manager.max_pending_jobs) { - res.status = 429; - res.set_content(R"({"error":"job queue is full"})", "application/json"); - return; - } - job->id = make_async_job_id(manager); - manager.jobs[job->id] = job; - manager.queue.push_back(job->id); - } +void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { + ServerRuntime* runtime = &rt; + RuntimeRoutes routes(svr, rt); - manager.cv.notify_one(); + routes.get("/sdcpp/v1/capabilities", [runtime](const httplib::Request&, httplib::Response& res) { + res.status = 200; + res.set_content(make_capabilities_json(*runtime).dump(), "application/json"); + }); - json out; - out["id"] = job->id; - out["kind"] = async_job_kind_name(job->kind); - out["status"] = async_job_status_name(job->status); - out["created"] = job->created_at; - out["poll_url"] = "/sdcpp/v1/jobs/" + job->id; + routes.post("/sdcpp/v1/img_gen", [runtime](const httplib::Request& req, httplib::Response& res) { + submit_generation_job(*runtime, req, res, IMG_GEN); + }); - res.status = 202; - res.set_content(out.dump(), "application/json"); - } catch (const json::parse_error& e) { - res.status = 400; - res.set_content(json({{"error", "invalid json"}, {"message", e.what()}}).dump(), "application/json"); - } catch (const std::exception& e) { - res.status = 500; - res.set_content(json({{"error", "server_error"}, {"message", e.what()}}).dump(), "application/json"); - } + routes.post("/sdcpp/v1/vid_gen", [runtime](const httplib::Request& req, httplib::Response& res) { + submit_generation_job(*runtime, req, res, VID_GEN); }); routes.get(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+))", [runtime](const httplib::Request& req, httplib::Response& res) { + res.set_header("Cache-Control", "no-store"); AsyncJobManager& manager = *runtime->async_job_manager; std::lock_guard lock(manager.mutex); purge_expired_jobs(manager); @@ -810,6 +592,7 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { }); routes.post(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+)/cancel)", [runtime](const httplib::Request& req, httplib::Response& res) { + res.set_header("Cache-Control", "no-store"); AsyncJobManager& manager = *runtime->async_job_manager; std::lock_guard lock(manager.mutex); purge_expired_jobs(manager); @@ -834,16 +617,8 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(R"({"error":"job queue state changed before cancellation"})", "application/json"); return; } - res.status = 200; - res.set_content(make_async_job_json(manager, job).dump(), "application/json"); - return; - } - - if (job.status == AsyncJobStatus::Generating) { + } else if (job.status == AsyncJobStatus::Generating) { job.cancel_requested.store(true); - res.status = 200; - res.set_content(make_async_job_json(manager, job).dump(), "application/json"); - return; } res.status = 200; diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 6ac3866c77..c513ab9f86 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -9,6 +10,7 @@ #include #include #include +#include #include "common/common.h" #include "common/log.h" @@ -56,139 +58,20 @@ bool validate_server_img_gen_request(const ServerRuntime& runtime, (params.height && !within_dimension_limit(*params.height))) return false; if (params.hires_enabled.value_or(false)) { - if ((params.hires_width && !within_dimension_limit(*params.hires_width)) || - (params.hires_height && !within_dimension_limit(*params.hires_height))) + const double width = params.width.value_or(runtime.default_gen_params->width.value_or(512)); + const double height = params.height.value_or(runtime.default_gen_params->height.value_or(512)); + const double scale = params.hires_scale.value_or(2.f); + const auto target_width = params.hires_width.value_or(0), target_height = params.hires_height.value_or(0); + if (!within_dimension_limit(target_width > 0 ? target_width : target_height > 0 ? target_height + : width * scale) || + !within_dimension_limit(target_height > 0 ? target_height : target_width > 0 ? target_width + : height * scale)) return false; - if (params.hires_width.value_or(0) <= 0 && params.hires_height.value_or(0) <= 0) { - // Use the documented library defaults for this resource-policy check only. - const float scale = params.hires_scale.value_or(2.f); - if (!within_dimension_limit(std::round(params.width.value_or(512) * scale)) || - !within_dimension_limit(std::round(params.height.value_or(512) * scale))) - return false; - } - } - if (!request.adetailer_enabled || runtime.default_gen_params->ad_model_path.empty()) { - return true; - } - auto pass_valid = [&](const ServerADetailerPass& pass) { - if ((pass.width && !within_dimension_limit(*pass.width)) || - (pass.height && !within_dimension_limit(*pass.height))) { - return false; - } - // Match the native key normalization, but leave full option parsing to ADetailer. - auto trim = [](const std::string& text) { - const auto first = text.find_first_not_of(" \t\r\n"); - return first == std::string::npos ? std::string() : text.substr(first, text.find_last_not_of(" \t\r\n") - first + 1); - }; - std::stringstream stream(pass.extra_args); - std::string item; - while (std::getline(stream, item, ',')) { - const auto equals = item.find('='); - if (equals == std::string::npos) { - continue; - } - auto key = trim(item.substr(0, equals)); - std::transform(key.begin(), key.end(), key.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); - if (key != "inpaint_width" && key != "inpaint_height" && key != "steps") { - continue; - } - const auto value = trim(item.substr(equals + 1)); - const int minimum = key == "steps" ? 0 : 1; - const int maximum = key == "steps" ? k_max_adetailer_steps : k_max_generation_dimension; - try { - size_t used = 0; - const int parsed = std::stoi(value, &used); - if (used == value.size() && parsed >= minimum && parsed <= maximum) { - continue; - } - } catch (const std::exception&) { - } - error_message = "ADetailer " + key + " must be between " + std::to_string(minimum) + " and " + std::to_string(maximum); - return false; - } - return true; - }; - if (request.adetailer_passes.empty()) { - ServerADetailerPass pass; - pass.extra_args = params.extra_ad_args; - return pass_valid(pass); - } - return std::all_of(request.adetailer_passes.begin(), request.adetailer_passes.end(), pass_valid); -} - -bool apply_server_adetailer(ServerRuntime& runtime, - ImgGenJobRequest& request, - SDImageVec& results) { - auto& gen_params = request.gen_params; - const auto& ad_model_path = runtime.default_gen_params->ad_model_path; - if (!request.adetailer_enabled || ad_model_path.empty()) { - return true; - } - std::string error_message; - if (!validate_server_img_gen_request(runtime, request, error_message)) { - LOG_ERROR("%s", error_message.c_str()); - return false; } - - std::vector passes = request.adetailer_passes; - if (passes.empty()) { - ServerADetailerPass pass; - pass.prompt = gen_params.ad_prompt; - pass.negative_prompt = gen_params.ad_negative_prompt; - pass.extra_args = gen_params.extra_ad_args; - passes.push_back(std::move(pass)); - } - - ADetailerCtxPtr ad_ctx(create_sd_adetailer(ad_model_path.c_str(), - runtime.ctx_params->n_threads, - runtime.ctx_params->effective_backend.c_str(), - runtime.ctx_params->effective_params_backend.c_str())); - if (ad_ctx == nullptr) { - LOG_ERROR("sd_adetailer_create failed"); + if ((!runtime.default_gen_params->ad_model_path.empty() && request.adetailer_enabled) || !request.adetailer_passes.empty()) { + error_message = "ADetailer requires a DGL script"; return false; } - - for (const auto& pass : passes) { - for (int i = 0; i < results.count(); ++i) { - if (results[i].data == nullptr) { - continue; - } - SDOptBuilder ad_options(gen_params.to_image_opt(true).release()); - ad_options.unset("width"); - ad_options.unset("height"); - ad_options.unset("strength"); - ad_options.set_string("adetail.prompt", pass.prompt); - ad_options.set_string("adetail.negative_prompt", pass.negative_prompt); - ad_options.set_string("adetail.args", pass.extra_args); - ad_options.set_int("seed", generation_seed(results.generation_info(i))); - ad_options.set_int("width", pass.width); - ad_options.set_int("height", pass.height); - ad_options.set_float("strength", pass.strength); - if (pass.clip_skip) { - ad_options.set_int("clip_skip", pass.clip_skip); - } - if (pass.automatic_scheduler) { - ad_options.set_string("sample.scheduler", "auto"); - } - - sd_result_t* detailed = nullptr; - if (!adetail_sd_image(ad_ctx.get(), - runtime.sd_ctx, - results[i], - ad_options.finish(), - &detailed) || - detailed == nullptr || sd_result_get_image_count(detailed) <= 0 || sd_tensor_data(sd_result_get_image(detailed, 0)) == nullptr) { - sd_result_free(detailed); - LOG_ERROR("ADetailer failed for image %d", i + 1); - return false; - } - results.append_generation_info(i, sd_result_get_generation_info(detailed, 0), runtime.ctx_params->lora_model_dir); - sd_image_free(&results[i]); - results[i] = take_result_image(detailed, 0); - - sd_result_free(detailed); - } - } return true; } @@ -210,11 +93,18 @@ static const std::string k_base64_chars = "0123456789+/"; std::string base64_encode(const std::vector& bytes) { + return base64_encode(bytes.data(), bytes.size()); +} + +std::string base64_encode(const void* data, size_t size) { std::string ret; - int val = 0; - int valb = -6; - for (uint8_t c : bytes) { - val = (val << 8) + c; + ret.reserve((size + 2) / 3 * 4); + uint32_t val = 0; + int valb = -6; + const auto* bytes = static_cast(data); + for (size_t i = 0; i < size; ++i) { + const auto c = bytes[i]; + val = (val << 8) + c; valb += 8; while (valb >= 0) { ret.push_back(k_base64_chars[(val >> valb) & 0x3F]); @@ -345,6 +235,9 @@ std::string video_mime_type(const std::string& output_format) { } bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) { + if (!has_current_model(runtime)) { + return false; + } if (mode == VID_GEN) { return sd_ctx_supports_video_generation(runtime.sd_ctx); } @@ -354,14 +247,54 @@ bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) return true; } +bool has_current_model(const ServerRuntime& runtime) { + return !runtime.ctx_params->model_path.empty() || !runtime.ctx_params->diffusion_model_path.empty(); +} + +bool generate_server_images(sd_ctx_t* ctx, ImgGenJobRequest& request, SDImageVec& results, std::string& error_message) { + auto params = request.to_image_opt(); + PromptImageCallbackGuard prompt_images(ctx, request.gen_params); + sd_result_t* generated = nullptr; + if (!generate_sd_image(ctx, params, &generated)) { + error_message = sd_get_last_error(); + if (error_message.empty()) + error_message = "generate_image returned no results"; + return false; + } + results.adopt(generated); + if (results.empty()) { + error_message = "generate_image returned no results"; + return false; + } + return true; +} + std::string unsupported_generation_mode_error(SDMode mode) { + if (const auto* error = sd_get_last_error(); *error) { + return error; + } if (mode == VID_GEN) { - return "loaded model does not support vid_gen"; + return "current model does not support vid_gen"; } if (mode == IMG_GEN) { - return "loaded model does not support img_gen"; + return "current model does not support img_gen"; + } + return "current model does not support requested mode"; +} + +static int parse_weight_ttl(int argc, const char** argv, int index, int& ttl) { + if (index + 1 < argc) { + const std::string_view value = argv[index + 1]; + const auto* end = value.data() + value.size(); + int seconds = 0; + const auto parsed = std::from_chars(value.data(), end, seconds); + if (parsed.ec == std::errc{} && parsed.ptr == end && seconds >= -1) { + ttl = seconds; + return 1; + } } - return "loaded model does not support requested mode"; + LOG_ERROR("%s expects an integer greater than or equal to -1", argv[index]); + return -1; } ArgOptions SDSvrParams::get_options() { @@ -370,6 +303,9 @@ ArgOptions SDSvrParams::get_options() { options.string_options = { {"-l", "--listen-ip", "server listen ip (default: 127.0.0.1)", 0, &listen_ip}, {"", "--serve-html-path", "path to HTML file to serve at root (optional)", 0, &serve_html_path}, + {"", "--dgl-dir", "Web UI script directory (default: dgl)", 0, &dgl_dir}, + {"", "--output-dir", "directory for DGL writes and output previews (default: /output)", 0, + &output_dir}, }; options.int_options = { @@ -384,6 +320,7 @@ ArgOptions SDSvrParams::get_options() { options.bool_options = { {"", "--color", "colors the logging tags according to level", true, &color}, + {"", "--no-media-view", "disable media file viewing", false, &media_view}, }; auto on_help_arg = [&](int, const char**, int, bool& valid) { @@ -394,6 +331,11 @@ ArgOptions SDSvrParams::get_options() { options.manual_options = { {"-h", "--help", "show this help message and exit", on_help_arg}, + {"", "--weight-residency-ttl", + "idle seconds before unloading model components from RAM and VRAM (-1 disabled, 0 immediate; default: -1)", + [this](int argc, const char** argv, int index) { + return parse_weight_ttl(argc, argv, index, weight_residency_ttl); + }}, {"", "--model-dir", "model root; repeat to search multiple directories (default: models)", [this](int argc, const char** argv, int index) { if (++index >= argc || argv[index][0] == '\0') @@ -431,14 +373,15 @@ bool SDSvrParams::validate() { LOG_ERROR("error: serve_html_path file does not exist: %s", serve_html_path.c_str()); return false; } + if (dgl_dir.empty()) { + LOG_ERROR("--dgl-dir requires a directory path"); + return false; + } return true; } bool SDSvrParams::resolve_and_validate() { - if (!validate()) { - return false; - } - return true; + return validate() && load_api_keys(); } std::string SDSvrParams::to_string() const { @@ -449,7 +392,12 @@ std::string SDSvrParams::to_string() const { << " listen_port: \"" << listen_port << "\",\n" << " max_pending_jobs: " << max_pending_jobs << ",\n" << " completed_ttl_seconds: " << completed_ttl_seconds << ",\n" + << " weight_residency_ttl: " << weight_residency_ttl << ",\n" << " serve_html_path: \"" << serve_html_path << "\",\n" + << " dgl_dir: \"" << dgl_dir << "\",\n" + << " api_keys: " << api_keys.size() << ",\n" + << " cors_origins: " << cors_origins.size() << ",\n" + << " media_view: " << std::boolalpha << media_view << ",\n" << "}"; return oss.str(); } @@ -564,10 +512,9 @@ void refresh_upscaler_cache(ServerRuntime& rt) { UpscalerEntry upscaler_entry; upscaler_entry.name = p.stem().u8string(); std::error_code abs_ec; - fs::path abs_path = fs::absolute(p, abs_ec); - upscaler_entry.fullpath = (abs_ec ? p : abs_path.lexically_normal()).u8string(); - upscaler_entry.model_name = "ESRGAN_4x"; - upscaler_entry.path = p.filename().u8string(); + fs::path abs_path = fs::absolute(p, abs_ec); + upscaler_entry.fullpath = (abs_ec ? p : abs_path.lexically_normal()).u8string(); + upscaler_entry.path = p.filename().u8string(); std::error_code size_ec; upscaler_entry.file_size = it->file_size(size_ec); @@ -577,19 +524,15 @@ void refresh_upscaler_cache(ServerRuntime& rt) { } std::error_code time_ec; - upscaler_entry.last_modified = it->last_write_time(time_ec); - auto previous = std::find_if(previous_cache.begin(), previous_cache.end(), [&](const UpscalerEntry& cached) { + upscaler_entry.last_modified = it->last_write_time(time_ec); + auto previous = std::find_if(previous_cache.begin(), previous_cache.end(), [&](const UpscalerEntry& cached) { return cached.fullpath == upscaler_entry.fullpath && cached.file_size == upscaler_entry.file_size && (!time_ec && cached.last_modified == upscaler_entry.last_modified); }); - upscaler_entry.image_upscale_factor = previous != previous_cache.end() - ? previous->image_upscale_factor - : sd_upscaler_probe_scale(upscaler_entry.fullpath.c_str()); - if (upscaler_entry.image_upscale_factor > 0) { - upscaler_entry.scale = upscaler_entry.image_upscale_factor; - upscaler_entry.model_name = "ESRGAN_" + std::to_string(upscaler_entry.scale) + "x"; - } + const int scale = previous != previous_cache.end() ? previous->scale : sd_upscaler_probe_scale(upscaler_entry.fullpath.c_str()); + upscaler_entry.scale = scale > 0 ? scale : 4; + upscaler_entry.model_name = "ESRGAN_" + std::to_string(upscaler_entry.scale) + "x"; new_cache.push_back(std::move(upscaler_entry)); it.increment(ec); diff --git a/examples/server/runtime.h b/examples/server/runtime.h index abb9766f71..7c20ec21e4 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -24,16 +24,27 @@ struct SDSvrParams { int listen_port = 1234; int max_pending_jobs = 64; int completed_ttl_seconds = 600; + int weight_residency_ttl = -1; std::string serve_html_path; + std::string dgl_dir = "dgl"; + bool media_view = true; std::vector model_dirs; + std::string output_dir; + std::vector api_keys; + std::string api_key_file; + std::vector cors_origins; bool normal_exit = false; sd_log_level_t log_level = SD_LOG_INFO; bool color = false; ArgOptions get_options(); + void add_access_options(ArgOptions& options, const std::vector& groups); bool validate(); bool resolve_and_validate(); std::string to_string() const; + +private: + bool load_api_keys(); }; struct LoraEntry { @@ -50,7 +61,6 @@ struct UpscalerEntry { std::string fullpath; std::string model_name; int scale = 4; - int image_upscale_factor = 0; uintmax_t file_size = 0; std::filesystem::file_time_type last_modified; }; @@ -124,6 +134,7 @@ struct VidGenJobRequest { }; std::string base64_encode(const std::vector& bytes); +std::string base64_encode(const void* bytes, size_t size); std::string normalize_output_format(std::string output_format); std::vector supported_img_output_formats(bool allow_webp = true); std::vector supported_vid_output_formats(); @@ -138,11 +149,11 @@ bool assign_output_options(VidGenJobRequest& request, std::string& error_message); std::string video_mime_type(const std::string& output_format); bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode); +bool has_current_model(const ServerRuntime& runtime); +void configure_server_file_access(ServerModels& models, const SDSvrParams& params, const SDContextParams& config); +bool generate_server_images(sd_ctx_t* ctx, ImgGenJobRequest& request, SDImageVec& results, std::string& error_message); std::string unsupported_generation_mode_error(SDMode mode); void refresh_lora_cache(ServerRuntime& rt); std::string get_lora_full_path(ServerRuntime& rt, const std::string& path); void refresh_upscaler_cache(ServerRuntime& rt); int64_t unix_timestamp_now_ms(); -bool apply_server_adetailer(ServerRuntime& runtime, - ImgGenJobRequest& request, - SDImageVec& results); diff --git a/examples/server/server_access.cpp b/examples/server/server_access.cpp new file mode 100644 index 0000000000..caa9e5c659 --- /dev/null +++ b/examples/server/server_access.cpp @@ -0,0 +1,269 @@ +#include "server_access.h" + +#include +#include +#include +#include +#include +#include + +#include "runtime.h" + +static bool is_registered_option(const std::vector& groups, std::string_view name) { + const auto contains = [name](const auto& options) { + return std::any_of(options.begin(), options.end(), [name](const auto& option) { + return name == option.short_name || name == option.long_name; + }); + }; + return std::any_of(groups.begin(), groups.end(), [&](const ArgOptions& options) { + return contains(options.string_options) || contains(options.int_options) || + contains(options.float_options) || contains(options.bool_options) || + contains(options.manual_options); + }); +} + +static bool append_option_list(const char* name, const char* value, const char* entry_name, std::vector& values) { + std::istringstream input(value); + const auto previous_count = values.size(); + for (std::string entry; std::getline(input, entry, ',');) { + if (!entry.empty()) { + values.push_back(entry); + } + } + if (values.size() == previous_count) { + LOG_ERROR("error: %s needs at least one %s", name, entry_name); + return false; + } + return true; +} + +void SDSvrParams::add_access_options(ArgOptions& options, const std::vector& groups) { + const auto add_option = [&](const char* name, const char* description, auto apply) { + const auto parse_value = [&groups, apply](int argc, const char** argv, int index, bool& error_reported) { + const int value_index = index + 1; + if (value_index >= argc || !argv[value_index][0] || is_registered_option(groups, argv[value_index])) { + LOG_ERROR("error: missing value for argument \"%s\"", argv[index]); + error_reported = true; + return -1; + } + return apply(value_index, argv) ? 1 : -1; + }; + options.manual_options.push_back({"", name, description, parse_value}); + }; + add_option("--api-key", "API key clients must send (Authorization: Bearer KEY or X-Api-Key); comma-separated for several", + [this](int index, const char** argv) { + return append_option_list(argv[index - 1], argv[index], "key", api_keys); + }); + add_option("--api-key-file", "file with API keys, one per line (keeps them off the command line)", + [this](int index, const char** argv) { + api_key_file = argv_to_utf8(index, argv); + return true; + }); + add_option("--cors-origins", "additional web origins allowed to make cross-origin requests, comma-separated (default: none)", + [this](int index, const char** argv) { + return append_option_list(argv[index - 1], argv[index], "origin", cors_origins); + }); +} + +bool SDSvrParams::load_api_keys() { + if (api_key_file.empty()) { + return true; + } + std::ifstream file(std::filesystem::u8path(api_key_file)); + if (!file) { + LOG_ERROR("error: can't read api_key_file: %s", api_key_file.c_str()); + return false; + } + const auto previous_count = api_keys.size(); + for (std::string line; std::getline(file, line);) { + const auto last = line.find_last_not_of(" \t\r\n"); + if (last != std::string::npos) { + const auto first = line.find_first_not_of(" \t"); + api_keys.push_back(line.substr(first, last - first + 1)); + } + } + if (api_keys.size() == previous_count) { + LOG_ERROR("error: api_key_file has no keys: %s", api_key_file.c_str()); + return false; + } + return true; +} + +static bool is_web_ui_request(const httplib::Request& req) { + return req.method == "GET" && req.path == "/"; +} + +static bool requires_api_key(const SDSvrParams& params, const httplib::Request& req) { + return !params.api_keys.empty() && req.method != "OPTIONS" && !is_web_ui_request(req); +} + +static bool api_key_matches(const std::vector& keys, std::string_view key) { + bool found = false; + // Compare every byte of every configured key without a prefix-dependent early return. + for (const auto& configured_key : keys) { + unsigned char diff = configured_key.size() != key.size(); + for (size_t i = 0; i < configured_key.size(); i++) { + diff |= static_cast(configured_key[i] ^ (i < key.size() ? key[i] : 0)); + } + found |= diff == 0; + } + return found; +} + +static bool has_valid_api_key(const httplib::Request& req, const std::vector& keys) { + const auto key = req.get_header_value("X-Api-Key"); + if (!key.empty()) { + return api_key_matches(keys, key); + } + + constexpr std::string_view scheme = "bearer"; + const auto auth = req.get_header_value("Authorization"); + const auto separator = auth.find(' '); + if (separator != scheme.size() || + !std::equal(scheme.begin(), scheme.end(), auth.begin(), [](char expected, unsigned char actual) { + return expected == std::tolower(actual); + })) { + return false; + } + const auto key_start = auth.find_first_not_of(' ', separator); + return key_start != std::string::npos && api_key_matches(keys, std::string_view(auth).substr(key_start)); +} + +static bool is_allowed_origin(const std::vector& allowed, std::string_view origin) { + return !origin.empty() && std::find(allowed.begin(), allowed.end(), origin) != allowed.end(); +} + +static void set_cors_headers(const httplib::Request& req, httplib::Response& res, const std::vector& allowed) { + const bool preflight = req.method == "OPTIONS"; + std::string vary = "Origin, Sec-Fetch-Site"; + if (preflight) + vary += ", Access-Control-Request-Headers"; + else if (is_web_ui_request(req)) + vary += ", Sec-Fetch-Mode, Sec-Fetch-Dest"; + res.set_header("Vary", vary); + + const auto origin = req.get_header_value("Origin"); + if (!is_allowed_origin(allowed, origin)) { + return; + } + res.set_header("Access-Control-Allow-Origin", origin); + res.set_header("Access-Control-Allow-Credentials", "true"); + res.set_header("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"); + const auto headers = preflight ? req.get_header_value("Access-Control-Request-Headers") : std::string{}; + res.set_header("Access-Control-Allow-Headers", headers.empty() ? "*" : headers); +} + +static bool is_server_host(std::string_view host, const std::string& listen_ip) { + if (host.empty()) + return false; + if (host.back() != ']') { + const auto port_separator = host.rfind(':'); + if (port_separator != std::string_view::npos) { + const auto port = host.substr(port_separator + 1); + if (port.empty() || port.find_first_not_of("0123456789") != std::string_view::npos) + return false; + host = host.substr(0, port_separator); + } + } + if (host == "localhost" || host == listen_ip) + return true; + if (host.size() > 2 && host.front() == '[' && host.back() == ']') { + const std::string ipv6(host.substr(1, host.size() - 2)); + in6_addr address{}; + return inet_pton(AF_INET6, ipv6.c_str(), &address) == 1; + } + const std::string ipv4(host); + in_addr address{}; + return inet_pton(AF_INET, ipv4.c_str(), &address) == 1; +} + +static bool is_allowed_request_origin(const httplib::Request& req, const SDSvrParams& params) { + if (req.get_header_value_count("Host") != 1 || + req.get_header_value_count("Origin") > 1 || req.get_header_value_count("Sec-Fetch-Site") > 1) + return false; + + // Same-origin browser headers alone do not distinguish a DNS-rebound hostname. + const auto host = req.get_header_value("Host"); + const auto http_origin = "http://" + host; + const auto https_origin = "https://" + host; + if (!is_server_host(host, params.listen_ip) && !is_allowed_origin(params.cors_origins, http_origin) && + !is_allowed_origin(params.cors_origins, https_origin)) + return false; + + if (is_web_ui_request(req) && req.get_header_value_count("Sec-Fetch-Mode") == 1 && + req.get_header_value_count("Sec-Fetch-Dest") == 1 && req.get_header_value("Sec-Fetch-Mode") == "navigate" && + req.get_header_value("Sec-Fetch-Dest") == "document") + return true; + + const auto origin = req.get_header_value("Origin"); + if (is_allowed_origin(params.cors_origins, origin)) + return true; + const auto site = req.get_header_value("Sec-Fetch-Site"); + return (site.empty() || site == "same-origin" || site == "none") && + (origin.empty() || origin == http_origin); +} + +SDHttpServer::SDHttpServer(const SDSvrParams& params) { + set_pre_routing_handler([¶ms](const httplib::Request& req, httplib::Response& res) { + if (!is_allowed_request_origin(req, params)) { + res.status = 403; + res.set_content(R"({"error":"Request origin is not allowed"})", "application/json"); + close_after_response_ = true; + return HandlerResponse::Handled; + } + if (req.method == "OPTIONS") { + close_after_response_ = req.has_header("Transfer-Encoding") || req.get_header_value_u64("Content-Length") > 0; + res.status = 204; + return HandlerResponse::Handled; + } + if (requires_api_key(params, req) && !has_valid_api_key(req, params.api_keys)) { + res.status = 401; + res.set_header("WWW-Authenticate", "Bearer realm=\"sd-server\""); + res.set_content(R"({"error":{"code":401,"message":"Invalid API Key","type":"authentication_error"}})", + "application/json"); + close_after_response_ = true; + return HandlerResponse::Handled; + } + return HandlerResponse::Unhandled; + }); + + set_post_routing_handler([¶ms](const httplib::Request& req, httplib::Response& res) { + if (close_after_response_) { + res.headers.erase("Connection"); + res.headers.erase("Keep-Alive"); + res.set_header("Connection", "close"); + } + if (requires_api_key(params, req)) { + res.headers.erase("Cache-Control"); + res.set_header("Cache-Control", "no-store"); + } + res.set_header("Cross-Origin-Resource-Policy", "same-origin"); + set_cors_headers(req, res, params.cors_origins); + }); +} + +thread_local bool SDHttpServer::close_after_response_ = false; + +// cpp-httplib can send Connection: close without stopping its keep-alive loop. +// Stop the loop after early responses so unread request bytes are discarded. +bool SDHttpServer::process_and_close_socket(socket_t socket) { + std::string remote_addr; + std::string local_addr; + int remote_port = 0; + int local_port = 0; + httplib::detail::get_remote_ip_and_port(socket, remote_addr, remote_port); + httplib::detail::get_local_ip_and_port(socket, local_addr, local_port); + const bool result = httplib::detail::process_server_socket( + svr_sock_, socket, keep_alive_max_count_, keep_alive_timeout_sec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, + [&](httplib::Stream& stream, bool close_connection, bool& connection_closed) { + close_after_response_ = false; + const bool written = process_request(stream, remote_addr, remote_port, local_addr, + local_port, close_connection, connection_closed, nullptr); + connection_closed |= close_after_response_; + return written; + }); + httplib::detail::shutdown_socket(socket); + httplib::detail::close_socket(socket); + return result; +} diff --git a/examples/server/server_access.h b/examples/server/server_access.h new file mode 100644 index 0000000000..074aabac76 --- /dev/null +++ b/examples/server/server_access.h @@ -0,0 +1,15 @@ +#pragma once + +#include "httplib.h" + +struct SDSvrParams; + +class SDHttpServer final : public httplib::Server { +public: + explicit SDHttpServer(const SDSvrParams& params); + +private: + bool process_and_close_socket(socket_t socket) override; + + static thread_local bool close_after_response_; +}; diff --git a/ggml b/ggml index eeda9ec48f..e9e6fe2c4c 160000 --- a/ggml +++ b/ggml @@ -1 +1 @@ -Subproject commit eeda9ec48fc84a3df0bb9dcc19ae9053075a2539 +Subproject commit e9e6fe2c4c460eb7e6293c512acd6df777b4a7ac diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index c5a25c6d10..9829afef09 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -35,8 +35,9 @@ typedef struct sd_ctx_t sd_ctx_t; typedef struct sd_result sd_result_t; typedef struct sd_opt sd_opt_t; typedef struct sd_upscaler sd_upscaler_t; -typedef struct sd_vid_upscaler sd_vid_upscaler_t; -typedef struct sd_adetailer sd_adetailer_t; +typedef struct sd_dgl_ctx_t sd_dgl_ctx_t; +typedef struct sd_dgl_result_t sd_dgl_result_t; +typedef struct sd_dgl_value_t sd_dgl_value_t; // Status and diagnostics @@ -58,6 +59,51 @@ typedef enum { // Valid until the next API call; free functions and tensor retain preserve it. SD_API const char* sd_get_last_error(void); +// Generation metadata + +// Returns inferred image parameters and infotext as UTF-8 JSON, or {} when no +// image parameters can be inferred. Does not execute source or read files. +// Borrowed until the next call to this function on the same thread. +// Returns NULL on failure; see sd_get_last_error(). +SD_API const char* sd_get_generation_metadata(const char* source); + +typedef enum { + SD_METADATA_READ_JSON = 1u << 0, + SD_METADATA_READ_RAW = 1u << 1, + SD_METADATA_READ_BRIEF = 1u << 2, + SD_METADATA_READ_STRUCTURAL = 1u << 3, +} sd_metadata_read_flags_t; + +// Reads container metadata without loading a model. Flags may be ORed together; +// zero selects the default text report. Returns NULL on failure. +// Borrowed until the next call to this function on the same thread. +SD_API const char* sd_read_metadata(const char* path, uint32_t flags); + +typedef enum { + SD_METADATA_PNG, + SD_METADATA_JPEG, + SD_METADATA_XMP, + SD_METADATA_AVI, +} sd_metadata_format_t; + +// Builds PNG iTXt chunks, JPEG COM segments, UTF-8 XMP or an AVI INFO chunk. +// PNG/JPEG/XMP contain the DGL source and inferred infotext; AVI stores source. +// Does not write files. Borrowed bytes remain valid until the next call to this +// function on the same thread. Empty source succeeds with NULL, 0. +// Output pointers are required and cleared on failure. +SD_API sd_status_t sd_get_metadata_chunk(const char* source, sd_metadata_format_t format, const void** data_out, size_t* size_out); + +// File access for generation and DGL contexts + +typedef enum { + SD_DGL_FILE_READ, + SD_DGL_FILE_READ_MODEL, + SD_DGL_FILE_WRITE, +} sd_dgl_file_access_t; + +// Return false to reject the access. The UTF-8 path is valid only during the callback. +typedef bool (*sd_dgl_file_access_cb_t)(const char* path, sd_dgl_file_access_t access, void* userdata); + // Tensors and media typedef int32_t sd_tensor_type_t; @@ -97,6 +143,10 @@ SD_API int64_t sd_tensor_dim(const sd_tensor_t* tensor, size_t axis); SD_API size_t sd_tensor_byte_size(const sd_tensor_t* tensor); SD_API const void* sd_tensor_data(const sd_tensor_t* tensor); +// Saves a NumPy .npy file. NumPy shape is the reverse of sd_tensor shape. +// Failures use sd_get_last_error(). +SD_API bool sd_tensor_save(const sd_tensor_t* tensor, const char* path); + // Options typedef struct { @@ -115,10 +165,6 @@ typedef sd_opt_t sd_img_gen_opt_t; typedef sd_opt_t sd_vid_gen_opt_t; typedef sd_opt_t sd_upscaler_opt_t; typedef sd_opt_t sd_upscale_opt_t; -typedef sd_opt_t sd_vid_upscaler_opt_t; -typedef sd_opt_t sd_vid_upscale_opt_t; -typedef sd_opt_t sd_adetailer_opt_t; -typedef sd_opt_t sd_adetail_opt_t; // Parameter keys and types are documented in docs/guides/c_api.md. // Setters replace values atomically; a failed setter preserves the previous value. @@ -131,10 +177,6 @@ SD_API sd_img_gen_opt_t* sd_img_gen_opt_create(void); SD_API sd_vid_gen_opt_t* sd_vid_gen_opt_create(void); SD_API sd_upscaler_opt_t* sd_upscaler_opt_create(void); SD_API sd_upscale_opt_t* sd_upscale_opt_create(void); -SD_API sd_vid_upscaler_opt_t* sd_vid_upscaler_opt_create(void); -SD_API sd_vid_upscale_opt_t* sd_vid_upscale_opt_create(void); -SD_API sd_adetailer_opt_t* sd_adetailer_opt_create(void); -SD_API sd_adetail_opt_t* sd_adetail_opt_create(void); SD_API void sd_opt_free(sd_opt_t* params); SD_API sd_status_t sd_opt_set_bool(sd_opt_t* params, const char* key, bool value); @@ -168,6 +210,16 @@ SD_API sd_status_t sd_opt_unset(sd_opt_t* params, const char* key); // its own configuration; params may be freed immediately after the call returns. SD_API sd_status_t sd_ctx_create(const sd_ctx_opt_t* params, sd_ctx_t** ctx_out); SD_API void sd_ctx_free(sd_ctx_t* ctx); +// Borrows the context used for generation, or returns NULL if ctx is NULL. +// It shares component caches and can run scripts between generation calls. +// Its lifetime is tied to ctx. Do not pass it to sd_dgl_ctx_free(). +SD_API sd_dgl_ctx_t* sd_ctx_get_dgl_ctx(sd_ctx_t* ctx); +// Copies the new model configuration into an idle context. The execution +// settings, callbacks, and DGL component cache belong to the existing context. +// Returns SD_STATUS_BUSY during generation, DGL execution, or a model probe. +SD_API sd_status_t sd_ctx_set_model_options(sd_ctx_t* ctx, const sd_ctx_opt_t* params); +// Applies to generated programs and model probing. Register or clear while idle. +SD_API sd_status_t sd_ctx_set_file_access_callback(sd_ctx_t* ctx, sd_dgl_file_access_cb_t callback, void* userdata); SD_API sd_status_t sd_generate_image(sd_ctx_t* ctx, const sd_img_gen_opt_t* params, sd_result_t** result_out); SD_API sd_status_t sd_generate_video(sd_ctx_t* ctx, const sd_vid_gen_opt_t* params, sd_result_t** result_out); @@ -175,12 +227,7 @@ SD_API sd_status_t sd_generate_video(sd_ctx_t* ctx, const sd_vid_gen_opt_t* para SD_API bool sd_ctx_supports_image_generation(const sd_ctx_t* sd_ctx); SD_API bool sd_ctx_supports_video_generation(const sd_ctx_t* sd_ctx); -// ControlNet hot-swap APIs are not safe to call while generation is in flight. -SD_API bool sd_ctx_load_control_net(sd_ctx_t* sd_ctx, const char* path); -SD_API bool sd_ctx_unload_control_net(sd_ctx_t* sd_ctx); -SD_API bool sd_ctx_has_control_net(const sd_ctx_t* sd_ctx); - -// Requires a loaded context; returns a static string owned by the library, or "Unknown". +// Probes model metadata lazily; returns a static string, or "Unknown" on error. SD_API const char* sd_get_model_version_name(const sd_ctx_t* sd_ctx); enum sd_cancel_mode_t { @@ -202,6 +249,10 @@ typedef enum { SD_RESULT_VIDEO = 2, } sd_result_kind_t; +// Probes the candidate model before replacing the current configuration. +// Accepts SD_RESULT_IMAGE or SD_RESULT_VIDEO and preserves the current model on failure. +SD_API sd_status_t sd_ctx_set_model_options_for_generation(sd_ctx_t* ctx, const sd_ctx_opt_t* params, sd_result_kind_t kind); + // Results own all outputs independently of ctx and params. Views are read-only and // borrowed until sd_result_free(). Retain a tensor to keep its data independently. // Media descriptors contain metadata and borrowed immutable tensor handles. @@ -212,7 +263,8 @@ SD_API const sd_tensor_t* sd_result_get_image(const sd_result_t* result, size_t // Materializes contiguous U8 [C,W,H,T] storage on first access. SD_API const sd_video_t* sd_result_get_video(const sd_result_t* result); -// Image metadata is per image; video metadata is shared by all frame indices. +// Returns the exact UTF-8 DGL program used for inference. Image programs are per image; +// video programs are shared by all frame indices. Host inputs must be supplied again to replay. SD_API const char* sd_result_get_generation_info(const sd_result_t* result, size_t index); SD_API const sd_audio_t* sd_result_get_audio(const sd_result_t* result); SD_API int sd_result_get_fps(const sd_result_t* result); @@ -296,35 +348,118 @@ SD_API int sd_upscaler_get_scale(const sd_upscaler_t* upscaler); // Reads model metadata only; returns 0 if it is not a recognized RGB upscaler. SD_API int sd_upscaler_probe_scale(const char* model_path); -// Video upscaling - -SD_API sd_status_t sd_vid_upscaler_create(const sd_vid_upscaler_opt_t* opt, sd_vid_upscaler_t** out); -SD_API void sd_vid_upscaler_free(sd_vid_upscaler_t* upscaler); -SD_API sd_status_t sd_upscale_video( - sd_vid_upscaler_t* upscaler, - const sd_vid_upscale_opt_t* opt, - sd_result_t** out); - -// ADetailer - -SD_API sd_status_t sd_adetailer_create(const sd_adetailer_opt_t* opt, sd_adetailer_t** out); -SD_API void sd_adetailer_free(sd_adetailer_t* adetailer); -SD_API sd_status_t sd_adetail( - sd_adetailer_t* adetailer, - sd_ctx_t* ctx, - const sd_adetail_opt_t* opt, - sd_result_t** out); - -// Image preprocessing - -SD_API sd_status_t sd_preprocess_canny( - const sd_tensor_t* image, - float high_threshold, - float low_threshold, - float weak, - float strong, - bool inverse, - sd_tensor_t** image_out); +// DGL (Diffusion Graph Language) + +SD_API const char* sd_dgl_builtin_catalog(void); + +// A context shares loaded components across scripts and runs one script at a time. +// Keep the context alive until all calls using it return. +SD_API sd_dgl_ctx_t* sd_dgl_ctx_create(void); +// Creates a context that releases models after their last use in each run. +SD_API sd_dgl_ctx_t* sd_dgl_ctx_create_once(void); +SD_API void sd_dgl_ctx_free(sd_dgl_ctx_t* ctx); +// Sets options on an idle context: max_vram, max_ram, conditioning_cache_size, batched_cfg, +// n_threads, auto_fit, enable_mmap, eager_load, disable_prefetch, disable_segmented_compute, +// embed_metadata (default on; controls generation metadata in DGL image/video saves), +// console_progress (default off; keeps built-in progress output alongside callbacks). +// Threading, placement and weight-loading options invalidate cached models when changed. +SD_API bool sd_dgl_ctx_set(sd_dgl_ctx_t* ctx, const char* key, const char* value); + +// Unloads cached model components and clears idle buffer caches on supported backends. +// The context keeps its settings and callbacks. +// Subsequent requests reload components as needed. Returns SD_STATUS_BUSY during execution. +SD_API sd_status_t sd_dgl_ctx_unload_models(sd_dgl_ctx_t* ctx); + +// Optional per-context callback. A null callback restores unrestricted file access. +SD_API bool sd_dgl_ctx_set_file_access_callback(sd_dgl_ctx_t* ctx, sd_dgl_file_access_cb_t callback, void* userdata); + +// Callbacks run synchronously on the executing thread. Set or clear while idle. +// Pass counts start at 1 in each run. Data supplied by the library is borrowed +// until the callback returns. Callbacks may request cancellation and must not throw. +typedef void (*sd_dgl_preview_cb_t)( + const sd_preview_info_t* info, + int step, + int frame_count, + const sd_tensor_t* const* frames, + bool is_noisy, + void* userdata); +SD_API sd_status_t sd_dgl_ctx_set_progress_callback(sd_dgl_ctx_t* ctx, sd_generation_progress_cb_t callback, void* userdata); +// Modes: none, proj, tae, vae. Pass NULL as callback to clear. +// Sampling uses projection previews by default. Positive intervals count +// completed logical steps; supply preview(decoder=...) for tae or vae decoding. +SD_API sd_status_t sd_dgl_ctx_set_preview_callback( + sd_dgl_ctx_t* ctx, + sd_dgl_preview_cb_t callback, + const char* mode, + int interval, + bool denoised, + bool noisy, + void* userdata); + +typedef struct { + const char* name; + const sd_tensor_t* tensor; +} sd_dgl_tensor_input_t; + +// Checks syntax and types without creating a context or loading models. +// Set allow_tensor_inputs to accept named tensor parameters in fn main(name, ...). +SD_API sd_status_t sd_dgl_check(const char* source, bool allow_tensor_inputs); + +// Compiles source once per call, binds inputs and executes in the required context. +// Supply every declared tensor parameter exactly once, or NULL, 0 for no inputs. +// The run retains tensors as needed; result tensors can share their storage. +// On failure, *result_out is NULL. Compare the return value with SD_STATUS_OK. +SD_API sd_status_t sd_dgl_run( + sd_dgl_ctx_t* ctx, + const char* source, + const sd_dgl_tensor_input_t* inputs, + size_t input_count, + sd_dgl_result_t** result_out); +// Thread-safe. Requests cooperative cancellation of the current run only, +// including during compilation; it is checked before execution begins. +// An idle context accepts the request without queuing it for the next run. +SD_API sd_status_t sd_dgl_ctx_cancel(sd_dgl_ctx_t* ctx); +// Alias for sd_get_last_error(). +SD_API const char* sd_dgl_error(void); + +SD_API void sd_dgl_result_free(sd_dgl_result_t* result); + +typedef enum { + SD_DGL_VALUE_INVALID = 0, + SD_DGL_VALUE_BOOL, + SD_DGL_VALUE_INT, + SD_DGL_VALUE_NUMBER, + SD_DGL_VALUE_STRING, + SD_DGL_VALUE_TENSOR, + SD_DGL_VALUE_LIST, + SD_DGL_VALUE_DICT, + SD_DGL_VALUE_OPAQUE = 11, + SD_DGL_VALUE_VOID = 12, + SD_DGL_VALUE_BYTES = 13, +} sd_dgl_value_kind_t; + +// Structured values, names and tensor handles are borrowed from the result. +// Retain tensors to use them after the result is freed. +SD_API const sd_dgl_value_t* sd_dgl_result_root(const sd_dgl_result_t* result); +SD_API sd_dgl_value_kind_t sd_dgl_value_kind(const sd_dgl_value_t* value); +SD_API size_t sd_dgl_value_count(const sd_dgl_value_t* value); +SD_API const sd_dgl_value_t* sd_dgl_value_at(const sd_dgl_value_t* value, size_t index); +SD_API const char* sd_dgl_value_name(const sd_dgl_value_t* value); +SD_API const sd_dgl_value_t* sd_dgl_value_field(const sd_dgl_value_t* value, const char* name); +SD_API sd_status_t sd_dgl_value_get_bool(const sd_dgl_value_t* value, bool* out); +SD_API sd_status_t sd_dgl_value_get_int(const sd_dgl_value_t* value, int64_t* out); +SD_API sd_status_t sd_dgl_value_get_number(const sd_dgl_value_t* value, double* out); +SD_API sd_status_t sd_dgl_value_get_string(const sd_dgl_value_t* value, const char** out, size_t* size); +// Borrowed immutable bytes, valid until the result is freed. No NUL terminator. +SD_API sd_status_t sd_dgl_value_get_bytes(const sd_dgl_value_t* value, const void** out, size_t* size); +SD_API const sd_tensor_t* sd_dgl_value_tensor(const sd_dgl_value_t* value); + +// Flat tensor convenience access. Scalar values are materialized as tensors on demand. +SD_API const char* sd_dgl_result_type(const sd_dgl_result_t* result); +SD_API size_t sd_dgl_result_count(const sd_dgl_result_t* result); +SD_API const char* sd_dgl_result_name(const sd_dgl_result_t* result, size_t index); +// Borrowed read-only tensor. Use sd_tensor_retain() to keep it past result free. +SD_API const sd_tensor_t* sd_dgl_result_tensor(const sd_dgl_result_t* result, const char* name); // Weight types and model conversion diff --git a/scripts/face_detect.py b/scripts/face_detect.py index e7a3eae1e3..3ce2778c8b 100644 --- a/scripts/face_detect.py +++ b/scripts/face_detect.py @@ -1,13 +1,10 @@ -import os import sys +from pathlib import Path import numpy as np -import torch from diffusers.utils import load_image # pip install insightface==0.7.3 from insightface.app import FaceAnalysis -from insightface.data import get_image as ins_get_image -from safetensors.torch import save_file ### # https://github.com/cubiq/ComfyUI_IPAdapter_plus/issues/165#issue-2055829543 @@ -38,51 +35,25 @@ def analyze_faces(face_analysis: FaceAnalysis, img_data: np.ndarray, det_size=(6 #face_detector = FaceAnalysis2(providers=['CUDAExecutionProvider'], allowed_modules=['detection', 'recognition']) face_detector = FaceAnalysis2(providers=['CPUExecutionProvider'], allowed_modules=['detection', 'recognition']) face_detector.prepare(ctx_id=0, det_size=(640, 640)) - #input_folder_name = './scarletthead_woman' - input_folder_name = sys.argv[1] - image_basename_list = os.listdir(input_folder_name) - image_path_list = sorted([os.path.join(input_folder_name, basename) for basename in image_basename_list]) - - input_id_images = [] - for image_path in image_path_list: - input_id_images.append(load_image(image_path)) - - id_embed_list = [] - - for img in input_id_images: - img = np.array(img) - img = img[:, :, ::-1] - faces = analyze_faces(face_detector, img) - if len(faces) > 0: - id_embed_list.append(torch.from_numpy((faces[0]['embedding']))) - - if len(id_embed_list) == 0: - raise ValueError(f"No face detected in input image pool") - - id_embeds = torch.stack(id_embed_list) - - # for r in id_embeds: - # print(r) - # #torch.save(id_embeds, input_folder_name+'/id_embeds.pt'); - # weights = dict() - # weights["id_embeds"] = id_embeds - # save_file(weights, input_folder_name+'/id_embeds.safetensors') - - binary_data = id_embeds.numpy().tobytes() - two = 4 - zero = 0 - one = 1 - tensor_name = "id_embeds" -# Write binary data to a file - with open(input_folder_name+'/id_embeds.bin', "wb") as f: - f.write(two.to_bytes(4, byteorder='little')) - f.write((len(tensor_name)).to_bytes(4, byteorder='little')) - f.write(zero.to_bytes(4, byteorder='little')) - f.write((id_embeds.shape[1]).to_bytes(4, byteorder='little')) - f.write((id_embeds.shape[0]).to_bytes(4, byteorder='little')) - f.write(one.to_bytes(4, byteorder='little')) - f.write(one.to_bytes(4, byteorder='little')) - f.write(tensor_name.encode('ascii')) - f.write(binary_data) - - \ No newline at end of file + input_dir = Path(sys.argv[1]) + image_extensions = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} + image_paths = sorted( + (path for path in input_dir.iterdir() + if path.is_file() and path.suffix.lower() in image_extensions), + key=lambda path: path.name, + ) + if not image_paths: + raise ValueError(f"No input images in '{input_dir}'") + + embeddings = [] + for image_path in image_paths: + image = np.asarray(load_image(str(image_path)))[:, :, ::-1] + faces = analyze_faces(face_detector, image) + if not faces: + raise ValueError(f"No face detected in '{image_path}'") + embedding = np.asarray(faces[0]["embedding"], dtype=np.float32) + if embedding.shape != (512,): + raise ValueError(f"Expected a 512-value face embedding for '{image_path}'") + embeddings.append(embedding) + + np.save(input_dir / "id_embeds.npy", np.stack(embeddings), allow_pickle=False) diff --git a/scripts/format-code.ps1 b/scripts/format-code.ps1 index 782e09205e..c5f87f68e8 100644 --- a/scripts/format-code.ps1 +++ b/scripts/format-code.ps1 @@ -27,8 +27,16 @@ $patterns = @( "src/extensions/*.cpp" "src/extensions/*.h" "src/extensions/*.hpp" - "src/pipeline/*.cpp" - "src/pipeline/*.h" + "src/dgl/*.cpp" + "src/dgl/*.h" + "src/dgl/syntax/*.cpp" + "src/dgl/syntax/*.h" + "src/dgl/bindings/*.cpp" + "src/dgl/bindings/*.h" + "src/dgl/models/*.cpp" + "src/dgl/models/*.h" + "src/dgl/ops/*.cpp" + "src/dgl/ops/*.h" "src/runtime/*.cpp" "src/runtime/*.h" "src/runtime/*.hpp" diff --git a/scripts/format-code.sh b/scripts/format-code.sh index c2806f6473..74ae208d8c 100644 --- a/scripts/format-code.sh +++ b/scripts/format-code.sh @@ -16,7 +16,11 @@ for f in src/*.cpp src/*.h src/*.hpp \ src/core/probe/*.cpp src/core/probe/*.h \ src/core/vulkan/*.cpp src/core/vulkan/*.h src/core/vulkan/shaders/*.comp \ src/extensions/*.cpp src/extensions/*.h src/extensions/*.hpp \ - src/pipeline/*.cpp src/pipeline/*.h \ + src/dgl/*.cpp src/dgl/*.h \ + src/dgl/syntax/*.cpp src/dgl/syntax/*.h \ + src/dgl/bindings/*.cpp src/dgl/bindings/*.h \ + src/dgl/models/*.cpp src/dgl/models/*.h \ + src/dgl/ops/*.cpp src/dgl/ops/*.h \ src/runtime/*.cpp src/runtime/*.h src/runtime/*.hpp \ src/model/*/*.cpp src/model/*/*.h src/model/*/*.hpp \ src/tokenizers/*.h src/tokenizers/*.cpp \ diff --git a/scripts/pulid_extract_id.py b/scripts/pulid_extract_id.py index a5740b27d1..05199beffd 100644 --- a/scripts/pulid_extract_id.py +++ b/scripts/pulid_extract_id.py @@ -1,8 +1,8 @@ """ Precompute a PuLID-Flux identity embedding from a single source portrait. -Writes a gguf file (a single tensor `pulid_id`) that stable-diffusion.cpp's -`--pulid-id-embedding` flag consumes. +Writes a gguf file (a single tensor `pulid_id`) consumed by the DGL +`pulid::load_embedding` function. Dependencies (recommended: vendor rather than pip-install due to upstream packaging quirks): diff --git a/src/api/api.cpp b/src/api/api.cpp index 72cd6d4049..fa6b766c5f 100644 --- a/src/api/api.cpp +++ b/src/api/api.cpp @@ -1,4 +1,5 @@ #include "api.h" +#include "generation.h" #include "options.h" #include "result.h" #include "tensor.h" @@ -10,11 +11,12 @@ #include "core/ggml_extend.h" #include "core/option_types.h" #include "core/util.h" -#include "pipeline/diffusion_engine.h" -#include "pipeline/generation.h" static thread_local char last_error[512] = {}; +sd_ctx_t::sd_ctx_t() = default; +sd_ctx_t::~sd_ctx_t() = default; + void sd::api::clear_error() { last_error[0] = '\0'; } @@ -69,177 +71,165 @@ sd_status_t sd_set_preview_callback(sd_preview_cb_t cb, const char* mode, int in return SD_STATUS_OK; } -void sd_set_prompt_image_callback(sd_ctx_t* ctx, sd_prompt_image_cb_t cb, void* data) { - if (ctx == nullptr || ctx->sd == nullptr) { +void sd_set_prompt_image_callback(sd_ctx_t* ctx, sd_prompt_image_cb_t callback, void* data) { + if (!ctx || !ctx->engine) return; - } - std::lock_guard lock(ctx->sd->execution_mutex); - if (!ctx->sd->executing_) { - ctx->sd->prompt_image_callback = cb; - ctx->sd->prompt_image_callback_data = data; + auto& engine = *ctx->engine; + std::lock_guard lock(engine.mutex); + if (!engine.executing) { + engine.prompt_image = callback; + engine.prompt_image_data = data; } } -void sd_set_generation_progress_callback(sd_ctx_t* ctx, sd_generation_progress_cb_t cb, void* data) { - if (ctx == nullptr || ctx->sd == nullptr) { +void sd_set_generation_progress_callback(sd_ctx_t* ctx, sd_generation_progress_cb_t callback, void* data) { + if (!ctx || !ctx->engine) return; + auto& engine = *ctx->engine; + std::lock_guard lock(engine.mutex); + if (!engine.executing) { + engine.progress = callback; + engine.progress_data = data; + engine.sample_pass = 0; } - std::lock_guard lock(ctx->sd->execution_mutex); - if (!ctx->sd->executing_) { - ctx->sd->generation_progress.set_callback(cb, data); - } -} - -static sd_ctx_t* create_context(const sd::ContextConfig& params) { - auto engine = std::make_unique(); - if (!engine->init(¶ms)) - return nullptr; - auto context = std::make_unique(); - context->sd = engine.release(); - return context.release(); } -sd_status_t sd_ctx_create(const sd_ctx_opt_t* params, sd_ctx_t** ctx_out) { - if (ctx_out) - *ctx_out = nullptr; +sd_status_t sd_ctx_create(const sd_ctx_opt_t* options, sd_ctx_t** out) { + if (out) + *out = nullptr; return sd::api::call([&] { - if (!ctx_out) + if (!out) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "ctx_out is required"); - sd::OptConfig config; - auto status = sd::api::resolve(params, sd::api::Context, config); - const auto& context = config.context; - if (status != SD_STATUS_OK) - return status; - *ctx_out = create_context(context); - return *ctx_out ? SD_STATUS_OK : sd::api::error(SD_STATUS_LOAD_FAILED, nullptr, "context creation failed; see log for details"); + auto ctx = std::make_unique(); + ctx->engine = std::make_unique(options, sd::api::Context); + *out = ctx.release(); + return SD_STATUS_OK; }, SD_STATUS_LOAD_FAILED); } -void sd_ctx_free(sd_ctx_t* sd_ctx) { - if (!sd_ctx) - return; - if (sd_ctx->sd != nullptr) { - delete sd_ctx->sd; - sd_ctx->sd = nullptr; - } - delete sd_ctx; +void sd_ctx_free(sd_ctx_t* context) { + delete context; +} + +sd_dgl_ctx_t* sd_ctx_get_dgl_ctx(sd_ctx_t* context) { + return context && context->engine ? &context->engine->execution : nullptr; } -SD_API void sd_cancel_generation(sd_ctx_t* sd_ctx, enum sd_cancel_mode_t mode) { - if (sd_ctx && sd_ctx->sd) { - if (mode < SD_CANCEL_ALL || mode > SD_CANCEL_RESET) { - mode = SD_CANCEL_ALL; +static sd_status_t set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* options, sd_result_kind_t kind) { + return sd::api::call([&] { + if (!context || !context->engine) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context is required"); + auto& engine = *context->engine; + std::unique_lock lock(engine.mutex, std::try_to_lock); + if (!lock.owns_lock()) + return sd::api::error(SD_STATUS_BUSY, nullptr, "context is busy"); + sd::api::GenerationRun replacement(engine); + sd::api::GenerationModel candidate(sd::api::copy_options(options), sd::api::Context); + if (kind != SD_RESULT_INVALID) { + sd::FileAccessScope access(engine.file_access); + const bool video = kind == SD_RESULT_VIDEO; + if (!sd::api::supports_generation(candidate.definition(engine), video)) + return sd::api::error(SD_STATUS_UNSUPPORTED, nullptr, video ? "selected model does not support vid_gen" : "selected model does not support img_gen"); } - sd_ctx->sd->set_cancel_flag(mode); - } + engine.model = std::move(candidate); + sd::api::clear_error(); + return SD_STATUS_OK; + }, + kind == SD_RESULT_INVALID ? SD_STATUS_INVALID_ARGUMENT : SD_STATUS_LOAD_FAILED); } -SD_API bool sd_ctx_supports_image_generation(const sd_ctx_t* sd_ctx) { - if (sd_ctx == nullptr || sd_ctx->sd == nullptr) { - return false; - } - return sd_version_supports_image_generation(sd_ctx->sd->version); +sd_status_t sd_ctx_set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* options) { + return set_model_options(context, options, SD_RESULT_INVALID); } -SD_API bool sd_ctx_supports_video_generation(const sd_ctx_t* sd_ctx) { - if (sd_ctx == nullptr || sd_ctx->sd == nullptr) { - return false; - } - if (sd_ctx->sd->config_->animatediff_loaded && sd_version_supports_animatediff(sd_ctx->sd->version)) { - return true; - } - return sd_version_supports_video_generation(sd_ctx->sd->version); +sd_status_t sd_ctx_set_model_options_for_generation(sd_ctx_t* context, const sd_ctx_opt_t* options, sd_result_kind_t kind) { + if (kind != SD_RESULT_IMAGE && kind != SD_RESULT_VIDEO) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "image or video result kind is required"); + return set_model_options(context, options, kind); } -SD_API bool sd_ctx_load_control_net(sd_ctx_t* sd_ctx, const char* path) { - if (sd_ctx == nullptr || sd_ctx->sd == nullptr || path == nullptr) { - return false; - } - return sd_ctx->sd->load_control_net_from_file(path); +void sd_cancel_generation(sd_ctx_t* context, enum sd_cancel_mode_t mode) { + if (!context || !context->engine) + return; + if (mode < SD_CANCEL_ALL || mode > SD_CANCEL_RESET) + mode = SD_CANCEL_ALL; + auto& engine = *context->engine; + std::lock_guard lock(engine.mutex); + if (!engine.executing) + return; + engine.cancellation.store(mode); + if (engine.active_run && mode != SD_CANCEL_NEW_LATENTS) + engine.active_run->set_cancelled(mode == SD_CANCEL_ALL); +} + +static const ModelDefinition* context_definition(const sd_ctx_t* context) { + const ModelDefinition* definition = nullptr; + sd::api::call([&] { + if (!context || !context->engine) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context is required"); + auto& engine = *context->engine; + std::lock_guard lock(engine.mutex); + const auto family = engine.model.family; + if (family != VERSION_COUNT) { + definition = find_model_definition(family); + } else { + sd::FileAccessScope access(engine.file_access); + definition = &engine.model.definition(engine); + } + sd::api::clear_error(); + return SD_STATUS_OK; + }, + SD_STATUS_LOAD_FAILED); + return definition; } -SD_API bool sd_ctx_unload_control_net(sd_ctx_t* sd_ctx) { - if (sd_ctx == nullptr || sd_ctx->sd == nullptr) { - return false; - } - return sd_ctx->sd->unload_control_net(); +bool sd_ctx_supports_image_generation(const sd_ctx_t* context) { + const auto* definition = context_definition(context); + return definition && sd::api::supports_generation(*definition, false); } -SD_API bool sd_ctx_has_control_net(const sd_ctx_t* sd_ctx) { - if (sd_ctx == nullptr || sd_ctx->sd == nullptr) { - return false; - } - if (sd_ctx->sd->control_net != nullptr) { - return true; - } - // z-image keeps control net weights inside the diffusion runner, registered - // under ModelComponent::ControlNet instead of a separate control_net runner. - return sd_ctx->sd->model_manager != nullptr && - sd_ctx->sd->model_manager->registered_params_size({ModelComponent::ControlNet}) > 0; +bool sd_ctx_supports_video_generation(const sd_ctx_t* context) { + const auto* definition = context_definition(context); + return definition && sd::api::supports_generation(*definition, true); } -const char* sd_get_model_version_name(const sd_ctx_t* sd_ctx) { - if (sd_ctx == nullptr || sd_ctx->sd == nullptr || sd_ctx->sd->version >= VERSION_COUNT) { - return "Unknown"; - } - return sd_version_name(sd_ctx->sd->version); +const char* sd_get_model_version_name(const sd_ctx_t* context) { + const auto* definition = context_definition(context); + return definition ? definition->name : "Unknown"; } -sd_status_t sd_generate_image(sd_ctx_t* ctx, const sd_img_gen_opt_t* params, sd_result_t** result_out) { - if (result_out) - *result_out = nullptr; +sd_status_t sd_ctx_set_file_access_callback(sd_ctx_t* context, sd_dgl_file_access_cb_t callback, void* data) { return sd::api::call([&] { - if (!result_out) - return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "result_out is required"); - sd::OptConfig config; - auto status = sd::api::resolve(params, sd::api::Image, config); - const auto& image = config.image; - if (status != SD_STATUS_OK) - return status; - sd::ImageGenerationResult* images = nullptr; - status = sd::generate_image(ctx, image, &images, params); - if (status != SD_STATUS_OK) - return status; - return sd::make_image_result(images, result_out) ? SD_STATUS_OK - : sd::api::error(SD_STATUS_OUT_OF_MEMORY, nullptr, "could not allocate result"); - }, - SD_STATUS_GENERATION_FAILED); + if (!context || !context->engine) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context is required"); + auto& engine = *context->engine; + std::unique_lock lock(engine.mutex, std::try_to_lock); + if (!lock.owns_lock() || engine.executing) + return sd::api::error(SD_STATUS_BUSY, nullptr, "context is busy"); + engine.file_access = {callback, data}; + return SD_STATUS_OK; + }); } -sd_status_t sd_generate_video(sd_ctx_t* ctx, const sd_vid_gen_opt_t* params, sd_result_t** result_out) { - if (result_out) - *result_out = nullptr; +sd_status_t sd_generate_image(sd_ctx_t* context, const sd_img_gen_opt_t* params, sd_result_t** out) { + if (out) + *out = nullptr; return sd::api::call([&] { - if (!result_out) - return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "result_out is required"); - sd::OptConfig config; - auto status = sd::api::resolve(params, sd::api::Video, config); - const auto& video = config.video; - if (status != SD_STATUS_OK) - return status; - sd::VideoGenerationResult* frames = nullptr; - status = sd::generate_video(ctx, video, &frames, params); - if (status != SD_STATUS_OK) - return status; - return sd::make_video_result(frames, result_out) ? SD_STATUS_OK - : sd::api::error(SD_STATUS_OUT_OF_MEMORY, nullptr, "could not allocate result"); + if (!out || !context || !context->engine) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context and result_out are required"); + return sd::api::generate_images(*context->engine, params, out); }, SD_STATUS_GENERATION_FAILED); } -sd_status_t sd_preprocess_canny(const sd_tensor_t* image, float high_threshold, float low_threshold, float weak, float strong, bool inverse, sd_tensor_t** image_out) { - if (image_out) - *image_out = nullptr; +sd_status_t sd_generate_video(sd_ctx_t* context, const sd_vid_gen_opt_t* params, sd_result_t** out) { + if (out) + *out = nullptr; return sd::api::call([&] { - if (!image || !image_out) - return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "image and image_out are required"); - sd::api::image_view(*image); - auto output = sd::api::allocate_tensor(image->type, image->shape); - memcpy(output.get()->mutable_data(), image->data(), image->bytes); - if (!sd::preprocess_canny(sd::api::image_view(*output.get()), high_threshold, low_threshold, weak, strong, inverse)) - return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "Canny preprocessing failed"); - *image_out = sd_tensor_retain(output.get()); - return SD_STATUS_OK; - }); + if (!out || !context || !context->engine) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context and result_out are required"); + return sd::api::generate_video(*context->engine, params, out); + }, + SD_STATUS_GENERATION_FAILED); } diff --git a/src/api/api.h b/src/api/api.h index 545859e960..5fbca07622 100644 --- a/src/api/api.h +++ b/src/api/api.h @@ -2,14 +2,20 @@ #define SD_INTERNAL_API_H #include +#include #include +#include "dgl/diagnostic.h" #include "stable-diffusion.h" -class StableDiffusionGGML; +namespace sd::api { + struct GenerationContext; +} struct sd_ctx_t { - StableDiffusionGGML* sd = nullptr; + std::unique_ptr engine; + sd_ctx_t(); + ~sd_ctx_t(); }; namespace sd::api { @@ -21,6 +27,8 @@ namespace sd::api { clear_error(); try { return function(); + } catch (const sd::dgl::Error& exception) { + return error(exception.status, nullptr, exception.what()); } catch (const std::bad_alloc&) { return error(SD_STATUS_OUT_OF_MEMORY, nullptr, "out of memory"); } catch (const std::exception& exception) { diff --git a/src/api/generation.cpp b/src/api/generation.cpp new file mode 100644 index 0000000000..d02d8a7096 --- /dev/null +++ b/src/api/generation.cpp @@ -0,0 +1,265 @@ +#include "api/generation.h" + +#include +#include +#include +#include + +#include "api/generation_program.h" +#include "api/result.h" +#include "api/tensor.h" +#include "core/ggml_extend_backend.h" +#include "core/image_geometry.h" +#include "core/util.h" +#include "dgl/diagnostic.h" +#include "dgl/executor.h" +#include "dgl/models/component_sources.h" +#include "model/vae/geometry.hpp" +#include "name_conversion.h" + +namespace sd::api { + GenerationModel::GenerationModel(std::shared_ptr source, Operation purpose) + : options(std::move(source)) { + const auto status = resolve(options.get(), purpose, config); + if (status != SD_STATUS_OK) + throw dgl::Error(status, sd_get_last_error()); + } + + GenerationContext::GenerationContext(const sd_opt_t* source, Operation purpose) + : model(copy_options(source), purpose), execution(!model.config.context.run_once) { + const auto& settings = model.config.context; + execution.set("n_threads", std::to_string(settings.n_threads)); + if (settings.linear_type) + execution.set("linear_type", settings.linear_type); + execution.set("conditioning_cache_size", std::to_string(settings.conditioning_cache_size)); + for (const auto& [key, enabled] : std::map{ + {"auto_fit", settings.auto_fit}, {"batched_cfg", settings.batched_cfg}, {"enable_mmap", settings.enable_mmap}, {"eager_load", settings.eager_load}, {"disable_prefetch", settings.disable_prefetch}, {"disable_segmented_compute", settings.disable_segmented_compute}}) + execution.set(key, enabled ? "true" : "false"); + if (settings.max_vram && *settings.max_vram) + execution.set("max_vram", settings.max_vram); + if (settings.max_ram && *settings.max_ram) + execution.set("max_ram", settings.max_ram); + if (settings.rpc_servers && *settings.rpc_servers && !add_rpc_devices(settings.rpc_servers)) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "cannot register RPC devices"); + } + + static bool contains_audio_vae(const ModelLoader& metadata, SDVersion version) { + for (const auto& name : metadata.get_tensor_names()) { + const auto canonical = convert_tensor_name(name, version); + if (canonical.rfind("audio_vae.", 0) == 0 || canonical.rfind("vocoder.", 0) == 0) + return true; + } + return false; + } + + const ModelDefinition& GenerationModel::definition(GenerationContext& context) { + std::lock_guard lock(context.mutex); + if (context.probing_model) + throw dgl::Error(SD_STATUS_BUSY, "model probe is in progress"); + context.probing_model = true; + struct ProbeGuard { + bool& probing; + ~ProbeGuard() { probing = false; } + } probe{context.probing_model}; + context.check_cancelled(); + const auto& settings = config.context; + const auto* path = settings.diffusion_model_path && *settings.diffusion_model_path ? settings.diffusion_model_path : settings.model_path; + if (!path || !*path) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "model_path or diffusion_model_path is required"); + require_file_access(path, SD_DGL_FILE_READ_MODEL); + if ((sd_version_is_minimax_h3(family) || sd_version_is_ltxav(family)) && settings.vae_path && *settings.vae_path) + require_file_access(settings.vae_path, SD_DGL_FILE_READ_MODEL); + bool changed = family == VERSION_COUNT; + if (!changed && !ModelLoader::dependencies_changed(probe_dependencies, changed)) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "cannot inspect model dependencies"); + if (changed) { + try { + ModelLoader::Dependencies dependencies; + ModelLoader metadata; + auto detected = dgl::models::resolve_family(VERSION_COUNT, path, &dependencies, &metadata); + ModelLoader vae_metadata; + bool inspected_vae = false; + if (detected == VERSION_MINIMAX_H3 && settings.vae_path && *settings.vae_path && std::string(settings.vae_path) != path) { + require_file_access(settings.vae_path, SD_DGL_FILE_READ_MODEL); + if (!vae_metadata.init_from_file(settings.vae_path)) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "cannot inspect video VAE metadata"); + inspected_vae = true; + const auto sources = vae_metadata.dependencies(); + dependencies.insert(dependencies.end(), sources.begin(), sources.end()); + for (const auto& [name, tensor] : vae_metadata.get_tensor_storage_map()) + if (ends_with(name, "decoder.proj_out.weight") && tensor.ne[1] == 768) + detected = VERSION_P_H3_IMAGE; + } + const auto* definition = find_model_definition(detected); + if (!definition) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "unsupported model family"); + default_prediction = definition->sampling.prediction_from_weights ? definition->sampling.prediction_from_weights(metadata.get_tensor_storage_map()) : definition->sampling.default_prediction; + wan_image_condition = detected == VERSION_WAN2_2_I2V; + wan_vision_condition = wan_end_vision = wan_vace = false; + if (sd_version_is_wan(detected)) + for (const auto& [name, tensor] : metadata.get_tensor_storage_map()) { + wan_vision_condition |= name.find("img_emb.") != std::string::npos; + wan_end_vision |= name.find("img_emb.emb_pos") != std::string::npos; + wan_vace |= name.find("vace_blocks.") != std::string::npos; + } + wan_image_condition |= wan_vision_condition; + embedded_audio_vae.clear(); + if (sd_version_is_ltxav(detected) || sd_version_is_minimax_h3(detected)) { + if (contains_audio_vae(metadata, detected)) { + embedded_audio_vae = path; + } else if (settings.vae_path && *settings.vae_path && std::string(settings.vae_path) != path && + (!settings.audio_vae_path || !*settings.audio_vae_path)) { + require_file_access(settings.vae_path, SD_DGL_FILE_READ_MODEL); + if (!inspected_vae && !vae_metadata.init_from_file(settings.vae_path)) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "cannot inspect video VAE metadata"); + if (!inspected_vae) { + const auto sources = vae_metadata.dependencies(); + dependencies.insert(dependencies.end(), sources.begin(), sources.end()); + } + if (contains_audio_vae(vae_metadata, detected)) + embedded_audio_vae = settings.vae_path; + } + } + context.check_cancelled(); + family = detected; + probe_dependencies = std::move(dependencies); + LOG_INFO("Detected model family: %s (%s)", sd_version_name(family), std::filesystem::u8path(path).filename().u8string().c_str()); + } catch (const dgl::Error&) { + family = VERSION_COUNT; + throw; + } catch (const std::exception& error) { + family = VERSION_COUNT; + throw dgl::Error(SD_STATUS_LOAD_FAILED, error.what()); + } + } + const auto* definition = find_model_definition(family); + if (!definition) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "unsupported model family"); + return *definition; + } + + bool supports_generation(const ModelDefinition& definition, bool video) { + return definition.traits.supports_video_generation == video && definition.version != VERSION_ESRGAN && + definition.version != VERSION_SEEDVR2 && definition.version != VERSION_RELAY_VSR; + } + + void GenerationContext::check_cancelled() const { + if (cancellation.load(std::memory_order_relaxed) == SD_CANCEL_ALL) + throw dgl::Error(SD_STATUS_CANCELLED, "generation cancelled"); + } + + GenerationRun::GenerationRun(GenerationContext& context) + : context_(context) { + std::unique_lock lock(context_.mutex, std::try_to_lock); + if (!lock.owns_lock() || context_.executing || context_.probing_model) + throw dgl::Error(SD_STATUS_BUSY, "context is busy"); + std::unique_lock execution_lock(context_.execution.mutex, std::try_to_lock); + if (!execution_lock.owns_lock() || context_.execution.active_run) + throw dgl::Error(SD_STATUS_BUSY, "DGL context is busy"); + context_.execution.generating = true; + context_.executing = true; + } + + GenerationRun::~GenerationRun() { + std::lock_guard lock(context_.mutex); + std::lock_guard execution_lock(context_.execution.mutex); + context_.execution.generating = false; + context_.cancellation.store(SD_CANCEL_RESET); + context_.executing = false; + } + + static void generation_progress(const sd_generation_progress_t* info, void* data) { + auto& context = *static_cast(data); + auto translated = *info; + translated.sample_pass += context.sample_pass; + if (context.progress) + context.progress(&translated, context.progress_data); + } + + dgl::Value execute_program(GenerationContext& context, const GenerationProgram& program, const dgl::Graph* compiled) { + context.check_cancelled(); + FileAccessScope access(context.file_access); + dgl::Graph graph; + if (!compiled) { + graph = dgl::compile(program.source, dgl::operations(), !program.inputs.empty()); + compiled = &graph; + } + context.check_cancelled(); + dgl::RunCallbacks callbacks; + callbacks.progress = generation_progress; + callbacks.progress_data = &context; + dgl::RunEvents events(callbacks, true); + struct ActiveRun { + GenerationContext& context; + dgl::RunEvents& events; + ~ActiveRun() { + std::lock_guard lock(context.mutex); + std::lock_guard execution_lock(context.execution.mutex); + context.sample_pass += events.preview_info().sample_pass; + context.active_run = nullptr; + context.execution.active_run = nullptr; + } + } active{context, events}; + { + std::lock_guard lock(context.mutex); + std::lock_guard execution_lock(context.execution.mutex); + context.active_run = &events; + context.execution.active_run = &events; + if (context.cancellation.load() == SD_CANCEL_ALL) + events.cancel(); + } + dgl::RunEventsScope scope(events); + dgl::RunState state{context.execution, events}; + LOG_DEBUG("Executing DGL program:\n%s", compiled->source.c_str()); + return dgl::run(*compiled, state, program.inputs); + } + + static int64_t resolved_seed(int64_t requested) { + if (requested >= 0) + return requested; + std::random_device entropy; + return int64_t((uint64_t(entropy()) << 32 | entropy()) & INT64_MAX); + } + + sd_status_t generate_images(GenerationContext& context, const sd_img_gen_opt_t* options, sd_result_t** out) { + GenerationRun request(context); + FileAccessScope access(context.file_access); + auto snapshot = copy_options(options); + OptConfig config; + const auto status = resolve(snapshot.get(), Image, config); + if (status != SD_STATUS_OK) + return status; + context.check_cancelled(); + const auto seed = resolved_seed(config.image.seed); + auto result = std::make_unique(); + for (int i = 0; i < config.image.batch_count; ++i) { + if (context.cancellation.load() == SD_CANCEL_NEW_LATENTS) + break; + auto program = image_program(context, config.image, snapshot.get(), int64_t((uint64_t(seed) + uint64_t(i)) & INT64_MAX)); + auto value = execute_program(context, program); + append_program_image(*result, value, program.source); + } + if (result->images.empty()) + throw dgl::Error(SD_STATUS_CANCELLED, "generation cancelled before the next image"); + context.check_cancelled(); + *out = result.release(); + return SD_STATUS_OK; + } + sd_status_t generate_video(GenerationContext& context, const sd_vid_gen_opt_t* options, sd_result_t** out) { + GenerationRun request(context); + FileAccessScope access(context.file_access); + auto snapshot = copy_options(options); + OptConfig config; + const auto status = resolve(snapshot.get(), Video, config); + if (status != SD_STATUS_OK) + return status; + auto program = video_program(context, config.video, snapshot.get(), resolved_seed(config.video.seed)); + auto value = execute_program(context, program); + auto result = std::make_unique(); + set_program_video(*result, value, program.source); + context.check_cancelled(); + *out = result.release(); + return SD_STATUS_OK; + } + +} diff --git a/src/api/generation.h b/src/api/generation.h new file mode 100644 index 0000000000..09f3c4461e --- /dev/null +++ b/src/api/generation.h @@ -0,0 +1,77 @@ +#ifndef __SD_API_GENERATION_H__ +#define __SD_API_GENERATION_H__ + +#include +#include +#include +#include + +#include "api/generation_template.h" +#include "api/options.h" +#include "dgl/context.h" +#include "dgl/graph.h" +#include "model_definition.h" + +namespace sd::api { + struct GenerationContext; + + struct GenerationModel { + std::shared_ptr options; + OptConfig config; + SDVersion family = VERSION_COUNT; + prediction_t default_prediction = PREDICTION_COUNT; + bool wan_image_condition = false; + bool wan_vision_condition = false; + bool wan_end_vision = false; + bool wan_vace = false; + std::string embedded_audio_vae; + ModelLoader::Dependencies probe_dependencies; + + GenerationModel(std::shared_ptr source, Operation purpose); + const ModelDefinition& definition(GenerationContext& context); + }; + + struct GenerationContext { + GenerationModel model; + sd_dgl_ctx_t execution; + FileAccessPolicy file_access; + std::recursive_mutex mutex; + bool executing = false; + bool probing_model = false; + std::atomic cancellation{SD_CANCEL_RESET}; + dgl::RunEvents* active_run = nullptr; + sd_generation_progress_cb_t progress = nullptr; + void* progress_data = nullptr; + sd_prompt_image_cb_t prompt_image = nullptr; + void* prompt_image_data = nullptr; + int sample_pass = 0; + + GenerationContext(const sd_opt_t* source, Operation purpose); + void check_cancelled() const; + }; + + bool supports_generation(const ModelDefinition& definition, bool video); + + class GenerationRun { + GenerationContext& context_; + + public: + explicit GenerationRun(GenerationContext& context); + ~GenerationRun(); + GenerationRun(const GenerationRun&) = delete; + GenerationRun& operator=(const GenerationRun&) = delete; + }; + + struct GenerationProgram { + std::string source; + dgl::Values inputs; + }; + + dgl::Value execute_program(GenerationContext& context, const GenerationProgram& program, const dgl::Graph* compiled = nullptr); + GenerationProgram image_program(GenerationContext& context, const ImageConfig& image, const sd_opt_t* explicit_options, int64_t seed); + GenerationProgram video_program(GenerationContext& context, const VideoConfig& video, const sd_opt_t* explicit_options, int64_t seed); + sd_status_t generate_images(GenerationContext& context, const sd_img_gen_opt_t* options, sd_result_t** result); + sd_status_t generate_video(GenerationContext& context, const sd_vid_gen_opt_t* options, sd_result_t** result); +} + +#endif // __SD_API_GENERATION_H__ diff --git a/src/api/generation_h3.cpp b/src/api/generation_h3.cpp new file mode 100644 index 0000000000..766c2ec956 --- /dev/null +++ b/src/api/generation_h3.cpp @@ -0,0 +1,117 @@ +#include "api/generation_program.h" + +#include +#include + +namespace sd::api { + static std::string expression_list(const std::vector& values) { + std::string result = "["; + for (size_t i = 0; i < values.size(); ++i) + result += (i ? ", " : "") + values[i]; + return result + "]"; + } + + void prepare_h3_references(GenerationTemplate& request, const std::string& first, const std::string& last) { + const auto images = bound_tensors(request.options, "ref_images"); + const auto videos = bound_videos(request.options, "ref_videos"); + const auto audios = bound_audios(request.options, "ref_audios"); + const bool references = !images.empty() || !videos.empty() || !audios.empty(); + const bool audio_references = !audios.empty() || std::any_of(videos.begin(), videos.end(), [](const sd_video_t& video) { return video.audio.data != nullptr; }); + if (audio_references && !request.flags.at("decode_audio").get()) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "MiniMax-H3 audio references require audio VAE weights"); + if (references && (!first.empty() || !last.empty())) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 references and start/end keyframes cannot be combined"); + if (!references && first.empty() && last.empty()) + return; + auto& prepare = request.fields["references"]; + std::vector visuals, sounds, presentation, blocks, keys; + const auto encode_visual = [&](const std::string& pixels, const nlohmann::json& options = nlohmann::json::object()) { + const auto name = "h3_visual_" + std::to_string(visuals.size()); + nlohmann::json parameters{{"name", name}, {"pixels", pixels}, {"encode_audio", false}, {"resize_video", false}, {"resize_image", false}}; + parameters.update(options); + prepare += request.render("video_reference", parameters); + visuals.push_back(name); + }; + const auto encode_sound = [&](const sd_audio_t& audio) { + const auto name = "h3_sound_" + std::to_string(sounds.size()); + bind_tensor(request.program, name + "_samples", audio.data); + const auto media = "{samples = " + name + "_samples, sample_rate = " + std::to_string(audio.sample_rate) + "}"; + prepare += request.render("video_reference", {{"encode_audio", true}, {"name", name}, {"sample_rate", audio.sample_rate}}); + sounds.push_back(name); + presentation.push_back("{audio = " + media + "}"); + }; + if (!references) { + std::vector key_images; + for (const auto& [pixels, index] : std::vector>{{first, "0"}, {last, "frames - 1"}}) { + if (pixels.empty()) + continue; + encode_visual(pixels); + key_images.push_back(pixels + "[:, :, 0]"); + keys.push_back(index); + } + request.fields["prompt_options"] += ", media = " + expression_list(key_images); + request.fields["negative_prompt_options"] += ", media = " + expression_list(key_images); + } + for (size_t i = 0; i < images.size(); ++i) { + const auto name = "h3_image_" + std::to_string(i); + bind_tensor(request.program, name, images[i]); + const int source_width = int(sd_tensor_dim(images[i], 1)), source_height = int(sd_tensor_dim(images[i], 2)); + const double scale = std::min(1.0, std::sqrt(double(request.values.at("width").get()) * request.values.at("height").get() / (double(source_width) * source_height))); + const int width = std::max(32, int(std::round(source_width * scale / 32)) * 32), height = std::max(32, int(std::round(source_height * scale / 32)) * 32); + blocks.push_back(literal({{"kind", "image"}, {"video", visuals.size()}})); + encode_visual(name + "_pixels", {{"resize_image", true}, {"source", name}, {"width", width}, {"height", height}}); + presentation.push_back("{image = " + name + "_pixels}"); + } + for (size_t i = 0; i < videos.size(); ++i) { + const auto& video = videos[i]; + const auto name = "h3_video_" + std::to_string(i); + bind_tensor(request.program, name, video.data); + const int count = int(sd_tensor_dim(video.data, 3)); + int frames = std::min(request.values.at("frames").get(), int(std::lround(double(count) * 24 / video.fps))); + if (frames < 5) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 reference video needs at least 5 frames at 24 fps"); + frames = (frames - 5) / 17 * 17 + 5; + std::vector indices; + for (int frame = 0; frame < frames; ++frame) + indices.push_back(std::min(count - 1, int(std::floor(double(frame) * video.fps / 24)))); + const int source_width = int(sd_tensor_dim(video.data, 1)), source_height = int(sd_tensor_dim(video.data, 2)); + const double ratio = double(source_width) / source_height; + double w = ratio >= 1 ? 768 * ratio : 768, h = ratio >= 1 ? 768 : 768 / ratio; + if (w * h > 768.0 * 1344) { + const auto scale = std::sqrt(768.0 * 1344 / (w * h)); + w *= scale; + h *= scale; + } + int width = std::max(32, int(std::round(w / 32)) * 32), height = std::max(32, int(std::round(h / 32)) * 32); + if (source_width * source_height < width * height) { + width = std::max(32, int(std::round(double(source_width) / 32)) * 32); + height = std::max(32, int(std::round(double(source_height) / 32)) * 32); + } + auto block = nlohmann::json{{"kind", video.audio.data ? "video_audio" : "video"}, {"video", visuals.size()}}; + if (video.audio.data) { + block["audio"] = sounds.size(); + encode_sound(video.audio); + } + blocks.push_back(literal(block)); + encode_visual(name + "_pixels", {{"resize_video", true}, {"source", name}, {"indices", literal(indices)}, {"width", width}, {"height", height}}); + presentation.push_back("{video = {frames = " + name + "_pixels, fps_num = 24, fps_den = 1}, stride = 12}"); + } + for (const auto& audio : audios) { + blocks.push_back(literal({{"kind", "audio"}, {"audio", sounds.size()}})); + encode_sound(audio); + } + std::string options = ", ref_latents = " + expression_list(visuals); + if (!sounds.empty()) + options += ", ref_audios = " + expression_list(sounds); + if (!blocks.empty()) + options += ", reference_blocks = " + expression_list(blocks); + if (!keys.empty()) + options += ", keyframe_indices = " + expression_list(keys); + request.fields["predictor_options"] += options; + request.fields["negative_predictor_options"] += options; + if (!presentation.empty()) { + request.fields["prompt_options"] += ", media = " + expression_list(presentation); + request.fields["negative_prompt_options"] += ", media = " + expression_list(presentation); + } + } +} diff --git a/src/api/generation_hires.cpp b/src/api/generation_hires.cpp new file mode 100644 index 0000000000..7c11b21dc8 --- /dev/null +++ b/src/api/generation_hires.cpp @@ -0,0 +1,127 @@ +#include "api/generation_program.h" + +#include +#include + +#include "core/image_geometry.h" +#include "model/vae/geometry.hpp" + +namespace sd::api { + void prepare_hires_program(GenerationTemplate& request) { + const auto& hires = request.image.hires; + const auto mode = text(hires.upscaler); + const bool enabled = hires.enabled && mode != "none"; + request.flags["hires"] = enabled; + if (!enabled) + return; + static const std::map modes{ + {"latent", "bilinear"}, {"latent_nearest", "nearest"}, {"latent_nearest_exact", "nearest_exact"}, {"latent_antialiased", "bilinear"}, {"latent_bicubic", "bicubic"}, {"latent_bicubic_antialiased", "bicubic"}, {"lanczos", "lanczos"}, {"nearest", "nearest"}, {"model", "nearest"}}; + const auto found = modes.find(mode); + if (found == modes.end()) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "unknown hires upscaler '" + mode + "'"); + const bool model = mode == "model"; + const bool pixels = !request.video && (model || mode == "lanczos" || mode == "nearest"); + const auto version = request.definition.version; + const bool ltx = sd_version_is_ltxav(version); + if (request.video && !ltx && version != VERSION_MINIMAX_H3) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "video hires supports LTX and MiniMax-H3; other workflows can be written in DGL"); + if (request.video && (mode == "lanczos" || mode == "nearest")) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "video hires requires a latent interpolation mode or a latent upscaler model"); + if (model && text(hires.model_path).empty()) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "hires model upscaling requires hires.model_path"); + const auto& settings = request.context.model.config.context; + const auto vae_version = request.definition.traits.vae_format_override && request.fields.at("vae_loader") != "load_tae" + ? sd::vae::version_for_format(settings.vae_format, version) + : version; + const int scale = sd_version_is_pid(version) || sd_version_is_minit2i(version) || version == VERSION_IRIS ? 1 : sd::vae::spatial_scale(vae_version); + const int multiple = scale * request.definition.geometry.diffusion_down_factor; + const double width = hires.target_width ? hires.target_width : hires.target_height ? hires.target_height + : std::round(request.values.at("width").get() * double(hires.scale)); + const double height = hires.target_height ? hires.target_height : hires.target_width ? hires.target_width + : std::round(request.values.at("height").get() * double(hires.scale)); + if (width < 1 || height < 1 || width > 16384 || height > 16384) + throw dgl::Error(SD_STATUS_OUT_OF_RANGE, "hires target dimensions must be in 1..16384"); + const auto& sampling = request.image.sample_params; + const int default_steps = sampling.custom_sigmas_count ? sampling.custom_sigmas_count - 1 : sampling.sample_steps; + const int steps = hires.steps > 0 ? hires.steps : default_steps; + const double raw_scheduler_steps = steps / double(hires.denoising_strength); + if (!hires.custom_sigmas_count && raw_scheduler_steps > 10000) + throw dgl::Error(SD_STATUS_OUT_OF_RANGE, "hires steps / denoising_strength exceeds 10000; supply hires.sigmas or increase the strength"); + int scheduler_steps = std::max(1, int(std::min(raw_scheduler_steps, 10000.0))); + // The templates keep the last steps + 1 sigmas. Partial denoising must trim at least the first sigma. + if (!hires.custom_sigmas_count && hires.denoising_strength < 1.f && scheduler_steps == steps) + ++scheduler_steps; + request.values.update({{"hires_target_width", sd::align_image_dimension(int(width), multiple)}, + {"hires_target_height", sd::align_image_dimension(int(height), multiple)}, + {"hires_steps", steps}, + {"hires_scheduler_steps", scheduler_steps}, + {"hires_mode", found->second}, + {"hires_antialias", mode == "latent_antialiased" || mode == "latent_bicubic_antialiased"}, + {"hires_vae_scale", scale}}); + if (hires.custom_sigmas_count) + request.values["hires_custom_sigmas"] = std::vector(hires.custom_sigmas, hires.custom_sigmas + hires.custom_sigmas_count); + if (model) { + request.values["hires_model_path"] = text(hires.model_path); + auto options = loader_options(settings, request.video ? SDBackendModule::DIFFUSION : SDBackendModule::UPSCALER, request.definition); + if (!request.video) { + auto placement = nlohmann::json::object(); + for (const auto* key : {"backend", "params_backend"}) + if (options.contains(key)) + placement[key] = options.at(key); + options = std::move(placement); + options["tile_size"] = hires.upscale_tile_size; + } else + options["family"] = ltx ? "ltxav" : "minimax_h3"; + request.fields["hires_model_options"] = arguments(options); + } + request.flags.update({{"hires_model", model}, {"hires_pixels", pixels}, {"hires_ltx", ltx}, {"hires_pixel_model", request.fields.at("entry") == "image_pixel"}, {"hires_sefi", sd_version_is_sefi_image(version)}, {"hires_h3_image", sd_version_is_minimax_h3_image(version)}, {"hires_custom_sigmas", hires.custom_sigmas_count > 0}}); + request.fields["result_latent"] = "hires_latent"; + request.fields["hires_sample_options"] = request.fields.at("sample_core"); + request.fields["hires_schedule_predictor"] = request.fields.at("schedule_predictor"); + if (request.video) { + request.fields["output_video_frames"] = "hires_video_shape[2]"; + request.fields["output_audio_shape"] = "hires_audio_shape"; + request.fields["hires_schedule_predictor"] = ltx ? "hires_guided" : "guided"; + request.fields["hires_positions_option"] = request.flags.at("last").get() ? ", video_positions = hires_positions" : ""; + if (ltx && request.flags.at("conditioned").get()) + request.fields["hires_sample_options"] += ", base = hires_base, denoise_mask = hires_packed_mask, mask_input = true"; + return; + } + const bool rebuild = request.flags.value("inpaint_model", false) || request.flags.value("unet_edit", false) || request.flags.value("native_control", false) || request.flags.value("z_control", false); + request.flags["hires_rebuild"] = rebuild; + request.fields["hires_positive_condition"] = request.fields.at("positive_condition"); + request.fields["hires_negative_condition"] = request.fields.at("negative_condition"); + request.fields["hires_guidance_options"] = request.fields.at("guidance_core"); + if (request.flags.value("image_guidance", false)) { + request.fields["hires_guidance_options"] += ", image_only = hires_image_only, image_scale = image_cfg_scale"; + request.fields["hires_image_only_condition"] = request.fields.at("image_only_condition"); + } + if (request.flags.value("z_control", false)) { + request.fields["hires_positive_condition"] = "hires_controlled_positive"; + request.fields["hires_negative_condition"] = "hires_controlled_negative"; + if (request.flags.value("reference_image_guidance", false)) { + request.fields["hires_negative_condition"] = "hires_controlled_unconditional"; + request.fields["hires_image_only_condition"] = "hires_controlled_negative"; + } + } + if (rebuild) { + auto options = request.fields.at("predictor_core") + request.fields.at("reference_predictor_options"); + if (request.flags.value("inpaint_model", false)) + options += ", concat = hires_inpaint_condition"; + else if (request.flags.value("unet_edit", false)) + options += ", concat = hires_edit_latent"; + else if (version == VERSION_FLUX_CONTROLS) + options += ", concat = hires_control_latent"; + request.fields["hires_predictor_options"] = options; + request.fields["hires_image_only_options"] = options; + request.fields["hires_negative_predictor_options"] = request.flags.value("image_guidance", false) + ? request.fields.at("predictor_core") + (request.flags.value("reference_image_guidance", false) ? "" : ", concat = hires_image_unconditional_concat") + : options; + request.fields["hires_schedule_predictor"] = "hires_guided"; + } + if (request.flags.value("mask_stage", false) || request.flags.value("has_mask", false)) { + request.fields["hires_mask"] = request.flags.value("inpaint_model", false) ? "denoise_mask" : "mask_latent"; + request.fields["hires_sample_options"] += ", base = hires_base, denoise_mask = hires_mask"; + } + } +} diff --git a/src/api/generation_image.cpp b/src/api/generation_image.cpp new file mode 100644 index 0000000000..8d2fa414a8 --- /dev/null +++ b/src/api/generation_image.cpp @@ -0,0 +1,259 @@ +#include "api/generation_program.h" + +#include +#include + +#include "core/file_access.h" +#include "core/image_geometry.h" +#include "core/util.h" +#include "model_loader.h" + +namespace sd::api { + static bool supports_reference_image_guidance(SDVersion version) { + return version == VERSION_FLUX || version == VERSION_CHROMA || sd_version_is_flux2(version) || + (sd_version_is_qwen_image(version) && version != VERSION_QWEN_IMAGE_2_1) || + sd_version_is_mage_flow(version) || sd_version_is_longcat(version) || + sd_version_is_z_image(version) || sd_version_is_boogu_image(version); + } + + static std::string reference_pixels(GenerationTemplate& request, const sd_tensor_t* tensor, size_t index, bool encode) { + const auto version = request.definition.version; + const auto name = "reference_" + std::to_string(index); + bind_tensor(request.program, name, tensor); + int width = int(sd_tensor_dim(tensor, 1)), height = int(sd_tensor_dim(tensor, 2)); + const int target_width = request.values.at("width"), target_height = request.values.at("height"); + const int factor = sd_version_is_qwen_image(version) ? 32 : 16; + if (version == VERSION_P_H3_IMAGE || version == VERSION_MINIMAX_H3_IMAGE) { + const double scale = version == VERSION_P_H3_IMAGE ? std::min(1.0, std::sqrt(double(target_width) * target_height / (double(width) * height))) : double(std::clamp(std::min(width, height), 1024, 2048)) / std::min(width, height); + width = std::max(32, int(std::nearbyint(width * scale / 32)) * 32); + height = std::max(32, int(std::nearbyint(height * scale / 32)) * 32); + } else if (version == VERSION_MOSS_IMAGE) { + const double scale = std::min(1.0, 1024.0 / std::max(width, height)); + width = std::max(factor, int(std::round(width * scale / factor)) * factor); + height = std::max(factor, int(std::round(height * scale / factor)) * factor); + } else if (version != VERSION_ANIMA && !sd_version_is_pid(version)) { + if (sd_version_is_llada_image(version) || sd_version_is_mage_flow(version) || (version == VERSION_FIBO2 && request.image.ref_images_count == 1)) { + width = target_width; + height = target_height; + } else { + const int pixels = version == VERSION_QWEN_IMAGE_2_1 ? target_width * target_height : 1024 * 1024; + if (version == VERSION_FIBO2) { + std::tie(width, height) = sd::select_image_size_bucket(width, height, pixels, factor, target_width, target_height); + } else { + const double w = std::sqrt(double(std::min(pixels, target_width * target_height)) * width / height); + height = std::max(factor, int(std::round(w * height / width / factor)) * factor); + width = std::max(factor, int(std::round(w / factor)) * factor); + } + } + } + const auto pixels = name + "_pixels"; + const auto scale = std::max(double(width) / sd_tensor_dim(tensor, 1), double(height) / sd_tensor_dim(tensor, 2)); + const auto resize_width = int(std::ceil(sd_tensor_dim(tensor, 1) * scale)); + const auto resize_height = int(std::ceil(sd_tensor_dim(tensor, 2) * scale)); + request.fields["references"] += request.render("image_reference", {{"name", name}, {"channels", request.definition.geometry.image_channels}, {"width", width}, {"height", height}, {"center_crop", version == VERSION_FIBO2}, {"resize_width", resize_width}, {"resize_height", resize_height}, {"crop_x", (resize_width - width) / 2}, {"crop_y", (resize_height - height) / 2}, {"mode", literal(sd_version_is_minimax_h3_image(version) ? "lanczos" : "bilinear")}, {"encode", encode}, {"augment", version == VERSION_MINIMAX_H3_IMAGE}, {"latent", "reference_latent_" + std::to_string(index)}}); + return pixels; + } + + static bool prompt_has_vision(const GenerationTemplate& request) { + const auto* vision_path = request.context.model.config.context.llm_vision_path; + if (vision_path && *vision_path) + return true; + const auto path = request.values.at("text_path").get(); + require_file_access(path, SD_DGL_FILE_READ_MODEL); + ModelLoader metadata; + if (!metadata.init_from_file(path)) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "cannot inspect text encoder metadata: " + path); + const auto names = metadata.get_tensor_names(); + return std::any_of(names.begin(), names.end(), [](const auto& name) { + return name.find("visual.") != std::string::npos; + }); + } + + static void image_references(GenerationTemplate& request) { + const auto version = request.definition.version; + const auto refs = bound_tensors(request.options, "ref_images"); + if (refs.empty() && !sd_version_is_unet_edit(version)) + return; + const bool moss_edit = version == VERSION_MOSS_IMAGE; + const bool qwen_edit = sd_version_is_qwen_image(version) && version != VERSION_QWEN_IMAGE_LAYERED; + const bool has_vision = (moss_edit || qwen_edit) && prompt_has_vision(request); + if (moss_edit && !has_vision) + LOG_INFO("MOSS-Image HQ edit is using text-only prompt conditioning; set llm_vision_path (--llm_vision) to add reference images to Qwen3.5"); + std::string pixels, latents; + const bool encode = version != VERSION_HIDREAM_O1; + for (size_t i = 0; i < refs.size(); ++i) { + const auto image = reference_pixels(request, refs[i], i, encode); + const auto latent = "reference_latent_" + std::to_string(i); + if (encode) + latents += (latents.empty() ? "" : ", ") + latent; + const auto prompt_image = version == VERSION_QWEN_IMAGE_2_1 || version == VERSION_FIBO2 || sd_version_is_llada_image(version) ? image : "reference_" + std::to_string(i) + "_original"; + pixels += (pixels.empty() ? "" : ", ") + prompt_image; + } + if (sd_version_is_minimax_h3_image(version)) { + auto blocks = nlohmann::json::array(); + for (size_t i = 0; i < refs.size(); ++i) + blocks.push_back({{"kind", "image"}, {"video", i}}); + request.fields["predictor_options"] += ", reference_blocks = " + literal(blocks); + request.fields["negative_predictor_options"] += ", reference_blocks = " + literal(blocks); + request.fields["reference_predictor_options"] += ", reference_blocks = " + literal(blocks); + } + if (has_vision || sd_version_is_minimax_h3_image(version) || + version == VERSION_FIBO2 || sd_version_is_llada_image(version) || sd_version_is_krea2(version) || + sd_version_is_mage_flow(version) || sd_version_is_longcat(version) || sd_version_is_boogu_image(version)) { + request.fields["prompt_options"] += ", media = [" + pixels + "]"; + if (!sd_version_is_llada_image(version) && version != VERSION_FIBO2) + request.fields["negative_prompt_options"] += ", media = [" + pixels + "]"; + } + if (encode && !sd_version_is_unet_edit(version)) { + const bool increase = sd_version_is_flux2(version) || sd_version_is_flux3(version) || + sd_version_is_qwen_image(version) || sd_version_is_minimax_h3_image(version) || + version == VERSION_FIBO2 || sd_version_is_krea2(version) || + version == VERSION_ANIMA || sd_version_is_mage_flow(version) || moss_edit; + std::string options = ", ref_latents = [" + latents + "], ref_index_mode = " + + literal(version == VERSION_QWEN_IMAGE_LAYERED ? "decrease" : increase ? "increase" + : "fixed") + + ", force_ref_timestep_zero = " + literal(sd_version_is_llada_image(version) || sd_version_is_krea2(version) || moss_edit); + if (moss_edit) + options += ", ref_rope_anchor = \"image_start\""; + request.fields["predictor_options"] += options; + request.fields["negative_predictor_options"] += options; + request.fields["reference_predictor_options"] += options; + } + if (sd_version_is_unet_edit(version)) { + request.fields["predictor_options"] += ", concat = edit_latent"; + request.fields["negative_predictor_options"] += ", concat = edit_latent"; + } + } + + static void image_inpaint(GenerationTemplate& request) { + const bool inpaint = sd_version_is_inpaint(request.definition.version); + const auto* mask = bound_tensor(request.options, "mask_image"); + if (!mask && !inpaint) + return; + if (mask) { + if (!request.image.init_image.data) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "mask_image requires init_image"); + bind_tensor(request.program, "input_mask", mask); + } + if (inpaint) { + request.fields["predictor_options"] += ", concat = inpaint_condition"; + request.fields["negative_predictor_options"] += ", concat = inpaint_condition"; + } + request.fields["sample_options"] += inpaint ? ", base = base, denoise_mask = denoise_mask" : ", base = base, denoise_mask = mask_latent"; + } + + static void image_control(GenerationTemplate& request) { + const auto version = request.definition.version; + if (!request.image.control_image.data) { + if (version == VERSION_FLUX_CONTROLS) { + request.fields["predictor_options"] += ", concat = tensor::zeros_like(base)"; + request.fields["negative_predictor_options"] += ", concat = tensor::zeros_like(base)"; + } + return; + } + bind_tensor(request.program, "input_control", bound_tensor(request.options, "control_image")); + if (version == VERSION_FLUX_CONTROLS || version == VERSION_FLEX_2) { + if (version == VERSION_FLUX_CONTROLS) { + request.fields["predictor_options"] += ", concat = control_latent"; + request.fields["negative_predictor_options"] += ", concat = control_latent"; + } + return; + } + const auto& settings = request.context.model.config.context; + if (!settings.control_net_path || !*settings.control_net_path) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "control_image requires control_net_path"); + request.values["control_path"] = settings.control_net_path; + request.values["control_strength"] = request.image.control_strength; + request.fields["control_options"] = arguments(loader_options(settings, SDBackendModule::CONTROL_NET, request.definition)); + request.fields["control_hint"] = sd_version_is_z_image(version) ? "control_hint" : "control_pixels"; + request.fields["control_type"] = literal(sd_control_type_name(request.image.control_type)); + request.fields["positive_condition"] = "controlled_positive"; + request.fields["negative_condition"] = "controlled_negative"; + } + + void prepare_image_program(GenerationTemplate& request) { + const auto version = request.definition.version; + const auto& settings = request.context.model.config.context; + const auto prediction = settings.prediction == PREDICTION_COUNT ? request.context.model.default_prediction : settings.prediction; + const bool inpaint = sd_version_is_inpaint(version); + const bool mask = bound_tensor(request.options, "mask_image"); + const bool refs = request.image.ref_images_count > 0; + const bool control = request.image.control_image.data; + const bool native_control = version == VERSION_FLUX_CONTROLS || version == VERSION_FLEX_2; + const auto image_scale = request.image.sample_params.guidance.img_cfg; + const bool reference_guidance = refs && supports_reference_image_guidance(version); + if (std::isfinite(image_scale) && image_scale != 1.f && + !sd_version_is_inpaint_or_unet_edit(version) && !reference_guidance) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "sample.guidance.img_cfg is not supported by this model with these inputs"); + if (version != VERSION_QWEN_IMAGE_LAYERED && request.options && scalar_values(request.options).contains("qwen_image_layers")) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "qwen_image_layers requires Qwen Image Layered"); + const bool image_guidance = (inpaint || sd_version_is_control(version) || (sd_version_is_unet_edit(version) && refs) || reference_guidance) && std::isfinite(image_scale) && image_scale != 1.f; + request.flags = { + {"has_init", bool(request.image.init_image.data)}, {"has_mask", mask}, {"mask_stage", mask || inpaint}, {"references", refs}, {"unet_edit", sd_version_is_unet_edit(version)}, {"inpaint_model", inpaint}, {"flux_fill", version == VERSION_FLUX_FILL}, {"flex", version == VERSION_FLEX_2}, {"control_image", control}, {"native_control", native_control}, {"controlnet", control && !native_control}, {"z_control", control && sd_version_is_z_image(version)}, {"image_guidance", image_guidance}, {"minit2i", sd_version_is_minit2i(version)}, {"ming", version == VERSION_MING_IMAGE}, {"ideogram", sd_version_is_ideogram4(version)}, {"separate_negative_model", false}, {"sdxl_zero", sd_version_is_sdxl(version) && text(request.image.negative_prompt).empty() && prediction != EDM_V_PRED}, {"layered", version == VERSION_QWEN_IMAGE_LAYERED}, {"ph3", version == VERSION_P_H3_IMAGE}, {"h3_reference_noise", version == VERSION_MINIMAX_H3_IMAGE && refs}, {"custom_sigmas", request.image.sample_params.custom_sigmas_count > 0}}; + request.fields["predictor_core"] = request.fields["predictor_options"]; + request.flags["raw_reference"] = version == VERSION_SD1_PIX2PIX; + request.flags["reference_image_guidance"] = reference_guidance && image_guidance; + request.flags["hidream_o1"] = version == VERSION_HIDREAM_O1; + request.flags["control_image_guidance"] = image_guidance && version == VERSION_FLUX_CONTROLS; + if (version == VERSION_MOSS_IMAGE) + request.fields["negative_predictor_options"] += ", skip_layers = [22]"; + if (sd_version_is_sensenova_u1(version)) { + request.fields["negative_prompt_input"] = "negative_prompt_raw"; + request.fields["negative_prompt_options"] += ", raw = true"; + } + request.fields["entry"] = mask || inpaint ? "image_inpaint" : refs || sd_version_is_unet_edit(version) ? "image_edit" + : "image"; + if (version == VERSION_QWEN_IMAGE_LAYERED) { + if (request.image.init_image.data) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "Qwen layered uses ref_images rather than init_image"); + request.fields["entry"] = "image_layered"; + request.values["layers"] = request.image.qwen_image_layers + 1; + } + if (sd_version_is_minimax_h3_image(version)) { + request.fields["entry"] = "image_h3"; + const auto options = version == VERSION_P_H3_IMAGE ? ", video_sigma_shift = 1, audio_length = 2, audio_sigma_shift = 1" : ", video_sigma_shift = 1"; + request.fields["predictor_options"] += options; + request.fields["negative_predictor_options"] += options; + } + if (sd_version_is_ideogram4(version) && !text(settings.uncond_diffusion_model_path).empty()) { + request.flags["separate_negative_model"] = true; + request.values["negative_model_path"] = settings.uncond_diffusion_model_path; + request.fields["negative_model"] = "negative_model"; + request.fields["schedule_predictor"] = "pos"; + } + if (sd_version_is_pid(version) || sd_version_is_minit2i(version) || version == VERSION_IRIS) { + request.fields["entry"] = "image_pixel"; + if (sd_version_is_pid(version) && !refs) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "PiD requires a reference image"); + } + request.fields["unconditional_prompt_options"] = request.fields["negative_prompt_options"]; + image_references(request); + image_control(request); + image_inpaint(request); + if (image_guidance) { + request.values["image_cfg_scale"] = image_scale; + request.fields["guidance_options"] += ", image_only = image_only, image_scale = image_cfg_scale"; + request.fields["image_only_condition"] = request.fields["negative_condition"]; + request.fields["image_only_options"] = request.fields["negative_predictor_options"]; + request.fields["negative_predictor_options"] = request.fields["predictor_core"]; + if (reference_guidance) + request.fields["negative_condition"] = request.flags.at("controlnet").get() ? "controlled_unconditional" : "unconditional_text"; + else + request.fields["negative_predictor_options"] += ", concat = image_unconditional_concat"; + } + if (sd_version_is_sefi_image(version)) { + request.fields["entry"] = "image_sefi"; + auto options = nlohmann::json::object(); + for (const auto& [key, value] : parse_key_value_args(request.image.sample_params.extra_sample_args, "SeFi scheduler arg")) { + if (key != "sefi_alpha" && key != "sefi_delta_t") + continue; + float number; + if (parse_strict_float(value, number)) + options[key == "sefi_alpha" ? "alpha" : "delta"] = number; + else + LOG_WARN("ignoring invalid SeFi scheduler arg '%s=%s'", key.c_str(), value.c_str()); + } + request.fields["sefi_schedule_options"] = arguments(options); + } + } +} diff --git a/src/api/generation_metadata.cpp b/src/api/generation_metadata.cpp new file mode 100644 index 0000000000..386ad9be6a --- /dev/null +++ b/src/api/generation_metadata.cpp @@ -0,0 +1,202 @@ +#include "api/api.h" +#include "api/metadata.h" + +#include +#include +#include + +#include "dgl/syntax/syntax.h" + +namespace sd::api { + using JSON = nlohmann::json; + using Expression = std::shared_ptr; + using Bindings = std::map; + + static Expression resolve_expression(Expression expr, const Bindings& bindings) { + std::set visited; + while (expr && expr->form == dgl::Expr::Form::Reference && bindings.count(expr->name)) { + if (!visited.insert(expr->name).second) + return {}; + expr = bindings.at(expr->name); + } + return expr; + } + + static JSON constant(Expression expr, const Bindings& bindings, int depth = 0) { + if (depth > 32) + return {}; + expr = resolve_expression(std::move(expr), bindings); + if (!expr) + return {}; + if (expr->form == dgl::Expr::Form::Literal) + return expr->literal; + if (expr->form == dgl::Expr::Form::List) { + auto values = JSON::array(); + for (const auto& item : expr->arguments) { + auto value = constant(item.second, bindings, depth + 1); + if (value.is_null()) + return {}; + values.push_back(std::move(value)); + } + return values; + } + return {}; + } + + static Expression argument(const dgl::Expr& call, const char* name, size_t position = SIZE_MAX) { + size_t index = 0; + for (const auto& [key, expr] : call.arguments) { + if (key == name || (key.empty() && index == position)) + return expr; + if (key.empty()) + ++index; + } + return {}; + } + + static void collect_calls(const Expression& expr, std::map>& calls) { + if (!expr) + return; + if (expr->form == dgl::Expr::Form::Call) + calls[expr->name].push_back(expr); + for (const auto& item : expr->arguments) + collect_calls(item.second, calls); + for (const auto& statement : expr->body) + collect_calls(statement.value, calls); + } + + static std::string filename(const std::string& path) { + const auto offset = path.find_last_of("/\\"); + return offset == std::string::npos ? path : path.substr(offset + 1); + } + + nlohmann::json generation_metadata(const std::string& source) noexcept { + try { + const auto syntax = dgl::parse_syntax(source, true); + Bindings bindings; + std::map> calls; + for (const auto& statement : syntax.entry.body) { + if (!statement.name.empty()) + bindings.emplace(statement.name, statement.value); + collect_calls(statement.value, calls); + } + if (calls["sample"].empty() && calls["sefi::sample"].empty()) + return JSON::object(); + for (const auto& shape : calls["latent_shape"]) + if (argument(*shape, "frames")) + return JSON::object(); + auto info = JSON::object(); + for (const auto* key : {"prompt", "negative_prompt", "seed", "width", "height", "steps", "cfg_scale", "method", "scheduler", "eta", "strength", "clip_skip", "model_path", "vae_path"}) { + if (bindings.count(key)) { + auto value = constant(bindings.at(key), bindings); + if (!value.is_null()) + info[key] = std::move(value); + } + } + for (const auto* key : {"prompt", "negative_prompt"}) + if (bindings.count(std::string("source_") + key)) + info[key] = constant(bindings.at(std::string("source_") + key), bindings); + const auto select = [&](const std::vector& candidates, const char* parameter, size_t position, const char* output) { + JSON selected; + for (const auto& call : candidates) { + const auto value = constant(argument(*call, parameter, position), bindings); + if (value.is_null() || (!selected.is_null() && selected != value)) { + info.erase(output); + return; + } + selected = value; + } + if (!selected.is_null()) + info[output] = std::move(selected); + }; + select(calls["load_dit"], "path", 0, "model_path"); + select(calls["load_unet"], "path", 0, "model_path"); + select(calls["load_vae"], "path", 0, "vae_path"); + select(calls["cfg"], "scale", 2, "cfg_scale"); + select(calls["make_sigmas"], "steps", SIZE_MAX, "steps"); + select(calls["make_sigmas"], "scheduler", SIZE_MAX, "scheduler"); + const auto samples = calls["sample"].size() + calls["sefi::sample"].size(); + if (samples == 1) { + auto& sample = calls["sample"].empty() ? calls["sefi::sample"] : calls["sample"]; + select(sample, "method", SIZE_MAX, "method"); + select(sample, "eta", SIZE_MAX, "eta"); + } else { + for (const auto* key : {"steps", "method", "eta", "scheduler", "strength"}) + info.erase(key); + } + auto loras = JSON::array(); + std::set patches; + for (const auto& call : calls["apply_lora"]) { + const auto patch = resolve_expression(argument(*call, "lora", 1), bindings); + if (!patch || patch->form != dgl::Expr::Form::Call || patch->name != "load_lora") + continue; + const auto path = constant(argument(*patch, "path", 0), bindings); + auto weight = constant(argument(*call, "weight"), bindings); + if (path.is_string() && !weight.is_null()) { + auto item = JSON{{"path", path}, {"weight", weight}}; + if (patches.insert(item.dump()).second) + loras.push_back(std::move(item)); + } + } + info["loras"] = std::move(loras); + std::string infotext = info.value("prompt", ""); + for (const auto& lora : info.value("loras", JSON::array())) { + auto name = filename(lora.at("path")); + const auto extension = name.find_last_of('.'); + if (extension != std::string::npos) + name.erase(extension); + if (!name.empty() && name.find_first_of(":<>\r\n") == std::string::npos) + infotext += (infotext.empty() ? "" : " ") + std::string(""; + } + const auto negative = info.value("negative_prompt", ""); + if (!negative.empty()) + infotext += "\nNegative prompt: " + negative; + infotext += "\n"; + bool first = true; + const auto field = [&](const std::string& key, const JSON& value) { + std::string text = value.is_string() ? value.get() : value.dump(); + if (text.find_first_of(",\n\r:\"") != std::string::npos) + text = JSON(text).dump(); + infotext += (first ? "" : ", ") + key + ": " + text; + first = false; + }; + for (const auto& [key, label] : std::map{{"steps", "Steps"}, {"cfg_scale", "CFG scale"}, {"seed", "Seed"}, {"eta", "Eta"}, {"strength", "Denoising strength"}}) + if (info.contains(key)) + field(label, info.at(key)); + const std::map samplers{{"euler", "Euler"}, {"euler_a", "Euler a"}, {"heun", "Heun"}, {"dpm2", "DPM2"}, {"dpm++2s_a", "DPM++ 2S a"}, {"dpm++2m", "DPM++ 2M"}, {"dpm++2m_sde", "DPM++ 2M SDE"}, {"lcm", "LCM"}}; + const std::map schedulers{{"discrete", "Normal"}, {"karras", "Karras"}, {"exponential", "Exponential"}, {"sgm_uniform", "SGM Uniform"}, {"simple", "Simple"}, {"ddim_uniform", "DDIM"}, {"beta", "Beta"}}; + for (const auto& [key, label, unknown, names] : {std::tuple{"method", "Sampler", "SDCPP Sampler", &samplers}, {"scheduler", "Schedule type", "SDCPP Schedule", &schedulers}}) + if (info.contains(key)) { + const auto name = info.at(key).get(); + const auto found = names->find(name); + field(found == names->end() ? unknown : label, found == names->end() ? name : found->second); + } + if (info.contains("width") && info.contains("height")) + field("Size", info.at("width").dump() + "x" + info.at("height").dump()); + for (const auto& [key, label] : std::map{{"model_path", "Model"}, {"vae_path", "VAE"}}) + if (info.contains(key)) + field(label, filename(info.at(key))); + if (info.value("clip_skip", 0) > 0) + field("Clip skip", info.at("clip_skip")); + field("Version", "stable-diffusion.cpp"); + info["infotext"] = std::move(infotext); + return info; + } catch (...) { + return JSON::object(); + } + } +} + +static thread_local std::string generation_metadata_json; + +const char* sd_get_generation_metadata(const char* source) { + const char* result = nullptr; + sd::api::call([&] { + if (!source) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "source is required"); + generation_metadata_json = sd::api::generation_metadata(source).dump(); + result = generation_metadata_json.c_str(); + return SD_STATUS_OK; + }); + return result; +} diff --git a/src/api/generation_program.cpp b/src/api/generation_program.cpp new file mode 100644 index 0000000000..30cb658fc7 --- /dev/null +++ b/src/api/generation_program.cpp @@ -0,0 +1,353 @@ +#include "api/generation_program.h" + +#include +#include + +#include "conditioning/prompt_input.h" +#include "core/image_geometry.h" +#include "model/vae/geometry.hpp" +#include "name_conversion.h" +#include "runtime/guidance.h" + +namespace sd::api { + std::string GenerationTemplate::render(const std::string& name, const nlohmann::json& overrides) const { + nlohmann::json parameters = fields; + parameters["flags"] = flags; + parameters["vae_run_options"] = vae_options; + for (auto it = overrides.begin(); it != overrides.end(); ++it) + parameters[it.key()] = it.value(); + return render_template(name, parameters); + } + + static std::string variables(const nlohmann::json& values) { + std::string result; + for (auto it = values.begin(); it != values.end(); ++it) + result += " " + it.key() + " = " + literal(it.value()) + "\n"; + return result; + } + + std::string text(const char* value) { + return value ? value : ""; + } + + static std::string module_option(const char* value, SDBackendModule module, bool (*parse)(const std::string&, SDBackendAssignment*, std::string*) = sd_parse_backend_assignment) { + if (!value || !*value) + return ""; + SDBackendAssignment assignment; + std::string error; + if (!parse(value, &assignment, &error)) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, error); + return assignment.get(module); + } + + nlohmann::json loader_options(const ContextConfig& settings, SDBackendModule module, const ModelDefinition& definition) { + nlohmann::json options{{"family", definition.id}}; + for (const auto& [key, value] : std::map{{"backend", settings.backend}, {"params_backend", settings.params_backend}, {"split_mode", settings.split_mode}}) { + const auto selected = module_option(value, module); + if (!selected.empty()) + options[key] = selected; + } + auto flash = module_option(settings.flash_attn_mode, module, sd_parse_flash_attention_assignment); + if (flash.empty()) { + if (settings.flash_attn) + flash = "on"; + else if (settings.diffusion_flash_attn) + flash = module == SDBackendModule::DIFFUSION ? "on" : "off"; + } + if (!flash.empty()) + options["flash_attn_mode"] = flash; + auto conv = module_option(settings.conv_direct_mode, module, sd_parse_conv_direct_assignment); + if (conv.empty() && (module == SDBackendModule::VAE ? settings.vae_conv_direct : settings.diffusion_conv_direct)) + conv = "on"; + if (!conv.empty()) + options["conv_direct_mode"] = conv; + if (settings.wtype != SD_TYPE_COUNT) + options["wtype"] = sd_type_name(settings.wtype); + for (const auto& [key, value] : std::map{{"model_args", settings.model_args}, {"tensor_type_rules", settings.tensor_type_rules}}) + if (value && *value) + options[key] = value; + if (settings.linear_scale) + options["linear_scale"] = settings.linear_scale; + if (settings.attn_scale) + options["attn_scale"] = settings.attn_scale; + if (module == SDBackendModule::DIFFUSION && settings.sage_attn) + options["sage_attn"] = true; + return options; + } + + static std::string tiling_options(const TilingConfig& config, bool circular_x, bool circular_y) { + std::string options; + if (circular_x) + options += ", circular_x = true"; + if (circular_y) + options += ", circular_y = true"; + if (config.enabled || config.temporal_tiling) { + auto fields = nlohmann::json{{"enabled", config.enabled}, {"temporal_tiling", config.temporal_tiling}, {"tile_size_w", config.tile_size_w}, {"tile_size_h", config.tile_size_h}, {"target_overlap", config.target_overlap}, {"rel_size_w", config.rel_size_w}, {"rel_size_h", config.rel_size_h}}; + if (config.extra_tiling_args && *config.extra_tiling_args) + fields["extra_args"] = config.extra_tiling_args; + const auto args = arguments(fields); + options += ", tiling = tiling(" + args.substr(2) + ")"; + } + return options; + } + + static std::string cache_options(const sd_opt_t* options) { + const auto values = scalar_values(options); + if (!values.contains("cache.mode") || values.at("cache.mode") == "disabled") + return ""; + auto fields = nlohmann::json::object(); + for (auto it = values.begin(); it != values.end(); ++it) { + if (it.key().rfind("cache.", 0) != 0) + continue; + const auto name = it.key().substr(6); + if (name == "fn_compute_blocks" || name == "bn_compute_blocks") + continue; + fields[name] = it.value(); + } + const auto args = arguments(fields); + return ", cache = cache(" + args.substr(2) + ")"; + } + + void bind_tensor(GenerationProgram& program, const std::string& name, const sd_tensor_t* tensor) { + if (!tensor) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "missing host tensor '" + name + "'"); + program.inputs.emplace(name, dgl::Value::object(std::shared_ptr(sd_tensor_retain(tensor), sd_tensor_free))); + } + + static std::string input_names(const GenerationProgram& program) { + std::string names; + for (const auto& [name, value] : program.inputs) + names += (names.empty() ? "" : ", ") + name; + return names; + } + + struct LoraBindings { + std::string source; + std::string model = "base_model"; + std::string text = "base_text"; + }; + + static LoraBindings lora_bindings(const ContextConfig& settings, SDVersion family, const sd_lora_t* loras, uint32_t count) { + LoraBindings result; + for (uint32_t i = 0; i < count; ++i) { + if (loras[i].is_high_noise) + continue; + ModelLoader metadata; + if (!metadata.init_from_file_and_convert_name(text(loras[i].path), "lora.", family)) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "cannot inspect LoRA '" + text(loras[i].path) + "'"); + bool diffusion = false, conditioning = false; + for (const auto& name : metadata.get_tensor_names()) { + diffusion |= is_diffusion_model_name(name); + conditioning |= is_cond_stage_model_name(name); + } + if (!diffusion && !conditioning) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "LoRA has no diffusion or text-encoder targets"); + const auto number = std::to_string(i); + const auto model = "model_" + number, encoder = "text_" + number; + result.source += render_template("lora", {{"name", "lora_" + number}, {"path", text(loras[i].path)}, {"diffusion", diffusion}, {"conditioning", conditioning}, {"model_result", model}, {"text_result", encoder}, {"model_source", result.model}, {"text_source", result.text}, {"weight", loras[i].multiplier}, {"mode", sd_lora_apply_mode_name(settings.lora_apply_mode)}}); + if (diffusion) + result.model = model; + if (conditioning) + result.text = encoder; + } + return result; + } + + struct ComponentBindings { + bool tae; + nlohmann::json values; + std::map fields; + }; + + static ComponentBindings component_bindings(const ContextConfig& settings, const ModelDefinition& definition) { + const auto primary = text(settings.diffusion_model_path).empty() ? text(settings.model_path) : text(settings.diffusion_model_path); + auto text_path = text(settings.llm_path); + if (text_path.empty()) + text_path = text(settings.model_path); + if (text_path.empty()) + for (const auto* path : {settings.clip_l_path, settings.t5xxl_path, settings.clip_g_path}) + if (path && *path) { + text_path = path; + break; + } + if (text_path.empty()) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "a checkpoint or text encoder path is required"); + const bool mandatory_tae = definition.version == VERSION_SDXS_512_DS || definition.version == VERSION_SDXS_09; + const bool tae = settings.taesd_path && *settings.taesd_path && (!settings.tae_preview_only || mandatory_tae); + auto vae_path = tae ? text(settings.taesd_path) : text(settings.vae_path); + if (vae_path.empty()) + vae_path = text(settings.model_path).empty() ? primary : text(settings.model_path); + auto text_options = loader_options(settings, SDBackendModule::TE, definition); + for (const auto& [key, path] : std::map{{"tokenizer", settings.tokenizer}, {"vision_path", settings.llm_vision_path}, {"connectors_path", settings.embeddings_connectors_path}, {"t5_path", settings.t5xxl_path}, {"clip_l_path", settings.clip_l_path}, {"clip_g_path", settings.clip_g_path}}) + if (path && *path) + text_options[key] = path; + if (sd_version_is_ltxav(definition.version) || definition.version == VERSION_P_H3_IMAGE) + text_options["projection_path"] = primary; + auto vae_options = loader_options(settings, SDBackendModule::VAE, definition); + if (sd_version_is_sdxl(definition.version) && !tae && + (settings.force_sdxl_vae_conv_scale || text(settings.vae_path).empty())) + vae_options["conv_scale"] = 0.03125; + if (!tae && settings.vae_format != SD_VAE_FORMAT_AUTO) { + static const char* formats[]{"flux", "sd3", "flux2", "wan"}; + vae_options["vae_format"] = formats[int(settings.vae_format)]; + } + return {tae, + {{"model_path", primary}, {"text_path", text_path}, {"vae_path", vae_path}}, + {{"model_loader", sd_version_is_unet(definition.version) ? "load_unet" : "load_dit"}, + {"model_options", arguments(loader_options(settings, SDBackendModule::DIFFUSION, definition))}, + {"text_options", arguments(text_options)}, + {"vae_loader", tae ? "load_tae" : "load_vae"}, + {"vae_options", arguments(vae_options)}}}; + } + + static GenerationProgram generation_program(GenerationContext& context, const ImageConfig& image, const sd_opt_t* explicit_options, int64_t seed, const VideoConfig* video) { + auto& model = context.model; + const auto& definition = model.definition(context); + const auto& settings = model.config.context; + if (!supports_generation(definition, video != nullptr)) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "this model requires a video or dedicated DGL workflow"); + const auto components = component_bindings(settings, definition); + const auto method = image.sample_params.sample_method == SAMPLE_METHOD_COUNT ? definition.sampling.default_sample_method : image.sample_params.sample_method; + auto scheduler = image.sample_params.scheduler; + if (scheduler == SCHEDULER_COUNT) { + scheduler = (settings.prediction == EDM_V_PRED || (settings.prediction == PREDICTION_COUNT && model.default_prediction == EDM_V_PRED)) ? EXPONENTIAL_SCHEDULER : method == LCM_SAMPLE_METHOD || method == TCD_SAMPLE_METHOD ? LCM_SCHEDULER + : method == DDIM_TRAILING_SAMPLE_METHOD ? SIMPLE_SCHEDULER + : definition.sampling.default_scheduler; + } + const auto predictor_options = arguments({{"prediction", settings.prediction == PREDICTION_COUNT ? "auto" : sd_prediction_name(settings.prediction)}, + {"guidance", image.sample_params.guidance.distilled_guidance}, + {"circular_x", image.circular_x}, + {"circular_y", image.circular_y}}); + const double eta = std::isfinite(image.sample_params.eta) ? image.sample_params.eta : definition.version == VERSION_HIDREAM_O1 ? 8.0 + : method == EULER_A_SAMPLE_METHOD || method == DPMPP2S_A_SAMPLE_METHOD || method == ER_SDE_SAMPLE_METHOD || method == EULER_A_CFG_PP_SAMPLE_METHOD || method == DPMPP2M_SDE_SAMPLE_METHOD || method == DPMPP2M_SDE_BT_SAMPLE_METHOD ? 1.0 + : 0.0; + auto values = components.values; + values.update({{"prompt", text(image.prompt)}, {"negative_prompt", text(image.negative_prompt)}, {"seed", seed}, {"width", image.width}, {"height", image.height}, {"steps", image.sample_params.sample_steps}, {"cfg_scale", image.sample_params.guidance.txt_cfg}, {"method", sd_sample_method_name(method)}, {"scheduler", sd_scheduler_name(scheduler)}, {"eta", eta}, {"rng_type", sd_rng_type_name(settings.rng_type)}}); + const auto vae_version = definition.traits.vae_format_override && !components.tae ? sd::vae::version_for_format(settings.vae_format, definition.version) : definition.version; + const int scale = sd_version_is_pid(definition.version) ? 1 : sd::vae::spatial_scale(vae_version); + const int multiple = scale * definition.geometry.diffusion_down_factor; + values["width"] = sd_version_is_minit2i(definition.version) ? 512 : sd::align_image_dimension(image.width, multiple); + values["height"] = sd_version_is_minit2i(definition.version) ? 512 : sd::align_image_dimension(image.height, multiple); + const auto axes = tiling_options(image.vae_tiling_params, image.circular_x, image.circular_y); + auto schedule_options = nlohmann::json::object(); + if (std::isfinite(image.sample_params.flow_shift)) + schedule_options["flow_shift"] = image.sample_params.flow_shift; + if (image.sample_params.extra_sample_args && *image.sample_params.extra_sample_args) + schedule_options["extra_args"] = image.sample_params.extra_sample_args; + if (image.sample_params.custom_sigmas_count) { + values["custom_sigmas"] = std::vector(image.sample_params.custom_sigmas, image.sample_params.custom_sigmas + image.sample_params.custom_sigmas_count); + if (!video) + values["steps"] = image.sample_params.custom_sigmas_count - 1; + } + GenerationProgram program; + if (video) { + values["frames"] = sd::vae::aligned_frames(definition.version, video->video_frames); + values["fps"] = sd_version_is_minimax_h3(definition.version) ? 24 : definition.version == VERSION_WAN2_2_S2V ? 16 + : video->fps; + } + const bool init = image.init_image.data; + if (!video && init) { + bind_tensor(program, "input_image", bound_tensor(explicit_options, "init_image")); + values["strength"] = image.strength; + } + const auto sampler_type = settings.sampler_rng_type == RNG_TYPE_COUNT ? settings.rng_type : settings.sampler_rng_type; + std::string preview_decoder = "vae"; + if (settings.tae_preview_only && settings.taesd_path && *settings.taesd_path) { + auto options = loader_options(settings, SDBackendModule::VAE, definition); + options["decode_only"] = true; + preview_decoder = "load_tae(" + literal(settings.taesd_path) + arguments(options) + ")"; + } + auto sample_options = cache_options(explicit_options) + ", observer = preview(decoder = " + preview_decoder + arguments({{"circular_x", image.circular_x}, {"circular_y", image.circular_y}}) + ")"; + if (image.sample_params.extra_sample_args && *image.sample_params.extra_sample_args) + sample_options += ", extra_args = " + literal(image.sample_params.extra_sample_args); + const auto to_vae = sd_version_is_unet(definition.version) ? "unet_to_vae_latents" : "dit_to_vae_latents"; + const auto patches = lora_bindings(settings, definition.version, image.loras, image.lora_count); + const auto apg = sd::guidance::parse_adaptive_projected_guidance_args(image.sample_params.extra_sample_args); + const bool use_apg = sd::guidance::is_adaptive_projected_guidance_enabled(apg); + const auto guidance_schedule = sd::guidance::parse_guidance_schedule(image.sample_params.extra_sample_args); + auto guidance_options = nlohmann::json::object(); + if (!guidance_schedule.empty()) + guidance_options["schedule"] = guidance_schedule; + if (use_apg) + guidance_options.update({{"eta", apg.eta}, {"momentum", apg.momentum}, {"norm_threshold", apg.norm_threshold}, {"norm_threshold_smoothing", apg.norm_threshold_smoothing}}); + std::map fields{{"patched_model", patches.model}, + {"patched_text", patches.text}, + {"references", ""}, + {"loras", patches.source}, + {"positive_condition", "positive"}, + {"negative_condition", "negative"}, + {"negative_model", "model"}, + {"prompt_options", ", clip_skip = " + std::to_string(image.clip_skip)}, + {"negative_prompt_options", ", clip_skip = " + std::to_string(image.clip_skip)}, + {"negative_prompt_input", "negative_prompt"}, + {"predictor_options", predictor_options}, + {"predictor_core", predictor_options}, + {"reference_predictor_options", ""}, + {"negative_predictor_options", predictor_options}, + {"guidance_options", arguments(guidance_options)}, + {"guidance_core", arguments(guidance_options)}, + {"guidance_function", use_apg ? "apg" : "cfg"}, + {"sample_options", sample_options}, + {"sample_core", sample_options}, + {"result_latent", "latent"}, + {"output_audio_shape", "audio_shape"}, + {"output_video_frames", "tensor::shape(video_base)[2]"}, + {"to_vae", to_vae}, + {"channels", std::to_string(definition.geometry.image_channels)}, + {"from_vae", sd_version_is_unet(definition.version) ? "vae_to_unet_latents" : "vae_to_dit_latents"}, + {"schedule_options", arguments(schedule_options)}, + {"schedule_predictor", "guided"}, + {"audio", "{}"}}; + fields.insert(components.fields.begin(), components.fields.end()); + GenerationTemplate request{context, image, explicit_options, definition, program, values, fields, video, axes, seed}; + if (video) + prepare_video_program(request); + else + prepare_image_program(request); + prepare_prompt_images(request); + if (sd_version_is_sensenova_u1(definition.version)) { + const auto input = sd::parse_prompt_input(values.at("negative_prompt").get(), true); + if (std::any_of(input.begin(), input.end(), [](const auto& part) { return part.type != sd::PromptPart::Type::TEXT; })) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "SenseNova U1.5 does not support inline prompt images or embeddings"); + values["negative_prompt_raw"] = "<|im_start|>user\n" + sd::prompt_input_text(input) + "<|im_end|>\n<|im_start|>assistant\n"; + } + request.flags["encode_negative"] = image.sample_params.guidance.txt_cfg != 1.f || use_apg || request.flags.value("image_guidance", false) || + method == EULER_CFG_PP_SAMPLE_METHOD || method == EULER_A_CFG_PP_SAMPLE_METHOD || + std::any_of(guidance_schedule.begin(), guidance_schedule.end(), [](float scale) { return scale != 1.f; }); + request.flags["shared_rng"] = sampler_type == settings.rng_type; + if (sampler_type != settings.rng_type) + values["sampler_rng_type"] = sd_rng_type_name(sampler_type); + prepare_hires_program(request); + fields["variables"] = variables(values); + fields["inputs"] = input_names(program); + program.source = request.render(fields.at("entry")); + return program; + } + + GenerationProgram image_program(GenerationContext& context, const ImageConfig& image, const sd_opt_t* explicit_options, int64_t seed) { + return generation_program(context, image, explicit_options, seed, nullptr); + } + + GenerationProgram video_program(GenerationContext& context, const VideoConfig& video, const sd_opt_t* explicit_options, int64_t seed) { + ImageConfig common; + common.loras = video.loras; + common.lora_count = video.lora_count; + common.prompt = video.prompt; + common.negative_prompt = video.negative_prompt; + common.clip_skip = video.clip_skip; + common.init_image = video.init_image; + common.ref_images = video.ref_images; + common.ref_images_count = video.ref_images_count; + common.width = video.width; + common.height = video.height; + common.sample_params = video.sample_params; + common.strength = video.strength; + common.vae_tiling_params = video.vae_tiling_params; + common.cache = video.cache; + common.hires = video.hires; + common.circular_x = video.circular_x; + common.circular_y = video.circular_y; + return generation_program(context, common, explicit_options, seed, &video); + } + +} diff --git a/src/api/generation_program.h b/src/api/generation_program.h new file mode 100644 index 0000000000..714e981896 --- /dev/null +++ b/src/api/generation_program.h @@ -0,0 +1,33 @@ +#ifndef __SD_API_GENERATION_PROGRAM_H__ +#define __SD_API_GENERATION_PROGRAM_H__ + +#include "api/generation.h" + +namespace sd::api { + struct GenerationTemplate { + GenerationContext& context; + const ImageConfig& image; + const sd_opt_t* options; + const ModelDefinition& definition; + GenerationProgram& program; + nlohmann::json& values; + std::map& fields; + const VideoConfig* video; + std::string vae_options; + int64_t seed; + nlohmann::json flags = nlohmann::json::object(); + + std::string render(const std::string& name, const nlohmann::json& overrides = nlohmann::json::object()) const; + }; + + std::string text(const char* value); + nlohmann::json loader_options(const ContextConfig& settings, SDBackendModule module, const ModelDefinition& definition); + void bind_tensor(GenerationProgram& program, const std::string& name, const sd_tensor_t* tensor); + void prepare_image_program(GenerationTemplate& request); + void prepare_video_program(GenerationTemplate& request); + void prepare_hires_program(GenerationTemplate& request); + void prepare_prompt_images(GenerationTemplate& request); + void prepare_h3_references(GenerationTemplate& request, const std::string& first, const std::string& last); +} + +#endif // __SD_API_GENERATION_PROGRAM_H__ diff --git a/src/api/generation_prompt.cpp b/src/api/generation_prompt.cpp new file mode 100644 index 0000000000..991e0a60ed --- /dev/null +++ b/src/api/generation_prompt.cpp @@ -0,0 +1,123 @@ +#include "api/generation_program.h" + +#include +#include + +#include "api/tensor.h" + +namespace sd::api { + static std::string embedding_lookup(std::string value) { + std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return std::tolower(c); }); + return value; + } + + static void prepare_textual_inversion(GenerationTemplate& request) { + const auto& config = request.context.model.config.context; + if (!config.embedding_count) + return; + std::vector> embeddings; + for (uint32_t i = 0; i < config.embedding_count; ++i) { + auto path = text(config.embeddings[i].path); + std::replace(path.begin(), path.end(), '\\', '/'); + if (path.find('>') != std::string::npos) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "embedding path cannot contain '>'"); + embeddings.emplace_back(embedding_lookup(config.embeddings[i].name), std::move(path)); + } + std::stable_sort(embeddings.begin(), embeddings.end(), [](const auto& a, const auto& b) { return a.first.size() > b.first.size(); }); + const auto word = [](unsigned char c) { return std::isalnum(c) || c == '_' || c >= 128; }; + for (const auto* key : {"prompt", "negative_prompt"}) { + const auto original = request.values.at(key).get(); + const auto lookup = embedding_lookup(original); + std::string rewritten; + for (size_t cursor = 0; cursor < original.size();) { + if (original[cursor] == '<') { + const auto end = original.find('>', cursor); + if (end != std::string::npos) { + rewritten += original.substr(cursor, end + 1 - cursor); + cursor = end + 1; + continue; + } + } + bool matched = false; + for (const auto& [name, path] : embeddings) { + const auto end = cursor + name.size(); + if ((cursor && word(original[cursor - 1])) || + lookup.compare(cursor, name.size(), name) || (end < original.size() && word(original[end]))) + continue; + rewritten += ""; + cursor = end; + matched = true; + break; + } + if (!matched) + rewritten += original[cursor++]; + } + if (rewritten != original) { + request.values[std::string("source_") + key] = original; + request.values[key] = std::move(rewritten); + } + } + } + + void prepare_prompt_images(GenerationTemplate& request) { + prepare_textual_inversion(request); + auto& context = request.context; + if (!context.prompt_image) + return; + std::map aliases; + for (const auto* key : {"prompt", "negative_prompt"}) { + const auto original = request.values.at(key).get(); + std::string rewritten; + size_t cursor = 0; + while (cursor < original.size()) { + const auto start = original.find(" slashes && original[start - slashes - 1] == '\\') + ++slashes; + rewritten += original.substr(cursor, start - cursor); + if (slashes % 2) { + rewritten += "', start + 7); + if (end == std::string::npos || end == start + 7) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "invalid inline prompt image"); + const auto source = original.substr(start + 7, end - start - 7); + auto found = aliases.find(source); + if (found == aliases.end()) { + if (aliases.size() >= 32) + throw dgl::Error(SD_STATUS_OUT_OF_RANGE, "a request supports at most 32 prompt images"); + context.check_cancelled(); + const sd_tensor_t* tensor = nullptr; + if (!context.prompt_image(source.c_str(), context.prompt_image_data, &tensor) || !tensor) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "cannot resolve prompt image '" + source + "'"); + image_view(*tensor); + auto copy = std::make_shared(tensor->type, tensor->shape(), tensor->data(), tensor->bytes); + const auto alias = "prompt_image_" + std::to_string(aliases.size()); + request.program.inputs.emplace(alias, dgl::Value::object(std::move(copy))); + found = aliases.emplace(source, alias).first; + } + rewritten += "second + ">"; + cursor = end + 1; + } + if (rewritten != original) { + request.values[std::string("source_") + key] = original; + request.values[key] = rewritten; + } + } + if (aliases.empty()) + return; + std::string bindings; + for (const auto& [source, alias] : aliases) + bindings += (bindings.empty() ? "" : ", ") + alias + " = " + alias; + const auto argument = ", image_bindings = {" + bindings + "}"; + request.fields["prompt_options"] += argument; + request.fields["negative_prompt_options"] += argument; + request.fields["unconditional_prompt_options"] += argument; + } +} diff --git a/src/api/generation_template.cpp b/src/api/generation_template.cpp new file mode 100644 index 0000000000..f56e09a45a --- /dev/null +++ b/src/api/generation_template.cpp @@ -0,0 +1,222 @@ +#include "api/generation_template.h" + +#include +#include +#include +#include +#include + +#include "api_templates.h" + +namespace sd::api { + std::string literal(const nlohmann::json& value) { + if (value.is_object()) { + std::string result = "{"; + for (auto it = value.begin(); it != value.end(); ++it) { + if (it != value.begin()) + result += ", "; + result += it.key() + " = " + literal(it.value()); + } + return result + "}"; + } + if (value.is_array()) { + std::string result = "["; + for (size_t i = 0; i < value.size(); ++i) + result += (i ? ", " : "") + literal(value[i]); + return result + "]"; + } + return value.dump(); + } + + std::string arguments(const nlohmann::json& values) { + if (!values.is_object()) + throw std::logic_error("template argument options must be an object"); + std::string result; + for (auto it = values.begin(); it != values.end(); ++it) + result += ", " + it.key() + " = " + literal(it.value()); + return result; + } + + struct TemplatePart { + enum class Kind { Text, + Variable, + Conditional, + Include } kind; + std::string value; + std::vector>> branches; + std::vector otherwise; + }; + + static std::string trim_template(std::string_view text) { + const auto start = text.find_first_not_of(" \t\r\n"); + if (start == std::string_view::npos) + return ""; + return std::string(text.substr(start, text.find_last_not_of(" \t\r\n") - start + 1)); + } + + class TemplateParser { + std::string name_; + std::string_view source_; + size_t offset_ = 0; + + [[noreturn]] void fail(const std::string& reason) const { + size_t line = 1; + for (size_t i = 0; i < offset_; ++i) + line += source_[i] == '\n'; + throw std::logic_error("template '" + name_ + "', line " + std::to_string(line) + ": " + reason); + } + + std::vector sequence(std::string& boundary) { + std::vector parts; + while (offset_ < source_.size()) { + const auto variable = source_.find("{{", offset_); + const auto control = source_.find("{%", offset_); + const auto begin = std::min(variable, control); + if (begin == std::string_view::npos) { + parts.push_back({TemplatePart::Kind::Text, std::string(source_.substr(offset_))}); + offset_ = source_.size(); + break; + } + if (begin > offset_) + parts.push_back({TemplatePart::Kind::Text, std::string(source_.substr(offset_, begin - offset_))}); + const bool is_variable = begin == variable; + const auto end = source_.find(is_variable ? "}}" : "%}", begin + 2); + if (end == std::string_view::npos) + fail("unterminated tag"); + const auto command = trim_template(source_.substr(begin + 2, end - begin - 2)); + offset_ = end + 2; + if (!is_variable) { + if (source_.substr(offset_, 2) == "\r\n") + offset_ += 2; + else if (offset_ < source_.size() && source_[offset_] == '\n') + ++offset_; + } + if (is_variable) { + if (command.empty()) + fail("empty variable"); + parts.push_back({TemplatePart::Kind::Variable, command}); + } else if (command == "else" || command == "endif" || command.rfind("elif ", 0) == 0) { + boundary = command; + return parts; + } else if (command.rfind("if ", 0) == 0) { + TemplatePart conditional{TemplatePart::Kind::Conditional}; + auto condition = trim_template(std::string_view(command).substr(3)); + std::string closing; + do { + if (condition.empty()) + fail("empty condition"); + closing.clear(); + conditional.branches.emplace_back(condition, sequence(closing)); + condition = closing.rfind("elif ", 0) == 0 ? trim_template(std::string_view(closing).substr(5)) : ""; + } while (!condition.empty()); + if (closing == "else") { + closing.clear(); + conditional.otherwise = sequence(closing); + } + if (closing != "endif") + fail("expected endif"); + parts.push_back(std::move(conditional)); + } else if (command.rfind("include ", 0) == 0) { + const auto path = trim_template(std::string_view(command).substr(8)); + if (path.size() < 3 || path.front() != '"' || path.back() != '"') + fail("include requires a quoted template name"); + parts.push_back({TemplatePart::Kind::Include, path.substr(1, path.size() - 2)}); + } else { + fail("unknown directive '" + command + "'"); + } + } + return parts; + } + + public: + TemplateParser(std::string name, std::string_view source) + : name_(std::move(name)), source_(source) {} + + std::vector parse() { + std::string boundary; + auto result = sequence(boundary); + if (!boundary.empty()) + fail("unexpected '" + boundary + "'"); + return result; + } + }; + + static const nlohmann::json& template_value(const nlohmann::json& values, const std::string& name) { + const auto* value = &values; + size_t start = 0; + do { + const auto dot = name.find('.', start); + const auto field = name.substr(start, dot - start); + if (!value->is_object() || !value->contains(field)) + throw std::logic_error("missing template variable '" + name + "'"); + value = &value->at(field); + if (dot == std::string::npos) + return *value; + start = dot + 1; + } while (start < name.size()); + throw std::logic_error("invalid template variable '" + name + "'"); + } + + static bool template_condition(const nlohmann::json& values, std::string name) { + const bool invert = name.rfind("not ", 0) == 0; + if (invert) + name = trim_template(std::string_view(name).substr(4)); + const auto& value = template_value(values, name); + if (!value.is_boolean()) + throw std::logic_error("template condition '" + name + "' must be boolean"); + return value.get() != invert; + } + + using ParsedTemplates = std::map>; + + static void render_parts(std::string& output, const std::vector& parts, const nlohmann::json& values, const ParsedTemplates& sources, int depth) { + if (depth > 16) + throw std::logic_error("template include depth exceeds 16"); + for (const auto& part : parts) { + if (part.kind == TemplatePart::Kind::Text) { + output += part.value; + } else if (part.kind == TemplatePart::Kind::Variable) { + const auto separator = part.value.find('|'); + const auto name = trim_template(std::string_view(part.value).substr(0, separator)); + const auto& value = template_value(values, name); + const auto filter = separator == std::string::npos ? "" : trim_template(std::string_view(part.value).substr(separator + 1)); + if (filter == "literal") + output += literal(value); + else if (filter == "args") + output += arguments(value); + else if (filter.empty()) + output += value.is_string() ? value.get() : literal(value); + else + throw std::logic_error("unknown template filter '" + filter + "'"); + } else if (part.kind == TemplatePart::Kind::Include) { + const auto include = sources.find(part.value); + if (include == sources.end()) + throw std::logic_error("unknown included template '" + part.value + "'"); + render_parts(output, include->second, values, sources, depth + 1); + } else { + const auto* selected = &part.otherwise; + for (const auto& [condition, branch] : part.branches) + if (template_condition(values, condition)) { + selected = &branch; + break; + } + render_parts(output, *selected, values, sources, depth); + } + } + } + + std::string render_template(const std::string& name, const nlohmann::json& values) { + static const auto sources = [] { + ParsedTemplates result; + for (const auto& [name, source] : templates::sources) + result.emplace(name, TemplateParser(name, source).parse()); + return result; + }(); + const auto source = sources.find(name); + if (source == sources.end()) + throw std::logic_error("unknown generation template '" + name + "'"); + std::string result; + render_parts(result, source->second, values, sources, 0); + return result; + } +} diff --git a/src/api/generation_template.h b/src/api/generation_template.h new file mode 100644 index 0000000000..2b7445ee03 --- /dev/null +++ b/src/api/generation_template.h @@ -0,0 +1,14 @@ +#ifndef __SD_API_GENERATION_TEMPLATE_H__ +#define __SD_API_GENERATION_TEMPLATE_H__ + +#include + +#include "json.hpp" + +namespace sd::api { + std::string literal(const nlohmann::json& value); + std::string arguments(const nlohmann::json& values); + std::string render_template(const std::string& name, const nlohmann::json& values); +} + +#endif diff --git a/src/api/generation_video.cpp b/src/api/generation_video.cpp new file mode 100644 index 0000000000..8e4a963d55 --- /dev/null +++ b/src/api/generation_video.cpp @@ -0,0 +1,155 @@ +#include "api/generation_program.h" + +#include +#include + +#include "model/vae/audio_geometry.hpp" + +namespace sd::api { + static void predictor_option(GenerationTemplate& request, const std::string& option) { + request.fields["predictor_options"] += option; + request.fields["negative_predictor_options"] += option; + } + + static bool keyframe(GenerationTemplate& request, const char* key, const char* name) { + const auto* tensor = bound_tensor(request.options, key); + if (!tensor) + return false; + bind_tensor(request.program, name, tensor); + return true; + } + + static void driving_audio(GenerationTemplate& request) { + const auto tracks = bound_audios(request.options, "ref_audios"); + if (tracks.size() > 1) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "Wan S2V accepts one driving audio track"); + request.flags["driving_audio"] = !tracks.empty(); + if (tracks.empty()) + return; + const auto& config = request.context.model.config.context; + if (!config.audio_encoder_path || !*config.audio_encoder_path) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "Wan S2V audio requires audio_encoder_path"); + bind_tensor(request.program, "driving_audio", tracks[0].data); + request.values["audio_encoder_path"] = config.audio_encoder_path; + request.values["sample_rate"] = tracks[0].sample_rate; + request.fields["audio_encoder_options"] = arguments(loader_options(config, SDBackendModule::TE, request.definition)); + request.fields["audio"] = "{samples = driving_audio[:, :math::floor(sample_rate * frames / fps)], sample_rate = sample_rate}"; + predictor_option(request, ", audio_embedding = audio_embedding"); + } + + static void audiovisual(GenerationTemplate& request) { + const bool h3 = sd_version_is_minimax_h3(request.definition.version); + const auto& settings = request.context.model.config.context; + auto path = text(settings.audio_vae_path); + if (path.empty()) + path = request.context.model.embedded_audio_vae; + request.flags["decode_audio"] = !path.empty(); + if (!path.empty()) + request.values["audio_vae_path"] = path; + else + request.values["empty_audio_shape"] = sd::vae::audio_latent_shape(request.definition.version, request.values.at("frames").get(), request.values.at("fps").get()); + const auto video_shift = std::isfinite(request.image.sample_params.flow_shift) ? request.image.sample_params.flow_shift : request.definition.sampling.default_flow_shift; + if (h3 && video_shift <= 0) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 flow shift must be positive"); + request.values["audio_scale"] = h3 ? video_shift / 3.f : 1.f; + request.fields["audio_vae_options"] = arguments(loader_options(settings, SDBackendModule::VAE, request.definition)); + predictor_option(request, h3 ? ", audio_length = audio_shape[0], fps = fps" : ", audio_length = audio_shape[1], fps = fps"); + if (h3) + predictor_option(request, ", video_sigma_shift = " + literal(video_shift)); + } + + static void dual_expert(GenerationTemplate& request) { + const auto& settings = request.context.model.config.context; + request.flags["dual"] = !text(settings.high_noise_diffusion_model_path).empty(); + if (!request.flags.at("dual").get()) + return; + if (!sd_version_is_wan(request.definition.version) && !sd_version_is_lingbot_video(request.definition.version)) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "two-model sampling requires Wan or LingBot; use DGL for other compositions"); + request.values["high_model_path"] = settings.high_noise_diffusion_model_path; + request.values["moe_boundary"] = request.video->moe_boundary; + request.flags["fixed_high_steps"] = request.video->high_noise_steps >= 0; + if (request.video->high_noise_steps >= 0) { + const int64_t high_steps = request.video->high_noise_steps; + const int64_t total_steps = request.image.sample_params.sample_steps + high_steps; + if (!request.image.sample_params.custom_sigmas_count && total_steps > 10000) + throw dgl::Error(SD_STATUS_OUT_OF_RANGE, "combined low/high-noise steps exceed 10000"); + request.values["steps"] = total_steps; + request.values["high_noise_steps"] = high_steps; + if (request.image.sample_params.custom_sigmas_count) { + request.values["steps"] = request.image.sample_params.custom_sigmas_count - 1; + if (high_steps > 0) + request.values["high_noise_steps"] = std::max(0, request.image.sample_params.custom_sigmas_count - 1 - request.image.sample_params.sample_steps); + } + } + std::string high = "high_base", patches; + for (uint32_t i = 0; i < request.video->lora_count; ++i) { + const auto& lora = request.video->loras[i]; + if (!lora.is_high_noise) + continue; + patches += request.render("lora", {{"name", "high_lora_" + std::to_string(i)}, {"path", text(lora.path)}, {"diffusion", true}, {"conditioning", false}, {"model_result", "high_model_" + std::to_string(i)}, {"model_source", high}, {"weight", lora.multiplier}, {"mode", sd_lora_apply_mode_name(settings.lora_apply_mode)}}); + high = "high_model_" + std::to_string(i); + } + request.fields["high_loras"] = patches; + request.fields["high_model"] = high; + } + + void prepare_video_program(GenerationTemplate& request) { + const auto version = request.definition.version; + const auto& settings = request.context.model.config.context; + const bool first = keyframe(request, "init_image", "first_frame"); + const bool last = keyframe(request, "end_image", "last_frame"); + const bool vace = request.context.model.wan_vace; + const bool s2v = version == VERSION_WAN2_2_S2V; + const bool frozen = (version == VERSION_WAN2_2_TI2V || sd_version_is_lingbot_video(version)) && (first || last); + const bool ltx = sd_version_is_ltxav(version); + const bool h3 = version == VERSION_MINIMAX_H3; + if (!h3 && !bound_videos(request.options, "ref_videos").empty()) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "reference videos require MiniMax-H3"); + if (!h3 && !s2v && !bound_audios(request.options, "ref_audios").empty()) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "reference audio requires MiniMax-H3 or Wan2.2 S2V"); + if (s2v && last) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "Wan2.2 S2V does not support an end image"); + const bool image_condition = !vace && !s2v && request.context.model.wan_image_condition; + request.flags = {{"first", first}, {"last", last}, {"conditioned", first || last}, {"vace", vace}, {"vace_reference", vace && first}, {"s2v_reference", s2v && first}, {"driving_audio", false}, {"image_condition", image_condition}, {"vision", image_condition && request.context.model.wan_vision_condition}, {"end_vision", request.context.model.wan_end_vision}, {"frozen", frozen}, {"hunyuan", sd_version_is_hunyuan_video(version) && (first || last)}, {"controls", false}, {"dual", false}, {"custom_sigmas", request.image.sample_params.custom_sigmas_count > 0}}; + request.fields["entry"] = ltx ? "video_ltx" : h3 ? "video_h3" + : "video_wan"; + if (image_condition || request.flags.at("hunyuan").get()) + predictor_option(request, ", concat = video_concat"); + if (frozen) + request.fields["sample_options"] += ", base = base, denoise_mask = video_mask, mask_input = true"; + if (vace) { + const auto* frames = bound_tensor(request.options, "control_frames"); + if (frames) { + bind_tensor(request.program, "control_video", frames); + request.values["control_count"] = std::min(sd_tensor_dim(frames, 3), request.values.at("frames").get()); + } + request.flags["controls"] = frames != nullptr; + predictor_option(request, ", vace_context = vace_context, vace_strength = " + literal(request.video->vace_strength)); + } else if (bound_tensor(request.options, "control_frames")) { + throw dgl::Error(SD_STATUS_UNSUPPORTED, "control frames require a VACE model or an explicit DGL workflow"); + } + if (s2v) { + if (first) + predictor_option(request, ", ref_latents = [reference_latent]"); + driving_audio(request); + } + if (request.flags.at("vision").get()) { + if (!settings.clip_vision_path || !*settings.clip_vision_path) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "Wan image conditioning requires clip_vision_path"); + request.values["vision_path"] = settings.clip_vision_path; + request.fields["vision_options"] = arguments(loader_options(settings, SDBackendModule::TE, request.definition)); + } + if (ltx || h3) { + audiovisual(request); + if (ltx && (first || last)) { + request.values["strength"] = request.image.strength; + request.fields["sample_options"] += ", base = base, denoise_mask = packed_mask, mask_input = true"; + if (last) + predictor_option(request, ", video_positions = positions"); + } + if (h3) + prepare_h3_references(request, first ? "first_frame_pixels" : "", last ? "last_frame_pixels" : ""); + } + dual_expert(request); + } +} diff --git a/examples/cli/image_metadata.cpp b/src/api/image_metadata.cpp similarity index 96% rename from examples/cli/image_metadata.cpp rename to src/api/image_metadata.cpp index bb5ab7cf84..5924800e53 100644 --- a/examples/cli/image_metadata.cpp +++ b/src/api/image_metadata.cpp @@ -1,4 +1,4 @@ -#include "image_metadata.h" +#include "api/api.h" #include #include @@ -26,7 +26,7 @@ extern "C" int mz_uncompress(unsigned char* pDest, const unsigned char* pSource, unsigned long source_len); -namespace { +namespace sd::metadata_reader { constexpr int MZ_OK = 0; constexpr int MZ_BUF_ERROR = -5; @@ -988,13 +988,13 @@ namespace { (marker == 0xFE) || (marker >= 0xE0 && marker <= 0xEF); if (marker == 0xFE) { - std::string comment = bytes_to_string(payload, payload + payload_size); - if (comment.rfind("parameters", 0) == 0 && - comment.size() > std::string("parameters").size() && - comment[std::string("parameters").size()] == '\0') { + std::string comment = bytes_to_string(payload, payload + payload_size); + const auto separator = comment.find('\0'); + const auto label = comment.substr(0, separator); + if (separator != std::string::npos && (label == "parameters" || label == "dgl")) { entry["data"] = json{ - {"label", "parameters"}, - {"text", comment.substr(std::string("parameters").size() + 1)}, + {"label", label}, + {"text", trim_trailing_nuls(comment.substr(separator + 1))}, }; } else { entry["data"] = json{{"text", trim_trailing_nuls(comment)}}; @@ -1430,24 +1430,31 @@ namespace { return false; } -} // namespace - -bool print_image_metadata(const std::string& image_path, - const MetadataReadOptions& options, - std::ostream& out, - std::string& error) { - json report; - if (!build_metadata_report(image_path, options.include_raw, report, error)) { - return false; - } - - json visible_report = filter_visible_entries(report, options.include_structural); - - if (options.output_format == MetadataOutputFormat::JSON) { - visible_report["file"] = image_path; - out << visible_report.dump(2, ' ', false, json::error_handler_t::replace) << "\n"; - } else { - print_text_report(image_path, visible_report, options.include_structural, options.brief, out); - } - return true; +} // namespace sd::metadata_reader + +static thread_local std::string metadata_report_text; + +const char* sd_read_metadata(const char* path, uint32_t flags) { + const char* result = nullptr; + sd::api::call([&] { + constexpr uint32_t allowed = SD_METADATA_READ_JSON | SD_METADATA_READ_RAW | SD_METADATA_READ_BRIEF | SD_METADATA_READ_STRUCTURAL; + if (!path || (flags & ~allowed)) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "path is required and metadata flags must be recognized"); + json report; + std::string error; + if (!sd::metadata_reader::build_metadata_report(path, flags & SD_METADATA_READ_RAW, report, error)) + return sd::api::error(SD_STATUS_LOAD_FAILED, nullptr, error.c_str()); + auto visible_report = sd::metadata_reader::filter_visible_entries(report, flags & SD_METADATA_READ_STRUCTURAL); + std::ostringstream output; + if (flags & SD_METADATA_READ_JSON) { + visible_report["file"] = path; + output << visible_report.dump(2, ' ', false, json::error_handler_t::replace) << "\n"; + } else { + sd::metadata_reader::print_text_report(path, visible_report, flags & SD_METADATA_READ_STRUCTURAL, flags & SD_METADATA_READ_BRIEF, output); + } + metadata_report_text = output.str(); + result = metadata_report_text.c_str(); + return SD_STATUS_OK; + }); + return result; } diff --git a/src/api/media_metadata.cpp b/src/api/media_metadata.cpp new file mode 100644 index 0000000000..ce3e5fc13d --- /dev/null +++ b/src/api/media_metadata.cpp @@ -0,0 +1,173 @@ +#include "api/metadata.h" + +#include +#include +#include + +#include "api/api.h" + +namespace sd::metadata { + static std::string xml_text(const std::string& info) { + std::string escaped; + for (char c : info) { + switch (c) { + case '&': + escaped += "&"; + break; + case '<': + escaped += "<"; + break; + case '>': + escaped += ">"; + break; + case '"': + escaped += """; + break; + case '\'': + escaped += "'"; + break; + default: + escaped += c; + break; + } + } + return escaped; + } + + std::string generation_xmp(const std::string& source, const std::string& parameters) { + if (source.empty()) + return ""; + return "" + "" + "" + + xml_text(source) + "" + xml_text(parameters) + + ""; + } + + static bool jpeg_comment(std::vector& comments, const std::string& label, const std::string& value) { + if (value.empty()) + return true; + const size_t size = label.size() + 1 + value.size() + 1; + if (size > jpeg_comment_max_bytes) + return false; + const size_t length = size + 2; + std::vector segment{0xff, 0xfe, uint8_t(length >> 8), uint8_t(length)}; + segment.insert(segment.end(), label.begin(), label.end()); + segment.push_back(0); + segment.insert(segment.end(), value.begin(), value.end()); + segment.push_back(0); + comments.insert(comments.end(), segment.begin(), segment.end()); + return true; + } + + bool jpeg_metadata(std::vector& comments, const std::string& source, const std::string& parameters) { + return source.empty() || (jpeg_comment(comments, "parameters", parameters) && jpeg_comment(comments, "dgl", source)); + } + + bool embed_jpeg_metadata(std::vector& image, const std::string& source, const std::string& parameters) { + if (source.empty()) + return true; + std::vector comments; + if (image.size() < 2 || !jpeg_metadata(comments, source, parameters)) + return false; + image.insert(image.begin() + 2, comments.begin(), comments.end()); + return true; + } + + static void append_u32(std::vector& bytes, uint32_t value) { + for (int i = 3; i >= 0; --i) + bytes.push_back(uint8_t(value >> (8 * i))); + } + + static bool png_text(std::vector& chunks, const std::string& label, const std::string& value) { + if (value.empty()) + return true; + const size_t size = label.size() + 5 + value.size(); + if (size > std::numeric_limits::max()) + return false; + append_u32(chunks, uint32_t(size)); + const size_t start = chunks.size(); + chunks.insert(chunks.end(), {'i', 'T', 'X', 't'}); + chunks.insert(chunks.end(), label.begin(), label.end()); + chunks.insert(chunks.end(), 5, 0); + chunks.insert(chunks.end(), value.begin(), value.end()); + uint32_t crc = 0xffffffff; + for (size_t i = start; i < chunks.size(); ++i) { + crc ^= chunks[i]; + for (int bit = 0; bit < 8; ++bit) + crc = (crc >> 1) ^ (0xedb88320u & (0u - (crc & 1))); + } + append_u32(chunks, ~crc); + return true; + } + + bool png_metadata(std::vector& chunks, const std::string& source, const std::string& parameters) { + return source.empty() || (png_text(chunks, "dgl", source) && png_text(chunks, "parameters", parameters)); + } + + bool embed_png_metadata(std::vector& image, const std::string& source, const std::string& parameters) { + if (source.empty()) + return true; + if (image.size() < 33 || std::memcmp(image.data() + 12, "IHDR", 4)) + return false; + std::vector chunks; + if (!png_metadata(chunks, source, parameters)) + return false; + image.insert(image.begin() + 33, chunks.begin(), chunks.end()); + return true; + } + + std::vector avi_info(const std::string& source) { + if (source.empty()) + return {}; + if (source.size() > std::numeric_limits::max() - 22) + throw std::runtime_error("generation metadata exceeds AVI container capacity"); + const auto size = uint32_t(source.size() + 1); + std::vector bytes{'L', 'I', 'S', 'T'}; + auto append_le = [&](uint32_t value) { + for (int i = 0; i < 4; ++i) + bytes.push_back(uint8_t(value >> (8 * i))); + }; + append_le(12 + size + (size & 1)); + bytes.insert(bytes.end(), {'I', 'N', 'F', 'O', 'I', 'C', 'M', 'T'}); + append_le(size); + bytes.insert(bytes.end(), source.begin(), source.end()); + bytes.push_back(0); + if (size & 1) + bytes.push_back(0); + return bytes; + } +} + +static thread_local std::vector metadata_chunk_bytes; + +sd_status_t sd_get_metadata_chunk(const char* source, sd_metadata_format_t format, const void** data_out, size_t* size_out) { + if (data_out) + *data_out = nullptr; + if (size_out) + *size_out = 0; + return sd::api::call([&] { + if (!source || !data_out || !size_out) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "source, data_out and size_out are required"); + auto& bytes = metadata_chunk_bytes; + bytes.clear(); + if (format == SD_METADATA_AVI) { + bytes = sd::metadata::avi_info(source); + } else { + if (format != SD_METADATA_PNG && format != SD_METADATA_JPEG && format != SD_METADATA_XMP) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "unknown metadata format"); + const auto info = sd::api::generation_metadata(source); + const auto parameters = info.value("infotext", ""); + if (format == SD_METADATA_XMP) { + const auto text = sd::metadata::generation_xmp(source, parameters); + bytes.assign(text.begin(), text.end()); + } else if (!(format == SD_METADATA_PNG ? sd::metadata::png_metadata(bytes, source, parameters) + : sd::metadata::jpeg_metadata(bytes, source, parameters))) { + return sd::api::error(SD_STATUS_OUT_OF_RANGE, nullptr, "generation metadata exceeds container capacity"); + } + } + *data_out = bytes.empty() ? nullptr : bytes.data(); + *size_out = bytes.size(); + return SD_STATUS_OK; + }); +} diff --git a/src/api/metadata.h b/src/api/metadata.h new file mode 100644 index 0000000000..b33837c0de --- /dev/null +++ b/src/api/metadata.h @@ -0,0 +1,25 @@ +#ifndef __SD_API_METADATA_H__ +#define __SD_API_METADATA_H__ + +#include +#include +#include +#include + +#include "json.hpp" + +namespace sd::api { + nlohmann::json generation_metadata(const std::string& source) noexcept; +} + +namespace sd::metadata { + constexpr std::size_t jpeg_comment_max_bytes = 65533; + std::string generation_xmp(const std::string& source, const std::string& parameters = {}); + bool png_metadata(std::vector& chunks, const std::string& source, const std::string& parameters); + bool jpeg_metadata(std::vector& comments, const std::string& source, const std::string& parameters); + bool embed_png_metadata(std::vector& image, const std::string& source, const std::string& parameters = {}); + bool embed_jpeg_metadata(std::vector& image, const std::string& source, const std::string& parameters = {}); + std::vector avi_info(const std::string& source); +} + +#endif // __SD_API_METADATA_H__ diff --git a/src/api/options.cpp b/src/api/options.cpp index 591cce3448..f056647adf 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -1,5 +1,7 @@ #include "options.h" +#include "core/ggml_extend_backend.h" #include "core/option_types.h" +#include "core/util.h" #include "tensor.h" #include @@ -8,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -97,16 +100,6 @@ static sd_vae_format_t parse_vae_format(const char* text) { return SD_VAE_FORMAT_COUNT; } -static sd_hires_upscaler_t parse_hires_upscaler(const char* text) { - static const char* names[] = {"none", "latent", "latent_nearest", "latent_nearest_exact", - "latent_antialiased", "latent_bicubic", "latent_bicubic_antialiased", - "lanczos", "nearest", "model"}; - for (int i = 0; i < SD_HIRES_UPSCALER_COUNT; ++i) - if (strcmp(text, names[i]) == 0) - return static_cast(i); - return SD_HIRES_UPSCALER_COUNT; -} - static bool valid_sigmas(const ParamValue& value) { const auto& sigmas = std::get>(value); if (sigmas.empty()) @@ -119,11 +112,6 @@ static bool valid_sigmas(const ParamValue& value) { return true; } -static bool valid_layers(const ParamValue& value) { - const auto& layers = std::get>(value); - return std::all_of(layers.begin(), layers.end(), [](int index) { return index >= 0; }); -} - template static ParamSpec parameter(const char* key, ParamType type, int operations, Apply apply) { return {key, type, operations, [apply](const ParamValue& value, sd::OptConfig& config) { @@ -311,6 +299,7 @@ static void add_context_specs(std::vector& specs) { ctx.string("clip_vision_path", &sd::ContextConfig::clip_vision_path); ctx.integer("conditioning_cache_size", &sd::ContextConfig::conditioning_cache_size, 0, INT32_MAX); ctx.string("control_net_path", &sd::ContextConfig::control_net_path); + ctx.string("max_ram", &sd::ContextConfig::max_ram); ctx.boolean("diffusion_conv_direct", &sd::ContextConfig::diffusion_conv_direct); ctx.boolean("diffusion_flash_attn", &sd::ContextConfig::diffusion_flash_attn); ctx.boolean("disable_prefetch", &sd::ContextConfig::disable_prefetch); @@ -322,20 +311,17 @@ static void add_context_specs(std::vector& specs) { ctx.boolean("flash_attn", &sd::ContextConfig::flash_attn); ctx.boolean("force_sdxl_vae_conv_scale", &sd::ContextConfig::force_sdxl_vae_conv_scale); ctx.string("high_noise_diffusion_model_path", &sd::ContextConfig::high_noise_diffusion_model_path); - ctx.string("ip_adapter_path", &sd::ContextConfig::ip_adapter_path); ctx.number("linear_scale", &sd::ContextConfig::linear_scale, 0, std::numeric_limits::max()); ctx.string("llm_path", &sd::ContextConfig::llm_path); ctx.string("llm_vision_path", &sd::ContextConfig::llm_vision_path); ctx.choice("lora_apply_mode", &sd::ContextConfig::lora_apply_mode, str_to_lora_apply_mode, LORA_APPLY_MODE_COUNT); ctx.string("max_vram", &sd::ContextConfig::max_vram); ctx.string("model_args", &sd::ContextConfig::model_args); - ctx.for_operations(Context | Upscaler | ADetailer).string("model_path", &sd::ContextConfig::model_path); - ctx.string("motion_module_path", &sd::ContextConfig::motion_module_path); - ctx.string("photo_maker_path", &sd::ContextConfig::photo_maker_path); + ctx.for_operations(Context | Upscaler).string("model_path", &sd::ContextConfig::model_path); ctx.choice("prediction", &sd::ContextConfig::prediction, str_to_prediction, PREDICTION_COUNT, true); - ctx.string("pulid_weights_path", &sd::ContextConfig::pulid_weights_path); ctx.choice("rng_type", &sd::ContextConfig::rng_type, str_to_rng_type, RNG_TYPE_COUNT, true); ctx.string("rpc_servers", &sd::ContextConfig::rpc_servers); + ctx.boolean("run_once", &sd::ContextConfig::run_once); ctx.boolean("sage_attn", &sd::ContextConfig::sage_attn); ctx.choice("sampler_rng_type", &sd::ContextConfig::sampler_rng_type, str_to_rng_type, RNG_TYPE_COUNT, true); ctx.string("split_mode", &sd::ContextConfig::split_mode); @@ -349,116 +335,86 @@ static void add_context_specs(std::vector& specs) { ctx.choice("vae_format", &sd::ContextConfig::vae_format, parse_vae_format, SD_VAE_FORMAT_COUNT); ctx.choice("wtype", &sd::ContextConfig::wtype, str_to_sd_type, SD_TYPE_COUNT, true); - specs.push_back(parameter("backend", ParamType::String, Context | Upscaler | VidUpscaler | ADetailer, [](const std::string& value, sd::OptConfig& config) { config.context.backend = value.c_str(); config.post.video_upscaler.backend = value.c_str(); })); - specs.push_back(parameter("conv_direct_mode", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.conv_direct_mode = value.c_str(); config.post.video_upscaler.conv_direct_mode = value.c_str(); })); - specs.push_back(parameter("diffusion_model_path", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.diffusion_model_path = value.c_str(); config.post.video_upscaler.diffusion_model_path = value.c_str(); })); - specs.push_back(parameter("flash_attn_mode", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.flash_attn_mode = value.c_str(); config.post.video_upscaler.flash_attn_mode = value.c_str(); })); + specs.push_back(parameter("backend", ParamType::String, Context | Upscaler, [](const std::string& value, sd::OptConfig& config) { config.context.backend = value.c_str(); })); + specs.push_back(parameter("conv_direct_mode", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.conv_direct_mode = value.c_str(); })); + specs.push_back(parameter("diffusion_model_path", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.diffusion_model_path = value.c_str(); })); + specs.push_back(parameter("flash_attn_mode", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.flash_attn_mode = value.c_str(); })); + auto linear_type = parameter( + "linear_type", ParamType::String, Context | Upscaler, [](const std::string& value, sd::OptConfig& config) { config.context.linear_type = value.c_str(); }); + linear_type.valid = [](const ParamValue& value) { + SDBackendAssignment assignment; + return sd_parse_linear_type_assignment(std::get(value), &assignment, nullptr); + }; + linear_type.invalid_reason = "expected auto, i8, raw, or module assignments such as dit=i8"; + specs.push_back(std::move(linear_type)); specs.push_back(integer_parameter( - "n_threads", Context | Upscaler | VidUpscaler | ADetailer, [](const int64_t& value, sd::OptConfig& config) { config.context.n_threads = static_cast(value); config.post.video_upscaler.n_threads = static_cast(value); }, 1, INT32_MAX)); - specs.push_back(parameter("params_backend", ParamType::String, Context | Upscaler | VidUpscaler | ADetailer, [](const std::string& value, sd::OptConfig& config) { config.context.params_backend = value.c_str(); config.post.video_upscaler.params_backend = value.c_str(); })); - specs.push_back(parameter("vae_path", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.vae_path = value.c_str(); config.post.video_upscaler.vae_path = value.c_str(); })); + "n_threads", Context | Upscaler, [](const int64_t& value, sd::OptConfig& config) { config.context.n_threads = static_cast(value); }, 1, INT32_MAX)); + specs.push_back(parameter("params_backend", ParamType::String, Context | Upscaler, [](const std::string& value, sd::OptConfig& config) { config.context.params_backend = value.c_str(); })); + specs.push_back(parameter("vae_path", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.vae_path = value.c_str(); })); } static void add_generation_specs(std::vector& specs) { using namespace sd::api; ParamGroup img(specs, Image, [](sd::OptConfig& config) { return std::tie(config.image); }); ParamGroup vid(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video); }); - ParamGroup preprocess(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.image_preprocess, config.video.image_preprocess); }); - ParamGroup photomaker(specs, Image, [](sd::OptConfig& config) { return std::tie(config.image.pm_params); }); - ParamGroup pulid(specs, Image, [](sd::OptConfig& config) { return std::tie(config.image.pulid_params); }); img.integer("batch_count", &sd::ImageConfig::batch_count, 1, INT32_MAX); img.image("control_image", &sd::ImageConfig::control_image); img.number("control_strength", &sd::ImageConfig::control_strength, 0, std::numeric_limits::max()); img.choice("control_type", &sd::ImageConfig::control_type, str_to_sd_control_type, SD_CONTROL_TYPE_COUNT); - img.image("ip_adapter_image", &sd::ImageConfig::ip_adapter_image); - img.number("ip_adapter_strength", &sd::ImageConfig::ip_adapter_strength, 0, std::numeric_limits::max()); img.image("mask_image", &sd::ImageConfig::mask_image); img.integer("qwen_image_layers", &sd::ImageConfig::qwen_image_layers, 0, INT32_MAX); vid.frames("control_frames", &sd::VideoConfig::control_frames, &sd::VideoConfig::control_frames_size); vid.image("end_image", &sd::VideoConfig::end_image); vid.number("moe_boundary", &sd::VideoConfig::moe_boundary, 0, 1); + vid.integer("high_noise_sample.steps", &sd::VideoConfig::high_noise_steps, -1, INT32_MAX); vid.array("ref_audios", &sd::VideoConfig::ref_audios, &sd::VideoConfig::ref_audios_count); vid.array("ref_videos", &sd::VideoConfig::ref_videos, &sd::VideoConfig::ref_videos_count); vid.number("vace_strength", &sd::VideoConfig::vace_strength, 0, std::numeric_limits::max()); vid.integer("video_frames", &sd::VideoConfig::video_frames, 1, INT32_MAX); - preprocess.string("image_preprocess.rules", &sd::ImagePreprocessConfig::rules); - - photomaker.string("photomaker.id_embed_path", &sd::PhotoMakerConfig::id_embed_path); - photomaker.array("photomaker.id_images", &sd::PhotoMakerConfig::id_images, &sd::PhotoMakerConfig::id_images_count); - photomaker.number("photomaker.style_strength", &sd::PhotoMakerConfig::style_strength, 0, 100); - - pulid.string("pulid.id_embedding_path", &sd::PuLIDConfig::id_embedding_path); - pulid.number("pulid.id_weight", &sd::PuLIDConfig::id_weight, 0, std::numeric_limits::max()); - - specs.push_back(parameter("circular_x", ParamType::Bool, Image | Video | ADetail, [](const bool& value, sd::OptConfig& config) { config.image.circular_x = value; config.video.circular_x = value; })); - specs.push_back(parameter("circular_y", ParamType::Bool, Image | Video | ADetail, [](const bool& value, sd::OptConfig& config) { config.image.circular_y = value; config.video.circular_y = value; })); + specs.push_back(parameter("circular_x", ParamType::Bool, Image | Video, [](const bool& value, sd::OptConfig& config) { config.image.circular_x = value; config.video.circular_x = value; })); + specs.push_back(parameter("circular_y", ParamType::Bool, Image | Video, [](const bool& value, sd::OptConfig& config) { config.image.circular_y = value; config.video.circular_y = value; })); specs.push_back(integer_parameter( - "clip_skip", Image | Video | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.clip_skip = static_cast(value); config.video.clip_skip = static_cast(value); }, INT32_MIN, INT32_MAX)); + "clip_skip", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.clip_skip = static_cast(value); config.video.clip_skip = static_cast(value); }, INT32_MIN, INT32_MAX)); specs.push_back(integer_parameter( - "fps", Video | VidUpscale, [](const int64_t& value, sd::OptConfig& config) { config.video.fps = static_cast(value); config.post.video_upscale.fps = static_cast(value); }, 1, INT32_MAX)); + "fps", Video, [](const int64_t& value, sd::OptConfig& config) { config.video.fps = static_cast(value); }, 1, INT32_MAX)); specs.push_back(integer_parameter( - "height", Image | Video | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.height = static_cast(value); config.video.height = static_cast(value); }, 1, INT32_MAX)); + "height", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.height = static_cast(value); config.video.height = static_cast(value); }, 1, INT32_MAX)); specs.push_back(parameter("init_image", ParamType::Tensor, Image | Video, [](const TensorValue& value, sd::OptConfig& config) { config.image.init_image = sd::api::image_view(*value.tensor.get()); config.video.init_image = config.image.init_image; })); - specs.push_back(parameter("loras", ParamType::Loras, Image | Video | ADetail, [](const LoraValues& value, sd::OptConfig& config) { config.image.loras = value.items.data(); config.image.lora_count = static_cast(value.items.size()); config.video.loras = value.items.data(); config.video.lora_count = static_cast(value.items.size()); })); - specs.push_back(parameter("negative_prompt", ParamType::String, Image | Video | ADetail, [](const std::string& value, sd::OptConfig& config) { config.image.negative_prompt = value.c_str(); config.video.negative_prompt = value.c_str(); })); - specs.push_back(parameter("prompt", ParamType::String, Image | Video | ADetail, [](const std::string& value, sd::OptConfig& config) { config.image.prompt = value.c_str(); config.video.prompt = value.c_str(); })); - specs.push_back(parameter("ref_image_args", ParamType::String, Image | Video, [](const std::string& value, sd::OptConfig& config) { config.image.ref_image_args = value.c_str(); config.video.ref_image_args = value.c_str(); })); + specs.push_back(parameter("loras", ParamType::Loras, Image | Video, [](const LoraValues& value, sd::OptConfig& config) { config.image.loras = value.items.data(); config.image.lora_count = static_cast(value.items.size()); config.video.loras = value.items.data(); config.video.lora_count = static_cast(value.items.size()); })); + specs.push_back(parameter("negative_prompt", ParamType::String, Image | Video, [](const std::string& value, sd::OptConfig& config) { config.image.negative_prompt = value.c_str(); config.video.negative_prompt = value.c_str(); })); + specs.push_back(parameter("prompt", ParamType::String, Image | Video, [](const std::string& value, sd::OptConfig& config) { config.image.prompt = value.c_str(); config.video.prompt = value.c_str(); })); specs.push_back(parameter("ref_images", ParamType::Tensors, Image | Video, [](const ImageValues& value, sd::OptConfig& config) { config.image.ref_images = const_cast(value.items.data()); config.image.ref_images_count = static_cast(value.items.size()); config.video.ref_images = config.image.ref_images; config.video.ref_images_count = config.image.ref_images_count; })); - specs.push_back(integer_parameter("seed", Image | Video | VidUpscale | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.seed = static_cast(value); config.video.seed = static_cast(value); config.post.video_upscale.seed = value; })); + specs.push_back(integer_parameter("seed", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.seed = static_cast(value); config.video.seed = static_cast(value); })); specs.push_back(float_parameter( - "strength", Image | Video | ADetail, [](const double& value, sd::OptConfig& config) { config.image.strength = static_cast(value); config.video.strength = static_cast(value); }, 0, 1)); + "strength", Image | Video, [](const double& value, sd::OptConfig& config) { config.image.strength = static_cast(value); config.video.strength = static_cast(value); }, 0, 1)); specs.push_back(integer_parameter( - "width", Image | Video | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.width = static_cast(value); config.video.width = static_cast(value); }, 1, INT32_MAX)); + "width", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.width = static_cast(value); config.video.width = static_cast(value); }, 1, INT32_MAX)); } static void add_sampling_specs(std::vector& specs) { using namespace sd::api; - ParamGroup high_noise(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video.high_noise_sample_params); }); - ParamGroup high_noise_guidance(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video.high_noise_sample_params.guidance); }); - ParamGroup high_noise_slg(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video.high_noise_sample_params.guidance.slg); }); - ParamGroup sample(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.sample_params, config.video.sample_params); }); - ParamGroup guidance(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.sample_params.guidance, config.video.sample_params.guidance); }); - ParamGroup slg(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.sample_params.guidance.slg, config.video.sample_params.guidance.slg); }); - - high_noise.string("high_noise_sample.args", &sd::SampleConfig::extra_sample_args); - high_noise.number("high_noise_sample.eta", &sd::SampleConfig::eta, 0, std::numeric_limits::max()); - high_noise.choice("high_noise_sample.method", &sd::SampleConfig::sample_method, str_to_sample_method, SAMPLE_METHOD_COUNT, true); - high_noise.integer("high_noise_sample.steps", &sd::SampleConfig::sample_steps, -1, INT32_MAX); - - high_noise_guidance.number("high_noise_sample.guidance.distilled_guidance", &sd::GuidanceConfig::distilled_guidance); - high_noise_guidance.number("high_noise_sample.guidance.img_cfg", &sd::GuidanceConfig::img_cfg); - high_noise_guidance.number("high_noise_sample.guidance.txt_cfg", &sd::GuidanceConfig::txt_cfg); - - high_noise_slg.number("high_noise_sample.guidance.slg.layer_end", &sd::SLGConfig::layer_end, 0, 1); - high_noise_slg.number("high_noise_sample.guidance.slg.layer_start", &sd::SLGConfig::layer_start, 0, 1); - high_noise_slg.array("high_noise_sample.guidance.slg.layers", &sd::SLGConfig::layers, &sd::SLGConfig::layer_count, valid_layers, "layer indices must be nonnegative"); - high_noise_slg.number("high_noise_sample.guidance.slg.scale", &sd::SLGConfig::scale, 0, std::numeric_limits::max()); + ParamGroup sample(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.sample_params, config.video.sample_params); }); + ParamGroup guidance(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.sample_params.guidance, config.video.sample_params.guidance); }); sample.string("sample.args", &sd::SampleConfig::extra_sample_args); sample.number("sample.eta", &sd::SampleConfig::eta, 0, std::numeric_limits::max()); sample.number("sample.flow_shift", &sd::SampleConfig::flow_shift, 0, std::numeric_limits::max()); sample.choice("sample.method", &sd::SampleConfig::sample_method, str_to_sample_method, SAMPLE_METHOD_COUNT, true); sample.choice("sample.scheduler", &sd::SampleConfig::scheduler, str_to_scheduler, SCHEDULER_COUNT, true); - sample.integer("sample.shifted_timestep", &sd::SampleConfig::shifted_timestep, 0, INT32_MAX); sample.array("sample.sigmas", &sd::SampleConfig::custom_sigmas, &sd::SampleConfig::custom_sigmas_count, valid_sigmas, "sigmas require at least two strictly decreasing nonnegative entries ending in zero, or an empty array"); sample.integer("sample.steps", &sd::SampleConfig::sample_steps, 1, INT32_MAX); guidance.number("sample.guidance.distilled_guidance", &sd::GuidanceConfig::distilled_guidance); guidance.number("sample.guidance.img_cfg", &sd::GuidanceConfig::img_cfg); guidance.number("sample.guidance.txt_cfg", &sd::GuidanceConfig::txt_cfg); - - slg.number("sample.guidance.slg.layer_end", &sd::SLGConfig::layer_end, 0, 1); - slg.number("sample.guidance.slg.layer_start", &sd::SLGConfig::layer_start, 0, 1); - slg.array("sample.guidance.slg.layers", &sd::SLGConfig::layers, &sd::SLGConfig::layer_count, valid_layers, "layer indices must be nonnegative"); - slg.number("sample.guidance.slg.scale", &sd::SLGConfig::scale, 0, std::numeric_limits::max()); } static void add_cache_specs(std::vector& specs) { using namespace sd::api; - ParamGroup cache(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.cache, config.video.cache); }); + ParamGroup cache(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.cache, config.video.cache); }); cache.integer("cache.bn_compute_blocks", &sd::CacheConfig::Bn_compute_blocks, 0, INT32_MAX); cache.number("cache.end_percent", &sd::CacheConfig::end_percent, 0, 1); @@ -489,22 +445,21 @@ static void add_cache_specs(std::vector& specs) { static void add_hires_specs(std::vector& specs) { using namespace sd::api; ParamGroup hires(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.hires, config.video.hires); }); - - hires.number("hires.denoising_strength", &sd::HiresConfig::denoising_strength, 0, 1); hires.boolean("hires.enabled", &sd::HiresConfig::enabled); + hires.string("hires.upscaler", &sd::HiresConfig::upscaler); hires.string("hires.model_path", &sd::HiresConfig::model_path); - hires.number("hires.scale", &sd::HiresConfig::scale, 0, std::numeric_limits::max()); - hires.array("hires.sigmas", &sd::HiresConfig::custom_sigmas, &sd::HiresConfig::custom_sigmas_count, valid_sigmas, "sigmas require at least two strictly decreasing nonnegative entries ending in zero, or an empty array"); - hires.integer("hires.steps", &sd::HiresConfig::steps, 0, INT32_MAX); - hires.integer("hires.target_height", &sd::HiresConfig::target_height, 0, INT32_MAX); - hires.integer("hires.target_width", &sd::HiresConfig::target_width, 0, INT32_MAX); + hires.number("hires.scale", &sd::HiresConfig::scale, std::numeric_limits::min(), 64); + hires.integer("hires.target_width", &sd::HiresConfig::target_width, 0, 16384); + hires.integer("hires.target_height", &sd::HiresConfig::target_height, 0, 16384); + hires.integer("hires.steps", &sd::HiresConfig::steps, 0, 10000); + hires.number("hires.denoising_strength", &sd::HiresConfig::denoising_strength, 0.0001, 1); hires.integer("hires.upscale_tile_size", &sd::HiresConfig::upscale_tile_size, 1, INT32_MAX); - hires.choice("hires.upscaler", &sd::HiresConfig::upscaler, parse_hires_upscaler, SD_HIRES_UPSCALER_COUNT); + hires.array("hires.sigmas", &sd::HiresConfig::custom_sigmas, &sd::HiresConfig::custom_sigmas_count, valid_sigmas, "hires sigmas require at least two strictly decreasing nonnegative entries ending in zero, or an empty array"); } static void add_tiling_specs(std::vector& specs) { using namespace sd::api; - ParamGroup tiling(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.vae_tiling_params, config.video.vae_tiling_params); }); + ParamGroup tiling(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.vae_tiling_params, config.video.vae_tiling_params); }); tiling.boolean("vae_tiling.enabled", &sd::TilingConfig::enabled); tiling.string("vae_tiling.extra_tiling_args", &sd::TilingConfig::extra_tiling_args); @@ -518,26 +473,23 @@ static void add_tiling_specs(std::vector& specs) { static void add_postprocess_specs(std::vector& specs) { using namespace sd::api; - ParamGroup input(specs, Upscale | ADetail, [](sd::OptConfig& config) { return std::tie(config.post); }); + ParamGroup input(specs, Upscale, [](sd::OptConfig& config) { return std::tie(config.post); }); ParamGroup upscaler(specs, Upscaler, [](sd::OptConfig& config) { return std::tie(config.post); }); - ParamGroup video_upscaler(specs, VidUpscaler, [](sd::OptConfig& config) { return std::tie(config.post.video_upscaler); }); - ParamGroup video_upscale(specs, VidUpscale, [](sd::OptConfig& config) { return std::tie(config.post.video_upscale); }); - ParamGroup adetail(specs, ADetail, [](sd::OptConfig& config) { return std::tie(config.post.adetail); }); - input.image("image", &sd::PostprocessConfig::image); - + input.integer("repeats", &sd::PostprocessConfig::repeats, 1, 16); upscaler.boolean("conv_direct", &sd::PostprocessConfig::conv_direct); upscaler.integer("tile_size", &sd::PostprocessConfig::tile_size, 1, INT32_MAX); +} - video_upscaler.integer("upscale_factor", &sd::VideoUpscalerConfig::upscale_factor, 1, INT32_MAX); - - video_upscale.frames("frames", &sd::VideoUpscaleConfig::frames, &sd::VideoUpscaleConfig::frame_count); - video_upscale.integer("window_size", &sd::VideoUpscaleConfig::window_size, 1, INT32_MAX); - video_upscale.integer("temporal_chunk_size", &sd::VideoUpscaleConfig::temporal_chunk_size, 1, INT32_MAX); - - adetail.string("adetail.prompt", &sd::ADetailConfig::prompt); - adetail.string("adetail.negative_prompt", &sd::ADetailConfig::negative_prompt); - adetail.string("adetail.args", &sd::ADetailConfig::extra_ad_args); +static bool dgl_only_parameter(const char* key) { + const std::string name = key; + if (name == "high_noise_sample.steps") + return false; + for (const auto* prefix : {"photomaker.", "pulid.", "high_noise_sample.", "sample.guidance.slg.", "adetail."}) + if (name.rfind(prefix, 0) == 0) + return true; + static const std::set names{"ip_adapter_path", "ip_adapter_image", "ip_adapter_strength", "motion_module_path", "photo_maker_path", "pulid_weights_path", "image_preprocess.rules", "sample.shifted_timestep"}; + return names.count(name) != 0; } static std::vector make_specs() { @@ -565,6 +517,8 @@ static const ParamSpec* find_spec(const char* key) { static sd_status_t check_key(sd_opt_t* params, const char* key, ParamType type, const ParamSpec** out) { if (!params || !key) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, key, "params and key are required"); + if (dgl_only_parameter(key)) + return sd::api::error(SD_STATUS_UNSUPPORTED, key, "this parameter requires an explicit DGL workflow (-M dgl --script FILE)"); *out = find_spec(key); if (!*out) return sd::api::error(SD_STATUS_UNKNOWN_KEY, key, "unknown parameter"); @@ -589,6 +543,8 @@ static sd_status_t store_value(sd_opt_t* params, const ParamSpec& spec, ParamVal if (spec.valid && !spec.valid(value)) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, spec.key, spec.invalid_reason); params->values.insert_or_assign(spec.key, std::move(value)); + if (strcmp(spec.key, "cache.fn_compute_blocks") == 0 || strcmp(spec.key, "cache.bn_compute_blocks") == 0) + LOG_WARN("parameter '%s' is ignored: condition-level caching does not support front/back block counts", spec.key); return SD_STATUS_OK; } @@ -615,22 +571,6 @@ sd_upscale_opt_t* sd_upscale_opt_create(void) { return create_opt(sd::api::Upscale); } -sd_vid_upscaler_opt_t* sd_vid_upscaler_opt_create(void) { - return create_opt(sd::api::VidUpscaler); -} - -sd_vid_upscale_opt_t* sd_vid_upscale_opt_create(void) { - return create_opt(sd::api::VidUpscale); -} - -sd_adetailer_opt_t* sd_adetailer_opt_create(void) { - return create_opt(sd::api::ADetailer); -} - -sd_adetail_opt_t* sd_adetail_opt_create(void) { - return create_opt(sd::api::ADetail); -} - void sd_opt_free(sd_opt_t* params) { delete params; } @@ -820,6 +760,8 @@ sd_status_t sd_opt_unset(sd_opt_t* params, const char* key) { return sd::api::call([&] { if (!params || !key) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, key, "params and key are required"); + if (dgl_only_parameter(key)) + return sd::api::error(SD_STATUS_UNSUPPORTED, key, "this parameter requires an explicit DGL workflow (-M dgl --script FILE)"); const auto* spec = find_spec(key); if (!spec) return sd::api::error(SD_STATUS_UNKNOWN_KEY, key, "unknown parameter"); @@ -834,6 +776,96 @@ bool sd::api::is_set(const sd_opt_t* params, const char* key) { return params && params->values.count(key) != 0; } +std::shared_ptr sd::api::copy_options(const sd_opt_t* params) { + if (!params) + throw sd::dgl::Error(SD_STATUS_INVALID_ARGUMENT, "params is required"); + auto copy = std::make_shared(*params); + for (auto& [key, value] : copy->values) { + if (auto* loras = std::get_if(&value)) { + for (size_t i = 0; i < loras->items.size(); ++i) + loras->items[i].path = loras->paths[i].c_str(); + } else if (auto* embeddings = std::get_if(&value)) { + for (size_t i = 0; i < embeddings->items.size(); ++i) { + embeddings->items[i].name = embeddings->strings[i * 2].c_str(); + embeddings->items[i].path = embeddings->strings[i * 2 + 1].c_str(); + } + } else if (auto* videos = std::get_if(&value)) { + for (size_t i = 0; i < videos->items.size(); ++i) + videos->items[i].frames = videos->frames[i].data(); + } + } + return copy; +} + +std::vector sd::api::explicit_keys(const sd_opt_t* params) { + std::vector keys; + if (params) + for (const auto& [key, value] : params->values) + keys.push_back(key); + return keys; +} + +const sd_tensor_t* sd::api::bound_tensor(const sd_opt_t* params, const char* key) { + if (!params) + return nullptr; + const auto found = params->values.find(key); + if (found == params->values.end()) + return nullptr; + const auto* value = std::get_if(&found->second); + return value ? value->tensor.get() : nullptr; +} + +std::vector sd::api::bound_tensors(const sd_opt_t* params, const char* key) { + std::vector tensors; + if (!params) + return tensors; + const auto found = params->values.find(key); + if (found == params->values.end()) + return tensors; + if (const auto* values = std::get_if(&found->second)) + for (const auto& tensor : values->tensors) + tensors.push_back(tensor.get()); + return tensors; +} + +std::vector sd::api::bound_audios(const sd_opt_t* params, const char* key) { + std::vector audios; + if (params && params->values.count(key)) + if (const auto* values = std::get_if(¶ms->values.at(key))) + for (size_t i = 0; i < values->items.size(); ++i) + audios.push_back({uint32_t(values->items[i].sample_rate), values->tensors[i].get()}); + return audios; +} + +std::vector sd::api::bound_videos(const sd_opt_t* params, const char* key) { + std::vector videos; + if (params && params->values.count(key)) + if (const auto* values = std::get_if(¶ms->values.at(key))) { + size_t tensor = 0; + for (const auto& item : values->items) { + sd_video_t video{values->tensors[tensor++].get(), item.fps, {}}; + if (item.audio.data) + video.audio = {uint32_t(item.audio.sample_rate), values->tensors[tensor++].get()}; + videos.push_back(video); + } + } + return videos; +} + +nlohmann::json sd::api::scalar_values(const sd_opt_t* params) { + auto values = nlohmann::json::object(); + if (params) + for (const auto& entry : params->values) + std::visit([&](const auto& item) { + using T = std::decay_t; + if constexpr (std::is_arithmetic_v || std::is_same_v || + std::is_same_v> || std::is_same_v>) + values[entry.first] = item; + }, + entry.second); + return values; +} + bool sd::api::has_prefix(const sd_opt_t* params, const char* prefix) { if (!params) return false; @@ -847,51 +879,18 @@ sd_status_t sd::api::resolve(const sd_opt_t* params, Operation operation, OptCon if (params->operation != operation) return error(SD_STATUS_UNSUPPORTED, nullptr, "option object has the wrong purpose for this operation"); config = OptConfig{}; - if (operation == ADetail) - config.image.strength = 0.4f; for (const auto& entry : params->values) { const auto* spec = find_spec(entry.first.c_str()); - if (!(spec->operations & operation)) - return error(SD_STATUS_UNSUPPORTED, spec->key, "parameter does not apply to this operation"); + if (!spec || !(spec->operations & operation)) + return error(SD_STATUS_UNSUPPORTED, entry.first.c_str(), "parameter does not apply to this operation"); spec->apply(entry.second, config); } - const auto& image = config.image; - const auto& video = config.video; - const bool sampling = operation == Image || operation == Video || operation == ADetail; - const auto& cache = operation == Video ? video.cache : image.cache; - if (sampling && cache.mode != SD_CACHE_DISABLED) { - if (cache.start_percent >= cache.end_percent) - return error(SD_STATUS_INVALID_ARGUMENT, "cache", "start_percent must precede end_percent"); - } - if (sampling) { - const auto& sample = operation == Video ? video.sample_params : image.sample_params; - if (sample.guidance.slg.layer_start > sample.guidance.slg.layer_end) - return error(SD_STATUS_INVALID_ARGUMENT, "sample.guidance.slg", "layer_start must not exceed layer_end"); - const auto& hires = operation == Video ? video.hires : image.hires; - if (hires.enabled && hires.upscaler != SD_HIRES_UPSCALER_NONE && - hires.scale <= 0.f && hires.target_width <= 0 && hires.target_height <= 0) - return error(SD_STATUS_INVALID_ARGUMENT, "hires", "enabled hires requires a positive scale or target size"); - } - if (operation == Video && video.high_noise_sample_params.guidance.slg.layer_start > video.high_noise_sample_params.guidance.slg.layer_end) - return error(SD_STATUS_INVALID_ARGUMENT, "high_noise_sample.guidance.slg", "layer_start must not exceed layer_end"); - if ((operation == Upscaler || operation == ADetailer) && (!config.context.model_path || !*config.context.model_path)) + const auto& cache = operation == Video ? config.video.cache : config.image.cache; + if ((operation == Image || operation == Video) && cache.mode != SD_CACHE_DISABLED && cache.start_percent >= cache.end_percent) + return error(SD_STATUS_INVALID_ARGUMENT, "cache", "start_percent must precede end_percent"); + if (operation == Upscaler && (!config.context.model_path || !*config.context.model_path)) return error(SD_STATUS_INVALID_ARGUMENT, "model_path", "model path is required"); - if (operation == VidUpscaler) { - const auto& load = config.post.video_upscaler; - if (!load.diffusion_model_path || !*load.diffusion_model_path || !load.vae_path || !*load.vae_path || load.upscale_factor <= 0) - return error(SD_STATUS_INVALID_ARGUMENT, nullptr, "diffusion_model_path, vae_path and upscale_factor are required"); - } - if ((operation == Upscale || operation == ADetail) && !config.post.image.data) - return error(SD_STATUS_INVALID_ARGUMENT, "image", "input image is required"); - if (operation == Upscale && config.post.image.channel != 3) + if (operation == Upscale && (!config.post.image.data || config.post.image.channel != 3)) return error(SD_STATUS_INVALID_ARGUMENT, "image", "upscaling requires an RGB image"); - if (operation == VidUpscale) { - const auto& input = config.post.video_upscale; - if (!input.frames || input.frame_count <= 0) - return error(SD_STATUS_INVALID_ARGUMENT, "frames", "video upscaling requires nonempty frames"); - for (int i = 0; i < input.frame_count; ++i) - if (input.frames[i].channel != 3 || input.frames[i].width != input.frames[0].width || input.frames[i].height != input.frames[0].height) - return error(SD_STATUS_INVALID_ARGUMENT, "frames", "frames must be RGB and have equal dimensions"); - } return SD_STATUS_OK; } diff --git a/src/api/options.h b/src/api/options.h index 6517829939..aab4f7b133 100644 --- a/src/api/options.h +++ b/src/api/options.h @@ -3,23 +3,31 @@ #include "api.h" #include "config.h" +#include "json.hpp" + +#include +#include +#include namespace sd::api { enum Operation { - Context = 1, - Image = 2, - Video = 4, - Upscaler = 8, - Upscale = 16, - VidUpscaler = 32, - VidUpscale = 64, - ADetailer = 128, - ADetail = 256 + Context = 1, + Image = 2, + Video = 4, + Upscaler = 8, + Upscale = 16 }; sd_status_t resolve(const sd_opt_t* params, Operation operation, OptConfig& config); bool is_set(const sd_opt_t* params, const char* key); bool has_prefix(const sd_opt_t* params, const char* prefix); + std::shared_ptr copy_options(const sd_opt_t* params); + std::vector explicit_keys(const sd_opt_t* params); + const sd_tensor_t* bound_tensor(const sd_opt_t* params, const char* key); + std::vector bound_tensors(const sd_opt_t* params, const char* key); + std::vector bound_audios(const sd_opt_t* params, const char* key); + std::vector bound_videos(const sd_opt_t* params, const char* key); + nlohmann::json scalar_values(const sd_opt_t* params); } #endif // SD_OPTIONS_H diff --git a/src/api/program_result.cpp b/src/api/program_result.cpp new file mode 100644 index 0000000000..6d314c96e0 --- /dev/null +++ b/src/api/program_result.cpp @@ -0,0 +1,68 @@ +#include "api/result.h" + +#include + +#include "dgl/diagnostic.h" +#include "dgl/value.h" + +namespace sd::api { + static const dgl::Value& field(const dgl::Value& value, const char* name) { + if (value.type().kind != dgl::Kind::Dict || !value.fields.count(name)) + throw dgl::Error(SD_STATUS_TYPE_MISMATCH, "generation result is missing '" + std::string(name) + "'"); + return value.fields.at(name); + } + + static void append_frames(sd_result_t& result, const sd_tensor_t& frames, bool video) { + const auto& shape = frames.shape(); + if (frames.type != SD_TENSOR_U8 || (shape.size() != 3 && shape.size() != 4) || + shape[0] < 1 || shape[0] > 4 || shape[1] <= 0 || shape[2] <= 0 || (shape.size() == 4 && shape[3] <= 0)) + throw dgl::Error(SD_STATUS_TYPE_MISMATCH, "generation pixels must be a packed U8 [C,W,H] image or [C,W,H,T] frames"); + const auto count = shape.size() == 4 ? shape[3] : 1; + if (!video && count != 1) + throw dgl::Error(SD_STATUS_TYPE_MISMATCH, "image program returned multiple frames"); + const auto bytes = frames.bytes / count; + const auto* pixels = static_cast(frames.data()); + for (int64_t i = 0; i < count; ++i) { + auto frame = allocate_tensor(SD_TENSOR_U8, {shape[0], shape[1], shape[2]}); + std::memcpy(frame.get()->mutable_data(), pixels + i * bytes, bytes); + result.images.push_back(std::move(frame)); + } + } + + void append_program_image(sd_result_t& result, const dgl::Value& value, const std::string& source) { + const auto& image = field(value, "image"); + const auto first = result.images.size(); + if (image.type() == dgl::Type{dgl::Kind::List, dgl::Kind::Tensor}) { + for (const auto& item : image.items) + append_frames(result, *item.as(), false); + } else { + append_frames(result, *image.as(), false); + } + result.kind = SD_RESULT_IMAGE; + for (size_t i = first; i < result.images.size(); ++i) + result.generation_infos.push_back(source); + } + + void set_program_video(sd_result_t& result, const dgl::Value& value, const std::string& source) { + const auto& video = field(value, "video"); + append_frames(result, *field(video, "frames").as(), true); + const auto numerator = field(video, "fps_num").scalar.get(); + const auto denominator = field(video, "fps_den").scalar.get(); + if (numerator <= 0 || denominator <= 0 || numerator % denominator || numerator / denominator > INT32_MAX) + throw dgl::Error(SD_STATUS_OUT_OF_RANGE, "C video result requires a positive integral frame rate"); + result.kind = SD_RESULT_VIDEO; + result.fps = int(numerator / denominator); + result.generation_infos = {source}; + const auto audio = value.fields.find("audio"); + if (audio == value.fields.end() || !audio->second.fields.count("samples")) + return; + const auto samples = field(audio->second, "samples").as(); + if (!samples->bytes) + return; + const auto rate = field(audio->second, "sample_rate").scalar.get(); + if (samples->type != SD_TENSOR_F32 || samples->shape().size() != 2 || samples->shape()[0] <= 0 || samples->shape()[0] > 32 || rate < 1000 || rate > 384000) + throw dgl::Error(SD_STATUS_TYPE_MISMATCH, "generation audio must contain F32 [channels,samples] and a valid sample rate"); + result.audio_tensor = TensorRef(samples.get()); + result.audio = {uint32_t(rate), result.audio_tensor.get()}; + } +} diff --git a/src/api/result.cpp b/src/api/result.cpp index 388f948cee..eee5ea07e0 100644 --- a/src/api/result.cpp +++ b/src/api/result.cpp @@ -5,150 +5,6 @@ #include #include -namespace sd { - using nlohmann::json; - - char* copy_generation_info(const json& info) { - const std::string text = info.dump(-1, ' ', false, json::error_handler_t::replace); - char* result = static_cast(malloc(text.size() + 1)); - if (result) - memcpy(result, text.c_str(), text.size() + 1); - return result; - } - - bool make_image_generation_result(sd::Image* images, int count, const std::vector& infos, sd::ImageGenerationResult** result_out) { - if (!result_out || !images || count <= 0 || infos.size() != static_cast(count)) { - sd::free_images(images, count); - return false; - } - auto* result = static_cast(calloc(1, sizeof(sd::ImageGenerationResult))); - if (!result) { - sd::free_images(images, count); - return false; - } - result->items = static_cast(calloc(count, sizeof(sd::ImageResult))); - if (!result->items) { - free(result); - sd::free_images(images, count); - return false; - } - result->count = count; - try { - for (int i = 0; i < count; ++i) { - result->items[i].image = images[i]; - images[i] = {}; - result->items[i].generation_info = copy_generation_info(infos[i]); - if (!result->items[i].generation_info) { - sd::free_images(images, count); - sd::free_image_generation_result(result); - return false; - } - } - } catch (...) { - sd::free_images(images, count); - sd::free_image_generation_result(result); - return false; - } - free(images); - *result_out = result; - return true; - } -} - -void sd::free_image_generation_result(sd::ImageGenerationResult* result) { - if (!result) - return; - for (int i = 0; i < result->count; ++i) { - free(result->items[i].image.data); - free(result->items[i].generation_info); - } - free(result->items); - free(result); -} - -void sd::free_video_generation_result(sd::VideoGenerationResult* result) { - if (!result) - return; - sd::free_images(result->frames, result->frame_count); - sd::free_audio(result->audio); - free(result->generation_info); - free(result); -} - -static sd::api::TensorRef consume_image(sd::Image& image) { - std::vector shape{image.channel, image.width, image.height}; - auto* data = image.data; - image.data = nullptr; - return sd::api::own_tensor(SD_TENSOR_U8, std::move(shape), data); -} - -bool sd::make_image_result(ImageGenerationResult* images, sd_result_t** result_out) { - if (result_out) - *result_out = nullptr; - std::unique_ptr owner(images, free_image_generation_result); - if (!result_out || !images) - return false; - auto result = std::make_unique(); - result->kind = SD_RESULT_IMAGE; - result->images.reserve(images->count); - result->generation_infos.reserve(images->count); - for (int i = 0; i < images->count; ++i) { - result->images.push_back(consume_image(images->items[i].image)); - result->generation_infos.emplace_back(images->items[i].generation_info ? images->items[i].generation_info : ""); - } - *result_out = result.release(); - return true; -} - -bool sd::make_image_result(sd::Image* images, int count, const std::vector& infos, sd_result_t** result_out) { - if (result_out) - *result_out = nullptr; - ImageGenerationResult* raw = nullptr; - if (!make_image_generation_result(images, count, infos, &raw)) - return false; - return make_image_result(raw, result_out); -} - -bool sd::make_video_result(VideoGenerationResult* video, sd_result_t** result_out) { - if (result_out) - *result_out = nullptr; - std::unique_ptr owner(video, free_video_generation_result); - if (!result_out || !video) - return false; - auto result = std::make_unique(); - result->kind = SD_RESULT_VIDEO; - result->fps = video->fps; - result->images.reserve(video->frame_count); - for (int i = 0; i < video->frame_count; ++i) - result->images.push_back(consume_image(video->frames[i])); - result->generation_infos.emplace_back(video->generation_info ? video->generation_info : ""); - if (video->audio) { - auto& audio = *video->audio; - std::vector shape{audio.channels, static_cast(audio.sample_count)}; - auto* data = audio.data; - audio.data = nullptr; - result->audio_tensor = sd::api::own_tensor(SD_TENSOR_F32, std::move(shape), data); - result->audio = {audio.sample_rate, result->audio_tensor.get()}; - } - *result_out = result.release(); - return true; -} - -void sd::free_images(sd::Image* result_images, int num_images) { - if (result_images == nullptr) { - return; - } - - for (int i = 0; i < num_images; ++i) { - if (result_images[i].data != nullptr) { - free(result_images[i].data); - result_images[i].data = nullptr; - } - } - - free(result_images); -} - void sd::free_audio(sd::Audio* audio) { if (audio == nullptr) { return; @@ -222,10 +78,10 @@ const sd_video_t* sd_result_get_video(const sd_result_t* result) { if (result->images.empty()) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "video has no frames"); const auto& first = *result->images.front().get(); - auto shape = first.shape; + auto shape = first.shape(); shape.push_back(static_cast(result->images.size())); for (const auto& frame : result->images) - if (frame->type != first.type || frame->shape != first.shape) + if (frame->type != first.type || frame->shape() != first.shape()) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "video frames must have identical shapes and types"); auto packed = sd::api::allocate_tensor(first.type, std::move(shape)); auto* destination = static_cast(packed.get()->mutable_data()); diff --git a/src/api/result.h b/src/api/result.h index 452055b478..1fe49d3dd4 100644 --- a/src/api/result.h +++ b/src/api/result.h @@ -7,39 +7,15 @@ #include #include "tensor.h" -#include "json.hpp" #include "stable-diffusion.h" -namespace sd { - struct ImageResult { - sd::Image image; - // Owned UTF-8 JSON using the sdcpp.generation/v1 schema. - char* generation_info; - }; - - struct ImageGenerationResult { - sd::ImageResult* items; - int count; - }; - - struct VideoGenerationResult { - sd::Image* frames; - int frame_count; - sd::Audio* audio; - int fps; - char* generation_info; - }; - - void free_image_generation_result(ImageGenerationResult* result); - void free_video_generation_result(VideoGenerationResult* result); - void free_images(sd::Image* images, int count); +namespace sd::dgl { + class Value; +} - char* copy_generation_info(const nlohmann::json& info); - // Consumes images even on failure. - bool make_image_generation_result(sd::Image* images, int count, const std::vector& infos, sd::ImageGenerationResult** result_out); - bool make_image_result(ImageGenerationResult* images, sd_result_t** result_out); - bool make_image_result(sd::Image* images, int count, const std::vector& infos, sd_result_t** result_out); - bool make_video_result(VideoGenerationResult* video, sd_result_t** result_out); +namespace sd::api { + void append_program_image(sd_result_t& result, const dgl::Value& value, const std::string& source); + void set_program_video(sd_result_t& result, const dgl::Value& value, const std::string& source); } struct sd_result { diff --git a/src/api/templates/README.md b/src/api/templates/README.md new file mode 100644 index 0000000000..3b8e0d5ae2 --- /dev/null +++ b/src/api/templates/README.md @@ -0,0 +1,54 @@ +# C API generation templates + +The generation C API selects an entry template for the request, renders a +complete DGL program and runs it with the input tensors supplied by the host. +`generation_info` contains the executed source. CMake embeds the templates +during configuration. + +| Template | Flow | +| --- | --- | +| [image.dgl](image.dgl) | Text-to-image and ordinary image-to-image | +| [image_inpaint.dgl](image_inpaint.dgl) | Masked sampling and native inpaint conditioning | +| [image_edit.dgl](image_edit.dgl) | Native reference-image editing | +| [image_pixel.dgl](image_pixel.dgl) | Pixel-space diffusion, with optional VAE-encoded references | +| `image_h3.dgl` | MiniMax-H3 Image and P-H3 latent packing | +| [image_layered.dgl](image_layered.dgl) | Qwen layered generation and per-layer decoding | +| [image_sefi.dgl](image_sefi.dgl) | SeFi dual schedules | +| [video_wan.dgl](video_wan.dgl) | Wan/Hunyuan video, VACE, S2V and dual experts | +| [video_ltx.dgl](video_ltx.dgl) | LTX video/audio generation and keyframes | +| `video_h3.dgl` | MiniMax-H3 video/audio generation and references | +| [upscale.dgl](upscale.dgl) | Standalone image upscaling, including repeats | + +## Editing a flow + +C++ resolves model families, request defaults, dimensions and host tensor +bindings. The entry template expresses the resulting workflow as DGL calls. +Use a template condition for an optional stage and an include for a helper +shared by several flows. Put the minimum DGL version at the top of each entry. +When a helper needs a newer version, update the entries that use it. +See the [DGL version rules](../../../docs/dgl.md#dgl-versions). + +For example, the image entry loads the components with these lines. + +```text + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +``` + +Here `model_path` and `text_path` are DGL variables in the rendered program. +C++ supplies `model_loader` as a function name and `model_options` as an +already formatted argument list, including its leading comma when nonempty. + +The value C++ supplies determines how to insert it into the script. + +| Template expression | Input | Rendered DGL | +| --- | --- | --- | +| `{{ value \| literal }}` | A raw value, such as a prompt or file path | A DGL literal with strings quoted and escaped | +| `{{ options \| args }}` | An object such as `{"family": "sd1"}` | `, family = "sd1"` (empty text for an empty object) | +| `{{model_options}}` | A trusted, preformatted argument list | The supplied text verbatim | + +Conditions use boolean fields, for example `{% if flags.has_init %}`, with +optional `elif`, `else` and `not`. Close them with `{% endif %}`. An include +such as `{% include "image_helpers" %}` uses the embedded template name. +Substitutions are evaluated once, so template-like text in a prompt stays text. diff --git a/src/api/templates/image.dgl b/src/api/templates/image.dgl new file mode 100644 index 0000000000..75e0745c2b --- /dev/null +++ b/src/api/templates/image.dgl @@ -0,0 +1,90 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "image_helpers" %} + +fn main({{inputs}}) { + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) +{% if flags.has_init %} + source = fit_canvas(input_image, width, height, mode = "nearest") + image_base = {{from_vae}}(vae, vae_encode(vae, image::to_f32(source, channels = {{channels}}), rng = encode_rng{{vae_run_options}})) +{% else %} + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) +{% endif %} + base = image_base +{% if flags.control_image %} + control_pixels = image::to_f32(fit_canvas(input_control, width, height, mode = "nearest"), channels = 3) +{% if flags.native_control %} + control_latent = {{from_vae}}(vae, vae_encode(vae, control_pixels, rng = encode_rng{{vae_run_options}})) +{% else %} + control_model = controlnet::load(control_path{{control_options}}) +{% if flags.z_control %} + control_encoded = {{from_vae}}(vae, vae_encode(vae, control_pixels, rng = encode_rng, posterior = "mode"{{vae_run_options}})) + control_hint = tensor::pad(control_encoded, [0, 0, 0, 0, 0, 33 - tensor::shape(control_encoded)[2]]) +{% endif %} +{% endif %} +{% endif %} +{% if flags.separate_negative_model %} + negative_model = load_dit(negative_model_path{{model_options}}) +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.minit2i %} + negative_text = zero_out(positive_text, fields = ["vector"]) +{% elif flags.ming %} + negative_text = zero_out(positive_text) +{% elif flags.ideogram %} + negative_text = {vector = tensor::vector([1])} +{% else %} +{% if flags.encode_negative %} + negative_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} +{% endif %} + positive = positive_text +{% if flags.sdxl_zero %} + negative = sdxl_zero_text(negative_text) +{% else %} + negative = negative_text +{% endif %} +{% if flags.control_image_guidance %} + image_unconditional_concat = tensor::zeros_like(base) +{% endif %} +{% include "image_predictors" %} +{% if flags.custom_sigmas %} + full_sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + full_sigmas = make_sigmas({{schedule_predictor}}, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} +{% if flags.has_init %} + sigmas = slice_sigmas_by_strength(full_sigmas, strength) +{% else %} + sigmas = full_sigmas +{% endif %} + rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} +{% if flags.hidream_o1 %} + start = add_noise(guided, base, tensor::mul(tensor::randn_like(base, rng = rng), eta), sigma = sigmas[0]) +{% else %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) +{% endif %} + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "image_hires" %} +{% endif %} + image = vae_decode(vae, {{to_vae}}(vae, {{result_latent}}){{vae_run_options}}) + return {image = image, latent = {{result_latent}}} +} diff --git a/src/api/templates/image_edit.dgl b/src/api/templates/image_edit.dgl new file mode 100644 index 0000000000..6cd8c839d8 --- /dev/null +++ b/src/api/templates/image_edit.dgl @@ -0,0 +1,105 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "image_helpers" %} + +fn main({{inputs}}) { + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) +{% if flags.has_init %} + source = fit_canvas(input_image, width, height, mode = "nearest") +{% if flags.raw_reference %} + image_base = vae_encode(vae, image::to_f32(source, channels = {{channels}}), rng = encode_rng, posterior = "mode"{{vae_run_options}}) +{% else %} + image_base = {{from_vae}}(vae, vae_encode(vae, image::to_f32(source, channels = {{channels}}), rng = encode_rng{{vae_run_options}})) +{% endif %} +{% else %} + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) +{% endif %} + base = image_base +{{references}} +{% if flags.unet_edit %} +{% if flags.references %} + edit_latent = tensor::interpolate(reference_latent_0, size = tensor::shape(base)[:2]) +{% else %} + edit_latent = tensor::zeros_like(base) +{% endif %} +{% if flags.image_guidance %} + image_unconditional_concat = tensor::zeros_like(edit_latent) +{% endif %} +{% endif %} +{% if flags.control_image %} + control_pixels = image::to_f32(fit_canvas(input_control, width, height, mode = "nearest"), channels = 3) +{% if flags.native_control %} + control_latent = {{from_vae}}(vae, vae_encode(vae, control_pixels, rng = encode_rng{{vae_run_options}})) +{% else %} + control_model = controlnet::load(control_path{{control_options}}) +{% if flags.z_control %} + control_encoded = {{from_vae}}(vae, vae_encode(vae, control_pixels, rng = encode_rng, posterior = "mode"{{vae_run_options}})) + control_hint = tensor::pad(control_encoded, [0, 0, 0, 0, 0, 33 - tensor::shape(control_encoded)[2]]) +{% endif %} +{% endif %} +{% endif %} +{% if flags.separate_negative_model %} + negative_model = load_dit(negative_model_path{{model_options}}) +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.minit2i %} + negative_text = zero_out(positive_text, fields = ["vector"]) +{% elif flags.ming %} + negative_text = zero_out(positive_text) +{% elif flags.ideogram %} + negative_text = {vector = tensor::vector([1])} +{% else %} +{% if flags.encode_negative %} + negative_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} +{% endif %} + positive = positive_text +{% if flags.sdxl_zero %} + negative = sdxl_zero_text(negative_text) +{% else %} + negative = negative_text +{% endif %} +{% if flags.control_image_guidance %} + image_unconditional_concat = tensor::zeros_like(base) +{% endif %} +{% include "image_predictors" %} +{% if flags.custom_sigmas %} + full_sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + full_sigmas = make_sigmas({{schedule_predictor}}, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} +{% if flags.has_init %} + sigmas = slice_sigmas_by_strength(full_sigmas, strength) +{% else %} + sigmas = full_sigmas +{% endif %} + rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} +{% if flags.hidream_o1 %} + start = add_noise(guided, base, tensor::mul(tensor::randn_like(base, rng = rng), eta), sigma = sigmas[0]) +{% else %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) +{% endif %} + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "image_hires" %} +{% endif %} + image = vae_decode(vae, {{to_vae}}(vae, {{result_latent}}){{vae_run_options}}) + return {image = image, latent = {{result_latent}}} +} diff --git a/src/api/templates/image_h3.dgl b/src/api/templates/image_h3.dgl new file mode 100644 index 0000000000..55a47cc1b6 --- /dev/null +++ b/src/api/templates/image_h3.dgl @@ -0,0 +1,89 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "image_helpers" %} + +fn main({{inputs}}) { + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) +{% if flags.has_init %} + source = fit_canvas(input_image, width, height, mode = "nearest") + image_encoded = {{from_vae}}(vae, vae_encode(vae, image::to_f32(source, channels = {{channels}}), rng = encode_rng{{vae_run_options}})) + image_base = tensor::reshape(image_encoded, latent_shape(vae, width = width, height = height)) +{% else %} + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) +{% endif %} +{% if flags.ph3 %} + image_shape = tensor::shape(image_base) + image_video = tensor::unsqueeze(image_base, axis = 2) + audio_channels = math::ceil_div(128, image_shape[0] * image_shape[1]) + base = tensor::concat([image_video, tensor::zeros([image_shape[0], image_shape[1], 1, audio_channels, 1])], axis = 3) +{% else %} + base = tensor::unsqueeze(image_base, axis = 2) +{% endif %} +{{references}} +{% if flags.control_image %} + control_pixels = image::to_f32(fit_canvas(input_control, width, height, mode = "nearest"), channels = 3) + control_model = controlnet::load(control_path{{control_options}}) +{% endif %} +{% if flags.mask_stage %} +{% if flags.has_mask %} + mask_pixels = tensor::threshold(image::to_f32(fit_canvas(tensor::grayscale(input_mask, axis = 0), width, height, mode = "nearest_exact")), threshold = 0.5) +{% else %} + mask_pixels = tensor::full([width, height, 1, 1], 1) +{% endif %} + base_shape = tensor::shape(base) + mask_scale = [math::floor(width / base_shape[0]), math::floor(height / base_shape[1])] + mask_latent = tensor::max_pool2d(mask_pixels, kernel = mask_scale, stride = mask_scale) +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.encode_negative %} + negative_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} + positive = positive_text + negative = negative_text +{% if flags.controlnet %} + controlled_positive = controlnet::apply(positive, control_model, {{control_hint}}, strength = control_strength, type = {{control_type}}) + controlled_negative = controlnet::apply(negative, control_model, {{control_hint}}, strength = control_strength, type = {{control_type}}) +{% endif %} + pos = predictor(model, {{positive_condition}}{{predictor_options}}) + neg = predictor({{negative_model}}, {{negative_condition}}{{negative_predictor_options}}) + guided = {{guidance_function}}(pos, neg, scale = cfg_scale{{guidance_options}}) +{% if flags.custom_sigmas %} + full_sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + full_sigmas = make_sigmas({{schedule_predictor}}, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} +{% if flags.has_init %} + sigmas = slice_sigmas_by_strength(full_sigmas, strength) +{% else %} + sigmas = full_sigmas +{% endif %} + rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "image_hires" %} +{% endif %} +{% if flags.ph3 %} + image = vae_decode(vae, dit_to_vae_latents(vae, {{result_latent}}[:, :, :, :24]){{vae_run_options}}) +{% else %} + image = vae_decode(vae, dit_to_vae_latents(vae, {{result_latent}}){{vae_run_options}}) +{% endif %} + return {image = image, latent = {{result_latent}}} +} diff --git a/src/api/templates/image_helpers.dgl b/src/api/templates/image_helpers.dgl new file mode 100644 index 0000000000..bb16609e55 --- /dev/null +++ b/src/api/templates/image_helpers.dgl @@ -0,0 +1,55 @@ +{% if flags.sdxl_zero %} +fn sdxl_zero_text(cond) { + zeroed = zero_out(cond, fields = ["crossattn"]) + pooled_zeros = tensor::zeros_like(cond.vector[:1280]) + adm = tensor::replace_slice(cond.vector, pooled_zeros, axis = 0, start = 0) + return {crossattn = zeroed.crossattn, vector = adm} +} + +{% endif %} +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn slice_sigmas_by_strength(sigmas, strength) { + steps = tensor::numel(sigmas) - 1 + retained = math::min(math::floor(steps * strength) + 1, steps) + return sigmas[steps - retained:] +} + +{% if flags.layered %} +fn decode_layer(index, args) { + latent = args.latent[:, :, index] + return vae_decode(args.vae, dit_to_vae_latents(args.vae, latent){{vae_run_options}}) +} +{% if flags.hires %} +{% if flags.hires_pixels %} +fn upscale_layer(index, args) { + latent = args.latent[:, :, index] + image = vae_decode(args.vae, dit_to_vae_latents(args.vae, latent), dtype = "f32"{{vae_run_options}}) +{% if flags.hires_model %} + upscaled = upscale(args.upscaler, image::to_u8(image)) + pixels = image::to_f32(tensor::interpolate(upscaled, size = args.size, axes = [1, 2], mode = args.mode)) +{% else %} + pixels = tensor::interpolate(image, size = args.size, mode = args.mode) +{% endif %} + encoded = vae_to_dit_latents(args.vae, vae_encode(args.vae, pixels, rng = args.rng{{vae_run_options}})) + return tensor::unsqueeze(encoded, axis = 2) +} +{% endif %} +{% endif %} +{% endif %} +{% if flags.h3_reference_noise %} +fn h3_image_reference_noise(latent, seed) { + shape = tensor::shape(latent) + patches = tensor::zeros([2, 2, shape[-2], math::floor(shape[0] / 2), math::floor(shape[1] / 2)]) + rng = make_rng("cpu", seed = seed) + noise = tensor::reshape(tensor::permute(tensor::randn_like(patches, rng = rng), [0, 3, 1, 4, 2]), shape) + return tensor::lerp(latent, noise, 0.001) +} +{% endif %} diff --git a/src/api/templates/image_hires.dgl b/src/api/templates/image_hires.dgl new file mode 100644 index 0000000000..14c09a5445 --- /dev/null +++ b/src/api/templates/image_hires.dgl @@ -0,0 +1,125 @@ + hires_rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + hires_sampler_rng = hires_rng +{% else %} + hires_sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} +{% if flags.ph3 %} + hires_source = latent[:, :, :, :24] +{% else %} + hires_source = latent +{% endif %} +{% if flags.hires_pixels %} +{% if flags.layered %} +{% if flags.hires_model %} + hires_upscaler = load_upscaler(hires_model_path{{hires_model_options}}) + hires_layers = map(tensor::to_list(tensor::arange(0, layers)), process = upscale_layer, args = {vae = vae, latent = latent, rng = hires_rng, upscaler = hires_upscaler, size = [hires_target_width, hires_target_height], mode = hires_mode}) +{% else %} + hires_layers = map(tensor::to_list(tensor::arange(0, layers)), process = upscale_layer, args = {vae = vae, latent = latent, rng = hires_rng, size = [hires_target_width, hires_target_height], mode = hires_mode}) +{% endif %} + hires_image_base = tensor::concat(hires_layers, axis = 2) +{% else %} +{% if flags.hires_pixel_model %} + hires_pixels = tensor::clamp(tensor::affine(hires_source, scale = 0.5, offset = 0.5), 0, 1) +{% elif flags.hires_sefi %} + hires_pixels = vae_decode(vae, {{to_vae}}(vae, hires_source[:, :, 16:144]), dtype = "f32"{{vae_run_options}}) +{% else %} + hires_pixels = vae_decode(vae, {{to_vae}}(vae, hires_source), dtype = "f32"{{vae_run_options}}) +{% endif %} +{% if flags.hires_model %} + hires_upscaler = load_upscaler(hires_model_path{{hires_model_options}}) + hires_upscaled = upscale(hires_upscaler, image::to_u8(hires_pixels)) + hires_resized = image::to_f32(tensor::interpolate(hires_upscaled, size = [hires_target_width, hires_target_height], axes = [1, 2], mode = hires_mode), channels = {{channels}}) +{% else %} + hires_resized = tensor::interpolate(hires_pixels, size = [hires_target_width, hires_target_height], mode = hires_mode) +{% endif %} +{% if flags.hires_pixel_model %} + hires_image_base = tensor::affine(hires_resized, scale = 2, offset = -1) +{% else %} + hires_encoded = {{from_vae}}(vae, vae_encode(vae, hires_resized, rng = hires_rng{{vae_run_options}})) +{% if flags.hires_h3_image %} + hires_image_base = tensor::reshape(hires_encoded, [math::floor(hires_target_width / hires_vae_scale), math::floor(hires_target_height / hires_vae_scale), 1, 24, 1]) +{% elif flags.hires_sefi %} + hires_image_base = tensor::concat([tensor::interpolate(latent[:, :, :16], size = [math::floor(hires_target_width / hires_vae_scale), math::floor(hires_target_height / hires_vae_scale)]), hires_encoded], axis = 2) +{% else %} + hires_image_base = hires_encoded +{% endif %} +{% endif %} +{% endif %} +{% else %} + hires_image_base = tensor::interpolate(hires_source, size = [math::floor(hires_target_width / hires_vae_scale), math::floor(hires_target_height / hires_vae_scale)], mode = hires_mode, antialias = hires_antialias) +{% endif %} +{% if flags.ph3 %} + hires_shape = tensor::shape(hires_image_base) + hires_audio = tensor::reshape(latent[:, :, :, 24:], [tensor::numel(latent[:, :, :, 24:])])[:128] + hires_audio_channels = math::ceil_div(128, hires_shape[0] * hires_shape[1]) + hires_base = tensor::concat([hires_image_base, tensor::reshape(tensor::pad(hires_audio, [0, hires_shape[0] * hires_shape[1] * hires_audio_channels - 128]), [hires_shape[0], hires_shape[1], 1, hires_audio_channels, 1])], axis = 3) +{% else %} + hires_base = hires_image_base +{% endif %} +{% if flags.mask_stage %} + hires_mask = tensor::interpolate({{hires_mask}}, size = tensor::shape(hires_base)[:2], mode = "nearest_max") +{% elif flags.has_mask %} + hires_mask = tensor::interpolate({{hires_mask}}, size = tensor::shape(hires_base)[:2], mode = "nearest_max") +{% endif %} +{% if flags.hires_rebuild %} +{% if flags.inpaint_model %} + hires_inpaint_condition = tensor::interpolate(inpaint_condition, size = tensor::shape(hires_base)[:2]) +{% elif flags.unet_edit %} + hires_edit_latent = tensor::interpolate(edit_latent, size = tensor::shape(hires_base)[:2]) +{% elif flags.native_control %} +{% if flags.control_image %} + hires_control_pixels = image::to_f32(fit_canvas(input_control, hires_target_width, hires_target_height, mode = "nearest"), channels = 3) + hires_control_latent = {{from_vae}}(vae, vae_encode(vae, hires_control_pixels, rng = hires_rng{{vae_run_options}})) +{% else %} + hires_control_latent = tensor::zeros_like(hires_base) +{% endif %} +{% endif %} +{% if flags.z_control %} + hires_control_pixels = image::to_f32(fit_canvas(input_control, hires_target_width, hires_target_height, mode = "nearest"), channels = 3) + hires_control_encoded = {{from_vae}}(vae, vae_encode(vae, hires_control_pixels, rng = hires_rng, posterior = "mode"{{vae_run_options}})) + hires_control_hint = tensor::pad(hires_control_encoded, [0, 0, 0, 0, 0, 33 - tensor::shape(hires_control_encoded)[2]]) + hires_controlled_positive = controlnet::apply(positive, control_model, hires_control_hint, strength = control_strength, type = {{control_type}}) + hires_controlled_negative = controlnet::apply(negative, control_model, hires_control_hint, strength = control_strength, type = {{control_type}}) +{% endif %} +{% if flags.image_guidance %} +{% if flags.reference_image_guidance %} +{% if flags.z_control %} + hires_controlled_unconditional = controlnet::apply(unconditional_text, control_model, hires_control_hint, strength = control_strength, type = {{control_type}}) +{% endif %} +{% else %} + hires_image_unconditional_concat = tensor::interpolate(image_unconditional_concat, size = tensor::shape(hires_base)[:2]) +{% endif %} +{% endif %} + hires_pos = predictor(model, {{hires_positive_condition}}{{hires_predictor_options}}) + hires_neg = predictor({{negative_model}}, {{hires_negative_condition}}{{hires_negative_predictor_options}}) +{% if flags.image_guidance %} + hires_image_only = predictor(model, {{hires_image_only_condition}}{{hires_image_only_options}}) +{% endif %} + hires_guided = {{guidance_function}}(hires_pos, hires_neg, scale = cfg_scale{{hires_guidance_options}}) +{% endif %} +{% if flags.hires_custom_sigmas %} + hires_sigmas = tensor::vector(hires_custom_sigmas, dtype = "f32") +{% elif flags.hires_sefi %} + hires_schedule = sefi::make_sigmas(steps = hires_scheduler_steps{{sefi_schedule_options}}) + hires_sigmas = hires_schedule.sigmas[-(hires_steps + 1):] +{% else %} + hires_schedule = make_sigmas({{hires_schedule_predictor}}, latent = hires_base, steps = hires_scheduler_steps, scheduler = scheduler{{schedule_options}}) + hires_sigmas = hires_schedule[-(hires_steps + 1):] +{% endif %} +{% if flags.hidream_o1 %} + hires_start = add_noise({{hires_schedule_predictor}}, hires_base, tensor::mul(tensor::randn_like(hires_base, rng = hires_rng), eta), sigma = hires_sigmas[0]) +{% else %} + hires_start = add_noise({{hires_schedule_predictor}}, hires_base, tensor::randn_like(hires_base, rng = hires_rng), sigma = hires_sigmas[0]) +{% endif %} +{% if flags.hires_sefi %} +{% if flags.hires_custom_sigmas %} + hires_semantic_schedule = sefi::make_sigmas(steps = tensor::numel(hires_sigmas) - 1{{sefi_schedule_options}}) + hires_semantic_sigmas = hires_semantic_schedule.semantic_sigmas +{% else %} + hires_semantic_sigmas = hires_schedule.semantic_sigmas[-(hires_steps + 1):] +{% endif %} + hires_latent = sefi::sample(hires_start, hires_sigmas, semantic_sigmas = hires_semantic_sigmas, predict = {{hires_schedule_predictor}}, method = method, rng = hires_sampler_rng, eta = eta{{hires_sample_options}}) +{% else %} + hires_latent = sample(hires_start, hires_sigmas, predict = {{hires_schedule_predictor}}, method = method, rng = hires_sampler_rng, eta = eta{{hires_sample_options}}) +{% endif %} diff --git a/src/api/templates/image_inpaint.dgl b/src/api/templates/image_inpaint.dgl new file mode 100644 index 0000000000..536e82039b --- /dev/null +++ b/src/api/templates/image_inpaint.dgl @@ -0,0 +1,147 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "image_helpers" %} + +fn main({{inputs}}) { + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) +{% if flags.has_init %} + source = fit_canvas(input_image, width, height, mode = "nearest") + image_base = {{from_vae}}(vae, vae_encode(vae, image::to_f32(source, channels = {{channels}}), rng = encode_rng{{vae_run_options}})) +{% else %} + image_base = tensor::zeros(latent_shape(vae, width = width, height = height)) +{% endif %} + base = image_base +{{references}} +{% if flags.unet_edit %} +{% if flags.references %} + edit_latent = tensor::interpolate(reference_latent_0, size = tensor::shape(base)[:2]) +{% else %} + edit_latent = tensor::zeros_like(base) +{% endif %} +{% if flags.image_guidance %} + image_unconditional_concat = tensor::zeros_like(edit_latent) +{% endif %} +{% endif %} +{% if flags.control_image %} + control_pixels = image::to_f32(fit_canvas(input_control, width, height, mode = "nearest"), channels = 3) +{% if flags.native_control %} + control_latent = {{from_vae}}(vae, vae_encode(vae, control_pixels, rng = encode_rng{{vae_run_options}})) +{% else %} + control_model = controlnet::load(control_path{{control_options}}) +{% if flags.z_control %} + control_encoded = {{from_vae}}(vae, vae_encode(vae, control_pixels, rng = encode_rng, posterior = "mode"{{vae_run_options}})) + control_hint = tensor::pad(control_encoded, [0, 0, 0, 0, 0, 33 - tensor::shape(control_encoded)[2]]) +{% endif %} +{% endif %} +{% endif %} +{% if flags.mask_stage %} +{% if flags.has_mask %} + mask_pixels = tensor::threshold(image::to_f32(fit_canvas(tensor::grayscale(input_mask, axis = 0), width, height, mode = "nearest_exact")), threshold = 0.5) +{% else %} + mask_pixels = tensor::full([width, height, 1, 1], 1) +{% endif %} + base_shape = tensor::shape(base) + mask_scale = [math::floor(width / base_shape[0]), math::floor(height / base_shape[1])] + mask_latent = tensor::max_pool2d(mask_pixels, kernel = mask_scale, stride = mask_scale) +{% if flags.inpaint_model %} +{% if flags.flex %} + masked_latent = tensor::mul(base, tensor::affine(mask_latent, scale = -1, offset = 1)) +{% elif flags.has_init %} + masked_pixels = tensor::lerp(image::to_f32(source, channels = {{channels}}), 0.5, mask_pixels) + masked_latent = {{from_vae}}(vae, vae_encode(vae, masked_pixels, rng = encode_rng{{vae_run_options}})) +{% else %} + masked_latent = tensor::zeros_like(base) +{% endif %} +{% if flags.flux_fill %} + mask_grid = tensor::reshape(mask_pixels, [mask_scale[0], base_shape[0], mask_scale[1], base_shape[1]]) + mask_channels = tensor::reshape(tensor::permute(mask_grid, [1, 3, 0, 2]), [base_shape[0], base_shape[1], mask_scale[0] * mask_scale[1], 1]) + inpaint_condition = tensor::concat([masked_latent, mask_channels], axis = 2) +{% if flags.image_guidance %} + image_unconditional_concat = tensor::concat([tensor::zeros_like(masked_latent), mask_channels], axis = 2) +{% endif %} +{% elif flags.flex %} +{% if flags.control_image %} + inpaint_condition = tensor::concat([masked_latent, mask_latent, control_latent], axis = 2) +{% if flags.image_guidance %} + image_unconditional_concat = tensor::concat([tensor::zeros_like(masked_latent), mask_latent, tensor::zeros_like(masked_latent)], axis = 2) +{% endif %} +{% else %} + inpaint_condition = tensor::concat([masked_latent, mask_latent, tensor::zeros_like(base)], axis = 2) +{% if flags.image_guidance %} + image_unconditional_concat = tensor::concat([tensor::zeros_like(masked_latent), mask_latent, tensor::zeros_like(masked_latent)], axis = 2) +{% endif %} +{% endif %} +{% else %} + inpaint_condition = tensor::concat([mask_latent, masked_latent], axis = 2) +{% if flags.image_guidance %} + image_unconditional_concat = tensor::concat([mask_latent, tensor::zeros_like(masked_latent)], axis = 2) +{% endif %} +{% endif %} + denoise_mask = tensor::max_pool2d(mask_latent, kernel = [3, 3], padding_before = [1, 1], padding_after = [1, 1]) +{% endif %} +{% endif %} +{% if flags.separate_negative_model %} + negative_model = load_dit(negative_model_path{{model_options}}) +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.minit2i %} + negative_text = zero_out(positive_text, fields = ["vector"]) +{% elif flags.ming %} + negative_text = zero_out(positive_text) +{% elif flags.ideogram %} + negative_text = {vector = tensor::vector([1])} +{% else %} +{% if flags.encode_negative %} + negative_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} +{% endif %} + positive = positive_text +{% if flags.sdxl_zero %} + negative = sdxl_zero_text(negative_text) +{% else %} + negative = negative_text +{% endif %} +{% if flags.control_image_guidance %} + image_unconditional_concat = tensor::zeros_like(base) +{% endif %} +{% include "image_predictors" %} +{% if flags.custom_sigmas %} + full_sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + full_sigmas = make_sigmas({{schedule_predictor}}, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} +{% if flags.has_init %} + sigmas = slice_sigmas_by_strength(full_sigmas, strength) +{% else %} + sigmas = full_sigmas +{% endif %} + rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} +{% if flags.hidream_o1 %} + start = add_noise(guided, base, tensor::mul(tensor::randn_like(base, rng = rng), eta), sigma = sigmas[0]) +{% else %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) +{% endif %} + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "image_hires" %} +{% endif %} + image = vae_decode(vae, {{to_vae}}(vae, {{result_latent}}){{vae_run_options}}) + return {image = image, latent = {{result_latent}}} +} diff --git a/src/api/templates/image_layered.dgl b/src/api/templates/image_layered.dgl new file mode 100644 index 0000000000..32848a641b --- /dev/null +++ b/src/api/templates/image_layered.dgl @@ -0,0 +1,52 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "image_helpers" %} + +fn main({{inputs}}) { + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) + image_shape = latent_shape(vae, width = width, height = height) + base = tensor::zeros([image_shape[0], image_shape[1], layers, image_shape[2], image_shape[3]]) +{{references}} +{% if flags.control_image %} + control_pixels = image::to_f32(fit_canvas(input_control, width, height, mode = "nearest"), channels = 3) + control_model = controlnet::load(control_path{{control_options}}) +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.encode_negative %} + negative_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} + positive = positive_text + negative = negative_text +{% include "image_predictors" %} +{% if flags.custom_sigmas %} + full_sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + full_sigmas = make_sigmas({{schedule_predictor}}, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} + sigmas = full_sigmas + rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "image_hires" %} +{% endif %} + image = map(tensor::to_list(tensor::arange(0, layers)), process = decode_layer, args = {vae = vae, latent = {{result_latent}}}) + return {image = image, latent = {{result_latent}}} +} diff --git a/src/api/templates/image_pixel.dgl b/src/api/templates/image_pixel.dgl new file mode 100644 index 0000000000..681470601b --- /dev/null +++ b/src/api/templates/image_pixel.dgl @@ -0,0 +1,64 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "image_helpers" %} + +fn main({{inputs}}) { + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) +{% if flags.has_init %} + source = image::to_f32(fit_canvas(input_image, width, height, mode = "nearest"), channels = {{channels}}) + base = tensor::affine(source, scale = 2, offset = -1) +{% else %} + base = tensor::zeros([width, height, {{channels}}, 1]) +{% endif %} +{{references}} +{% if flags.has_mask %} + mask_pixels = tensor::threshold(image::to_f32(fit_canvas(tensor::grayscale(input_mask, axis = 0), width, height, mode = "nearest_exact")), threshold = 0.5) + mask_latent = mask_pixels +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.minit2i %} + negative_text = zero_out(positive_text, fields = ["vector"]) +{% else %} +{% if flags.encode_negative %} + negative_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} +{% endif %} + pos = predictor(model, positive_text{{predictor_options}}) + neg = predictor(model, negative_text{{negative_predictor_options}}) + guided = {{guidance_function}}(pos, neg, scale = cfg_scale{{guidance_options}}) +{% if flags.custom_sigmas %} + full_sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + full_sigmas = make_sigmas({{schedule_predictor}}, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} +{% if flags.has_init %} + sigmas = slice_sigmas_by_strength(full_sigmas, strength) +{% else %} + sigmas = full_sigmas +{% endif %} + rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "image_hires" %} +{% endif %} + pixels = tensor::clamp(tensor::affine({{result_latent}}, scale = 0.5, offset = 0.5), 0, 1) + return {image = image::to_u8(pixels), latent = {{result_latent}}} +} diff --git a/src/api/templates/image_predictors.dgl b/src/api/templates/image_predictors.dgl new file mode 100644 index 0000000000..2ff3cc8e77 --- /dev/null +++ b/src/api/templates/image_predictors.dgl @@ -0,0 +1,16 @@ +{% if flags.reference_image_guidance %} + unconditional_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{unconditional_prompt_options}}) +{% endif %} +{% if flags.controlnet %} + controlled_positive = controlnet::apply(positive, control_model, {{control_hint}}, strength = control_strength, type = {{control_type}}) + controlled_negative = controlnet::apply(negative, control_model, {{control_hint}}, strength = control_strength, type = {{control_type}}) +{% if flags.reference_image_guidance %} + controlled_unconditional = controlnet::apply(unconditional_text, control_model, {{control_hint}}, strength = control_strength, type = {{control_type}}) +{% endif %} +{% endif %} + pos = predictor(model, {{positive_condition}}{{predictor_options}}) + neg = predictor({{negative_model}}, {{negative_condition}}{{negative_predictor_options}}) +{% if flags.image_guidance %} + image_only = predictor(model, {{image_only_condition}}{{image_only_options}}) +{% endif %} + guided = {{guidance_function}}(pos, neg, scale = cfg_scale{{guidance_options}}) diff --git a/src/api/templates/image_reference.dgl b/src/api/templates/image_reference.dgl new file mode 100644 index 0000000000..41988f3731 --- /dev/null +++ b/src/api/templates/image_reference.dgl @@ -0,0 +1,17 @@ + {{name}}_original = image::to_f32({{name}}, channels = {{channels}}) +{% if center_crop %} + {{name}}_resized = tensor::interpolate({{name}}_original, size = [{{resize_width}}, {{resize_height}}], mode = "lanczos") + {{name}}_pixels = tensor::crop({{name}}_resized, axes = [0, 1], start = [{{crop_x}}, {{crop_y}}], size = [{{width}}, {{height}}]) +{% else %} + {{name}}_pixels = tensor::interpolate({{name}}_original, size = [{{width}}, {{height}}], mode = {{mode}}) +{% endif %} +{% if encode %} +{% if flags.raw_reference %} + {{latent}} = vae_encode(vae, {{name}}_pixels, rng = encode_rng, posterior = "mode"{{vae_run_options}}) +{% elif augment %} + {{latent}}_raw = vae_to_dit_latents(vae, vae_encode(vae, {{name}}_pixels, rng = encode_rng{{vae_run_options}})) + {{latent}} = h3_image_reference_noise({{latent}}_raw, seed) +{% else %} + {{latent}} = vae_to_dit_latents(vae, vae_encode(vae, {{name}}_pixels, rng = encode_rng{{vae_run_options}})) +{% endif %} +{% endif %} diff --git a/src/api/templates/image_sefi.dgl b/src/api/templates/image_sefi.dgl new file mode 100644 index 0000000000..f7e799a937 --- /dev/null +++ b/src/api/templates/image_sefi.dgl @@ -0,0 +1,81 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "image_helpers" %} + +fn main({{inputs}}) { + base_model = {{model_loader}}(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) +{% if flags.has_init %} + source = fit_canvas(input_image, width, height, mode = "nearest") + image_base = {{from_vae}}(vae, vae_encode(vae, image::to_f32(source, channels = {{channels}}), rng = encode_rng{{vae_run_options}})) + base = tensor::pad(image_base, [0, 0, 0, 0, 16, 0]) +{% else %} + base = tensor::zeros(latent_shape(vae, width = width, height = height)) +{% endif %} +{{references}} +{% if flags.control_image %} + control_pixels = image::to_f32(fit_canvas(input_control, width, height, mode = "nearest"), channels = 3) + control_model = controlnet::load(control_path{{control_options}}) +{% endif %} +{% if flags.mask_stage %} +{% if flags.has_mask %} + mask_pixels = tensor::threshold(image::to_f32(fit_canvas(tensor::grayscale(input_mask, axis = 0), width, height, mode = "nearest_exact")), threshold = 0.5) +{% else %} + mask_pixels = tensor::full([width, height, 1, 1], 1) +{% endif %} + base_shape = tensor::shape(base) + mask_scale = [math::floor(width / base_shape[0]), math::floor(height / base_shape[1])] + mask_latent = tensor::max_pool2d(mask_pixels, kernel = mask_scale, stride = mask_scale) +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.encode_negative %} + negative_text = encode_prompt(text, {{negative_prompt_input}}, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} + positive = positive_text + negative = negative_text +{% if flags.controlnet %} + controlled_positive = controlnet::apply(positive, control_model, {{control_hint}}, strength = control_strength, type = {{control_type}}) + controlled_negative = controlnet::apply(negative, control_model, {{control_hint}}, strength = control_strength, type = {{control_type}}) +{% endif %} + pos = predictor(model, {{positive_condition}}{{predictor_options}}) + neg = predictor({{negative_model}}, {{negative_condition}}{{negative_predictor_options}}) + guided = {{guidance_function}}(pos, neg, scale = cfg_scale{{guidance_options}}) +{% if flags.custom_sigmas %} + full_sigmas = tensor::vector(custom_sigmas, dtype = "f32") + dual_schedule = sefi::make_sigmas(steps = tensor::numel(full_sigmas) - 1{{sefi_schedule_options}}) +{% else %} + dual_schedule = sefi::make_sigmas(steps = steps{{sefi_schedule_options}}) + full_sigmas = dual_schedule.sigmas +{% endif %} +{% if flags.has_init %} + sigmas = slice_sigmas_by_strength(full_sigmas, strength) + semantic_sigmas = dual_schedule.semantic_sigmas[-tensor::numel(sigmas):] +{% else %} + sigmas = full_sigmas + semantic_sigmas = dual_schedule.semantic_sigmas +{% endif %} + rng = make_rng(rng_type, seed = seed) +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sefi::sample(start, sigmas, predict = guided, semantic_sigmas = semantic_sigmas, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "image_hires" %} +{% endif %} + image = vae_decode(vae, dit_to_vae_latents(vae, {{result_latent}}[:, :, 16:144]){{vae_run_options}}) + return {image = image, latent = {{result_latent}}} +} diff --git a/src/api/templates/lora.dgl b/src/api/templates/lora.dgl new file mode 100644 index 0000000000..c12578f3fb --- /dev/null +++ b/src/api/templates/lora.dgl @@ -0,0 +1,7 @@ + {{name}} = load_lora({{path|literal}}) +{% if diffusion %} + {{model_result}} = apply_lora({{model_source}}, {{name}}, weight = {{weight}}, mode = {{mode|literal}}) +{% endif %} +{% if conditioning %} + {{text_result}} = apply_lora({{text_source}}, {{name}}, weight = {{weight}}, mode = {{mode|literal}}) +{% endif %} diff --git a/src/api/templates/upscale.dgl b/src/api/templates/upscale.dgl new file mode 100644 index 0000000000..daa4649de0 --- /dev/null +++ b/src/api/templates/upscale.dgl @@ -0,0 +1,17 @@ +# version: 0.0.0 + +var { + model_path = {{model_path}} + tile_size = {{tile_size}} + repeats = {{repeats}} +} + +fn enlarge(image, index, model) { + return upscale(model, image) +} + +fn main(input_image) { + model = load_upscaler(model_path{{loader_options}}, tile_size = tile_size) + image = fold(tensor::to_list(tensor::arange(0, repeats)), input_image, process = enlarge, model = model) + return {image = image} +} diff --git a/src/api/templates/video_h3.dgl b/src/api/templates/video_h3.dgl new file mode 100644 index 0000000000..db9a360c03 --- /dev/null +++ b/src/api/templates/video_h3.dgl @@ -0,0 +1,75 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "video_helpers" %} + +fn main({{inputs}}) { + base_model = load_dit(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) +{% if flags.first %} + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) +{% endif %} +{% if flags.last %} + last_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(last_frame, width, height, mode = "nearest"), channels = 3), axis = 2) +{% endif %} +{% if flags.decode_audio %} + audio_vae = load_audio_vae(audio_vae_path{{audio_vae_options}}) + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) +{% else %} + audio_shape = empty_audio_shape +{% endif %} + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) +{{references}} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.encode_negative %} + negative_text = encode_prompt(text, negative_prompt, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} +{% if flags.vision %} + positive = {crossattn = positive_text.crossattn, vector = vision_condition} + negative = {crossattn = negative_text.crossattn, vector = vision_condition} +{% else %} + positive = positive_text + negative = negative_text +{% endif %} + pos = predictor(model, positive{{predictor_options}}) + neg = predictor(model, negative{{negative_predictor_options}}) + guided = {{guidance_function}}(pos, neg, scale = cfg_scale{{guidance_options}}) +{% if flags.custom_sigmas %} + sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} + rng = encode_rng +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "video_hires" %} +{% endif %} + video_latent = {{result_latent}}[:, :, :{{output_video_frames}}, :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent){{vae_run_options}}) +{% if flags.decode_audio %} + sound_latent = unpack_audio({{result_latent}}, channels = tensor::shape(video_base)[3], audio_shape = {{output_audio_shape}}, audio_scale = audio_scale) + decoded_audio = audio_vae_decode(audio_vae, sound_latent) + max_audio_samples = math::floor(tensor::shape(output_frames)[3] * decoded_audio.sample_rate / fps) + audio = {samples = decoded_audio.samples[:, :max_audio_samples], sample_rate = decoded_audio.sample_rate} +{% else %} + audio = {} +{% endif %} + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = {{result_latent}}, audio = audio} +} diff --git a/src/api/templates/video_helpers.dgl b/src/api/templates/video_helpers.dgl new file mode 100644 index 0000000000..6728be799c --- /dev/null +++ b/src/api/templates/video_helpers.dgl @@ -0,0 +1,34 @@ +fn fit_canvas(input, width, height, mode) { + shape = tensor::shape(input) + crop_width = math::min(shape[1], math::floor(shape[2] * width / height)) + crop_height = math::min(shape[2], math::floor(shape[1] * height / width)) + start = [math::floor((shape[1] - crop_width) / 2), math::floor((shape[2] - crop_height) / 2)] + cropped = tensor::crop(input, axes = [1, 2], start = start, size = [crop_width, crop_height]) + return tensor::interpolate(cropped, size = [width, height], axes = [1, 2], mode = mode) +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn h3_reference_noise(latent, seed) { + rng = make_rng("cuda", seed = seed) + return tensor::lerp(latent, tensor::randn_like(latent, rng = rng), 0.001) +} + +fn control_frame_pixels(index, args) { + pixels = image::to_f32(fit_canvas(args.frames[:, :, :, index], args.width, args.height, mode = "nearest"), channels = 3) + return tensor::unsqueeze(pixels, axis = 2) +} diff --git a/src/api/templates/video_hires.dgl b/src/api/templates/video_hires.dgl new file mode 100644 index 0000000000..4ca476ec1e --- /dev/null +++ b/src/api/templates/video_hires.dgl @@ -0,0 +1,70 @@ + hires_source = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] +{% if flags.hires_model %} + hires_upscaler = load_latent_upscaler(hires_model_path{{hires_model_options}}) +{% if flags.hires_ltx %} + hires_upscaled = upscale_latent(hires_upscaler, dit_to_vae_latents(vae, hires_source)) + hires_upscaled_shape = tensor::shape(hires_upscaled) + hires_video = vae_to_dit_latents(vae, tensor::reshape(hires_upscaled, [hires_upscaled_shape[0], hires_upscaled_shape[1], hires_upscaled_shape[2], hires_upscaled_shape[3], 1])) +{% else %} + hires_upscaled = upscale_latent(hires_upscaler, hires_source, width = math::floor(hires_target_width / hires_vae_scale), height = math::floor(hires_target_height / hires_vae_scale)) + hires_upscaled_shape = tensor::shape(hires_upscaled) + hires_video = tensor::reshape(hires_upscaled, [hires_upscaled_shape[0], hires_upscaled_shape[1], hires_upscaled_shape[2], hires_upscaled_shape[3], 1]) +{% endif %} +{% else %} + hires_video = tensor::interpolate(hires_source, size = [math::floor(hires_target_width / hires_vae_scale), math::floor(hires_target_height / hires_vae_scale)], mode = hires_mode, antialias = hires_antialias) +{% endif %} + hires_video_shape = tensor::shape(hires_video) + hires_original_audio = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) +{% if flags.hires_ltx %} + hires_width = hires_video_shape[0] * hires_vae_scale + hires_height = hires_video_shape[1] * hires_vae_scale + hires_frames = (hires_video_shape[2] - 1) * 8 + 1 +{% if flags.decode_audio %} + hires_audio_shape = audio_latent_shape(audio_vae, frames = hires_frames, fps = fps) +{% else %} + hires_audio_shape = [16, math::ceil(hires_frames * 25 / fps), 8, 1] +{% endif %} + hires_audio_retained = math::min(audio_shape[1], hires_audio_shape[1]) + hires_audio = tensor::pad(hires_original_audio[:, :hires_audio_retained], [0, 0, 0, hires_audio_shape[1] - hires_audio_retained]) +{% if flags.conditioned %} + hires_video_mask = tensor::full([hires_video_shape[0], hires_video_shape[1], hires_video_shape[2], 1, 1], 1) +{% if flags.first %} + hires_first_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, hires_width, hires_height, mode = "nearest"), channels = 3), axis = 2) + hires_first_latent = vae_to_dit_latents(vae, vae_encode(vae, hires_first_pixels, rng = encode_rng{{vae_run_options}})) + hires_first = tensor::replace_slice(hires_video, hires_first_latent, axis = 2, start = 0) + hires_first_mask = tensor::index_fill(hires_video_mask, axis = 2, indices = [0], value = 0) +{% else %} + hires_first = hires_video + hires_first_mask = hires_video_mask +{% endif %} +{% if flags.last %} + hires_last_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(last_frame, hires_width, hires_height, mode = "nearest"), channels = 3), axis = 2) + hires_last_latent = vae_to_dit_latents(vae, vae_encode(vae, hires_last_pixels, rng = encode_rng{{vae_run_options}})) + hires_conditioned = tensor::concat([hires_first, hires_last_latent], axis = 2) + hires_condition_mask = tensor::concat([hires_first_mask, tensor::zeros([hires_video_shape[0], hires_video_shape[1], tensor::shape(hires_last_latent)[2], 1, 1])], axis = 2) + hires_positions = ltx::video_positions(hires_first, keyframe_latent_frames = tensor::shape(hires_last_latent)[2], keyframe_frame_index = hires_frames - 1, keyframe_pixel_frames = 1, fps = fps) +{% else %} + hires_conditioned = hires_first + hires_condition_mask = hires_first_mask +{% endif %} + hires_base = pack_av(hires_conditioned, hires_audio, audio_scale = audio_scale) + hires_packed_shape = tensor::shape(hires_base) + hires_packed_mask = tensor::concat([tensor::broadcast_to(hires_condition_mask, tensor::shape(hires_conditioned)), tensor::full([hires_packed_shape[0], hires_packed_shape[1], hires_packed_shape[2], hires_packed_shape[3] - hires_video_shape[3], 1], 1)], axis = 3) +{% else %} + hires_base = pack_av(hires_video, hires_audio, audio_scale = audio_scale) +{% endif %} + hires_pos = predictor(model, positive{{predictor_core}}, audio_length = hires_audio_shape[1], fps = fps{{hires_positions_option}}) + hires_neg = predictor(model, negative{{predictor_core}}, audio_length = hires_audio_shape[1], fps = fps{{hires_positions_option}}) + hires_guided = {{guidance_function}}(hires_pos, hires_neg, scale = cfg_scale{{guidance_options}}) +{% else %} + hires_audio_shape = audio_shape + hires_base = pack_av(hires_video, hires_original_audio, audio_scale = audio_scale) +{% endif %} +{% if flags.hires_custom_sigmas %} + hires_sigmas = tensor::vector(hires_custom_sigmas, dtype = "f32") +{% else %} + hires_schedule = make_sigmas({{hires_schedule_predictor}}, latent = hires_base, steps = hires_scheduler_steps, scheduler = scheduler{{schedule_options}}) + hires_sigmas = hires_schedule[-(hires_steps + 1):] +{% endif %} + hires_start = add_noise({{hires_schedule_predictor}}, hires_base, tensor::randn_like(hires_base, rng = rng), sigma = hires_sigmas[0]) + hires_latent = sample(hires_start, hires_sigmas, predict = {{hires_schedule_predictor}}, method = method, rng = sampler_rng, eta = eta{{hires_sample_options}}) diff --git a/src/api/templates/video_ltx.dgl b/src/api/templates/video_ltx.dgl new file mode 100644 index 0000000000..a22ccec8bf --- /dev/null +++ b/src/api/templates/video_ltx.dgl @@ -0,0 +1,101 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "video_helpers" %} + +fn main({{inputs}}) { + base_model = load_dit(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) +{% if flags.first %} + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) +{% endif %} +{% if flags.last %} + last_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(last_frame, width, height, mode = "nearest"), channels = 3), axis = 2) +{% endif %} + video_shape = tensor::shape(video_base) +{% if flags.conditioned %} + video_mask = tensor::full([video_shape[0], video_shape[1], video_shape[2], 1, 1], 1) +{% if flags.first %} + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = encode_rng{{vae_run_options}})) + video_first = tensor::replace_slice(video_base, first_latent, axis = 2, start = 0) + mask_first = tensor::index_fill(video_mask, axis = 2, indices = [0], value = 1 - strength) +{% else %} + video_first = video_base + mask_first = video_mask +{% endif %} +{% if flags.last %} + last_latent = vae_to_dit_latents(vae, vae_encode(vae, last_frame_pixels, rng = encode_rng{{vae_run_options}})) + tail_mask = tensor::full([video_shape[0], video_shape[1], tensor::shape(last_latent)[2], 1, 1], 1 - strength) + video_conditioned = tensor::concat([video_first, last_latent], axis = 2) + mask_conditioned = tensor::concat([mask_first, tail_mask], axis = 2) + positions = ltx::video_positions(video_first, keyframe_latent_frames = tensor::shape(last_latent)[2], keyframe_frame_index = frames - 1, keyframe_pixel_frames = 1, fps = fps) +{% else %} + video_conditioned = video_first + mask_conditioned = mask_first +{% endif %} +{% endif %} +{% if flags.decode_audio %} + audio_vae = load_audio_vae(audio_vae_path{{audio_vae_options}}) + audio_shape = audio_latent_shape(audio_vae, frames = frames, fps = fps) +{% else %} + audio_shape = empty_audio_shape +{% endif %} +{% if flags.conditioned %} + base = pack_av(video_conditioned, tensor::zeros(audio_shape), audio_scale = audio_scale) + packed_shape = tensor::shape(base) + full_video_mask = tensor::broadcast_to(mask_conditioned, tensor::shape(video_conditioned)) + packed_mask = tensor::concat([full_video_mask, tensor::full([packed_shape[0], packed_shape[1], packed_shape[2], packed_shape[3] - video_shape[3], 1], 1)], axis = 3) +{% else %} + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.encode_negative %} + negative_text = encode_prompt(text, negative_prompt, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} +{% if flags.vision %} + positive = {crossattn = positive_text.crossattn, vector = vision_condition} + negative = {crossattn = negative_text.crossattn, vector = vision_condition} +{% else %} + positive = positive_text + negative = negative_text +{% endif %} + pos = predictor(model, positive{{predictor_options}}) + neg = predictor(model, negative{{negative_predictor_options}}) + guided = {{guidance_function}}(pos, neg, scale = cfg_scale{{guidance_options}}) +{% if flags.custom_sigmas %} + sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} + rng = encode_rng +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% if flags.hires %} +{% include "video_hires" %} +{% endif %} + video_latent = {{result_latent}}[:, :, :{{output_video_frames}}, :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent){{vae_run_options}}) +{% if flags.decode_audio %} + sound_latent = unpack_audio({{result_latent}}, channels = tensor::shape(video_base)[3], audio_shape = {{output_audio_shape}}, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) +{% else %} + audio = {} +{% endif %} + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = {{result_latent}}, audio = audio} +} diff --git a/src/api/templates/video_reference.dgl b/src/api/templates/video_reference.dgl new file mode 100644 index 0000000000..7e295b2b8c --- /dev/null +++ b/src/api/templates/video_reference.dgl @@ -0,0 +1,11 @@ +{% if encode_audio %} + {{name}} = audio_vae_encode(audio_vae, {{name}}_samples, sample_rate = {{sample_rate}}) +{% else %} +{% if resize_video %} + {{source}}_pixels = image::to_f32(tensor::interpolate(tensor::index_select({{source}}, axis = 3, indices = {{indices}}), size = [{{width}}, {{height}}], axes = [1, 2]), channels = 3) +{% elif resize_image %} + {{source}}_pixels = image::to_f32(tensor::interpolate({{source}}, size = [{{width}}, {{height}}], axes = [1, 2]), channels = 3) +{% endif %} + {{name}}_raw = vae_to_dit_latents(vae, vae_encode(vae, {{pixels}}, rng = encode_rng{{vae_run_options}})) + {{name}} = h3_reference_noise({{name}}_raw, seed) +{% endif %} diff --git a/src/api/templates/video_wan.dgl b/src/api/templates/video_wan.dgl new file mode 100644 index 0000000000..e237d289c2 --- /dev/null +++ b/src/api/templates/video_wan.dgl @@ -0,0 +1,206 @@ +# version: 0.0.0 + +var { +{{variables}} +} + +{% include "video_helpers" %} + +fn main({{inputs}}) { + base_model = load_dit(model_path{{model_options}}) + base_text = load_text_encoder(text_path{{text_options}}) + vae = {{vae_loader}}(vae_path{{vae_options}}) +{{loras}} + model = {{patched_model}} + text = {{patched_text}} + encode_rng = make_rng(rng_type, seed = seed) + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) +{% if flags.first %} + first_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(first_frame, width, height, mode = "nearest"), channels = 3), axis = 2) +{% endif %} +{% if flags.last %} + last_frame_pixels = tensor::unsqueeze(image::to_f32(fit_canvas(last_frame, width, height, mode = "nearest"), channels = 3), axis = 2) +{% endif %} +{% if flags.vace %} + control_blank = tensor::full([width, height, frames, 3, 1], 0.5) +{% if flags.controls %} + control_indices = tensor::to_list(tensor::arange(0, control_count)) + control_parts = map(control_indices, process = control_frame_pixels, args = {frames = control_video, width = width, height = height}) + control_short = tensor::concat(control_parts, axis = 2) + control_pixels = tensor::pad(control_short, [0, 0, 0, 0, 0, frames - tensor::shape(control_short)[2]], value = 0.5) +{% else %} + control_pixels = control_blank +{% endif %} + inactive = vae_to_dit_latents(vae, vae_encode(vae, control_blank, rng = encode_rng{{vae_run_options}})) + reactive = vae_to_dit_latents(vae, vae_encode(vae, control_pixels, rng = encode_rng{{vae_run_options}})) + vace_shape = tensor::shape(inactive) + vace_channels = math::floor(width / vace_shape[0]) * math::floor(height / vace_shape[1]) + vace_mask = tensor::full([vace_shape[0], vace_shape[1], vace_shape[2], vace_channels, 1], 1) + vace_video = tensor::concat([inactive, reactive], axis = 3) +{% if flags.first %} + vace_reference = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = encode_rng{{vae_run_options}})) + reference_context = tensor::concat([vace_reference, tensor::zeros_like(vace_reference)], axis = 3) + vace_pixels = tensor::concat([reference_context, vace_video], axis = 2) + vace_masks = tensor::pad(vace_mask, [0, 0, 0, 0, 1, 0]) + base = tensor::pad(video_base, [0, 0, 0, 0, 1, 0]) +{% else %} + vace_pixels = vace_video + vace_masks = vace_mask + base = video_base +{% endif %} + vace_context = tensor::concat([vace_pixels, vace_masks], axis = 3) +{% elif flags.image_condition %} + condition_blank = tensor::full([width, height, frames, 3, 1], 0.5) +{% if flags.first %} + condition_first = tensor::replace_slice(condition_blank, first_frame_pixels, axis = 2, start = 0) +{% else %} + condition_first = condition_blank +{% endif %} +{% if flags.last %} + condition_pixels = tensor::replace_slice(condition_first, last_frame_pixels, axis = 2, start = frames - 1) +{% else %} + condition_pixels = condition_first +{% endif %} + condition_latent = vae_to_dit_latents(vae, vae_encode(vae, condition_pixels, rng = encode_rng{{vae_run_options}})) + condition_shape = tensor::shape(condition_latent) + mask_blank = tensor::zeros([condition_shape[0], condition_shape[1], condition_shape[2], 4, 1]) +{% if flags.first %} + first_mask = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 1) +{% else %} + first_mask = mask_blank +{% endif %} +{% if flags.last %} + last_mask = tensor::index_fill(first_mask[:, :, :, 3:4], axis = 2, indices = [condition_shape[2] - 1], value = 1) + image_mask = tensor::replace_slice(first_mask, last_mask, axis = 3, start = 3) +{% else %} + image_mask = first_mask +{% endif %} + video_concat = tensor::concat([image_mask, condition_latent], axis = 3) + base = video_base +{% elif flags.frozen %} + video_shape = tensor::shape(video_base) + mask_blank = tensor::full([video_shape[0], video_shape[1], video_shape[2], 1, 1], 1) +{% if flags.first %} + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = encode_rng{{vae_run_options}})) + base_first = tensor::replace_slice(video_base, first_latent, axis = 2, start = 0) + mask_first = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 0) +{% else %} + base_first = video_base + mask_first = mask_blank +{% endif %} +{% if flags.last %} + last_latent = vae_to_dit_latents(vae, vae_encode(vae, last_frame_pixels, rng = encode_rng{{vae_run_options}})) + base = tensor::replace_slice(base_first, last_latent, axis = 2, start = video_shape[2] - 1) + video_mask = tensor::index_fill(mask_first, axis = 2, indices = [video_shape[2] - 1], value = 0) +{% else %} + base = base_first + video_mask = mask_first +{% endif %} +{% else %} + base = video_base +{% endif %} +{% if flags.s2v_reference %} + reference_video = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = encode_rng{{vae_run_options}})) + reference_shape = tensor::shape(reference_video) + reference_latent = tensor::reshape(reference_video, reference_shape[:4]) +{% endif %} +{% if flags.driving_audio %} + audio_encoder = load_audio_encoder(audio_encoder_path{{audio_encoder_options}}) + speech = encode_audio(audio_encoder, driving_audio, sample_rate = sample_rate) + audio_embedding = wan::s2v_audio_window(speech, latent_frames = tensor::shape(video_base)[2]) +{% endif %} +{% if flags.hunyuan %} + concat_shape = tensor::shape(video_base) + concat_blank = tensor::zeros_like(video_base) + mask_blank = tensor::zeros([concat_shape[0], concat_shape[1], concat_shape[2], 1, 1]) +{% if flags.first %} + first_latent = vae_to_dit_latents(vae, vae_encode(vae, first_frame_pixels, rng = encode_rng{{vae_run_options}})) + concat_first = tensor::replace_slice(concat_blank, first_latent[:, :, :1], axis = 2, start = 0) + mask_first = tensor::index_fill(mask_blank, axis = 2, indices = [0], value = 1) +{% else %} + concat_first = concat_blank + mask_first = mask_blank +{% endif %} +{% if flags.last %} + last_latent = vae_to_dit_latents(vae, vae_encode(vae, last_frame_pixels, rng = encode_rng{{vae_run_options}})) + concat_latent = tensor::replace_slice(concat_first, last_latent[:, :, :1], axis = 2, start = concat_shape[2] - 1) + concat_mask = tensor::index_fill(mask_first, axis = 2, indices = [concat_shape[2] - 1], value = 1) +{% else %} + concat_latent = concat_first + concat_mask = mask_first +{% endif %} + video_concat = tensor::concat([concat_latent, concat_mask], axis = 3) +{% endif %} +{% if flags.vision %} + vision = load_vision_encoder(vision_path{{vision_options}}) +{% if flags.first %} + vision_first = encode_vision(vision, image::to_u8(first_frame_pixels[:, :, 0])) +{% else %} + vision_first = encode_vision(vision, image::to_u8(tensor::full([width, height, 3, 1], 0.5)), zero_input = true) +{% endif %} +{% if flags.end_vision %} +{% if flags.last %} + vision_end = encode_vision(vision, image::to_u8(last_frame_pixels[:, :, 0])) +{% else %} + vision_end = encode_vision(vision, image::to_u8(tensor::full([width, height, 3, 1], 0.5)), zero_input = true) +{% endif %} + vision_condition = tensor::concat([vision_first, vision_end], axis = 1) +{% else %} + vision_condition = vision_first +{% endif %} +{% endif %} +{% if flags.dual %} + high_base = load_dit(high_model_path{{model_options}}) +{{high_loras}} +{% endif %} + positive_text = encode_prompt(text, prompt, width = width, height = height{{prompt_options}}) +{% if flags.encode_negative %} + negative_text = encode_prompt(text, negative_prompt, width = width, height = height{{negative_prompt_options}}) +{% else %} + negative_text = positive_text +{% endif %} +{% if flags.vision %} + positive = {crossattn = positive_text.crossattn, vector = vision_condition} + negative = {crossattn = negative_text.crossattn, vector = vision_condition} +{% else %} + positive = positive_text + negative = negative_text +{% endif %} + pos = predictor(model, positive{{predictor_options}}) + neg = predictor(model, negative{{negative_predictor_options}}) + guided = {{guidance_function}}(pos, neg, scale = cfg_scale{{guidance_options}}) +{% if flags.dual %} + high_pos = predictor({{high_model}}, positive{{predictor_options}}) + high_neg = predictor({{high_model}}, negative{{negative_predictor_options}}) + high_guided = {{guidance_function}}(high_pos, high_neg, scale = cfg_scale{{guidance_options}}) +{% endif %} +{% if flags.custom_sigmas %} + sigmas = tensor::vector(custom_sigmas, dtype = "f32") +{% else %} + sigmas = make_sigmas(guided, latent = base, steps = steps, scheduler = scheduler{{schedule_options}}) +{% endif %} + rng = encode_rng +{% if flags.shared_rng %} + sampler_rng = rng +{% else %} + sampler_rng = make_rng(sampler_rng_type, seed = seed) +{% endif %} + start = add_noise(guided, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) +{% if flags.dual %} +{% if flags.fixed_high_steps %} + split = math::min(high_noise_steps, tensor::numel(sigmas) - 1) +{% else %} + split = math::min(tensor::count_nonzero(tensor::threshold(sigmas, threshold = moe_boundary)), tensor::numel(sigmas) - 1) +{% endif %} + handoff = sample(start, sigmas[:split + 1], predict = high_guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) + latent = sample(handoff, sigmas[split:], predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% else %} + latent = sample(start, sigmas, predict = guided, method = method, rng = sampler_rng, eta = eta{{sample_options}}) +{% endif %} +{% if flags.vace_reference %} + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent[:, :, 1:]){{vae_run_options}}) +{% else %} + output_frames = vae_decode(vae, dit_to_vae_latents(vae, latent){{vae_run_options}}) +{% endif %} + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = {{audio}}} +} diff --git a/src/api/tensor.cpp b/src/api/tensor.cpp index 756753560f..7f0db51cb9 100644 --- a/src/api/tensor.cpp +++ b/src/api/tensor.cpp @@ -4,9 +4,23 @@ #include #include #include +#include #include #include +#include "core/file_access.h" +#include "model_io/npy_io.h" + +bool sd_tensor_save(const sd_tensor_t* tensor, const char* path) { + return sd::api::call([&] { + if (!tensor || !path || !*path) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "tensor and path are required"); + sd::require_file_access(path, SD_DGL_FILE_WRITE); + sd::npy::write(std::filesystem::u8path(path), tensor->type, tensor->shape(), tensor->data(), tensor->bytes); + return SD_STATUS_OK; + }) == SD_STATUS_OK; +} + static size_t element_size(sd_tensor_type_t type) { switch (type) { case SD_TENSOR_U8: @@ -61,7 +75,10 @@ static sd_tensor_t::Storage allocate_storage(sd_tensor_type_t type, std::vector< } sd_tensor_t::sd_tensor_t(sd_tensor_type_t type, std::vector shape) - : type(type), shape(std::move(shape)), bytes(sd::api::tensor_byte_size(type, this->shape)), storage_(allocate_storage(type, this->shape, bytes)) {} + : shape_(std::move(shape)), + type(type), + bytes(sd::api::tensor_byte_size(type, shape_)), + storage_(allocate_storage(type, shape_, bytes)) {} static std::vector validated_shape(sd_tensor_type_t type, std::vector shape, const void* data, size_t size) { if (size != sd::api::tensor_byte_size(type, shape) || (size && !data)) @@ -86,7 +103,7 @@ sd::api::TensorRef sd::api::own_tensor(sd_tensor_type_t type, std::vector 4 || s[1] <= 0 || s[2] <= 0 || s[1] > INT32_MAX || s[2] > INT32_MAX || !tensor.data()) throw std::invalid_argument("image requires U8 [channels,width,height], channels in [1,4], and positive dimensions"); @@ -97,13 +114,14 @@ sd::Audio sd::api::audio_view(const sd_audio_t& audio) { if (!audio.data || audio.sample_rate == 0) throw std::invalid_argument("audio requires samples and a positive sample rate"); const auto& t = *audio.data; - if (t.type != SD_TENSOR_F32 || t.shape.size() != 2 || t.shape[0] <= 0 || t.shape[0] > UINT32_MAX || t.shape[1] <= 0 || !t.data()) + const auto& s = t.shape(); + if (t.type != SD_TENSOR_F32 || s.size() != 2 || s[0] <= 0 || s[0] > UINT32_MAX || s[1] <= 0 || !t.data()) throw std::invalid_argument("audio requires F32 [channels,samples] with positive dimensions"); - return {audio.sample_rate, uint32_t(t.shape[0]), uint64_t(t.shape[1]), const_cast(static_cast(t.data()))}; + return {audio.sample_rate, uint32_t(s[0]), uint64_t(s[1]), const_cast(static_cast(t.data()))}; } std::vector sd::api::video_frames(const sd_tensor_t& tensor) { - const auto& s = tensor.shape; + const auto& s = tensor.shape(); if (tensor.type != SD_TENSOR_U8 || s.size() != 4 || s[0] < 1 || s[0] > 4 || s[1] <= 0 || s[2] <= 0 || s[3] <= 0 || s[1] > INT32_MAX || s[2] > INT32_MAX || s[3] > INT32_MAX || !tensor.data()) throw std::invalid_argument("video requires U8 [channels,width,height,frames] with positive dimensions"); @@ -172,7 +190,7 @@ sd_tensor_type_t sd_tensor_type(const sd_tensor_t* tensor) { return valid_tensor(tensor) ? tensor->type : 0; } size_t sd_tensor_rank(const sd_tensor_t* tensor) { - return valid_tensor(tensor) ? tensor->shape.size() : 0; + return valid_tensor(tensor) ? tensor->shape().size() : 0; } size_t sd_tensor_byte_size(const sd_tensor_t* tensor) { return valid_tensor(tensor) ? tensor->bytes : 0; @@ -183,9 +201,9 @@ const void* sd_tensor_data(const sd_tensor_t* tensor) { int64_t sd_tensor_dim(const sd_tensor_t* tensor, size_t axis) { if (!valid_tensor(tensor)) return 0; - if (axis >= tensor->shape.size()) { + if (axis >= tensor->shape().size()) { sd::api::error(SD_STATUS_OUT_OF_RANGE, nullptr, "invalid tensor axis"); return 0; } - return tensor->shape[axis]; + return tensor->shape()[axis]; } diff --git a/src/api/tensor.h b/src/api/tensor.h index 9d5728708a..a9affa6985 100644 --- a/src/api/tensor.h +++ b/src/api/tensor.h @@ -16,14 +16,34 @@ namespace sd::api { size_t tensor_byte_size(sd_tensor_type_t type, const std::vector& shape); + + template + constexpr sd_tensor_type_t tensor_dtype() { + if constexpr (std::is_same_v) { + return SD_TENSOR_U8; + } else if constexpr (std::is_same_v) { + return SD_TENSOR_I32; + } else if constexpr (std::is_same_v) { + return SD_TENSOR_I64; + } else if constexpr (std::is_same_v) { + return SD_TENSOR_F32; + } else { + static_assert(std::is_same_v, "unsupported tensor type"); + return SD_TENSOR_F64; + } + } } struct sd_tensor_t { using Storage = std::variant, sd::Tensor, sd::Tensor, sd::Tensor, sd::Tensor>; + +private: + const std::vector shape_; + +public: mutable std::atomic references{1}; - sd_tensor_type_t type; - std::vector shape; - size_t bytes; + const sd_tensor_type_t type; + const size_t bytes; private: Storage storage_; @@ -33,19 +53,22 @@ struct sd_tensor_t { sd_tensor_t(sd_tensor_type_t type, std::vector shape, const void* data, size_t size); template - explicit sd_tensor_t(sd::Tensor tensor) - : type(std::is_same_v ? SD_TENSOR_U8 : std::is_same_v ? SD_TENSOR_I32 - : std::is_same_v ? SD_TENSOR_I64 - : std::is_same_v ? SD_TENSOR_F32 - : SD_TENSOR_F64), - shape(tensor.shape()), - bytes(sd::api::tensor_byte_size(type, shape)), + explicit sd_tensor_t(sd::Tensor tensor, bool scalar = false) + : shape_(scalar ? std::vector{} : tensor.shape()), + type(sd::api::tensor_dtype()), + bytes(sd::api::tensor_byte_size(type, shape_)), storage_(std::move(tensor)) { - static_assert(std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v, "unsupported tensor type"); - if (std::get>(storage_).numel() != static_cast(bytes / sizeof(T))) + if (as().numel() != static_cast(bytes / sizeof(T))) throw std::invalid_argument("tensor shape and storage size do not match"); } + const std::vector& shape() const { return shape_; } + + template + const sd::Tensor& as() const { + return std::get>(storage_); + } + const void* data() const { return bytes ? std::visit([](const auto& tensor) -> const void* { return tensor.data(); }, storage_) : nullptr; } @@ -81,7 +104,6 @@ namespace sd::api { explicit operator bool() const { return tensor_ != nullptr; } }; - size_t tensor_byte_size(sd_tensor_type_t type, const std::vector& shape); TensorRef own_tensor(sd_tensor_type_t type, std::vector shape, void* data); TensorRef allocate_tensor(sd_tensor_type_t type, std::vector shape); sd::Image image_view(const sd_tensor_t& tensor); diff --git a/src/api/upscaler.cpp b/src/api/upscaler.cpp new file mode 100644 index 0000000000..a7e70db1b3 --- /dev/null +++ b/src/api/upscaler.cpp @@ -0,0 +1,121 @@ +#include "api/generation.h" + +#include "api/result.h" +#include "dgl/executor.h" +#include "dgl/models/upscaler.h" +#include "dgl/run_plan.h" +#include "model/upscaler/scale.hpp" + +struct sd_upscaler { + sd::api::GenerationContext context; + std::shared_ptr model; + sd::dgl::Graph program; + std::string source; + + explicit sd_upscaler(const sd_opt_t* options) + : context(options, sd::api::Upscaler) {} +}; + +namespace sd::api { + static std::string upscale_source(const OptConfig& config, int repeats) { + const auto& settings = config.context; + std::string options; + for (const auto& [name, spec] : std::map{{"backend", settings.backend}, {"params_backend", settings.params_backend}}) { + if (!spec || !*spec) + continue; + SDBackendAssignment assignment; + std::string error; + if (!sd_parse_backend_assignment(spec, &assignment, &error)) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, error); + options += ", " + name + " = " + nlohmann::json(assignment.get(SDBackendModule::UPSCALER)).dump(); + } + if (config.post.conv_direct) + options += ", direct = true"; + return render_template("upscale", {{"model_path", nlohmann::json(settings.model_path).dump()}, + {"tile_size", std::to_string(config.post.tile_size)}, + {"repeats", std::to_string(repeats)}, + {"loader_options", options}}); + } +} + +sd_status_t sd_upscaler_create(const sd_upscaler_opt_t* options, sd_upscaler_t** out) { + if (out) + *out = nullptr; + return sd::api::call([&] { + if (!out) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "out is required"); + auto result = std::make_unique(options); + result->source = sd::api::upscale_source(result->context.model.config, 1); + result->program = sd::dgl::compile(result->source, sd::dgl::operations(), true); + const auto& resource = result->program.resources.at(0); + auto arguments = resource.arguments; + sd::dgl::RunEvents events({}, false); + sd::dgl::RunEventsScope scope(events); + sd::dgl::RunState state{result->context.execution, events}; + sd::dgl::RunPlan plan(result->program, state); + result->model = plan.load_resource(resource.expression, *resource.operation, arguments).as(); + if (result->model->get_scale() <= 0) + throw sd::dgl::Error(SD_STATUS_LOAD_FAILED, "invalid image upscaler scale"); + *out = result.release(); + return SD_STATUS_OK; + }, + SD_STATUS_LOAD_FAILED); +} + +void sd_upscaler_free(sd_upscaler_t* upscaler) { + delete upscaler; +} + +int sd_upscaler_get_scale(const sd_upscaler_t* upscaler) { + sd::api::clear_error(); + if (!upscaler || !upscaler->model) { + sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "upscaler is required"); + return 0; + } + return upscaler->model->get_scale(); +} + +int sd_upscaler_probe_scale(const char* path) { + int scale = 0; + sd::api::call([&] { + if (!path || !*path) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, "model_path", "model path is required"); + scale = sd::upscaling::probe_scale(path); + return scale ? SD_STATUS_OK : sd::api::error(SD_STATUS_LOAD_FAILED, "model_path", "not a recognized RGB upscaler"); + }, + SD_STATUS_LOAD_FAILED); + return scale; +} + +sd_status_t sd_upscale(sd_upscaler_t* upscaler, const sd_upscale_opt_t* options, sd_result_t** out) { + if (out) + *out = nullptr; + return sd::api::call([&] { + if (!out || !upscaler) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "upscaler and out are required"); + sd::api::GenerationRun request(upscaler->context); + auto snapshot = sd::api::copy_options(options); + sd::OptConfig config; + const auto status = sd::api::resolve(snapshot.get(), sd::api::Upscale, config); + if (status != SD_STATUS_OK) + return status; + int64_t width = config.post.image.width, height = config.post.image.height; + const auto scale = upscaler->model->get_scale(); + for (int i = 0; i < config.post.repeats; ++i) { + width *= scale; + height *= scale; + if (width > 16384 || height > 16384 || width * height > 64 * 1024 * 1024) + throw sd::dgl::Error(SD_STATUS_OUT_OF_RANGE, "upscaled output exceeds 16384 per axis or 64 megapixels"); + } + const auto* input = sd::api::bound_tensor(snapshot.get(), "image"); + sd::api::GenerationProgram program; + program.source = config.post.repeats == 1 ? upscaler->source : sd::api::upscale_source(upscaler->context.model.config, config.post.repeats); + program.inputs.emplace("input_image", sd::dgl::Value::object(std::shared_ptr(sd_tensor_retain(input), sd_tensor_free))); + auto value = sd::api::execute_program(upscaler->context, program, config.post.repeats == 1 ? &upscaler->program : nullptr); + auto result = std::make_unique(); + sd::api::append_program_image(*result, value, program.source); + *out = result.release(); + return SD_STATUS_OK; + }, + SD_STATUS_GENERATION_FAILED); +} diff --git a/src/conditioning/conditioner.cpp b/src/conditioning/conditioner.cpp new file mode 100644 index 0000000000..f683550426 --- /dev/null +++ b/src/conditioning/conditioner.cpp @@ -0,0 +1,48 @@ +#include "conditioning/conditioner.h" + +#include + +#include "core/ggml_runner.h" + +sd::Tensor sd::apply_token_weights(sd::Tensor hidden_states, + const std::vector& weights) { + if (hidden_states.empty()) { + return hidden_states; + } + + bool all_one = true; + for (float weight : weights) { + if (weight != 1.0f) { + all_one = false; + break; + } + } + if (all_one) { + return hidden_states; + } + + if (hidden_states.dim() == 1) { + hidden_states.unsqueeze_(1); + } + + GGML_ASSERT(static_cast(hidden_states.shape()[1]) == weights.size()); + + float original_mean = hidden_states.mean(); + auto chunk_weights = sd::Tensor::from_vector(weights); + chunk_weights.reshape_({1, static_cast(weights.size())}); + hidden_states *= chunk_weights; + float new_mean = hidden_states.mean(); + if (std::isfinite(original_mean) && std::isfinite(new_mean) && new_mean != 0.0f) { + hidden_states *= (original_mean / new_mean); + } + + return hidden_states; +} + +void Conditioner::set_flash_attention_enabled(bool enabled) { + for_each_runner([enabled](GGMLRunner& runner) { runner.set_flash_attention_enabled(enabled); }); +} + +void Conditioner::set_linear_i8_enabled(bool enabled) { + for_each_runner([enabled](GGMLRunner& runner) { runner.set_linear_i8_enabled(enabled); }); +} diff --git a/src/conditioning/conditioner.h b/src/conditioning/conditioner.h new file mode 100644 index 0000000000..450914ddb4 --- /dev/null +++ b/src/conditioning/conditioner.h @@ -0,0 +1,139 @@ +#ifndef __SD_CONDITIONING_CONDITIONER_H__ +#define __SD_CONDITIONING_CONDITIONER_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "conditioning/prompt_input.h" +#include "core/tensor.hpp" +#include "ggml-backend.h" +#include "model/diffusion/minimax_h3_reference.hpp" + +struct GGMLRunner; +struct WeightAdapter; + +namespace sd { + struct TextualInversion; + Tensor apply_token_weights(Tensor hidden_states, const std::vector& weights); +} + +struct SDCondition { + sd::Tensor c_crossattn; + sd::Tensor c_vector; + sd::Tensor c_concat; + sd::Tensor c_t5_ids; + sd::Tensor c_t5_weights; + sd::Tensor c_input_ids; + sd::Tensor c_position_ids; + sd::Tensor c_token_types; + sd::Tensor c_vinput_mask; + std::vector>> c_image_embeds; + std::vector> c_ref_images; + std::vector> c_ref_audios; + std::vector c_reference_blocks; + + std::vector> extra_c_crossattns; + + SDCondition() = default; + + SDCondition(sd::Tensor c_crossattn, + sd::Tensor c_vector, + sd::Tensor c_concat) + : c_crossattn(std::move(c_crossattn)), c_vector(std::move(c_vector)), c_concat(std::move(c_concat)) {} + + bool empty() const { + if (!c_crossattn.empty() || !c_vector.empty() || !c_concat.empty() || + !c_t5_ids.empty() || !c_t5_weights.empty() || + !c_input_ids.empty() || !c_position_ids.empty() || + !c_token_types.empty() || !c_vinput_mask.empty()) { + return false; + } + + for (const auto& image_embed : c_image_embeds) { + if (!image_embed.second.empty()) { + return false; + } + } + + for (const auto& tensor : c_ref_images) { + if (!tensor.empty()) { + return false; + } + } + + for (const auto& tensor : c_ref_audios) { + if (!tensor.empty()) { + return false; + } + } + + for (const auto& tensor : extra_c_crossattns) { + if (!tensor.empty()) { + return false; + } + } + + return true; + } +}; + +enum class MiniMaxH3PresentationKind { + IMAGE, + VIDEO, + AUDIO, +}; + +struct MiniMaxH3PresentationItem { + MiniMaxH3PresentationKind kind = MiniMaxH3PresentationKind::IMAGE; + std::vector> frames; + std::vector timestamps; +}; + +struct ConditionerParams { + std::string text; + const sd::PromptInput* prompt_input = nullptr; + int clip_skip = -1; + int width = -1; + int height = -1; + bool zero_out_masked = false; + const std::vector>* ref_images = nullptr; // for qwen image edit + const std::vector* minimax_h3_references = nullptr; + std::optional system_prompt; + bool raw = false; + std::shared_ptr textual_inversion; +}; + +struct Conditioner { + virtual int resolve_clip_skip(int) const { return 0; } + virtual bool supports_prompt_images() const { return false; } + virtual size_t max_reference_images() const { return 0; } + virtual bool supports_multimodal_prompt() const { return false; } + virtual bool supports_prompt_formatting() const { return false; } + virtual ~Conditioner() = default; + +public: + virtual SDCondition get_learned_condition(int n_threads, + const ConditionerParams& conditioner_params) = 0; + virtual void get_param_tensors(std::map& tensors) = 0; + virtual void get_param_tensor_ops(std::map& tensor_ops) {} + virtual void set_max_graph_vram_bytes(size_t max_vram_bytes) {} + virtual void set_runtime_backends(const std::vector& backends) {} + virtual void set_graph_cut_layer_split_enabled(bool enabled) {} + virtual void set_graph_cut_layer_split_backend_vram_limits(const std::vector& limits) {} + virtual void get_layer_split_param_tensors(std::map& tensors) {} + virtual void for_each_runner(const std::function& visit) = 0; + void set_flash_attention_enabled(bool enabled); + void set_linear_i8_enabled(bool enabled); + virtual void set_scale_overrides(float linear_scale, float attn_scale) {} + virtual void set_weight_adapter(const std::shared_ptr& adapter) {} + virtual void runner_end() {} +}; + +#endif // __SD_CONDITIONING_CONDITIONER_H__ diff --git a/src/conditioning/conditioner.hpp b/src/conditioning/conditioner.hpp index 808375c4e6..38084593b9 100644 --- a/src/conditioning/conditioner.hpp +++ b/src/conditioning/conditioner.hpp @@ -3,14 +3,20 @@ #include #include +#include #include #include #include #include #include #include +#include "conditioning/conditioner.h" #include "conditioning/prompt_input.h" +#include "conditioning/prompt_templates.h" +#include "conditioning/textual_inversion.h" #include "core/ggml_tensor_utils.h" +#include "core/image_geometry.h" +#include "core/image_tensor.h" #include "core/tensor_ggml.hpp" #include "core/util.h" @@ -18,153 +24,13 @@ #include "model/te/clip.hpp" #include "model/te/llada_image_te.hpp" #include "model/te/llm.hpp" +#include "model/te/ltx_connector.hpp" #include "model/te/ming_image_te.hpp" -#include "model/te/ph3_image_connector.hpp" #include "model/te/t5.hpp" #include "model_loader.h" #include "tokenizers/sensenova_u1_tokenizer.h" #include "tokenizers/tokenizer_config.h" -struct SDCondition { - sd::Tensor c_crossattn; - sd::Tensor c_vector; - sd::Tensor c_concat; - sd::Tensor c_t5_ids; - sd::Tensor c_t5_weights; - sd::Tensor c_input_ids; - sd::Tensor c_position_ids; - sd::Tensor c_token_types; - sd::Tensor c_vinput_mask; - std::vector>> c_image_embeds; - std::vector> c_ref_images; - std::vector> c_ref_audios; - std::vector c_reference_blocks; - - std::vector> extra_c_crossattns; - - SDCondition() = default; - - SDCondition(sd::Tensor c_crossattn, - sd::Tensor c_vector, - sd::Tensor c_concat) - : c_crossattn(std::move(c_crossattn)), c_vector(std::move(c_vector)), c_concat(std::move(c_concat)) {} - - bool empty() const { - if (!c_crossattn.empty() || !c_vector.empty() || !c_concat.empty() || - !c_t5_ids.empty() || !c_t5_weights.empty() || - !c_input_ids.empty() || !c_position_ids.empty() || - !c_token_types.empty() || !c_vinput_mask.empty()) { - return false; - } - - for (const auto& image_embed : c_image_embeds) { - if (!image_embed.second.empty()) { - return false; - } - } - - for (const auto& tensor : c_ref_images) { - if (!tensor.empty()) { - return false; - } - } - - for (const auto& tensor : c_ref_audios) { - if (!tensor.empty()) { - return false; - } - } - - for (const auto& tensor : extra_c_crossattns) { - if (!tensor.empty()) { - return false; - } - } - - return true; - } -}; - -enum class MiniMaxH3PresentationKind { - IMAGE, - VIDEO, - AUDIO, -}; - -struct MiniMaxH3PresentationItem { - MiniMaxH3PresentationKind kind = MiniMaxH3PresentationKind::IMAGE; - std::vector> frames; - std::vector timestamps; -}; - -static inline sd::Tensor apply_token_weights(sd::Tensor hidden_states, - const std::vector& weights) { - if (hidden_states.empty()) { - return hidden_states; - } - - bool all_one = true; - for (float weight : weights) { - if (weight != 1.0f) { - all_one = false; - break; - } - } - if (all_one) { - return hidden_states; - } - - if (hidden_states.dim() == 1) { - hidden_states.unsqueeze_(1); - } - - GGML_ASSERT(static_cast(hidden_states.shape()[1]) == weights.size()); - - float original_mean = hidden_states.mean(); - auto chunk_weights = sd::Tensor::from_vector(weights); - chunk_weights.reshape_({1, static_cast(weights.size())}); - hidden_states *= chunk_weights; - float new_mean = hidden_states.mean(); - if (std::isfinite(original_mean) && std::isfinite(new_mean) && new_mean != 0.0f) { - hidden_states *= (original_mean / new_mean); - } - - return hidden_states; -} - -struct ConditionerParams { - std::string text; - const sd::PromptInput* prompt_input = nullptr; - int clip_skip = -1; - int width = -1; - int height = -1; - bool zero_out_masked = false; - const std::vector>* ref_images = nullptr; // for qwen image edit - const std::vector* minimax_h3_references = nullptr; - RefImageParams ref_image_params; -}; - -struct Conditioner { - virtual int resolve_clip_skip(int) const { return 0; } - virtual bool supports_prompt_images() const { return false; } - virtual ~Conditioner() = default; - -public: - virtual SDCondition get_learned_condition(int n_threads, - const ConditionerParams& conditioner_params) = 0; - virtual void get_param_tensors(std::map& tensors) = 0; - virtual void get_param_tensor_ops(std::map& tensor_ops) {} - virtual void set_max_graph_vram_bytes(size_t max_vram_bytes) {} - virtual void set_runtime_backends(const std::vector& backends) {} - virtual void set_graph_cut_layer_split_enabled(bool enabled) {} - virtual void set_graph_cut_layer_split_backend_vram_limits(const std::vector& limits) {} - virtual void get_layer_split_param_tensors(std::map& tensors) {} - virtual void set_flash_attention_enabled(bool enabled) = 0; - virtual void set_scale_overrides(float linear_scale, float attn_scale) {} - virtual void set_weight_adapter(const std::shared_ptr& adapter) {} - virtual void runner_end() {} -}; - // ldm.modules.encoders.modules.FrozenCLIPEmbedder // Ref: https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/cad87bf4e3e0b0a759afa94e933527c3123d59bc/modules/sd_hijack_clip.py#L283 struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { @@ -246,10 +112,10 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { } } - void set_flash_attention_enabled(bool enabled) override { - text_model->set_flash_attention_enabled(enabled); + void for_each_runner(const std::function& visit) override { + visit(*text_model); if (sd_version_is_sdxl(version)) { - text_model2->set_flash_attention_enabled(enabled); + visit(*text_model2); } } @@ -310,30 +176,8 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { ggml_type embd2_type = text_model2 ? text_model2->model.get_token_embed_weight()->type : embd_type; int64_t hidden_size = text_model->model.hidden_size; int64_t hidden_size2 = text_model2 ? text_model2->model.hidden_size : 0; - auto on_load = [&](const TensorStorage& tensor_storage, ggml_tensor** dst_tensor) { - if (tensor_storage.ne[0] == hidden_size) { - embd = ggml_new_tensor_2d(embd_ctx.get(), embd_type, hidden_size, tensor_storage.n_dims > 1 ? tensor_storage.ne[1] : 1); - if (embd == nullptr) { - return false; - } - *dst_tensor = embd; - } else if (text_model2) { - if (tensor_storage.ne[0] == hidden_size2) { - embd2 = ggml_new_tensor_2d(embd_ctx.get(), embd2_type, hidden_size2, tensor_storage.n_dims > 1 ? tensor_storage.ne[1] : 1); - if (embd2 == nullptr) { - return false; - } - *dst_tensor = embd2; - } else { - LOG_VERBOSE("embedding skipped, wrong hidden size, got %i, expected %i or %i", tensor_storage.ne[0], hidden_size, hidden_size2); - } - } else { - LOG_VERBOSE("embedding skipped, wrong hidden size, got %i, expected %i", tensor_storage.ne[0], hidden_size); - } - return true; - }; - model_loader.set_n_threads(1); - if (!model_loader.load_tensors(on_load)) { + if (!sd::read_textual_inversion(model_loader, embd_ctx.get(), hidden_size, hidden_size2, + embd_type, embd2_type, embd, embd2)) { LOG_ERROR("embedding '%s' failed", embd_name.c_str()); return false; } @@ -397,9 +241,14 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { } std::pair, std::vector> tokenize(std::string text, - size_t min_length = 0, - size_t max_length = 0, - bool allow_overflow_expand = true) { + size_t min_length = 0, + size_t max_length = 0, + bool allow_overflow_expand = true, + const sd::PromptInput* input = nullptr, + const sd::TextualInversion* inversion = nullptr) { + sd::PromptInputTemplate prompt_template(input); + if (input) + text = prompt_template.text; auto parsed_attention = parse_prompt_attention(text); { @@ -438,7 +287,20 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { } std::vector curr_tokens; - if (!tokenizer->encode(curr_text, curr_tokens, on_new_token_cb)) { + if (inversion) { + for (const auto& part : prompt_template.expand(curr_text)) { + if (part.type == sd::PromptPart::Type::TEXT) { + std::vector text_tokens; + if (!tokenizer->encode(part.content, text_tokens)) + return {}; + curr_tokens.insert(curr_tokens.end(), text_tokens.begin(), text_tokens.end()); + } else if (part.type == sd::PromptPart::Type::EMBEDDING) { + const auto& range = inversion->token_ranges.at(part.content); + for (int i = range.first; i < range.second; ++i) + curr_tokens.push_back(text_model->model.vocab_size + i); + } + } + } else if (!tokenizer->encode(curr_text, curr_tokens, on_new_token_cb)) { return {}; } tokens.insert(tokens.end(), curr_tokens.begin(), curr_tokens.end()); @@ -461,7 +323,8 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { int clip_skip, int width, int height, - bool zero_out_masked = false) { + bool zero_out_masked = false, + const sd::TextualInversion* inversion = nullptr) { int64_t t0 = ggml_time_ms(); sd::Tensor hidden_states; // [n_token, hidden_size] or [n_token, hidden_size + hidden_size2] sd::Tensor pooled; @@ -501,8 +364,11 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { max_token_idx, false, clip_skip, - false); - GGML_ASSERT(!chunk_hidden_states.empty()); + false, + inversion ? &inversion->first : nullptr); + if (chunk_hidden_states.empty()) { + return {}; + } if (sd_version_is_sdxl(version)) { auto chunk_hidden_states2 = text_model2->compute(n_threads, input_ids2, @@ -511,8 +377,11 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { max_token_idx, false, clip_skip, - false); - GGML_ASSERT(!chunk_hidden_states2.empty()); + false, + inversion ? &inversion->second : nullptr); + if (chunk_hidden_states2.empty()) { + return {}; + } chunk_hidden_states = sd::ops::concat(chunk_hidden_states, chunk_hidden_states2, 0); if (chunk_idx == 0) { @@ -523,14 +392,17 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { max_token_idx, true, clip_skip, - false); - GGML_ASSERT(!pooled.empty()); + false, + inversion ? &inversion->second : nullptr); + if (pooled.empty()) { + return {}; + } } } int64_t t1 = ggml_time_ms(); LOG_VERBOSE("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); - chunk_hidden_states = apply_token_weights(std::move(chunk_hidden_states), chunk_weights); + chunk_hidden_states = sd::apply_token_weights(std::move(chunk_hidden_states), chunk_weights); if (zero_out_masked) { chunk_hidden_states.fill_(0.0f); @@ -579,7 +451,11 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { SDCondition get_learned_condition(int n_threads, const ConditionerParams& conditioner_params) override { - auto tokens_and_weights = tokenize(conditioner_params.text, text_model->model.n_token, text_model->model.n_token, true); + const auto* inversion = conditioner_params.textual_inversion.get(); + if (inversion) + conditioner_params.textual_inversion->load(text_model->model.hidden_size, text_model2 ? text_model2->model.hidden_size : 0); + auto tokens_and_weights = tokenize(conditioner_params.text, text_model->model.n_token, text_model->model.n_token, true, + inversion ? conditioner_params.prompt_input : nullptr, inversion); if (tokens_and_weights.first.empty()) { return {}; } @@ -591,7 +467,7 @@ struct FrozenCLIPEmbedderWithCustomWords : public Conditioner { conditioner_params.clip_skip, conditioner_params.width, conditioner_params.height, - conditioner_params.zero_out_masked); + conditioner_params.zero_out_masked, inversion); } }; @@ -764,15 +640,15 @@ struct SD3CLIPEmbedder : public Conditioner { } } - void set_flash_attention_enabled(bool enabled) override { + void for_each_runner(const std::function& visit) override { if (clip_l) { - clip_l->set_flash_attention_enabled(enabled); + visit(*clip_l); } if (clip_g) { - clip_g->set_flash_attention_enabled(enabled); + visit(*clip_g); } if (t5) { - t5->set_flash_attention_enabled(enabled); + visit(*t5); } } @@ -959,8 +835,9 @@ struct SD3CLIPEmbedder : public Conditioner { false, clip_skip, false); - GGML_ASSERT(!chunk_hidden_states_l.empty()); - chunk_hidden_states_l = ::apply_token_weights(std::move(chunk_hidden_states_l), chunk_weights); + if (chunk_hidden_states_l.empty()) + return {}; + chunk_hidden_states_l = sd::apply_token_weights(std::move(chunk_hidden_states_l), chunk_weights); if (chunk_idx == 0) { auto it = std::find(chunk_tokens.begin(), chunk_tokens.end(), clip_l_tokenizer->EOS_TOKEN_ID); @@ -973,7 +850,8 @@ struct SD3CLIPEmbedder : public Conditioner { true, clip_skip, false); - GGML_ASSERT(!pooled_l.empty()); + if (pooled_l.empty()) + return {}; } } else { chunk_hidden_states_l = sd::Tensor::zeros({768, static_cast(chunk_len), 1}); @@ -1002,8 +880,9 @@ struct SD3CLIPEmbedder : public Conditioner { false, clip_skip, false); - GGML_ASSERT(!chunk_hidden_states_g.empty()); - chunk_hidden_states_g = ::apply_token_weights(std::move(chunk_hidden_states_g), chunk_weights); + if (chunk_hidden_states_g.empty()) + return {}; + chunk_hidden_states_g = sd::apply_token_weights(std::move(chunk_hidden_states_g), chunk_weights); if (chunk_idx == 0) { auto it = std::find(chunk_tokens.begin(), chunk_tokens.end(), clip_g_tokenizer->EOS_TOKEN_ID); @@ -1016,7 +895,8 @@ struct SD3CLIPEmbedder : public Conditioner { true, clip_skip, false); - GGML_ASSERT(!pooled_g.empty()); + if (pooled_g.empty()) + return {}; } } else { chunk_hidden_states_g = sd::Tensor::zeros({1280, static_cast(chunk_len), 1}); @@ -1039,8 +919,9 @@ struct SD3CLIPEmbedder : public Conditioner { input_ids, sd::Tensor(), false); - GGML_ASSERT(!chunk_hidden_states_t5.empty()); - chunk_hidden_states_t5 = ::apply_token_weights(std::move(chunk_hidden_states_t5), chunk_weights); + if (chunk_hidden_states_t5.empty()) + return {}; + chunk_hidden_states_t5 = sd::apply_token_weights(std::move(chunk_hidden_states_t5), chunk_weights); } else { chunk_hidden_states_t5 = sd::Tensor::zeros({4096, static_cast(chunk_len), 1}); } @@ -1063,7 +944,7 @@ struct SD3CLIPEmbedder : public Conditioner { } int64_t t1 = ggml_time_ms(); - LOG_VERBOSE("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); + LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); if (zero_out_masked) { chunk_hidden_states.fill_(0.0f); } @@ -1190,12 +1071,12 @@ struct FluxCLIPEmbedder : public Conditioner { } } - void set_flash_attention_enabled(bool enabled) override { + void for_each_runner(const std::function& visit) override { if (clip_l) { - clip_l->set_flash_attention_enabled(enabled); + visit(*clip_l); } if (t5) { - t5->set_flash_attention_enabled(enabled); + visit(*t5); } } @@ -1354,7 +1235,7 @@ struct FluxCLIPEmbedder : public Conditioner { LOG_ERROR("Flux T5 encoding failed at chunk %d/%zu", chunk_idx + 1, chunk_count); return {}; } - chunk_hidden_states = ::apply_token_weights(std::move(chunk_hidden_states), chunk_weights); + chunk_hidden_states = sd::apply_token_weights(std::move(chunk_hidden_states), chunk_weights); if (zero_out_masked) { chunk_hidden_states.fill_(0.0f); } @@ -1363,7 +1244,7 @@ struct FluxCLIPEmbedder : public Conditioner { } int64_t t1 = ggml_time_ms(); - LOG_VERBOSE("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); + LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); if (!hidden_states.empty()) { hidden_states = sd::ops::concat(hidden_states, chunk_hidden_states, 1); } else { @@ -1475,9 +1356,9 @@ struct T5CLIPEmbedder : public Conditioner { } } - void set_flash_attention_enabled(bool enabled) override { + void for_each_runner(const std::function& visit) override { if (t5) { - t5->set_flash_attention_enabled(enabled); + visit(*t5); } } @@ -1597,8 +1478,9 @@ struct T5CLIPEmbedder : public Conditioner { input_ids, t5_attn_mask_chunk, false); - GGML_ASSERT(!chunk_hidden_states.empty()); - chunk_hidden_states = apply_token_weights(std::move(chunk_hidden_states), chunk_weights); + if (chunk_hidden_states.empty()) + return {}; + chunk_hidden_states = sd::apply_token_weights(std::move(chunk_hidden_states), chunk_weights); if (zero_out_masked) { auto chunk_mask_tensor = sd::Tensor::from_vector(chunk_mask) @@ -1607,7 +1489,7 @@ struct T5CLIPEmbedder : public Conditioner { } int64_t t1 = ggml_time_ms(); - LOG_VERBOSE("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); + LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); if (!hidden_states.empty()) { hidden_states = sd::ops::concat(hidden_states, chunk_hidden_states, 1); @@ -1695,9 +1577,9 @@ struct MiniT2IConditioner : public Conditioner { } } - void set_flash_attention_enabled(bool enabled) override { + void for_each_runner(const std::function& visit) override { if (t5) { - t5->set_flash_attention_enabled(enabled); + visit(*t5); } } @@ -1732,14 +1614,8 @@ struct MiniT2IConditioner : public Conditioner { if (!tokenizer.encode(conditioner_params.text, tokens)) { return {}; } - if (tokens.size() > prompt_length) { - tokens.resize(prompt_length); - } - std::vector mask(tokens.size(), 1.0f); - while (tokens.size() < prompt_length) { - tokens.push_back(tokenizer.PAD_TOKEN_ID); - mask.push_back(0.0f); - } + std::vector mask; + tokenizer.pad_tokens(tokens, nullptr, &mask, prompt_length, prompt_length, false); sd::Tensor input_ids({static_cast(tokens.size())}, tokens); std::vector t5_mask(mask.size(), 0.0f); @@ -1750,7 +1626,8 @@ struct MiniT2IConditioner : public Conditioner { input_ids, sd::Tensor::from_vector(t5_mask), false); - GGML_ASSERT(!hidden_states.empty()); + if (hidden_states.empty()) + return {}; result.c_crossattn = std::move(hidden_states); result.c_vector = sd::Tensor::from_vector(mask); return result; @@ -1758,6 +1635,8 @@ struct MiniT2IConditioner : public Conditioner { }; struct SenseNovaU1Conditioner : public Conditioner { + bool supports_prompt_formatting() const override { return true; } + static constexpr size_t kMaxPromptTokens = 12288; SenseNovaU1Tokenizer tokenizer; @@ -1765,41 +1644,11 @@ struct SenseNovaU1Conditioner : public Conditioner { SD_UNUSED(tensors); } - void set_flash_attention_enabled(bool enabled) override { - SD_UNUSED(enabled); - } - - static std::string build_query(const std::string& text, bool is_negative) { - static const std::string kSystemMessage = - "You are an image generation and editing assistant that accurately understands and executes user intent.\n\n" - "You support two modes:\n\n1. Think Mode:\nIf the task requires reasoning, you MUST start with a " - " block. Put all reasoning inside the block using plain text. DO NOT include any image tags. " - "Keep it reasonable and directly useful for producing the final image.\n\n2. Non-Think Mode:\nIf no reasoning " - "is needed, directly produce the final image.\n\nTask Types:\n\nA. Text-to-Image Generation:\n- Generate a " - "high-quality image based on the user's description.\n- Ensure visual clarity, semantic consistency, and " - "completeness.\n- DO NOT introduce elements that contradict or override the user's intent.\n\nB. Image Editing:\n" - "- Use the provided image(s) as input or reference for modification or transformation.\n- The result can be an " - "edited image or a new image based on the reference(s).\n- Preserve all unspecified attributes unless explicitly " - "changed.\n\nGeneral Rules:\n- For any visible text in the image, follow the language specified for the rendered " - "text in the user's description, not the language of the prompt. If no language is specified, use the user's input " - "language."; + void for_each_runner(const std::function&) override {} - std::string query; - if (!is_negative) { - query += "<|im_start|>system\n"; - query += kSystemMessage; - query += "<|im_end|>\n"; - } - query += "<|im_start|>user\n"; - query += text; - query += "<|im_end|>\n<|im_start|>assistant\n"; - query += is_negative ? "" : "\n\n\n\n"; - return query; - } - - SDCondition tokenize_condition(const std::string& text, bool is_negative) { + SDCondition tokenize_condition(const std::string& text) { std::vector tokens; - if (!tokenizer.encode(build_query(text, is_negative), tokens)) { + if (!tokenizer.encode(text, tokens)) { return {}; } if (tokens.empty() || tokens.size() > kMaxPromptTokens) { @@ -1817,15 +1666,14 @@ struct SenseNovaU1Conditioner : public Conditioner { SDCondition get_learned_condition(int n_threads, const ConditionerParams& conditioner_params) override { SD_UNUSED(n_threads); - return tokenize_condition(conditioner_params.text, false); - } - - SDCondition get_unconditional_condition(const std::string& text) { - return tokenize_condition(text, true); + return tokenize_condition(conditioner_params.raw ? conditioner_params.text + : sd::prompt_templates::sensenova_u1(conditioner_params.text, conditioner_params.system_prompt)); } }; struct AnimaConditioner : public Conditioner { + bool supports_prompt_formatting() const override { return true; } + std::shared_ptr qwen_tokenizer; T5UniGramTokenizer t5_tokenizer; std::shared_ptr llm; @@ -1874,8 +1722,8 @@ struct AnimaConditioner : public Conditioner { llm->get_param_tensors(tensors, "text_encoders.llm"); } - void set_flash_attention_enabled(bool enabled) override { - llm->set_flash_attention_enabled(enabled); + void for_each_runner(const std::function& visit) override { + visit(*llm); } void set_scale_overrides(float linear_scale, float attn_scale) override { @@ -1890,8 +1738,8 @@ struct AnimaConditioner : public Conditioner { llm->runner_end(); } - std::tuple, std::vector, std::vector, std::vector> tokenize(std::string text) { - auto parsed_attention = parse_prompt_attention(text); + std::tuple, std::vector, std::vector, std::vector> tokenize(std::string text, bool raw = false, const std::optional& system = std::nullopt) { + auto parsed_attention = raw ? std::vector>{{text, 1.f}} : parse_prompt_attention(text); { std::stringstream ss; @@ -1908,6 +1756,11 @@ struct AnimaConditioner : public Conditioner { std::vector t5_tokens; std::vector t5_weights; + if (!raw && system && !system->empty()) { + if (!qwen_tokenizer->encode(sd::prompt_templates::with_system("", system), qwen_tokens)) + return {}; + qwen_weights.assign(qwen_tokens.size(), 1.f); + } for (const auto& item : parsed_attention) { const std::string& curr_text = item.first; std::vector curr_tokens; @@ -1942,7 +1795,7 @@ struct AnimaConditioner : public Conditioner { const ConditionerParams& conditioner_params) override { int64_t t0 = ggml_time_ms(); - auto tokenized = tokenize(conditioner_params.text); + auto tokenized = tokenize(conditioner_params.text, conditioner_params.raw, conditioner_params.system_prompt); auto& qwen_tokens = std::get<0>(tokenized); auto& qwen_weights = std::get<1>(tokenized); auto& t5_tokens = std::get<2>(tokenized); @@ -1960,13 +1813,14 @@ struct AnimaConditioner : public Conditioner { {}, false, false); - GGML_ASSERT(!hidden_states.empty()); - hidden_states = apply_token_weights(std::move(hidden_states), qwen_weights); + if (hidden_states.empty()) + return {}; + hidden_states = sd::apply_token_weights(std::move(hidden_states), qwen_weights); auto t5_ids_tensor = sd::Tensor::from_vector(t5_tokens); auto t5_weight_tensor = sd::Tensor::from_vector(t5_weights); int64_t t1 = ggml_time_ms(); - LOG_VERBOSE("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); + LOG_INFO("computing condition graph completed, taking %" PRId64 " ms", t1 - t0); SDCondition result; result.c_crossattn = std::move(hidden_states); @@ -1976,1649 +1830,142 @@ struct AnimaConditioner : public Conditioner { } }; -struct LLMEmbedder : public Conditioner { - SDVersion version; - std::shared_ptr tokenizer; - std::shared_ptr llm; - std::shared_ptr byt5; - std::shared_ptr ph3_connector; +struct MingImageEmbedder : public Conditioner { + bool supports_prompt_formatting() const override { return true; } - bool supports_prompt_images() const override { - return llm->supports_prompt_images(); - } + std::shared_ptr tokenizer; + std::shared_ptr text_model; + const std::string prefix = "text_encoders"; - LLMEmbedder(ggml_backend_t backend, - const String2TensorStorage& tensor_storage_map = {}, - SDVersion version = VERSION_QWEN_IMAGE, - const std::string prefix = "", - bool enable_vision = false, - std::shared_ptr weight_manager = nullptr, - const TokenizerConfig& tokenizers = {}) - : version(version) { + MingImageEmbedder(ggml_backend_t backend, const String2TensorStorage& tensors, std::shared_ptr weight_manager, const TokenizerConfig& tokenizers) { if (!tokenizers.has(TokenizerConfig::MAIN)) { - if (sd_version_is_lens(version)) { - throw std::runtime_error("Lens requires an external GPT-OSS tokenizer.json; pass --tokenizer FILE or set the tokenizer context option"); - } - if (sd_version_is_pid(version)) { - throw std::runtime_error("PiD requires an external Gemma 2 tokenizer.json; pass --tokenizer FILE or set the tokenizer context option"); - } - if (version == VERSION_MOSS_IMAGE) { - throw std::runtime_error("MOSS-Image requires the official Qwen3.5 tokenizer.json; pass --tokenizer FILE or set the tokenizer context option"); - } - } - LLM::LLMArch arch = LLM::LLMArch::QWEN2_5_VL; - if (version == VERSION_FLUX2) { - arch = LLM::LLMArch::MISTRAL_SMALL_3_2; - } else if (sd_version_is_ernie_image(version)) { - arch = LLM::LLMArch::MINISTRAL_3_3B; - } else if (sd_version_is_lens(version)) { - arch = LLM::LLMArch::GPT_OSS_20B; - } else if (sd_version_is_pid(version)) { - arch = LLM::LLMArch::GEMMA2_2B; - } else if (version == VERSION_FIBO2 || - version == VERSION_QWEN_IMAGE_2_1 || - sd_version_is_flux3(version) || - sd_version_is_lingbot_video(version) || - sd_version_is_ideogram4(version) || - sd_version_is_boogu_image(version) || - sd_version_is_sefi_image(version) || - sd_version_is_krea2(version) || - sd_version_is_minimax_h3(version) || - sd_version_is_mage_flow(version) || - version == VERSION_IRIS) { - arch = LLM::LLMArch::QWEN3_VL; - } else if (sd_version_is_z_image(version) || sd_version_is_z_image_l2p(version) || version == VERSION_OVIS_IMAGE || version == VERSION_FLUX2_KLEIN) { - arch = LLM::LLMArch::QWEN3; - } else if (version == VERSION_MOSS_IMAGE) { - arch = LLM::LLMArch::QWEN3_5; - } - if (arch == LLM::LLMArch::QWEN2_5_VL || arch == LLM::LLMArch::QWEN3_VL || arch == LLM::LLMArch::QWEN3_5) { - for (const auto& entry : tensor_storage_map) { - if (starts_with(entry.first, "text_encoders.llm.visual.")) { - enable_vision = true; - break; - } - } - } - llm = std::make_shared(arch, - backend, - tensor_storage_map, - "text_encoders.llm", - enable_vision, - weight_manager); - if (sd_version_is_minimax_h3(version)) { - const bool has_ph3_connector = tensor_storage_map.count(std::string(PH3ImageTextConnectorRunner::prefix) + ".proj.weight") != 0; - if (has_ph3_connector) { - if (llm->config.num_layers != 36 || llm->config.hidden_size != 2560) { - throw std::runtime_error("The P-H3-Image text connector requires the Qwen3-VL-4B text encoder"); - } - ph3_connector = std::make_shared(backend, tensor_storage_map, weight_manager); - } else if (llm->config.hidden_size == 2560) { - throw std::runtime_error( - sd_format("%s with Qwen3-VL-4B requires the P-H3-Image text connector; " - "pass it with --embeddings-connectors or use the MiniMax-H3 Qwen3-VL-32B text encoder", - sd_version_name(version))); - } else if (llm->config.hidden_size != 5120 || (llm->config.num_layers != 50 && llm->config.num_layers != 64)) { - throw std::runtime_error( - sd_format("%s requires the MiniMax-H3 Qwen3-VL-32B text encoder or Qwen3-VL-4B with the P-H3-Image text connector", - sd_version_name(version))); - } - } - int pad_id = 151643; - if (arch == LLM::LLMArch::MISTRAL_SMALL_3_2 || arch == LLM::LLMArch::MINISTRAL_3_3B) { - pad_id = 11; - } else if (arch == LLM::LLMArch::GPT_OSS_20B) { - pad_id = 199999; - } else if (arch == LLM::LLMArch::GEMMA2_2B) { - pad_id = 0; - } else if (arch == LLM::LLMArch::QWEN3_5) { - pad_id = 248044; - } - tokenizer = tokenizers.create(TokenizerConfig::MAIN, llm->config.vocab_size, pad_id); - if (!tokenizer) { - if (arch == LLM::LLMArch::MISTRAL_SMALL_3_2 || arch == LLM::LLMArch::MINISTRAL_3_3B) { - tokenizer = std::make_shared(); - } else { - tokenizer = std::make_shared(); - } - } - if (sd_version_is_hunyuan_video(version)) { - const std::string byt5_prefix = "text_encoders.t5xxl.transformer"; - for (const auto& [name, _] : tensor_storage_map) { - if (starts_with(name, byt5_prefix + ".")) { - byt5 = std::make_shared(backend, - tensor_storage_map, - byt5_prefix, - false, - weight_manager); - break; - } - } + throw std::runtime_error("Ming-Image requires the Ling tokenizer.json; pass --tokenizer FILE"); } + text_model = std::make_shared(backend, tensors, prefix, weight_manager); + tokenizer = tokenizers.create(TokenizerConfig::MAIN, text_model->config.backbone.vocab_size, 156895); } void get_param_tensors(std::map& tensors) override { - llm->get_param_tensors(tensors, "text_encoders.llm"); - if (ph3_connector) { - ph3_connector->get_param_tensors(tensors); - } - if (byt5) { - byt5->get_param_tensors(tensors, "text_encoders.t5xxl.transformer"); - } + text_model->get_param_tensors(tensors, prefix); } - - void get_param_tensor_ops(std::map& tensor_ops) override { - llm->get_param_tensor_ops(tensor_ops); + void get_param_tensor_ops(std::map& ops) override { + text_model->get_param_tensor_ops(ops); } - - void set_max_graph_vram_bytes(size_t max_vram_bytes) override { - llm->set_max_graph_vram_bytes(max_vram_bytes); - if (ph3_connector) { - ph3_connector->set_max_graph_vram_bytes(max_vram_bytes); - } - if (byt5) { - byt5->set_max_graph_vram_bytes(max_vram_bytes); - } + void get_layer_split_param_tensors(std::map& tensors) override { + text_model->get_param_tensors(tensors, prefix); } + void for_each_runner(const std::function& visit) override { visit(*text_model); } + void set_max_graph_vram_bytes(size_t bytes) override { text_model->set_max_graph_vram_bytes(bytes); } + void set_runtime_backends(const std::vector& backends) override { text_model->set_runtime_backends(backends); } + void set_graph_cut_layer_split_enabled(bool enabled) override { text_model->set_graph_cut_layer_split_enabled(enabled); } + void set_graph_cut_layer_split_backend_vram_limits(const std::vector& limits) override { text_model->set_graph_cut_layer_split_backend_vram_limits(limits); } + void set_scale_overrides(float linear, float attention) override { text_model->set_scale_overrides(linear, attention); } + void set_weight_adapter(const std::shared_ptr& adapter) override { text_model->set_weight_adapter(adapter); } + void runner_end() override { text_model->runner_end(); } - void set_runtime_backends(const std::vector& backends) override { - llm->set_runtime_backends(backends); - if (ph3_connector) { - ph3_connector->set_runtime_backends(backends); + SDCondition get_learned_condition(int n_threads, const ConditionerParams& input) override { + if (input.ref_images != nullptr && !input.ref_images->empty()) { + LOG_ERROR("Ming-Image currently supports text-to-image only"); + return {}; } - if (byt5) { - byt5->set_runtime_backends(backends); + std::string prompt = sd::prompt_templates::ming_image(input.text, input.system_prompt, input.raw); + std::vector tokens; + if (!tokenizer->encode(prompt, tokens, nullptr) || tokens.empty()) { + return {}; } - } - - void set_graph_cut_layer_split_enabled(bool enabled) override { - if (llm) { - llm->set_graph_cut_layer_split_enabled(enabled); + if (tokens.size() + 258 > 32768) { + LOG_ERROR("Ming-Image prompt exceeds the text encoder context length"); + return {}; } - if (byt5) { - byt5->set_graph_cut_layer_split_enabled(enabled); + auto output = text_model->compute(n_threads, tokens); + if (output.empty()) { + return {}; } + SDCondition result; + result.c_crossattn = sd::ops::slice(sd::ops::slice(output, 1, 0, 256), 0, 0, text_model->config.caption_dim); + result.extra_c_crossattns.push_back(sd::ops::slice(output, 1, 256, output.shape()[1])); + return result; } +}; - void set_graph_cut_layer_split_backend_vram_limits(const std::vector& limits) override { - if (llm) { - llm->set_graph_cut_layer_split_backend_vram_limits(limits); - } - if (byt5) { - byt5->set_graph_cut_layer_split_backend_vram_limits(limits); - } - } +struct LTXAVTextProjection : public GGMLBlock { + static constexpr int64_t kHiddenSize = 3840; + static constexpr int64_t kNumStates = 49; + bool dual_projection = false; - void get_layer_split_param_tensors(std::map& tensors) override { - llm->get_param_tensors(tensors, "text_encoders.llm"); - if (byt5) { - byt5->get_param_tensors(tensors, "text_encoders.t5xxl.transformer"); + LTXAVTextProjection(bool dual_projection = false) + : dual_projection(dual_projection) { + if (dual_projection) { + blocks["video_aggregate_embed"] = std::make_shared(kHiddenSize * kNumStates, 4096, true); + blocks["audio_aggregate_embed"] = std::make_shared(kHiddenSize * kNumStates, 2048, true); + } else { + blocks["projection"] = std::make_shared(kHiddenSize * kNumStates, kHiddenSize, false); } } - void set_flash_attention_enabled(bool enabled) override { - llm->set_flash_attention_enabled(enabled); - if (ph3_connector) { - ph3_connector->set_flash_attention_enabled(enabled); - } - if (byt5) { - byt5->set_flash_attention_enabled(enabled); + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) { + if (!dual_projection) { + auto projection = std::dynamic_pointer_cast(blocks["projection"]); + return projection->forward(ctx, x); } + + auto video_projection = std::dynamic_pointer_cast(blocks["video_aggregate_embed"]); + auto audio_projection = std::dynamic_pointer_cast(blocks["audio_aggregate_embed"]); + auto video_in = ggml_ext_scale(ctx, x, std::sqrt(4096.f / static_cast(kHiddenSize))); + auto audio_in = ggml_ext_scale(ctx, x, std::sqrt(2048.f / static_cast(kHiddenSize))); + auto video = video_projection->forward(ctx, video_in); + auto audio = audio_projection->forward(ctx, audio_in); + return ggml_concat(ctx->ggml_ctx, video, audio, 0); } +}; - void set_scale_overrides(float linear_scale, float attn_scale) override { - llm->set_scale_overrides(linear_scale, attn_scale); - if (ph3_connector) { - ph3_connector->set_scale_overrides(linear_scale, attn_scale); - } - if (byt5) { - byt5->set_scale_overrides(linear_scale, attn_scale); - } +struct LTXAVTextProjectionRunner : public GGMLRunner { + LTXAVTextProjection model; + + LTXAVTextProjectionRunner(ggml_backend_t backend, + const String2TensorStorage& tensor_storage_map = {}, + const std::string& prefix = "", + std::shared_ptr weight_manager = nullptr) + : GGMLRunner(backend, weight_manager), + model(tensor_storage_map.find(prefix + ".video_aggregate_embed.weight") != tensor_storage_map.end()) { + model.init(params_ctx, tensor_storage_map, prefix); } - void set_weight_adapter(const std::shared_ptr& adapter) override { - if (ph3_connector) { - ph3_connector->set_weight_adapter(adapter); - } - if (llm) { - llm->set_weight_adapter(adapter); - } - if (byt5) { - byt5->set_weight_adapter(adapter); - } + std::string get_desc() override { + return "ltxav_text_projection"; } - void runner_end() override { - if (ph3_connector) { - ph3_connector->runner_end(); - } - if (llm) { - llm->runner_end(); - } - if (byt5) { - byt5->runner_end(); - } + void get_param_tensors(std::map& tensors, const std::string& prefix) { + model.get_param_tensors(tensors, prefix); } - static std::vector> parse_text_attention(const std::string& text, - const std::pair& attn_range, - bool spell_quotes) { - std::vector> parsed_attention; - if (attn_range.first >= 0 && attn_range.second > 0) { - if (attn_range.first > 0) { - parsed_attention.emplace_back(text.substr(0, attn_range.first), 1.f); - } - if (attn_range.second - attn_range.first > 0) { - auto new_parsed_attention = parse_prompt_attention(text.substr(attn_range.first, attn_range.second - attn_range.first)); - if (spell_quotes) { - new_parsed_attention = split_quotation_attention(new_parsed_attention); - } - parsed_attention.insert(parsed_attention.end(), - new_parsed_attention.begin(), - new_parsed_attention.end()); - } - if (attn_range.second < text.size()) { - parsed_attention.emplace_back(text.substr(attn_range.second), 1.f); - } - } else { - parsed_attention.emplace_back(text, 1.f); - } + ggml_cgraph* build_graph(const sd::Tensor& x_tensor) { + ggml_cgraph* gf = ggml_new_graph(compute_ctx); + auto x = make_input(x_tensor); + auto runner_ctx = get_context(); + auto out = model.forward(&runner_ctx, x); + ggml_build_forward_expand(gf, out); + return gf; + } - return parsed_attention; + sd::Tensor compute(int n_threads, + const sd::Tensor& x, + bool auto_runner_end = true) { + auto get_graph = [&]() -> ggml_cgraph* { + return build_graph(x); + }; + return take_or_empty(GGMLRunner::compute(get_graph, n_threads, auto_runner_end)); } +}; - std::tuple, std::vector, std::vector> tokenize(std::string text, - const std::pair& attn_range, - size_t min_length = 0, - size_t max_length = 100000000, - bool spell_quotes = false, - const std::string& suffix = "", - const std::vector>>& image_embeds = {}) { - auto parsed_attention = parse_text_attention(text, attn_range, spell_quotes); +// LLaDA-Image's text path is a three-stage pipeline rather than a single encoder pass: +// the token embeddings feed a QueryFormer whose 256 queries are appended to the backbone +// input, and the backbone's final hidden states are projected to the denoiser's caption dim. +// Ref: LLaDAImagePipeline._encode_text. +struct LLaDAImageEmbedder : public Conditioner { + bool supports_prompt_formatting() const override { return true; } + size_t max_reference_images() const override { return sigvq ? 1 : 0; } - { - std::stringstream ss; - ss << "["; - for (const auto& item : parsed_attention) { - ss << "['" << item.first << "', " << item.second << "], "; - } - ss << "]"; - LOG_VERBOSE("parse '%s' to %s", escape_newlines(text).c_str(), escape_newlines(ss.str()).c_str()); - } - - std::vector tokens; - std::vector weights; - for (const auto& item : parsed_attention) { - const std::string& curr_text = item.first; - float curr_weight = item.second; - std::vector curr_tokens; - if (!tokenizer->encode(curr_text, curr_tokens, nullptr)) { - return {}; - } - tokens.insert(tokens.end(), curr_tokens.begin(), curr_tokens.end()); - weights.insert(weights.end(), curr_tokens.size(), curr_weight); - } - - for (const auto& image_embed : image_embeds) { - const int index = image_embed.first; - const int64_t count = image_embed.second.shape()[1]; - if (index < 0 || static_cast(index) >= tokens.size() || count < 1) { - LOG_ERROR("Invalid reference image token range"); - return {}; - } - const int token = tokens[index]; - const float weight = weights[index]; - tokens.insert(tokens.begin() + index, count - 1, token); - weights.insert(weights.begin() + index, count - 1, weight); - } - - if (!suffix.empty()) { - std::vector suffix_tokens; - if (!tokenizer->encode(suffix, suffix_tokens) || suffix_tokens.size() >= max_length) { - return {}; - } - // Reserve the assistant-turn marker before truncating the caption. - if (tokens.size() > max_length - suffix_tokens.size()) { - tokens.resize(max_length - suffix_tokens.size()); - weights.resize(tokens.size()); - } - tokens.insert(tokens.end(), suffix_tokens.begin(), suffix_tokens.end()); - weights.insert(weights.end(), suffix_tokens.size(), 1.f); - } - - if (sd_version_is_flux3(version)) { - min_length = std::min(max_length, ((tokens.size() + 79) / 80) * 80); - } - std::vector mask; - tokenizer->pad_tokens(tokens, &weights, &mask, min_length, max_length); - - // Keep masks and weights in expanded coordinates, but only look up one token per image. - for (auto it = image_embeds.rbegin(); it != image_embeds.rend(); ++it) { - const int64_t begin = it->first; - const int64_t end = begin + it->second.shape()[1]; - if (begin < 0 || end > static_cast(tokens.size())) { - LOG_ERROR("Reference image exceeds the tokenized context"); - return {}; - } - tokens.erase(tokens.begin() + begin + 1, tokens.begin() + end); - } - - // for (int i = 0; i < tokens.size(); i++) { - // std::cout << tokens[i] << ":" << weights[i] << ", " << i << std::endl; - // } - // std::cout << std::endl; - - return {tokens, weights, mask}; - } - - bool prepare_prompt_tokens(int n_threads, - const sd::PromptInputTemplate& input_template, - const std::string& prompt, - const std::pair& attn_range, - int min_length, - int max_length, - bool spell_quotes, - const std::string& suffix, - const LLM::ImageEmbeds& images, - const LLM::DeepStackImageEmbeds& deepstack, - const std::vector& grids, - LLM::PromptTokens& result) { - sd::PromptInput input; - auto text = parse_text_attention(prompt, attn_range, spell_quotes); - text.emplace_back(suffix, 1.f); - for (const auto& span : text) { - auto parts = input_template.expand(span.first, span.second); - input.insert(input.end(), std::make_move_iterator(parts.begin()), std::make_move_iterator(parts.end())); - } - max_length = std::min(max_length, static_cast(llm->config.max_position_embeddings)); - if (!llm->prepare_prompt(n_threads, *tokenizer, input, max_length, result, images, deepstack, grids)) { - return false; - } - auto expanded = result.tokens; - for (const auto& image : result.image_embeds) { - expanded.insert(expanded.begin() + image.first, image.second.shape()[1] - 1, expanded[image.first]); - } - if (sd_version_is_flux3(version)) { - min_length = std::min(max_length, ((result.expanded_length + 79) / 80) * 80); - } - tokenizer->pad_tokens(expanded, &result.weights, &result.mask, min_length, max_length); - const int leading_padding = static_cast(std::find(result.mask.begin(), result.mask.end(), 1.f) - result.mask.begin()); - for (auto& image : result.image_embeds) { - image.first += leading_padding; - } - for (auto& layer : result.deepstack_image_embeds) { - for (auto& image : layer) { - image.first += leading_padding; - } - } - for (auto& grid : result.image_grids) { - grid.index += leading_padding; - } - for (auto it = result.image_embeds.rbegin(); it != result.image_embeds.rend(); ++it) { - expanded.erase(expanded.begin() + it->first + 1, expanded.begin() + it->first + it->second.shape()[1]); - } - result.tokens = std::move(expanded); - result.expanded_length = static_cast(result.weights.size()); - return true; - } - - sd::Tensor encode_prompt(int n_threads, - const std::string prompt, - const std::pair& prompt_attn_range, - int min_length, - int hidden_states_min_length, - const std::vector>>& image_embeds, - const std::set& out_layers, - int prompt_template_encode_start_idx, - bool spell_quotes = false, - int max_length = 100000000, - const LLM::DeepStackImageEmbeds& deepstack_image_embeds = {}, - const std::vector& image_grids = {}, - const std::string& prompt_suffix = "", - sd::Tensor* output_mask = nullptr, - const sd::PromptInputTemplate* input_template = nullptr, - LLM::PromptTokens* output_prompt_tokens = nullptr) { - LLM::PromptTokens prepared; - if (input_template != nullptr && - !prepare_prompt_tokens(n_threads, *input_template, prompt, prompt_attn_range, min_length, max_length, - spell_quotes, prompt_suffix, image_embeds, deepstack_image_embeds, image_grids, prepared)) { - return {}; - } - auto tokens_weights_mask = input_template == nullptr - ? tokenize(prompt, prompt_attn_range, min_length, max_length, spell_quotes, prompt_suffix, image_embeds) - : std::make_tuple(prepared.tokens, prepared.weights, prepared.mask); - auto& tokens = std::get<0>(tokens_weights_mask); - auto& weights = std::get<1>(tokens_weights_mask); - auto& mask = std::get<2>(tokens_weights_mask); - - if (tokens.empty()) { - return {}; - } - - sd::Tensor input_ids({static_cast(tokens.size())}, tokens); - sd::Tensor attention_mask; - if (!mask.empty()) { - attention_mask = sd::Tensor({static_cast(mask.size()), static_cast(mask.size())}); - const float masked_attention_value = -std::numeric_limits::max() / 4.0f; - for (size_t i1 = 0; i1 < mask.size(); ++i1) { - for (size_t i0 = 0; i0 < mask.size(); ++i0) { - float value = 0.0f; - if (mask[i0] == 0.0f) { - value += masked_attention_value; - } - if (i0 > i1) { - value += masked_attention_value; - } - attention_mask[static_cast(i0 + mask.size() * i1)] = value; - } - } - } - - sd::Tensor position_ids; - if (sd_version_is_flux3(version)) { - position_ids = sd::Tensor::zeros({static_cast(weights.size() * 4)}); - if (input_template != nullptr) { - position_ids.values() = LLM::LLMRunner::build_position_ids(llm->config, weights.size(), prepared.image_grids); - } - for (size_t axis = 0; axis < 4; ++axis) { - for (size_t i = 0; i < weights.size(); ++i) { - position_ids[axis * weights.size() + i] = mask[i] == 0.f ? 1 : (input_template == nullptr ? static_cast(i) : position_ids[axis * weights.size() + i]); - } - } - } - auto hidden_states = llm->compute(n_threads, - input_ids, - attention_mask, - input_template == nullptr ? image_embeds : prepared.image_embeds, - out_layers, - false, - false, - input_template == nullptr ? deepstack_image_embeds : prepared.deepstack_image_embeds, - input_template == nullptr ? image_grids : prepared.image_grids, - position_ids); - if (hidden_states.empty()) { - LOG_ERROR("LLM prompt encoding failed"); - return {}; - } - if (ph3_connector) { - hidden_states = ph3_connector->compute(n_threads, hidden_states); - if (hidden_states.empty()) { - return {}; - } - } - hidden_states = apply_token_weights(std::move(hidden_states), weights); - GGML_ASSERT(hidden_states.shape()[1] > prompt_template_encode_start_idx); - - int64_t zero_pad_len = 0; - if (hidden_states_min_length > 0) { - if (hidden_states.shape()[1] - prompt_template_encode_start_idx < hidden_states_min_length) { - zero_pad_len = hidden_states_min_length - hidden_states.shape()[1] + prompt_template_encode_start_idx; - } - } - - sd::Tensor new_hidden_states = sd::ops::slice(hidden_states, - 1, - prompt_template_encode_start_idx, - hidden_states.shape()[1]); - if (zero_pad_len > 0) { - auto pad_shape = new_hidden_states.shape(); - pad_shape[1] = zero_pad_len; - new_hidden_states = sd::ops::concat(new_hidden_states, - sd::Tensor::zeros(std::move(pad_shape)), - 1); - } - - if (output_mask != nullptr) { - *output_mask = sd::Tensor::zeros({new_hidden_states.shape()[1]}); - for (size_t i = prompt_template_encode_start_idx; i < mask.size(); ++i) { - output_mask->data()[i - prompt_template_encode_start_idx] = mask[i]; - } - } - if (output_prompt_tokens != nullptr && input_template != nullptr) { - *output_prompt_tokens = std::move(prepared); - } - return new_hidden_states; - } - - void resize_image_dims(int height, int width, int& h_bar, int& w_bar, int factor, int min_size, int max_size, RefImageResizeMode mode) { - if (min_size > 0 && min_size == max_size) { - if (mode == RefImageResizeMode::AREA) { - double beta = std::sqrt(static_cast(min_size) / (static_cast(height) * width)); - h_bar = std::max(static_cast(factor), - static_cast(std::round(height * beta / factor)) * static_cast(factor)); - w_bar = std::max(static_cast(factor), - static_cast(std::round(width * beta / factor)) * static_cast(factor)); - } else if (mode == RefImageResizeMode::LONGEST_SIDE) { - int current_max_side = std::max(height, width); - double beta = static_cast(min_size) / current_max_side; - h_bar = std::max(static_cast(factor), - static_cast(std::round(height * beta / factor)) * static_cast(factor)); - w_bar = std::max(static_cast(factor), - static_cast(std::round(width * beta / factor)) * static_cast(factor)); - } - return; - } - - if (mode == RefImageResizeMode::AREA) { - double current_area = static_cast(h_bar) * w_bar; - if (max_size > 0 && current_area > max_size) { - double beta = std::sqrt((static_cast(height) * width) / static_cast(max_size)); - h_bar = std::max(static_cast(factor), - static_cast(std::floor(height / beta / factor)) * static_cast(factor)); - w_bar = std::max(static_cast(factor), - static_cast(std::floor(width / beta / factor)) * static_cast(factor)); - } else if (min_size > 0 && current_area < min_size) { - double beta = std::sqrt(static_cast(min_size) / (static_cast(height) * width)); - h_bar = static_cast(std::ceil(height * beta / factor)) * static_cast(factor); - w_bar = static_cast(std::ceil(width * beta / factor)) * static_cast(factor); - } - } else if (mode == RefImageResizeMode::LONGEST_SIDE) { - int current_max_side = std::max(height, width); - if (max_size > 0 && current_max_side > max_size) { - double beta = static_cast(max_size) / current_max_side; - h_bar = std::max(static_cast(factor), - static_cast(std::floor(height * beta / factor)) * static_cast(factor)); - w_bar = std::max(static_cast(factor), - static_cast(std::floor(width * beta / factor)) * static_cast(factor)); - } else if (min_size > 0 && current_max_side < min_size) { - double beta = static_cast(min_size) / current_max_side; - h_bar = static_cast(std::ceil(height * beta / factor)) * static_cast(factor); - w_bar = static_cast(std::ceil(width * beta / factor)) * static_cast(factor); - } - } - } - - bool expand_vision_marker(const std::string& prompt, - size_t& marker_start, - std::vector> outputs, - int grid_h, - int grid_w, - std::vector>>& image_embeds, - LLM::DeepStackImageEmbeds& deepstack_image_embeds, - std::vector& image_grids, - int max_length = std::numeric_limits::max()) { - if (outputs.empty()) { - return false; - } - const std::string placeholder = "<|image_pad|>"; - size_t position = prompt.find(placeholder, marker_start); - if (position == std::string::npos) { - LOG_ERROR("Reference image marker is missing"); - return false; - } - std::vector prefix_tokens; - if (!tokenizer->encode(prompt.substr(0, position), prefix_tokens, nullptr)) { - return false; - } - int index = static_cast(prefix_tokens.size()); - for (const auto& image_embed : image_embeds) { - index += static_cast(image_embed.second.shape()[1]) - 1; - } - int count = static_cast(outputs[0].shape()[1]); - if (index > max_length || count > max_length - index) { - LOG_ERROR("Reference images exceed the %d-token context", max_length); - return false; - } - if (deepstack_image_embeds.empty()) { - deepstack_image_embeds.resize(outputs.size() - 1); - } - GGML_ASSERT(deepstack_image_embeds.size() == outputs.size() - 1); - image_embeds.emplace_back(index, std::move(outputs[0])); - for (size_t layer = 1; layer < outputs.size(); ++layer) { - deepstack_image_embeds[layer - 1].emplace_back(index, std::move(outputs[layer])); - } - image_grids.push_back({index, count, grid_h, grid_w}); - marker_start = position + placeholder.size(); - return true; - } - - SDCondition get_learned_condition(int n_threads, - const ConditionerParams& params) override { - ConditionerParams conditioner_params = params; - sd::PromptInputTemplate input_template(params.prompt_input); - if (params.prompt_input != nullptr) { - if (!supports_prompt_images()) { - LOG_ERROR("This conditioner does not support inline prompt images"); - return {}; - } - conditioner_params.text = input_template.text; - } - std::string prompt; - std::pair prompt_attn_range; - std::vector extra_prompts; - std::vector> extra_prompts_attn_range; - std::vector>> image_embeds; - LLM::DeepStackImageEmbeds deepstack_image_embeds; - std::vector image_grids; - int prompt_template_encode_start_idx = 34; - int min_length = 0; // pad tokens - int max_length = 100000000; - int hidden_states_min_length = 0; // zero pad hidden_states - bool spell_quotes = false; - std::set out_layers; - std::string prompt_suffix; - sd::Tensor text_mask; - - int64_t t0 = ggml_time_ms(); - RefImageResizeMode resize_mode = conditioner_params.ref_image_params.vlm_resize_mode; - - if (sd_version_is_minimax_h3(version)) { - prompt_template_encode_start_idx = 0; - // The final tap is normalized; LLMRunner exposes it at num_layers + 1. - out_layers = ph3_connector ? std::set{13, 19, 25, 31, 37} : std::set{50}; - prompt_attn_range = {0, 0}; - - if (llm->enable_vision) { - const int patch_size = llm->config.vision.patch_size; - const int factor = patch_size * llm->config.vision.spatial_merge_size; - - auto resize_for_vision = [&](const sd::Tensor& image) { - int height = static_cast(image.shape()[1]); - int width = static_cast(image.shape()[0]); - int h_bar = std::max(factor, static_cast(std::round(static_cast(height) / factor)) * factor); - int w_bar = std::max(factor, static_cast(std::round(static_cast(width) / factor)) * factor); - resize_image_dims(height, - width, - h_bar, - w_bar, - factor, - 3136, - 12845056, - RefImageResizeMode::AREA); - auto resized = sd::ops::interpolate( - image, - std::vector{w_bar, h_bar, image.shape()[2], image.shape()[3]}); - for (int64_t i = 0; i < resized.numel(); ++i) { - resized[i] = std::clamp(resized[i], 0.f, 1.f) * 2.f - 1.f; - } - return resized; - }; - - auto add_vision_outputs = [&](std::vector> image_outputs, - int grid_h, - int grid_w) { - GGML_ASSERT(image_outputs.size() == 4); - prompt += "<|vision_start|>"; - size_t marker_start = prompt.size(); - prompt += "<|image_pad|><|vision_end|>"; - return expand_vision_marker(prompt, marker_start, std::move(image_outputs), grid_h, grid_w, - image_embeds, deepstack_image_embeds, image_grids); - }; - - const auto* references = conditioner_params.minimax_h3_references; - if (references != nullptr && !references->empty()) { - int picture_index = 0; - int video_index = 0; - int audio_index = 0; - for (const auto& item : *references) { - if (item.kind == MiniMaxH3PresentationKind::AUDIO) { - prompt += "