Compare commits

..

9 commits

Author SHA1 Message Date
leejet
e637c7bccd
feat(server): update Web UI comparison and input sizing (#2437)
Some checks are pending
CI / Build and push container images (push) Waiting to run
CI / ubuntu-latest-cmake (push) Waiting to run
CI / ubuntu-latest-cmake-vulkan (push) Waiting to run
CI / macOS-latest-cmake (push) Waiting to run
CI / windows-latest-cmake (cpu, -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_LIBS=ON -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / windows-latest-cmake (cuda12, -DSD_CUDA=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CUDA_COMPILER_LAUNCHER=ccache -DSD_BUILD_SHARED_LIBS=ON -DCMAKE_CUDA_ARCHITECTURES='61;70;75;80;86;89;90;100;120' -DCMAKE_CUDA_FL… (push) Waiting to run
CI / windows-latest-cmake (vulkan, -DSD_VULKAN=ON -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / windows-latest-rocm (push) Waiting to run
CI / ubuntu-latest-rocm (10.1.0, x64, gfx900;gfx906;gfx908;gfx90a;gfx90c;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201) (push) Waiting to run
CI / release (push) Blocked by required conditions
2026-11-27 00:08:50 +08:00
leejet
ea3f6ec703
fix: load LTX INT8 ConvRot checkpoints (#2436) 2026-11-26 23:50:53 +08:00
leejet
6b51a955b4
refactor: reuse INT8 GEMM for W4A8 (#2435)
Some checks are pending
CI / windows-latest-cmake (cuda12, -DSD_CUDA=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CUDA_COMPILER_LAUNCHER=ccache -DSD_BUILD_SHARED_LIBS=ON -DCMAKE_CUDA_ARCHITECTURES='61;70;75;80;86;89;90;100;120' -DCMAKE_CUDA_FL… (push) Waiting to run
CI / windows-latest-cmake (vulkan, -DSD_VULKAN=ON -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / windows-latest-rocm (push) Waiting to run
CI / ubuntu-latest-rocm (10.1.0, x64, gfx900;gfx906;gfx908;gfx90a;gfx90c;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201) (push) Waiting to run
CI / ubuntu-latest-cmake (push) Waiting to run
CI / ubuntu-latest-cmake-vulkan (push) Waiting to run
CI / Build and push container images (push) Waiting to run
CI / windows-latest-cmake (cpu, -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_LIBS=ON -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / macOS-latest-cmake (push) Waiting to run
CI / release (push) Blocked by required conditions
2026-11-26 23:00:12 +08:00
losewayy
00a944fdf4
perf: enable rms_affine modulation fusion for lingbot video (#2422) 2026-11-26 21:48:54 +08:00
leejet
fce8619ba0
fix: support fused QKV in FLUX.3 checkpoints (#2434) 2026-11-26 21:36:01 +08:00
stduhpf
439e77a52e
feat: support -mlp variants of ClipProj-MiniMax-H3 (#2424) 2026-11-26 21:12:17 +08:00
Jasper Blues
514e786d84
fix: load the LTX-2.5 keyframe embedding as F32 (#2432) 2026-11-26 21:05:59 +08:00
leejet
456f52d2de
fix: resize Qwen Image Edit vision references (#2433) 2026-11-26 21:03:58 +08:00
leejet
52491bd9f1
feat: add inline media previews to the DGL editor (#2423)
Some checks are pending
CI / ubuntu-latest-cmake (push) Waiting to run
CI / ubuntu-latest-cmake-vulkan (push) Waiting to run
CI / Build and push container images (push) Waiting to run
CI / macOS-latest-cmake (push) Waiting to run
CI / windows-latest-cmake (cpu, -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_LIBS=ON -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / windows-latest-cmake (cuda12, -DSD_CUDA=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CUDA_COMPILER_LAUNCHER=ccache -DSD_BUILD_SHARED_LIBS=ON -DCMAKE_CUDA_ARCHITECTURES='61;70;75;80;86;89;90;100;120' -DCMAKE_CUDA_FL… (push) Waiting to run
CI / windows-latest-cmake (vulkan, -DSD_VULKAN=ON -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON) (push) Waiting to run
CI / windows-latest-rocm (push) Waiting to run
CI / ubuntu-latest-rocm (10.1.0, x64, gfx900;gfx906;gfx908;gfx90a;gfx90c;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201) (push) Waiting to run
CI / release (push) Blocked by required conditions
2026-11-26 02:38:21 +08:00
65 changed files with 1455 additions and 1811 deletions

1
.gitignore vendored
View file

@ -5,6 +5,7 @@ tests/
/dgl/*
!/dgl/.gitkeep
logs/
input/
output/
.vscode/
.idea/

View file

@ -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`:
@ -286,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

View file

@ -1163,8 +1163,7 @@ 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 from the existing job result; ordinary tensors
remain available for inspection.
editor displays returned media and ordinary tensor metadata in the job result.
| Encoding | MIME type | Requirements |
| --- | --- | --- |
@ -1892,7 +1891,8 @@ 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. With a callback, the host controls their display.
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

View file

@ -31,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
@ -98,10 +98,9 @@ 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.
- 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 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`
@ -116,7 +115,7 @@ backend when it supports the operation, with ggml's usual CPU fallback. The
additional quantization step can change the output compared with runtime
application.
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.
The shared CUDA/HIP/MUSA convrot activation paths support H64 and H256.
## Packed INT4 convrot
@ -130,49 +129,35 @@ 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

View file

@ -70,8 +70,7 @@ small learned matrix that replaces the 32B encoder:
```
The `mmh3-4b-*` matrices expect a Qwen3-VL-4B encoder and the `mmh3-8b-*`
matrices a Qwen3-VL-8B encoder; match the two. Only the linear matrices are
supported, not the `-mlp` residual variants. ClipProj is a community proof of
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.

View file

@ -31,8 +31,7 @@ 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. Only the linear matrices are supported,
not the `-mlp` residual variants. Reference-image editing needs the encoder's
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

View file

@ -178,3 +178,9 @@ To use the new Qwen Image Edit 2511 mode, `--model-args qwen_image_zero_cond_t=t
```
<img alt="qwen_image_edit_2509" src="../../assets/qwen/qwen_image_edit_2511.png" />
## 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.

View file

@ -78,6 +78,7 @@ add_executable(${TARGET}
routes_sdapi.cpp
routes_sdcpp.cpp
routes_dgl.cpp
routes_media.cpp
)
if(APPLE)
sd_set_macos_rpaths(${TARGET})

View file

@ -126,21 +126,46 @@ and are not parsed by the native server API.
### DGL editor
Open the Web UI using the local server address and select **DGL** in the header.
Select a saved script or choose **New**. **Duplicate** saves a copy of the
current editor text under a new name. Edit **File name** before saving to save
under a different name. **Run** submits the editor text to the generation queue,
so you can run unsaved edits. The results panel shows text, scalar and tensor
information and returned 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.
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 does not encode them again. Tensor frames can be inspected separately
with **Inspect tensor frames**; they are not fetched automatically.
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.
Use a relative path under the server's working directory, such as
`assets/reference.png` or `output/clip.webm`. Turn off **Media view** in the
editor toolbar to hide the preview. The server previews files under `input/`,
`output/`, and `assets/`. 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
@ -433,29 +458,37 @@ configured defaults.
| --- | --- | --- |
| `--listen-ip <ip>` | `127.0.0.1` | Server listen address |
| `--listen-port <port>` | `1234` | Server listen port |
| `--dgl-dir <path>` | `dgl` | Script directory for the local DGL editor |
| `--dgl-dir <path>` | `dgl` | Script directory for the DGL editor |
| `--no-media-view` | Off | Disable the media view endpoint |
| `--max-pending-jobs <count>` | `64` | Maximum async jobs queued or generating |
| `--completed-ttl-seconds <seconds>` | `600` | Retention time for completed async jobs |
### Access
By default any program on the machine, and any web page open in a browser on
it, can call the server. To limit that:
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 <key>` | none | Key clients must send as `Authorization: Bearer <key>` or `X-Api-Key: <key>`. Separate multiple keys with commas. |
| `--api-key-file <file>` | none | The same, one key per line, so keys don't show in the process list |
| `--cors-origins <origins>` | any | Web origins allowed to read the server's answers in a browser, comma-separated |
| `--cors-origins <origins>` | none | Additional browser origins allowed to make cross-origin requests, comma-separated |
With a key, the page at `/` still loads, but the bundled Web UI can't send
the key, so its calls get `401`; it is meant for use without a key.
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`.
`--cors-origins` only decides which web pages may read the answers: other
pages get no CORS headers, but their requests still reach the server. To
refuse requests, set a key as well.
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.

View file

@ -768,8 +768,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 |
@ -858,6 +858,7 @@ Top-level fields:
| `loras` | `array<object>` | Available LoRA entries |
| `upscalers` | `array<object>` | Available highres upscalers, built-in and model-backed |
| `preview_modes` | `array<string>` | Available preview modes, e.g. `["none", "proj", "tae", "vae"]` |
| `media_view` | `boolean` | Whether the media view endpoint is enabled |
| `limits` | `object` | Shared queue and size limits |
`model`
@ -1071,11 +1072,12 @@ Typical status codes:
#### `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:
@ -1827,20 +1829,31 @@ Example cancelled job:
- `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`, `output`, or `assets`
in the server's working directory. `path` is a slash-separated relative path
within that 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 are available to the local, same-origin Web UI. The server uses
the working directory's ./dgl directory unless --dgl-dir is set.
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 with HTTP 202 |
| GET /sdcpp/v1/dgl/jobs/{id} | Returns the job status, error or result with tensor descriptions and inline encoded media |
| POST /sdcpp/v1/dgl/jobs/{id}/cancel | Cancels a queued job or requests cancellation of a running job. Send `Content-Type: application/json`. |
| GET /sdcpp/v1/dgl/jobs/{id}/outputs/{index}?frame=0 | Returns a PNG of an image output or a video frame. Output and frame indexes start at zero. |
| 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
@ -1878,9 +1891,7 @@ The name of a root media dict is `result`.
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 result; it does not encode a video,
convert Base64 again, or require frame requests. The frame endpoint remains
available for explicit tensor inspection. Native `/sdcpp/v1/vid_gen` is unchanged.
`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

View file

@ -126,22 +126,25 @@ static void finish_job_progress(AsyncGenerationJob& job) {
job.progress.finished = std::chrono::steady_clock::now();
}
static void job_progress_callback(const sd_generation_progress_t* progress, void* data) noexcept {
try {
auto& job = *static_cast<AsyncGenerationJob*>(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_;
AsyncGenerationJob& job_;
static void progress_callback(const sd_generation_progress_t* progress, void* data) {
auto& guard = *static_cast<JobCallbacksGuard*>(data);
update_job_progress(guard.job_, progress->stage, progress->detail,
progress->sample_pass, progress->completed, progress->total, progress->unit);
}
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() {
@ -153,6 +156,24 @@ public:
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:
@ -503,7 +524,7 @@ bool execute_vid_gen_job(ServerRuntime& runtime,
return true;
}
int64_t dgl_image_frame_count(const sd_tensor_t* tensor) {
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);
@ -602,6 +623,23 @@ static json describe_dgl_result(const sd_dgl_result_t* 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<const ServerFileAccess*>(userdata);
std::error_code error;
@ -655,16 +693,18 @@ namespace {
const bool readable = !error && (fs::is_regular_file(status) || fs::is_directory(status));
if (access == SD_DGL_FILE_READ)
return readable;
const auto key = model_path_key(resolved);
if (readable || status.type() == fs::file_type::not_found) {
if (policy.configured_files.count(key))
return true;
if (std::any_of(policy.model_bundles.begin(), policy.model_bundles.end(), [&](const fs::path& root) { return model_path_inside(root, resolved); }))
return true;
}
return readable && 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);
});
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;
}
@ -689,7 +729,6 @@ void configure_server_file_access(ServerModels& models, const SDSvrParams& param
static sd_status_t execute_dgl_job(ServerRuntime& runtime,
AsyncGenerationJob& job,
std::shared_ptr<sd_dgl_result_t>& result,
json& result_info,
std::string& error_message) {
try {
@ -699,17 +738,19 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime,
std::lock_guard<std::mutex> lock(*runtime.sd_ctx_mutex);
if (job.cancel_requested.load())
return SD_STATUS_CANCELLED;
JobCancellationMonitor cancellation(job, [ctx = runtime.sd_ctx]() {
sd_dgl_ctx_cancel(sd_ctx_get_dgl_ctx(ctx));
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(sd_ctx_get_dgl_ctx(runtime.sd_ctx), source.c_str(), nullptr, 0, &raw_result);
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;
}
}
result.reset(raw_result, sd_dgl_result_free);
std::unique_ptr<sd_dgl_result_t, decltype(&sd_dgl_result_free)> result(raw_result, sd_dgl_result_free);
result_info = describe_dgl_result(result.get());
return SD_STATUS_OK;
} catch (const std::exception& error) {
@ -796,11 +837,10 @@ void async_job_worker(ServerRuntime& runtime) {
std::string output_media_mime_type;
int output_frame_count = 0;
int output_fps = 0;
std::shared_ptr<sd_dgl_result_t> dgl_result;
json dgl_result_info;
std::string error_message;
const char* error_code = "generation_failed";
bool ok = false;
bool ok = false;
if (job->kind == AsyncJobKind::ImgGen) {
ok = execute_img_gen_job(runtime, *job, output_images, output_info, error_message);
@ -814,7 +854,7 @@ void async_job_worker(ServerRuntime& runtime) {
output_info,
error_message);
} else if (job->kind == AsyncJobKind::Dgl) {
const auto status = execute_dgl_job(runtime, *job, dgl_result, dgl_result_info, error_message);
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";
@ -845,7 +885,6 @@ 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 = std::move(dgl_result);
job->dgl_result_info = std::move(dgl_result_info);
job->error_code.clear();
job->error_message.clear();

View file

@ -56,7 +56,6 @@ struct AsyncGenerationJob {
ImgGenJobRequest img_gen;
VidGenJobRequest vid_gen;
std::string dgl_source;
std::shared_ptr<sd_dgl_result_t> dgl_result;
json dgl_result_info;
std::vector<std::string> result_images_b64;
json result_generation_info;
@ -99,7 +98,6 @@ 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);
int64_t dgl_image_frame_count(const sd_tensor_t* tensor);
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,

@ -1 +1 @@
Subproject commit d9fd4e6a938b74ad97c7e464a8e689474b70c533
Subproject commit dd77dc8255bfd2371f733b894f7f773d05b92aa0

View file

@ -1,6 +1,7 @@
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
@ -103,6 +104,8 @@ int main(int argc, const char** argv) {
}
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;
@ -151,6 +154,7 @@ 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);
register_openai_api_endpoints(svr, runtime);
register_sdapi_endpoints(svr, runtime);
register_sdcpp_api_endpoints(svr, runtime);

View file

@ -6,6 +6,7 @@
#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, const SDSvrParams& svr_params);
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);

View file

@ -1,14 +1,11 @@
#include "routes.h"
#include <algorithm>
#include <charconv>
#include <fstream>
#include <optional>
#include <stdexcept>
#include <string_view>
#include "async_jobs.h"
#include "common/media_io.h"
namespace {
namespace fs = std::filesystem;
@ -32,31 +29,9 @@ namespace {
res.set_content(json({{"error", message}}).dump(-1, ' ', false, json::error_handler_t::replace), "application/json");
}
bool local_origin(const Request& req) {
if (req.remote_addr != "127.0.0.1" && req.remote_addr != "::1" && req.remote_addr != "::ffff:127.0.0.1")
return false;
const auto host = req.get_header_value("Host");
const auto port = ":" + std::to_string(req.local_port);
const auto origin = req.get_header_value("Origin");
const auto site = req.get_header_value("Sec-Fetch-Site");
if ((!site.empty() && site != "same-origin" && site != "none") ||
(!origin.empty() && origin != "http://" + host && origin != "https://" + host))
return false;
for (const std::string address : {"localhost", "127.0.0.1", "[::1]"}) {
if (host == address || host == address + port)
return true;
}
return false;
}
httplib::Server::Handler local_dgl_route(httplib::Server::Handler handler) {
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");
res.set_header("Cross-Origin-Resource-Policy", "same-origin");
if (!local_origin(req)) {
send_error(res, 403, "DGL is available from the local server's Web UI");
return;
}
if (req.method == "POST") {
const auto content_type = req.get_header_value("Content-Type");
if (content_type.substr(0, content_type.find(';')) != "application/json") {
@ -125,54 +100,11 @@ namespace {
std::error_code ignored;
fs::remove(staging, ignored);
}
std::optional<size_t> parse_index(std::string_view value) {
size_t index = 0;
const auto parsed = std::from_chars(value.data(), value.data() + value.size(), index);
if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size())
return std::nullopt;
return index;
}
std::shared_ptr<AsyncGenerationJob> find_dgl_job(AsyncJobManager& manager, const std::string& id, Response& res) {
purge_expired_jobs(manager);
auto it = manager.jobs.find(id);
if (it != manager.jobs.end() && it->second->kind == AsyncJobKind::Dgl)
return it->second;
const bool expired = manager.expired_jobs.count(id) != 0;
send_error(res, expired ? 410 : 404, expired ? "Job expired" : "Job not found");
return {};
}
void send_output_preview(const Request& req, Response& res, const sd_dgl_result_t* result) {
const auto output = parse_index(req.matches[2].str());
if (!output || *output >= sd_dgl_result_count(result)) {
send_error(res, 404, "Output not found");
return;
}
const auto* tensor = sd_dgl_result_tensor(result, sd_dgl_result_name(result, *output));
const auto frames = dgl_image_frame_count(tensor);
const auto frame = req.has_param("frame") ? parse_index(req.get_param_value("frame")) : std::optional<size_t>(0);
if (!frame || *frame >= static_cast<size_t>(frames)) {
send_error(res, 404, "Frame not found");
return;
}
const size_t stride = sd_tensor_byte_size(tensor) / static_cast<size_t>(frames);
const auto* pixels = static_cast<const uint8_t*>(sd_tensor_data(tensor)) + *frame * stride;
const auto png = encode_image_to_vector(EncodedImageFormat::PNG, pixels,
int(sd_tensor_dim(tensor, 1)), int(sd_tensor_dim(tensor, 2)),
int(sd_tensor_dim(tensor, 0)));
if (png.empty()) {
send_error(res, 500, "Could not encode preview");
return;
}
res.set_content(reinterpret_cast<const char*>(png.data()), png.size(), "image/png");
}
}
void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
auto workspace = std::make_shared<DglWorkspace>(runtime.svr_params->dgl_dir);
svr.Get("/sdcpp/v1/dgl/scripts", local_dgl_route([workspace](const Request&, Response& res) {
svr.Get("/sdcpp/v1/dgl/scripts", with_dgl_errors([workspace](const Request&, Response& res) {
std::lock_guard<std::mutex> lock(workspace->mutex);
std::vector<std::string> names;
if (fs::exists(workspace->directory)) {
@ -186,7 +118,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
send_json(res, 200, {{"directory", workspace->directory.generic_u8string()}, {"scripts", names}});
}));
svr.Get("/sdcpp/v1/dgl/script", local_dgl_route([workspace](const Request& req, Response& res) {
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");
@ -201,7 +133,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
send_json(res, 200, {{"source", read_script(path)}});
}));
svr.Post("/sdcpp/v1/dgl/script", local_dgl_route([workspace](const Request& req, Response& res) {
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<std::string>();
const auto source = body.at("source").get<std::string>();
@ -227,7 +159,7 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
send_json(res, updating ? 200 : 201, {{"name", name}});
}));
svr.Post("/sdcpp/v1/dgl/jobs", local_dgl_route([&runtime](const Request& req, Response& res) {
svr.Post("/sdcpp/v1/dgl/jobs", with_dgl_errors([&runtime](const Request& req, Response& res) {
auto source = json::parse(req.body).at("source").get<std::string>();
if (source.empty() || !valid_source(source)) {
send_error(res, 400, "Expected non-empty UTF-8 source");
@ -247,49 +179,10 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) {
job->id = make_async_job_id(manager);
manager.jobs.emplace(job->id, job);
manager.queue.push_back(job->id);
send_json(res, 202, make_async_job_json(manager, *job));
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();
}));
svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+))", local_dgl_route([&runtime](const Request& req, Response& res) {
auto& manager = *runtime.async_job_manager;
std::lock_guard<std::mutex> lock(manager.mutex);
if (auto job = find_dgl_job(manager, req.matches[1].str(), res))
send_json(res, 200, make_async_job_json(manager, *job));
}));
svr.Post(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/cancel)", local_dgl_route([&runtime](const Request& req, Response& res) {
auto& manager = *runtime.async_job_manager;
std::lock_guard<std::mutex> lock(manager.mutex);
auto job = find_dgl_job(manager, req.matches[1].str(), res);
if (!job)
return;
if (job->status == AsyncJobStatus::Queued) {
if (!cancel_queued_job(manager, *job)) {
send_error(res, 409, "Job queue state changed before cancellation");
return;
}
} else if (job->status == AsyncJobStatus::Generating) {
job->cancel_requested.store(true);
}
send_json(res, 200, make_async_job_json(manager, *job));
}));
svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+)/outputs/([0-9]+))", local_dgl_route([&runtime](const Request& req, Response& res) {
auto& manager = *runtime.async_job_manager;
std::shared_ptr<sd_dgl_result_t> result;
{
std::lock_guard<std::mutex> lock(manager.mutex);
const auto job = find_dgl_job(manager, req.matches[1].str(), res);
if (!job)
return;
result = job->dgl_result;
}
if (!result) {
send_error(res, 404, "Job has no result");
return;
}
send_output_preview(req, res, result.get());
}));
}

View file

@ -0,0 +1,276 @@
#include "routes.h"
#include <array>
#include <limits>
#include <string_view>
#include <utility>
#ifdef _WIN32
#include <winternl.h>
#else
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cerrno>
#endif
namespace media_view {
#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 working_directory() {
return FileHandle(CreateFileW(L".", FILE_TRAVERSE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr));
}
static FileHandle open_child(const FileHandle& parent, const std::string& part, bool directory) {
static const auto open_file = reinterpret_cast<decltype(&NtOpenFile)>(
GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtOpenFile"));
if (!open_file)
return FileHandle();
auto name = std::filesystem::u8path(part).native();
const auto bytes = static_cast<USHORT>(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<bool>(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<uint64_t>(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<LONGLONG>(offset);
DWORD count = 0;
if (!SetFilePointerEx(file.get(), position, nullptr, FILE_BEGIN) ||
!ReadFile(file.get(), buffer, static_cast<DWORD>(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 working_directory() {
return FileHandle(open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
}
static FileHandle open_child(const FileHandle& parent, const std::string& 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<uint64_t>(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<off_t>(offset));
} while (count < 0 && errno == EINTR);
return count > 0 ? static_cast<size_t>(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_media(const std::string& root, std::string_view path) {
if (root != "input" && root != "output" && root != "assets")
return FileHandle();
const auto cwd = working_directory();
if (!cwd)
return FileHandle();
auto 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, std::string(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<unsigned char>(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<unsigned char>(bytes.front()) & (0xffu >> width);
for (size_t i = 1; i < width; ++i)
size = (size << 8) | static_cast<unsigned char>(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_t>(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_t>(size)) == "webm";
header.remove_prefix(static_cast<size_t>(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<unsigned char>(header[i]);
if (box_size >= 16 && box_size <= size)
return "video/mp4";
}
return nullptr;
}
static bool set_media_content(const std::string& root, const std::string& path, httplib::Response& res) {
auto file = open_media(root, path);
if (!file)
return false;
const auto size = file_size(file);
if (size == 0 || size > std::numeric_limits<size_t>::max())
return false;
std::array<char, 256> 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_t>(size), type,
[file = std::make_shared<FileHandle>(std::move(file))](size_t offset, size_t length, httplib::DataSink& sink) {
std::array<char, 64 * 1024> 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, const SDSvrParams& params) {
svr.Get("/sdcpp/v1/view", [enabled = params.media_view](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(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;
});
}

View file

@ -341,6 +341,7 @@ static json make_capabilities_json(ServerRuntime& runtime) {
};
result["generation_features"] = generation_features;
result["generation_model_selection"] = true;
result["media_view"] = runtime.svr_params->media_view;
result["runtime"] = model_status(runtime);
result["current_mode"] = current_mode;
result["supported_modes"] = supported_modes;
@ -549,17 +550,13 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) {
});
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<std::mutex> lock(manager.mutex);
purge_expired_jobs(manager);
std::string job_id = req.matches[1];
auto it = manager.jobs.find(job_id);
if (it != manager.jobs.end() && it->second->kind == AsyncJobKind::Dgl) {
res.status = 404;
res.set_content(R"({"error":"job not found"})", "application/json");
return;
}
if (it == manager.jobs.end()) {
if (manager.expired_jobs.find(job_id) != manager.expired_jobs.end()) {
res.status = 410;
@ -576,6 +573,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<std::mutex> lock(manager.mutex);
purge_expired_jobs(manager);
@ -594,27 +592,14 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) {
}
auto& job = *it->second;
if (job.kind == AsyncJobKind::Dgl) {
res.status = 404;
res.set_content(R"({"error":"job not found"})", "application/json");
return;
}
if (job.status == AsyncJobStatus::Queued) {
if (!cancel_queued_job(manager, job)) {
res.status = 409;
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;

View file

@ -318,6 +318,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) {
@ -400,6 +401,7 @@ std::string SDSvrParams::to_string() const {
<< " 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();
}

View file

@ -28,6 +28,7 @@ struct SDSvrParams {
int weight_residency_ttl = -1;
std::string serve_html_path;
std::string dgl_dir = "dgl";
bool media_view = true;
std::vector<std::string> model_dirs;
std::vector<std::string> api_keys;
std::string api_key_file;

View file

@ -59,7 +59,7 @@ void SDSvrParams::add_access_options(ArgOptions& options, const std::vector<ArgO
api_key_file = argv_to_utf8(index, argv);
return true;
});
add_option("--cors-origins", "web origins allowed to read cross-origin responses, comma-separated (default: any)",
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);
});
@ -89,8 +89,12 @@ bool SDSvrParams::load_api_keys() {
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" && !(req.method == "GET" && req.path == "/");
return !params.api_keys.empty() && req.method != "OPTIONS" && !is_web_ui_request(req);
}
static bool api_key_matches(const std::vector<std::string>& keys, std::string_view key) {
@ -125,23 +129,88 @@ static bool has_valid_api_key(const httplib::Request& req, const std::vector<std
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<std::string>& 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<std::string>& allowed) {
const bool preflight = req.method == "OPTIONS";
res.set_header("Vary", preflight ? "Origin, Access-Control-Request-Headers" : "Origin");
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 (!allowed.empty() && std::find(allowed.begin(), allowed.end(), origin) == allowed.end()) {
if (!is_allowed_origin(allowed, origin)) {
return;
}
res.set_header("Access-Control-Allow-Origin", 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-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([&params](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;
@ -168,6 +237,7 @@ SDHttpServer::SDHttpServer(const SDSvrParams& params) {
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);
});
}

View file

@ -360,7 +360,8 @@ 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).
// 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);

View file

@ -2068,22 +2068,27 @@ struct LLMEmbedder : public Conditioner {
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;
const bool has_clipproj_connector = tensor_storage_map.count(std::string(ClipProjConnectorRunner::prefix) + ".W") != 0;
const bool has_clipproj_connector = tensor_storage_map.count(std::string(ClipProjConnectorRunner::prefix) + ".mean_in") != 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<PH3ImageTextConnectorRunner>(backend, tensor_storage_map, weight_manager);
} else if (has_clipproj_connector) {
clipproj_connector = std::make_shared<ClipProjConnectorRunner>(backend, llm->config.hidden_size, tensor_storage_map, weight_manager);
clipproj_connector = std::make_shared<ClipProjConnectorRunner>(backend, llm->config.hidden_size, 5120, 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; "
sd_format("%s with Qwen3-VL-4B requires a text connector; pass the P-H3-Image text connector "
"or a ClipProj projection with --embeddings-connectors, or use the MiniMax-H3 Qwen3-VL-32B text encoder",
sd_version_name(version)));
} else if (llm->config.hidden_size == 4096) {
throw std::runtime_error(
sd_format("%s with Qwen3-VL-8B requires a ClipProj 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_format("%s requires the MiniMax-H3 Qwen3-VL-32B text encoder or Qwen3-VL-4B with the P-H3-Image (or a ClipProj) text connector, or Qwen3-VL-8B with a ClipProj projection",
sd_version_name(version)));
}
}
@ -2662,6 +2667,7 @@ struct LLMEmbedder : public Conditioner {
prompt = system_prefix("");
prompt_template_encode_start_idx = 0;
// The final tap is normalized; LLMRunner exposes it at num_layers + 1.
// clipproj taps out at layer 24 in all versions so far, so it should be fine to hardcode it there
out_layers = ph3_connector ? std::set<int>{13, 19, 25, 31, 37} : std::set<int>{clipproj_connector ? 24 : 50};
prompt_attn_range = {0, 0};
@ -2931,6 +2937,13 @@ struct LLMEmbedder : public Conditioner {
int h_bar = static_cast<int>(std::round(static_cast<double>(height) / factor) * factor);
int w_bar = static_cast<int>(std::round(static_cast<double>(width) / factor) * factor);
if (version == VERSION_QWEN_IMAGE) {
constexpr double target_area = 384.0 * 384.0;
const double scale = std::sqrt(target_area / (static_cast<double>(width) * height));
h_bar = std::max(factor, static_cast<int>(std::round(height * scale / factor)) * factor);
w_bar = std::max(factor, static_cast<int>(std::round(width * scale / factor)) * factor);
}
LOG_VERBOSE("resize conditioner ref image %d from %dx%d to %dx%d", i, height, width, h_bar, w_bar);
auto resized_image = clip_preprocess(image, w_bar, h_bar);

View file

@ -13,6 +13,7 @@ namespace sd_cpu {
SDI8Operation op;
int64_t rows;
int8_t* quant;
int8_t* decoded;
float* scales;
float* output;
};
@ -36,11 +37,30 @@ namespace sd_cpu {
visit([&](int64_t i, float value) { dst[i] = static_cast<int8_t>(std::max(-127L, std::min(127L, std::lrintf(value * inverse)))); });
}
}
static void decode_w4a8(ggml_tensor*, int ith, int nth, void* data) {
const auto& e = *static_cast<I8Execution*>(data);
const auto* packed = static_cast<const uint8_t*>(e.op.weight->data);
const auto* codebook = static_cast<const float*>(e.op.codebook->data);
const auto* scales = static_cast<const uint8_t*>(e.op.relative_scale->data);
auto* decoded = e.decoded;
const auto to_float = ggml_get_type_traits(GGML_TYPE_F8_E4M3)->to_float;
const int64_t groups = ggml_nelements(e.op.relative_scale);
for (int64_t g = ith; g < groups; g += nth) {
float relative;
to_float(scales + g, &relative, 1);
for (int i = 0; i < 16; ++i) {
const int code = (packed[g * 8 + i / 2] >> (4 * (i % 2))) & 15;
const float value = codebook[code] * relative;
decoded[g * 16 + i] = std::isnan(value) ? 0 : int8_t(std::clamp(std::nearbyint(value), -127.f, 127.f));
}
}
}
static void multiply(ggml_tensor*, int ith, int nth, void* data) {
auto& e = *static_cast<I8Execution*>(data);
const auto& op = e.op;
const int64_t k = op.weight->ne[0], n = op.weight->ne[1];
const auto* w = static_cast<const int8_t*>(op.weight->data);
const int64_t k = op.k(), n = op.weight->ne[1];
const auto* w = e.decoded ? e.decoded : static_cast<const int8_t*>(op.weight->data);
const auto* ws = op.weight_scale ? static_cast<const float*>(op.weight_scale->data) : nullptr;
const auto* bias = op.bias ? static_cast<const float*>(op.bias->data) : nullptr;
for (int64_t index = ith; index < e.rows * n; index += nth) {
@ -79,7 +99,7 @@ namespace sd_cpu {
SDI8Operation op;
if (!sd_ggml_i8_describe(nodes[0], &op))
return GGML_STATUS_FAILED;
*bytes = quant_workspace(nodes[0], op) + ggml_nbytes(nodes[0]);
*bytes = quant_workspace(nodes[0], op) + ggml_nbytes(nodes[0]) + op.decoded_weight_bytes();
return GGML_STATUS_SUCCESS;
}
static ggml_status convrot_prepare(ggml_backend_t, ggml_tensor* const* nodes, int, void**, size_t* bytes, void*) {
@ -111,6 +131,12 @@ namespace sd_cpu {
e.quant = static_cast<int8_t*>(e.op.input->data);
e.scales = e.op.packed ? reinterpret_cast<float*>(e.quant + e.op.input->ne[0] * ((e.rows + 3) / 4 * 4)) : static_cast<float*>(e.op.input_scale->data);
}
if (e.op.codebook) {
e.decoded = reinterpret_cast<int8_t*>(scratch + quant_size + ggml_nbytes(dst));
auto status = run(context->backend, dst, decode_w4a8, &e);
if (status != GGML_STATUS_SUCCESS)
return status;
}
bool alias = false;
for (auto* input : dst->src)
alias |= overlaps(dst, input);

View file

@ -15,42 +15,23 @@ namespace sd_cpu {
auto& e = *static_cast<W4Execution*>(data);
const auto& op = e.op;
const int64_t k = op.input->ne[0], n = op.weight->ne[1];
const auto* w = static_cast<const uint8_t*>(op.weight->data);
const auto* x = static_cast<const int8_t*>(op.input->data);
const auto* xs = reinterpret_cast<const float*>(x + k * ((e.rows + 3) / 4 * 4));
const auto* ws = static_cast<const float*>(op.weight_scale->data);
const auto* bias = op.bias ? static_cast<const float*>(op.bias->data) : nullptr;
const auto* sc = op.s_channel ? static_cast<const float*>(op.s_channel->data) : nullptr;
const auto* sr = op.s_rel ? static_cast<const uint8_t*>(op.s_rel->data) : nullptr;
const auto to_float = ggml_get_type_traits(GGML_TYPE_F8_E4M3)->to_float;
const auto* w = static_cast<const uint8_t*>(op.weight->data);
const auto* x = static_cast<const int8_t*>(op.input->data);
const auto* xs = reinterpret_cast<const float*>(x + k * ((e.rows + 3) / 4 * 4));
const auto* ws = static_cast<const float*>(op.weight_scale->data);
const auto* bias = op.bias ? static_cast<const float*>(op.bias->data) : nullptr;
for (int64_t index = ith; index < n * e.rows; index += nth) {
const int64_t row = index / n, col = index % n;
const auto* packed = w + col * (k / 2);
float value;
if (op.kind == SDW4Kind::W4A4) {
uint32_t sum = 0;
for (int64_t i = 0; i < k; ++i) {
const int nibble = (packed[i / 2] >> (4 * (i % 2))) & 15;
sum += uint32_t(((nibble ^ 8) - 8) * int32_t(x[row * k + i]));
}
int32_t signed_sum;
std::memcpy(&signed_sum, &sum, sizeof(sum));
value = float(signed_sum) * xs[row] * ws[col];
} else {
float sum = 0.f;
for (int64_t g = 0; g < k / 16; ++g) {
float relative;
to_float(sr + col * (k / 16) + g, &relative, 1);
const float scale = sc[col] * relative;
for (int j = 0; j < 16; ++j) {
const int64_t i = g * 16 + j;
const int code = (packed[i / 2] >> (4 * (i % 2))) & 15;
sum += (ws[code] * scale) * float(x[row * k + i]);
}
}
value = sum * xs[row];
uint32_t sum = 0;
for (int64_t i = 0; i < k; ++i) {
const int nibble = (packed[i / 2] >> (4 * (i % 2))) & 15;
sum += uint32_t(((nibble ^ 8) - 8) * int32_t(x[row * k + i]));
}
e.output[index] = value + (bias ? bias[col] : 0.f);
int32_t signed_sum;
std::memcpy(&signed_sum, &sum, sizeof(sum));
const float value = float(signed_sum) * xs[row] * ws[col];
e.output[index] = value + (bias ? bias[col] : 0.f);
}
}

View file

@ -60,8 +60,6 @@ if(SD_HIPBLAS)
set_source_files_properties(${SD_CUDA_SOURCES} PROPERTIES COMPILE_OPTIONS "-ffast-math")
# LoRA merging must detect NaNs and infinities before requantization.
set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/i8_lora_merge_hip.cu" PROPERTIES COMPILE_OPTIONS "-fno-fast-math")
# W4A8 WMMA uses the wave64 fragment layout on both GFX11 and GFX12.
set_property(SOURCE "${CMAKE_CURRENT_BINARY_DIR}/w4_hip.cu" APPEND PROPERTY COMPILE_OPTIONS "-mwavefrontsize64")
target_link_libraries(${SD_CUDA_TARGET} PRIVATE hip::host roc::hipblas)
target_link_libraries(${SD_LIB} PRIVATE hip::host roc::hipblas)
find_package(hipblaslt CONFIG QUIET)

View file

@ -332,7 +332,7 @@ namespace sd_i8_gated {
const bool scaled = producer->op == GGML_OP_SCALE;
const auto* mat = scaled ? producer->src[0] : producer;
SDI8Operation op;
if (!sd_ggml_i8_describe(mat, &op) || op.input->type != GGML_TYPE_I8 || !op.weight_scale || op.bias)
if (!sd_ggml_i8_describe(mat, &op) || op.codebook || op.input->type != GGML_TYPE_I8 || !op.weight_scale || op.bias)
continue;
int scale_index = -1;
for (int j = i - 1; j >= 0 && j >= i - 64; --j) {
@ -362,7 +362,7 @@ namespace sd_i8_gated {
for (int i = 0; i < std::min(available, 5); ++i)
nodes[i] = ggml_graph_node(const_cast<ggml_cgraph*>(graph), first + i);
SDI8Operation mat;
if (!sd_ggml_i8_describe(nodes[0], &mat) || mat.input->type != GGML_TYPE_I8 || !mat.weight_scale || mat.bias)
if (!sd_ggml_i8_describe(nodes[0], &mat) || mat.codebook || mat.input->type != GGML_TYPE_I8 || !mat.weight_scale || mat.bias)
return 0;
const int64_t rows = ggml_nrows(nodes[0]), n = nodes[0]->ne[0], k = mat.weight->ne[0];
if (rows < (small_rows_enabled(rows, n, k) ? 1 : 128) || rows > INT_MAX || n > INT_MAX || k > INT_MAX || n % 128 || k % 64 ||

View file

@ -294,7 +294,7 @@ namespace sd_i8_cutlass {
};
struct Plan {
DeviceInfo device;
int64_t rows, n, k;
int64_t rows, n, k, output_stride;
SDI8GemmActivation activation;
bool packed_w4;
bool split;
@ -308,11 +308,11 @@ namespace sd_i8_cutlass {
typename Types::Epilogue::Arguments epilogue;
if constexpr (Types::kBias) {
// A negative zero default preserves signed-zero outputs.
epilogue = {{scales, {bias, -0.f, {}}, {}}, {out, {p.n, cute::_1{}, p.rows * p.n}}};
epilogue = {{scales, {bias, -0.f, {}}, {}}, {out, {p.output_stride, cute::_1{}, p.rows * p.output_stride}}};
} else if constexpr (Types::kGated) {
epilogue = {scales, {{out, {p.n, cute::_1{}, p.rows * p.n}}, p.activation == SDI8GemmActivation::Situ}};
} else {
epilogue = {scales, {out, {p.n, cute::_1{}, p.rows * p.n}}};
epilogue = {scales, {out, {p.output_stride, cute::_1{}, p.rows * p.output_stride}}};
}
return {cutlass::gemm::GemmUniversalMode::kGemm, {int(p.rows), int(p.n), int(p.k)}, 1, epilogue, x, reinterpret_cast<const typename Types::Weight*>(w), nullptr, nullptr, p.rows * p.k, p.n * p.k, 0, 0, p.k, p.k, 0, 0};
}
@ -415,23 +415,25 @@ namespace sd_i8_cutlass {
}
}
struct SDI8CudaGemmPlan : sd_i8_cutlass::Plan {};
static SDI8CudaGemmPlan* prepare_gemm(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, SDI8GemmActivation activation, size_t* workspace, bool packed_w4, bool split) {
static SDI8CudaGemmPlan* prepare_gemm(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, SDI8GemmActivation activation, size_t* workspace, bool packed_w4, bool split, int64_t output_stride) {
#ifdef SD_CUDA_FORCE_CUBLAS
return nullptr;
#else
const auto info = sd_i8_cutlass::device_info(device);
const bool gated = activation != SDI8GemmActivation::None;
if ((packed_w4 && (gated || k > INT_MAX / 1024)) || info.major < 8 || rows < (sd_i8_cutlass::small_rows_enabled(rows, n, k) ? 1 : 128) ||
rows > INT_MAX || n < 1 || n > INT_MAX || k < 1 || k > INT_MAX || k % 64 || n % (gated ? 256 : 128))
rows > INT_MAX || n < 1 || n > INT_MAX || k < 1 || k > INT_MAX || k % 64 || n % (gated ? 256 : 128) ||
output_stride < n || output_stride > INT_MAX || output_stride % 4)
return nullptr;
auto* p = new SDI8CudaGemmPlan;
p->device = info;
p->rows = rows;
p->n = n;
p->k = k;
p->activation = activation;
p->packed_w4 = packed_w4;
p->split = split;
auto* p = new SDI8CudaGemmPlan;
p->device = info;
p->rows = rows;
p->n = n;
p->output_stride = output_stride;
p->k = k;
p->activation = activation;
p->packed_w4 = packed_w4;
p->split = split;
if (!sd_i8_cutlass::configure(*p)) {
delete p;
return nullptr;
@ -441,12 +443,15 @@ static SDI8CudaGemmPlan* prepare_gemm(ggml_backend_dev_t device, int64_t rows, i
#endif
}
SDI8CudaGemmPlan* sd_cuda_i8_gemm_prepare(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, SDI8GemmActivation activation, size_t* workspace, bool packed_w4) {
return prepare_gemm(device, rows, n, k, activation, workspace, packed_w4, false);
return prepare_gemm(device, rows, n, k, activation, workspace, packed_w4, false, n);
}
SDI8CudaGemmPlan* sd_cuda_i8_gemm_prepare_strided(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, int64_t output_stride, size_t* workspace) {
return prepare_gemm(device, rows, n, k, SDI8GemmActivation::None, workspace, false, false, output_stride);
}
SDI8CudaGemmPlan* sd_cuda_i8_gemm_prepare_split(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, size_t* workspace) {
if (n > INT_MAX / 2 || k > INT_MAX / 16384)
return nullptr;
return prepare_gemm(device, rows, 2 * n, k, SDI8GemmActivation::Swiglu, workspace, false, true);
return prepare_gemm(device, rows, 2 * n, k, SDI8GemmActivation::Swiglu, workspace, false, true, 2 * n);
}
ggml_status sd_cuda_i8_gemm_execute(SDI8CudaGemmPlan* plan, const int8_t* x, const int8_t* w, const float* xs, const float* ws, float* out, void* scratch, cudaStream_t stream, const float* bias) {
if (bias && (plan->activation != SDI8GemmActivation::None || plan->packed_w4))

View file

@ -7,6 +7,7 @@ enum class SDI8GemmActivation { None,
Swiglu,
Situ };
SDI8CudaGemmPlan* sd_cuda_i8_gemm_prepare(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, SDI8GemmActivation activation, size_t* workspace, bool packed_w4 = false);
SDI8CudaGemmPlan* sd_cuda_i8_gemm_prepare_strided(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, int64_t output_stride, size_t* workspace);
ggml_status sd_cuda_i8_gemm_execute(SDI8CudaGemmPlan* plan, const int8_t* x, const int8_t* w, const float* xs, const float* ws, float* out, void* scratch, cudaStream_t stream, const float* bias = nullptr);
// n is the width of each branch; gate/up weights and scales remain separate.
SDI8CudaGemmPlan* sd_cuda_i8_gemm_prepare_split(ggml_backend_dev_t device, int64_t rows, int64_t n, int64_t k, size_t* workspace);

View file

@ -190,7 +190,7 @@ static bool aligned(const ggml_tensor* tensor) {
static bool projection_supports(ggml_backend_dev_t device, const ggml_tensor* mat, const ggml_tensor* view) {
SDI8Operation op;
if (!sd_ggml_i8_describe(mat, &op) || !op.packed || !op.weight_scale || op.bias)
if (!sd_ggml_i8_describe(mat, &op) || op.codebook || !op.packed || !op.weight_scale || op.bias)
return false;
const auto* w = op.weight;
const auto* x = op.input;
@ -221,13 +221,16 @@ bool sd_cuda_i8_rope_supports(ggml_backend_dev_t device, const ggml_tensor* mat,
template <class Out, bool RMS = true>
static cudaError_t projection_launch(cudaStream_t stream, const ggml_tensor* mat, const ggml_tensor* view, const ggml_tensor* norm, const ggml_tensor* mul, const ggml_tensor* rope, void* output, float scale, int64_t prefix_tokens) {
using P = ProjectionKernel<Out, RMS>;
using Gemm = typename P::Gemm;
const int rows = int(ggml_nrows(mat)), n = int(mat->ne[0]), k = int(mat->src[0]->ne[0]);
const auto* x = static_cast<const int8_t*>(mat->src[1]->data);
const auto* w = static_cast<const int8_t*>(mat->src[0]->data);
using P = ProjectionKernel<Out, RMS>;
using Gemm = typename P::Gemm;
SDI8Operation op;
if (!sd_ggml_i8_describe(mat, &op))
return cudaErrorInvalidValue;
const int rows = int(ggml_nrows(mat)), n = int(mat->ne[0]), k = int(op.weight->ne[0]);
const auto* x = static_cast<const int8_t*>(op.input->data);
const auto* w = static_cast<const int8_t*>(op.weight->data);
const auto* xs = reinterpret_cast<const float*>(x + int64_t(k) * ((int64_t(rows) + 3) / 4 * 4));
const auto* ws = static_cast<const float*>(mat->src[2]->data);
const auto* ws = static_cast<const float*>(op.weight_scale->data);
const auto* nw = RMS ? static_cast<const float*>(mul->src[1]->data) : nullptr;
const auto* pe = RMS ? static_cast<const float*>(rope->src[1]->data) : nullptr;
// The visitor forms FP32 addresses even when its only writes target the FP16 output.

View file

@ -449,19 +449,91 @@ namespace SD_CUDA_NAMESPACE {
}
return (reinterpret_cast<uintptr_t>(tensor->data) + offset) % alignment == 0;
}
static __global__ void mul_mat_i8_dot(const int* weights, const int* activations, int* output, int64_t words, int64_t n, int64_t rows) {
constexpr int tile = 32;
constexpr int slice = 8;
__shared__ int w_tile[tile][slice];
__shared__ int x_tile[tile][slice];
const int lx = threadIdx.x, ly = threadIdx.y;
const int lane = ly * 16 + lx;
const int load_row = lane / slice, load_word = lane % slice;
for (int64_t row = int64_t(blockIdx.y) * tile; row < rows; row += int64_t(gridDim.y) * tile) {
for (int64_t col = int64_t(blockIdx.x) * tile; col < n; col += int64_t(gridDim.x) * tile) {
int sum[2][2] = {};
for (int64_t k = 0; k < words; k += slice) {
const int64_t word = k + load_word;
w_tile[load_row][load_word] = col + load_row < n && word < words ? weights[(col + load_row) * words + word] : 0;
x_tile[load_row][load_word] = row + load_row < rows && word < words ? activations[(row + load_row) * words + word] : 0;
__syncthreads();
#pragma unroll
for (int i = 0; i < slice; ++i) {
sum[0][0] = cuda_dot_i8x4(w_tile[lx][i], x_tile[ly][i], sum[0][0]);
sum[0][1] = cuda_dot_i8x4(w_tile[lx + 16][i], x_tile[ly][i], sum[0][1]);
sum[1][0] = cuda_dot_i8x4(w_tile[lx][i], x_tile[ly + 16][i], sum[1][0]);
sum[1][1] = cuda_dot_i8x4(w_tile[lx + 16][i], x_tile[ly + 16][i], sum[1][1]);
}
__syncthreads();
}
for (int j = 0; j < 2; ++j) {
const int64_t r = row + ly + 16 * j;
for (int i = 0; i < 2; ++i) {
const int64_t c = col + lx + 16 * i;
if (r < rows && c < n)
output[r * n + c] = sum[j][i];
}
}
}
}
}
static __global__ void decode_w4a8(const uint8_t* packed, const float* codebook, const uint8_t* scales, int8_t* decoded, int64_t groups) {
const int64_t stride = int64_t(blockDim.x) * gridDim.x;
for (int64_t g = int64_t(blockDim.x) * blockIdx.x + threadIdx.x; g < groups; g += stride) {
const uint8_t bits = scales[g];
const int exponent = (bits >> 3) & 15, mantissa = bits & 7;
const float magnitude = exponent == 0 ? float(mantissa) * (1.f / 512.f)
: __int_as_float(((exponent + 120) << 23) | (mantissa << 20));
const float relative = bits & 128 ? -magnitude : magnitude;
#pragma unroll
for (int i = 0; i < 8; ++i) {
const uint8_t byte = packed[g * 8 + i];
#pragma unroll
for (int j = 0; j < 2; ++j) {
const float value = codebook[(byte >> (4 * j)) & 15] * relative;
const bool invalid = (bits & 127) == 127 || (__float_as_uint(value) & 0x7fffffff) > 0x7f800000;
decoded[g * 16 + 2 * i + j] = invalid ? 0 : int8_t(__float2int_rn(fminf(127.f, fmaxf(-127.f, value))));
}
}
}
}
static CUDAError decode_w4a8_weights(const SDI8Operation& op, int8_t* decoded, int64_t first, int64_t cols, CUDAStream stream) {
const int64_t groups_per_col = op.k() / 16;
const int64_t groups = cols * groups_per_col;
const auto blocks = unsigned(std::min<int64_t>((groups + 127) / 128, 65535));
decode_w4a8<<<blocks, 128, 0, stream>>>(
static_cast<const uint8_t*>(op.weight->data) + first * (op.k() / 2),
static_cast<const float*>(op.codebook->data),
static_cast<const uint8_t*>(op.relative_scale->data) + first * groups_per_col, decoded, groups);
return cuda_last_error();
}
static bool blas_supported(ggml_backend_dev_t device, const ggml_ext_gpu_device_info& info, int64_t n) {
return info.int8_blas && n % 4 == 0 &&
ggml_backend_reg_get_proc_address(ggml_backend_dev_backend_reg(device), "ggml_ext_gpu_blas_v1");
}
static bool supports(ggml_backend_dev_t device, const ggml_tensor* node, void*) {
SDI8Operation op;
if (!sd_ggml_i8_describe(node, &op) || !aligned(node))
return false;
const int64_t k = op.weight->ne[0], n = op.weight->ne[1], rows = ggml_nrows(node);
if (k > INT_MAX || n > INT_MAX || rows > INT_MAX - 3 || k % 4 || n % 4 || (op.input->type == GGML_TYPE_F32 && op.group_size && (op.group_size != 256 || rows > INT_MAX / (k / 256))))
const int64_t k = op.k(), n = op.weight->ne[1], rows = ggml_nrows(node);
if (k > INT_MAX || n > INT_MAX || rows > INT_MAX - 3 || k % 4 || (op.input->type == GGML_TYPE_F32 && op.group_size && (op.group_size != 256 || rows > INT_MAX / (k / 256))))
return false;
for (auto* input : node->src)
if (!aligned(input))
return false;
const auto info = cuda_device_info(device);
return info.int8_blas &&
ggml_backend_reg_get_proc_address(ggml_backend_dev_backend_reg(device), "ggml_ext_gpu_blas_v1");
return cuda_device_info(device).device >= 0;
}
template <bool Quantize>
static __global__ void convrot_h64(const float* src, int8_t* dst, float* partial, const float* scales, int64_t k) {
@ -524,8 +596,14 @@ namespace SD_CUDA_NAMESPACE {
return disabled;
}
#ifdef SD_CUDA_I8_CUTLASS
static int64_t w4a8_chunk_cols(int64_t k) {
constexpr int64_t decoded_bytes = 16 * 1024 * 1024;
constexpr int64_t alignment = 256;
return std::max(alignment, decoded_bytes / k / alignment * alignment);
}
static bool cutlass_compatible(const SDI8Operation& op, const ggml_tensor* dst) {
return op.weight_scale && op.weight->ne[0] <= INT_MAX / 16384 && aligned(op.bias, 16) &&
return op.weight_scale && op.k() <= INT_MAX / 16384 && aligned(op.bias, 16) &&
aligned(op.weight, 16) && aligned(op.weight_scale, 16) && aligned(dst, 16) &&
(op.input->type == GGML_TYPE_F32 || (aligned(op.input, 16) && aligned(op.input_scale, 16)));
}
@ -537,7 +615,7 @@ namespace SD_CUDA_NAMESPACE {
#if defined(SD_CUDA_VENDOR_HIP)
static bool match_gated_residual(const ggml_tensor* mat, const ggml_tensor* mul, const ggml_tensor* add, const SDI8Operation& op) {
if (mul->op != GGML_OP_MUL || mul->src[0] != mat || add->op != GGML_OP_ADD || !aligned(op.weight_scale, 16))
if (mat->ne[0] % 4 || mul->op != GGML_OP_MUL || mul->src[0] != mat || add->op != GGML_OP_ADD || !aligned(op.weight_scale, 16))
return false;
const auto* gate = mul->src[1];
const auto* residual = residual_input(mul, add);
@ -584,6 +662,10 @@ namespace SD_CUDA_NAMESPACE {
SDI8Operation op;
if (!supports(device, mat, nullptr) || !sd_ggml_i8_describe(mat, &op) || !op.weight_scale || op.bias)
return 0;
#ifdef SD_CUDA_I8_CUTLASS
if (op.codebook && mat->ne[0] > w4a8_chunk_cols(op.k()))
return 0;
#endif
const auto* next = ggml_graph_node(g, first + 1);
#if defined(SD_CUDA_VENDOR_HIP)
if (first + 2 < ggml_graph_n_nodes(g) && match_gated_residual(mat, next, ggml_graph_node(g, first + 2), op))
@ -603,7 +685,7 @@ namespace SD_CUDA_NAMESPACE {
#ifdef SD_CUDA_I8_CUTLASS
if (!next->data && !next->buffer && !next->view_src && cutlass_compatible(op, next)) {
size_t workspace = 0;
auto* gemm = sd_cuda_i8_gemm_prepare(device, ggml_nrows(mat), mat->ne[0], op.weight->ne[0], SDI8GemmActivation::Situ, &workspace);
auto* gemm = sd_cuda_i8_gemm_prepare(device, ggml_nrows(mat), mat->ne[0], op.k(), SDI8GemmActivation::Situ, &workspace);
const bool supported = gemm != nullptr;
sd_cuda_i8_gemm_free(gemm);
return supported ? 2 : 0;
@ -623,7 +705,7 @@ namespace SD_CUDA_NAMESPACE {
#ifdef SD_CUDA_I8_CUTLASS
if (!next->data && !next->buffer && !next->view_src && cutlass_compatible(op, next)) {
size_t workspace = 0;
auto* gemm = sd_cuda_i8_gemm_prepare(device, ggml_nrows(mat), mat->ne[0], op.weight->ne[0], SDI8GemmActivation::Swiglu, &workspace);
auto* gemm = sd_cuda_i8_gemm_prepare(device, ggml_nrows(mat), mat->ne[0], op.k(), SDI8GemmActivation::Swiglu, &workspace);
const bool fused_epilogue = gemm != nullptr;
sd_cuda_i8_gemm_free(gemm);
// ConvRot is a separate launch either way. Keep its input in the
@ -642,11 +724,38 @@ namespace SD_CUDA_NAMESPACE {
Kind kind;
int group;
int64_t k, n, rows, padded;
size_t quant, scales, accum, partial, output, gemm_offset;
size_t quant, scales, decoded_weight, accum, partial, output, gemm_offset;
SDI8CudaGemmPlan* gemm = nullptr;
bool fused_activation = false;
bool situ = false;
#ifdef SD_CUDA_I8_CUTLASS
SDI8CudaGemmPlan* tail_gemm = nullptr;
#endif
int64_t chunk_cols = 0;
bool use_blas = false;
bool fused_activation = false;
bool situ = false;
};
#ifdef SD_CUDA_I8_CUTLASS
static void prepare_w4a8_chunks(ggml_backend_dev_t device, Plan& p, size_t& workspace) {
const int64_t cols = w4a8_chunk_cols(p.k);
if (p.n <= cols || p.n % 128)
return;
size_t chunk_bytes = 0, tail_bytes = 0;
auto* gemm = sd_cuda_i8_gemm_prepare_strided(device, p.rows, cols, p.k, p.n, &chunk_bytes);
if (!gemm)
return;
const int64_t tail_cols = p.n % cols;
if (tail_cols) {
p.tail_gemm = sd_cuda_i8_gemm_prepare_strided(device, p.rows, tail_cols, p.k, p.n, &tail_bytes);
if (!p.tail_gemm) {
sd_cuda_i8_gemm_free(gemm);
return;
}
}
p.gemm = gemm;
p.chunk_cols = cols;
workspace = std::max(chunk_bytes, tail_bytes);
}
#endif
static size_t reserve(size_t& total, size_t bytes) {
const size_t offset = total;
total += (bytes + 255) / 256 * 256;
@ -664,7 +773,7 @@ namespace SD_CUDA_NAMESPACE {
: count == 1 ? MAT
: dst->op == GGML_OP_CONCAT ? CONCAT
: GATED;
p->k = mat ? op.weight->ne[0] : dst->ne[0];
p->k = mat ? op.k() : dst->ne[0];
p->n = mat ? nodes[0]->ne[0] : 0;
p->rows = mat ? ggml_nrows(nodes[0]) : ggml_nrows(dst->src[0]);
p->padded = (p->rows + 3) / 4 * 4;
@ -674,13 +783,16 @@ namespace SD_CUDA_NAMESPACE {
sd_ggml_convrot_describe(dst, &p->group);
size_t total = 0;
if (mat) {
p->quant = reserve(total, op.input->type == GGML_TYPE_F32 || (!op.packed && p->rows != p->padded) ? size_t(p->k) * p->padded : 0);
p->scales = reserve(total, op.input->type == GGML_TYPE_F32 ? size_t(p->rows) * sizeof(float) : 0);
p->use_blas = blas_supported(device, p->device, p->n);
p->quant = reserve(total, op.input->type == GGML_TYPE_F32 || (!op.packed && p->rows != p->padded) ? size_t(p->k) * p->padded : 0);
p->scales = reserve(total, op.input->type == GGML_TYPE_F32 ? size_t(p->rows) * sizeof(float) : 0);
#ifdef SD_CUDA_I8_CUTLASS
size_t gemm_bytes = 0;
// Retain cuBLAS when I32 accumulation can overflow.
if (cutlass_compatible(op, dst) && (!op.bias || p->kind == MAT) &&
if (p->use_blas && cutlass_compatible(op, dst) && (!op.bias || p->kind == MAT) &&
(p->kind != CONCAT || ggml_nbytes(dst->src[0]) % 16 == 0)) {
if (op.codebook && p->kind == MAT)
prepare_w4a8_chunks(device, *p, gemm_bytes);
if (p->kind == GATED || p->kind == SWIGLU_QUANTIZE) {
const auto activation = p->situ ? SDI8GemmActivation::Situ : SDI8GemmActivation::Swiglu;
p->gemm = sd_cuda_i8_gemm_prepare(device, p->rows, p->n, p->k, activation, &gemm_bytes);
@ -691,6 +803,7 @@ namespace SD_CUDA_NAMESPACE {
}
p->gemm_offset = reserve(total, gemm_bytes);
#endif
p->decoded_weight = reserve(total, p->chunk_cols ? size_t(p->chunk_cols) * p->k : op.decoded_weight_bytes());
const bool intermediate = !p->gemm || p->kind == SWIGLU_QUANTIZE || (p->kind == GATED && !p->fused_activation);
p->accum = reserve(total, intermediate ? size_t(p->fused_activation ? p->n / 2 : p->n) * p->padded * sizeof(float) : 0);
}
@ -708,8 +821,10 @@ namespace SD_CUDA_NAMESPACE {
static void destroy(void* state, void*) {
auto* p = static_cast<Plan*>(state);
#ifdef SD_CUDA_I8_CUTLASS
if (p)
if (p) {
sd_cuda_i8_gemm_free(p->gemm);
sd_cuda_i8_gemm_free(p->tail_gemm);
}
#endif
delete p;
}
@ -731,7 +846,7 @@ namespace SD_CUDA_NAMESPACE {
if (mat->view_src || !supports(device, mat, nullptr) || !ggml_are_same_shape(mat, glu))
return false;
if (!sd_ggml_i8_describe(glu->src[0], &gate) || !sd_ggml_i8_describe(glu->src[1], &up) ||
gate.input != up.input || gate.input_scale != up.input_scale || gate.packed != up.packed ||
gate.codebook || up.codebook || gate.input != up.input || gate.input_scale != up.input_scale || gate.packed != up.packed ||
gate.input->type != GGML_TYPE_I8 || gate.bias || up.bias || !gate.weight_scale || !up.weight_scale ||
!ggml_are_same_shape(gate.weight, up.weight))
return false;
@ -909,7 +1024,6 @@ namespace SD_CUDA_NAMESPACE {
}
static ggml_status execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int count, void* state, void*) {
const auto& p = *static_cast<const Plan*>(state);
auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(execution->backend));
ggml_ext_gpu_context context;
if (!cuda_context(execution->backend, &context) || context.device != p.device.device)
return GGML_STATUS_FAILED;
@ -967,6 +1081,13 @@ namespace SD_CUDA_NAMESPACE {
}
if (error != cuda_success || cuda_last_error() != cuda_success)
return GGML_STATUS_FAILED;
const auto* weight = static_cast<const int8_t*>(op.weight->data);
if (op.codebook && !p.chunk_cols) {
auto* decoded = reinterpret_cast<int8_t*>(scratch_at(p.decoded_weight));
if (decode_w4a8_weights(op, decoded, 0, p.n, stream) != cuda_success)
return GGML_STATUS_FAILED;
weight = decoded;
}
const auto* ws = op.weight_scale ? static_cast<const float*>(op.weight_scale->data) : nullptr;
const auto* bias = op.bias ? static_cast<const float*>(op.bias->data) : nullptr;
const size_t prefix = p.kind == CONCAT ? ggml_nbytes(dst->src[0]) : 0;
@ -974,23 +1095,42 @@ namespace SD_CUDA_NAMESPACE {
auto* accum = reinterpret_cast<int32_t*>(scratch_at(p.accum));
const bool intermediate = p.kind == SWIGLU_QUANTIZE || (p.kind == GATED && !p.fused_activation);
#ifdef SD_CUDA_I8_CUTLASS
if (p.gemm) {
auto status = sd_cuda_i8_gemm_execute(p.gemm, quant, static_cast<const int8_t*>(op.weight->data), scales, ws,
if (p.chunk_cols) {
auto* decoded = reinterpret_cast<int8_t*>(scratch_at(p.decoded_weight));
// A weight slice can stay in L2 across activation tiles.
for (int64_t first = 0; first < p.n; first += p.chunk_cols) {
const int64_t cols = std::min(p.chunk_cols, p.n - first);
if (decode_w4a8_weights(op, decoded, first, cols, stream) != cuda_success)
return GGML_STATUS_FAILED;
auto* gemm = cols == p.chunk_cols ? p.gemm : p.tail_gemm;
auto status = sd_cuda_i8_gemm_execute(gemm, quant, decoded, scales, ws + first, gemm_output + first,
scratch_at(p.gemm_offset), stream, bias ? bias + first : nullptr);
if (status != GGML_STATUS_SUCCESS)
return status;
}
} else if (p.gemm) {
auto status = sd_cuda_i8_gemm_execute(p.gemm, quant, weight, scales, ws,
intermediate ? reinterpret_cast<float*>(accum) : gemm_output, scratch_at(p.gemm_offset), stream, bias);
if (status != GGML_STATUS_SUCCESS)
return status;
} else
#endif
{
if (!p.use_blas) {
const dim3 grid(unsigned(std::min<int64_t>((p.n + 31) / 32, 65535)), unsigned(std::min<int64_t>((p.rows + 31) / 32, 65535)));
mul_mat_i8_dot<<<grid, dim3(16, 16), 0, stream>>>(reinterpret_cast<const int*>(weight),
reinterpret_cast<const int*>(quant), accum, p.k / 4, p.n, p.rows);
if (cuda_last_error() != cuda_success)
return GGML_STATUS_FAILED;
}
#if !defined(SD_CUDA_VENDOR_MUSA)
else {
auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(execution->backend));
auto blas_query = reinterpret_cast<ggml_ext_gpu_blas_fn>(ggml_backend_reg_get_proc_address(reg, "ggml_ext_gpu_blas_v1"));
auto handle = blas_query ? blas_query(execution->backend) : nullptr;
if (!handle)
return GGML_STATUS_FAILED;
#if defined(SD_CUDA_VENDOR_MUSA)
return GGML_STATUS_FAILED;
#else
#if defined(SD_CUDA_VENDOR_HIP)
const HipI8Gemm gemm{int(p.n), int(p.padded), int(p.k), op.weight->data, quant, accum,
const HipI8Gemm gemm{int(p.n), int(p.padded), int(p.k), weight, quant, accum,
static_cast<hipblasHandle_t>(handle), stream};
#ifdef SD_HIP_I8_LT
if (!hip_i8_gemm_lt(context.device, gemm) && gemm.run_hipblas() != HIPBLAS_STATUS_SUCCESS)
@ -1001,13 +1141,13 @@ namespace SD_CUDA_NAMESPACE {
const int32_t alpha = 1, beta = 0;
const auto status = cublasGemmEx(static_cast<cublasHandle_t>(handle), CUBLAS_OP_T, CUBLAS_OP_N,
int(p.n), int(p.padded), int(p.k), &alpha,
op.weight->data, CUDA_R_8I, int(p.k), quant, CUDA_R_8I, int(p.k),
weight, CUDA_R_8I, int(p.k), quant, CUDA_R_8I, int(p.k),
&beta, accum, CUDA_R_32I, int(p.n), CUBLAS_COMPUTE_32I, CUBLAS_GEMM_DEFAULT_TENSOR_OP);
if (status != CUBLAS_STATUS_SUCCESS)
#endif
return GGML_STATUS_FAILED;
#endif
}
#endif
const auto* values = reinterpret_cast<const float*>(accum);
if (p.kind == SWIGLU_QUANTIZE) {
if (p.fused_activation)
@ -1037,7 +1177,7 @@ namespace SD_CUDA_NAMESPACE {
reinterpret_cast<float4*>(gemm_output), p.n / 4, p.rows);
} else
#endif
if ((reinterpret_cast<uintptr_t>(ws) | reinterpret_cast<uintptr_t>(bias) | reinterpret_cast<uintptr_t>(gemm_output)) % 16 == 0) {
if (p.n % 4 == 0 && (reinterpret_cast<uintptr_t>(ws) | reinterpret_cast<uintptr_t>(bias) | reinterpret_cast<uintptr_t>(gemm_output)) % 16 == 0) {
dequantize_i32_rows_vec4_cuda<<<dim3(unsigned((p.n + 1023) / 1024), gy, gz), 256, 0, stream>>>(
reinterpret_cast<const int4*>(accum), scales, reinterpret_cast<const float4*>(ws), reinterpret_cast<const float4*>(bias), reinterpret_cast<float4*>(gemm_output), p.n / 4, p.rows);
} else {
@ -1066,7 +1206,8 @@ namespace SD_CUDA_NAMESPACE {
ggml_tensor* nodes[] = {ggml_graph_node(g, first), ggml_graph_node(g, first + 1), ggml_graph_node(g, first + 2), ggml_graph_node(g, first + 3)};
SDI8Operation gate, up;
int group;
if (!split_describe(device, nodes, gate, up) || !gate.packed ||
if (!blas_supported(device, cuda_device_info(device), nodes[2]->ne[0]) ||
!split_describe(device, nodes, gate, up) || !gate.packed ||
nodes[3]->src[0] != nodes[2] || !sd_ggml_convrot_describe(nodes[3], &group) || group != 256 ||
!convrot_supports(device, nodes[3], nullptr) ||
size_t(nodes[2]->ne[0]) * sizeof(float) + 128 <= cuda_device_info(device).shared_memory)

View file

@ -20,6 +20,23 @@
#endif
namespace SD_CUDA_NAMESPACE {
static __device__ __forceinline__ int32_t cuda_dot_i8x4(int32_t a, int32_t b, int32_t acc) {
#if defined(SD_CUDA_VENDOR_HIP) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1200__) || defined(__gfx1201__))
return __builtin_amdgcn_sudot4(true, a, true, b, acc, false);
#elif defined(SD_CUDA_VENDOR_HIP) && (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__) || defined(__gfx1033__) || defined(__gfx1034__) || defined(__gfx1035__) || defined(__gfx1036__) || defined(__gfx906__) || defined(__gfx908__) || defined(__gfx90a__) || defined(__gfx942__))
return __builtin_amdgcn_sdot4(a, b, acc, false);
#elif defined(SD_CUDA_VENDOR_MUSA) || (!defined(SD_CUDA_VENDOR_HIP) && __CUDA_ARCH__ >= 610)
return __dp4a(a, b, acc);
#else
uint32_t sum = uint32_t(acc);
const auto* av = reinterpret_cast<const int8_t*>(&a);
const auto* bv = reinterpret_cast<const int8_t*>(&b);
for (int i = 0; i < 4; ++i)
sum += uint32_t(int(av[i]) * int(bv[i]));
return int32_t(sum);
#endif
}
#if defined(SD_CUDA_VENDOR_HIP)
using CUDAError = hipError_t;
using CUDAStream = hipStream_t;

View file

@ -6,7 +6,6 @@
#include <mutex>
#include <unordered_map>
#include "i8_gemm.h"
#include "w4_mma.h"
#endif
namespace SD_CUDA_NAMESPACE {
@ -22,31 +21,6 @@ namespace SD_CUDA_NAMESPACE {
#endif
}
// Signed byte dots preserve the INT4 grid after the XOR-8 bias correction.
static __device__ __forceinline__ int dot4(int a, int b, int c) {
#if defined(SD_CUDA_VENDOR_HIP) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1200__) || defined(__gfx1201__))
return __builtin_amdgcn_sudot4(true, a, true, b, c, false);
#elif defined(SD_CUDA_VENDOR_HIP) && (defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__) || defined(__gfx1034__) || defined(__gfx1035__) || defined(__gfx1036__) || defined(__gfx906__) || defined(__gfx908__) || defined(__gfx90a__) || defined(__gfx942__))
return __builtin_amdgcn_sdot4(a, b, c, false);
#elif defined(SD_CUDA_VENDOR_MUSA) || (!defined(SD_CUDA_VENDOR_HIP) && __CUDA_ARCH__ >= 610)
return __dp4a(a, b, c);
#else
const auto* av = reinterpret_cast<const signed char*>(&a);
const auto* bv = reinterpret_cast<const signed char*>(&b);
for (int i = 0; i < 4; ++i)
c += int(av[i]) * int(bv[i]);
return c;
#endif
}
static __device__ __forceinline__ float fp8_e4m3(uint8_t v) {
const int exponent = (v >> 3) & 15, mantissa = v & 7;
float result = exponent == 15 && mantissa == 7 ? __int_as_float(0x7fc00000) : exponent == 0 ? ldexpf(float(mantissa), -9)
: ldexpf(1.f + float(mantissa) / 8.f, exponent - 7);
return v & 128 ? -result : result;
}
// A CTA shares decoded weights across 32 activation rows. Each double-buffered
// stage covers 64 K values; W4A8 restores the codebook scale per 16-value group.
static __device__ __forceinline__ uint32_t perm_bytes(uint32_t lo, uint32_t hi, uint32_t sel) {
#if defined(SD_CUDA_VENDOR_HIP)
return __builtin_amdgcn_perm(hi, lo, sel);
@ -132,7 +106,7 @@ namespace SD_CUDA_NAMESPACE {
const int a = (fr < rows && xb < x_words) ? (int)xi[(size_t)fr * x_words + xb] : 0;
const int b = (fr < rows && xb + 1 < x_words) ? (int)xi[(size_t)fr * x_words + xb + 1] : 0;
interleave_act_pair(a, b, &x_tile[0][tr * MUL_MAT_W4_SLOTS + (fl >> 1) * 4 + (fl & 1) * 2]);
my_sum += dot4(a, 0x01010101, 0) + dot4(b, 0x01010101, 0);
my_sum += cuda_dot_i8x4(a, 0x01010101, 0) + cuda_dot_i8x4(b, 0x01010101, 0);
}
__syncthreads();
@ -167,7 +141,7 @@ namespace SD_CUDA_NAMESPACE {
const int a = (fr < rows && xb < x_words) ? (int)xi[(size_t)fr * x_words + xb] : 0;
const int b = (fr < rows && xb + 1 < x_words) ? (int)xi[(size_t)fr * x_words + xb + 1] : 0;
interleave_act_pair(a, b, &x_tile[nbuf][tr * MUL_MAT_W4_SLOTS + (fl >> 1) * 4 + (fl & 1) * 2]);
my_sum += dot4(a, 0x01010101, 0) + dot4(b, 0x01010101, 0);
my_sum += cuda_dot_i8x4(a, 0x01010101, 0) + cuda_dot_i8x4(b, 0x01010101, 0);
}
}
#pragma unroll
@ -193,22 +167,22 @@ namespace SD_CUDA_NAMESPACE {
const uint32_t we = (gl * 4 + jp * 2) * MUL_MAT_W4_OUT;
const uint32_t wo = we + MUL_MAT_W4_OUT;
acc0a = dot4(w_dec[buf][we + lx], ue0, acc0a);
acc1a = dot4(w_dec[buf][we + 16 + lx], ue0, acc1a);
acc2a = dot4(w_dec[buf][we + 32 + lx], ue0, acc2a);
acc3a = dot4(w_dec[buf][we + 48 + lx], ue0, acc3a);
acc0b = dot4(w_dec[buf][wo + lx], uo0, acc0b);
acc1b = dot4(w_dec[buf][wo + 16 + lx], uo0, acc1b);
acc2b = dot4(w_dec[buf][wo + 32 + lx], uo0, acc2b);
acc3b = dot4(w_dec[buf][wo + 48 + lx], uo0, acc3b);
acc4a = dot4(w_dec[buf][we + lx], ue1, acc4a);
acc5a = dot4(w_dec[buf][we + 16 + lx], ue1, acc5a);
acc6a = dot4(w_dec[buf][we + 32 + lx], ue1, acc6a);
acc7a = dot4(w_dec[buf][we + 48 + lx], ue1, acc7a);
acc4b = dot4(w_dec[buf][wo + lx], uo1, acc4b);
acc5b = dot4(w_dec[buf][wo + 16 + lx], uo1, acc5b);
acc6b = dot4(w_dec[buf][wo + 32 + lx], uo1, acc6b);
acc7b = dot4(w_dec[buf][wo + 48 + lx], uo1, acc7b);
acc0a = cuda_dot_i8x4(w_dec[buf][we + lx], ue0, acc0a);
acc1a = cuda_dot_i8x4(w_dec[buf][we + 16 + lx], ue0, acc1a);
acc2a = cuda_dot_i8x4(w_dec[buf][we + 32 + lx], ue0, acc2a);
acc3a = cuda_dot_i8x4(w_dec[buf][we + 48 + lx], ue0, acc3a);
acc0b = cuda_dot_i8x4(w_dec[buf][wo + lx], uo0, acc0b);
acc1b = cuda_dot_i8x4(w_dec[buf][wo + 16 + lx], uo0, acc1b);
acc2b = cuda_dot_i8x4(w_dec[buf][wo + 32 + lx], uo0, acc2b);
acc3b = cuda_dot_i8x4(w_dec[buf][wo + 48 + lx], uo0, acc3b);
acc4a = cuda_dot_i8x4(w_dec[buf][we + lx], ue1, acc4a);
acc5a = cuda_dot_i8x4(w_dec[buf][we + 16 + lx], ue1, acc5a);
acc6a = cuda_dot_i8x4(w_dec[buf][we + 32 + lx], ue1, acc6a);
acc7a = cuda_dot_i8x4(w_dec[buf][we + 48 + lx], ue1, acc7a);
acc4b = cuda_dot_i8x4(w_dec[buf][wo + lx], uo1, acc4b);
acc5b = cuda_dot_i8x4(w_dec[buf][wo + 16 + lx], uo1, acc5b);
acc6b = cuda_dot_i8x4(w_dec[buf][wo + 32 + lx], uo1, acc6b);
acc7b = cuda_dot_i8x4(w_dec[buf][wo + 48 + lx], uo1, acc7b);
}
}
__syncthreads();
@ -241,531 +215,6 @@ namespace SD_CUDA_NAMESPACE {
}
}
#define MUL_MAT_W4A8_BLOCK 16
#define MUL_MAT_W4A8_ROWS (2 * MUL_MAT_W4A8_BLOCK)
#define MUL_MAT_W4A8_GPS 4
#define MUL_MAT_W4A8_SLOTS (4 * MUL_MAT_W4A8_GPS)
#define MUL_MAT_W4A8_OUT (MUL_MAT_W4A8_BLOCK * 4)
#if defined(SD_CUDA_VENDOR_HIP) && defined(__HIP_DEVICE_COMPILE__)
// __has_builtin checks the active device target's features, not just whether
// the compiler recognizes the name. Prefer the non-replicated fragment layout.
#if __has_builtin(__builtin_amdgcn_wmma_i32_16x16x16_iu8_w64_gfx12)
#define SD_W4_WMMA_GFX12
#elif __has_builtin(__builtin_amdgcn_wmma_i32_16x16x16_iu8_w64)
#define SD_W4_WMMA_GFX11
#endif
#endif
// Keep each intrinsic paired with its fragment layout, including on newer GPUs.
#if defined(SD_W4_WMMA_GFX11)
typedef int v4si32_w4a8 __attribute__((ext_vector_type(4)));
static __device__ __forceinline__ void mul_mat_w4a8_convrot_wmma(
const char* __restrict__ w,
const char* __restrict__ x,
const float* __restrict__ codebook,
const float* __restrict__ s_channel,
const uint8_t* __restrict__ s_rel,
const float* __restrict__ act_scales,
const float* __restrict__ bias,
float* __restrict__ y,
const uint32_t n,
const uint32_t rows,
const uint32_t k,
const uint32_t r_base) {
const uint32_t o_base = blockIdx.x * MUL_MAT_W4A8_OUT;
const uint32_t idx = threadIdx.y * MUL_MAT_W4A8_BLOCK + threadIdx.x;
const uint32_t wv = idx >> 6;
const uint32_t lane = idx & 63;
const uint32_t j = lane & 15;
const uint32_t q = lane >> 4;
const uint32_t ocol = o_base + wv * 16 + j;
const uint32_t ra = r_base + j;
__shared__ __align__(4) int8_t cb8[16];
__shared__ float s_cb;
__shared__ int lut[256];
__shared__ float s_lut[256];
const uint32_t w_words = k / 8;
const uint32_t x_words = k / 4;
const uint32_t groups = k / 16;
const int* wi = (const int*)w;
const int* xi = (const int*)x;
if (idx == 0) {
float amax = 0.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
amax = fmaxf(amax, fabsf(codebook[i]));
}
s_cb = amax / 127.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
const int v = s_cb == 0.f ? 0 : lrintf(codebook[i] / s_cb);
cb8[i] = (int8_t)(v < -127 ? -127 : (v > 127 ? 127 : v));
}
#pragma unroll
for (int b = 0; b < 256; ++b) {
lut[b] = (cb8[b & 0xF] & 0xFF) | ((cb8[b >> 4] & 0xFF) << 8);
}
#pragma unroll
for (int b = 0; b < 256; ++b) {
s_lut[b] = fp8_e4m3(uint8_t(b));
}
}
__syncthreads();
const bool o_valid = ocol < n;
const float s_chan = o_valid ? s_channel[ocol] : 0.0f;
const float scb = s_cb;
float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};
const v4si32_w4a8 zero = {};
int w0c = 0, w1c = 0, xc0 = 0, xc1 = 0, xc2 = 0, xc3 = 0, sc = 0;
int w0n = 0, w1n = 0, xn0 = 0, xn1 = 0, xn2 = 0, xn3 = 0, sn = 0;
{
const int* xr = xi + (size_t)ra * x_words;
xc0 = ra < rows ? xr[0] : 0;
xc1 = ra < rows ? xr[1] : 0;
xc2 = ra < rows ? xr[2] : 0;
xc3 = ra < rows ? xr[3] : 0;
if (o_valid) {
const int* wp = wi + (size_t)ocol * w_words;
w0c = wp[0];
w1c = wp[1];
sc = s_rel[(size_t)ocol * groups];
}
}
if (groups > 1) {
const int* xr = xi + (size_t)ra * x_words + 4;
xn0 = ra < rows ? xr[0] : 0;
xn1 = ra < rows ? xr[1] : 0;
xn2 = ra < rows ? xr[2] : 0;
xn3 = ra < rows ? xr[3] : 0;
if (o_valid) {
const int* wp = wi + (size_t)ocol * w_words + 2;
w0n = wp[0];
w1n = wp[1];
sn = s_rel[(size_t)ocol * groups + 1];
}
}
for (uint32_t g = 0; g < groups; ++g) {
v4si32_w4a8 bfrag = {};
float s = 0.0f;
if (o_valid) {
bfrag = {
(lut[w0c & 0xFF] & 0xFFFF) | ((lut[(w0c >> 8) & 0xFF] & 0xFFFF) << 16),
(lut[(w0c >> 16) & 0xFF] & 0xFFFF) | ((lut[(w0c >> 24) & 0xFF] & 0xFFFF) << 16),
(lut[w1c & 0xFF] & 0xFFFF) | ((lut[(w1c >> 8) & 0xFF] & 0xFFFF) << 16),
(lut[(w1c >> 16) & 0xFF] & 0xFFFF) | ((lut[(w1c >> 24) & 0xFF] & 0xFFFF) << 16),
};
s = scb * (s_chan * s_lut[sc & 0xFF]);
}
const v4si32_w4a8 afrag = {xc0, xc1, xc2, xc3};
const v4si32_w4a8 dfrag =
__builtin_amdgcn_wmma_i32_16x16x16_iu8_w64(true, afrag, true, bfrag, zero, false);
w0c = w0n;
w1c = w1n;
sc = sn;
xc0 = xn0;
xc1 = xn1;
xc2 = xn2;
xc3 = xn3;
if (g + 2 < groups) {
const int* xr = xi + (size_t)ra * x_words + (g + 2) * 4;
xn0 = ra < rows ? xr[0] : 0;
xn1 = ra < rows ? xr[1] : 0;
xn2 = ra < rows ? xr[2] : 0;
xn3 = ra < rows ? xr[3] : 0;
if (o_valid) {
const int* wp = wi + (size_t)ocol * w_words + (g + 2) * 2;
w0n = wp[0];
w1n = wp[1];
sn = s_rel[(size_t)ocol * groups + g + 2];
}
}
acc[0] = fmaf((float)dfrag.x, s, acc[0]);
acc[1] = fmaf((float)dfrag.y, s, acc[1]);
acc[2] = fmaf((float)dfrag.z, s, acc[2]);
acc[3] = fmaf((float)dfrag.w, s, acc[3]);
}
if (o_valid) {
#pragma unroll
for (uint32_t d = 0; d < 4; ++d) {
const uint32_t r = r_base + 4 * d + q;
if (r < rows) {
float value = acc[d] * act_scales[r];
if (bias != nullptr) {
value += bias[ocol];
}
y[(size_t)r * n + ocol] = value;
}
}
}
}
#endif
#if defined(SD_W4_WMMA_GFX12)
typedef int v4si32_w4a8_g12 __attribute__((ext_vector_type(4)));
static __device__ __forceinline__ void mul_mat_w4a8_convrot_wmma_gfx12(
const char* __restrict__ w,
const char* __restrict__ x,
const float* __restrict__ codebook,
const float* __restrict__ s_channel,
const uint8_t* __restrict__ s_rel,
const float* __restrict__ act_scales,
const float* __restrict__ bias,
float* __restrict__ y,
const uint32_t n,
const uint32_t rows,
const uint32_t k,
const uint32_t r_base) {
const uint32_t o_base = blockIdx.x * MUL_MAT_W4A8_OUT;
const uint32_t idx = threadIdx.y * MUL_MAT_W4A8_BLOCK + threadIdx.x;
const uint32_t wv = idx >> 6;
const uint32_t lane = idx & 63;
const uint32_t j = lane & 15;
const uint32_t h = lane >> 4;
const uint32_t kh = ((h & 1) << 1) | (h >> 1);
const uint32_t ocol = o_base + wv * 16 + j;
const uint32_t ra = r_base + j;
__shared__ __align__(4) int8_t cb8[16];
__shared__ float s_cb;
__shared__ int lut[256];
__shared__ float s_lut[256];
const uint32_t w_words = k / 8;
const uint32_t x_words = k / 4;
const uint32_t groups = k / 16;
const int* wi = (const int*)w;
const int* xi = (const int*)x;
if (idx == 0) {
float amax = 0.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
amax = fmaxf(amax, fabsf(codebook[i]));
}
s_cb = amax / 127.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
const int v = s_cb == 0.f ? 0 : lrintf(codebook[i] / s_cb);
cb8[i] = (int8_t)(v < -127 ? -127 : (v > 127 ? 127 : v));
}
#pragma unroll
for (int b = 0; b < 256; ++b) {
lut[b] = (cb8[b & 0xF] & 0xFF) | ((cb8[b >> 4] & 0xFF) << 8);
}
#pragma unroll
for (int b = 0; b < 256; ++b) {
s_lut[b] = fp8_e4m3(uint8_t(b));
}
}
__syncthreads();
const bool o_valid = ocol < n;
const float s_chan = o_valid ? s_channel[ocol] : 0.0f;
const float scb = s_cb;
float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};
const v4si32_w4a8_g12 zero = {};
int w0c = 0, w1c = 0, xc = 0, sc = 0;
int w0n = 0, w1n = 0, xn = 0, sn = 0;
{
const int* xr = xi + (size_t)ra * x_words;
xc = ra < rows ? xr[kh] : 0;
if (o_valid) {
const int* wp = wi + (size_t)ocol * w_words;
w0c = wp[0];
w1c = wp[1];
sc = s_rel[(size_t)ocol * groups];
}
}
if (groups > 1) {
const int* xr = xi + (size_t)ra * x_words;
xn = ra < rows ? xr[4 + kh] : 0;
if (o_valid) {
const int* wp = wi + (size_t)ocol * w_words + 2;
w0n = wp[0];
w1n = wp[1];
sn = s_rel[(size_t)ocol * groups + 1];
}
}
for (uint32_t g = 0; g < groups; ++g) {
int bfrag = 0;
float s = 0.0f;
if (o_valid) {
const int bwd = (kh & 2) ? w1c : w0c;
const int bsh = (kh & 1) * 16;
bfrag = (lut[(bwd >> bsh) & 0xFF] & 0xFFFF) |
((lut[(bwd >> (bsh + 8)) & 0xFF] & 0xFFFF) << 16);
s = scb * (s_chan * s_lut[sc & 0xFF]);
}
const v4si32_w4a8_g12 dfrag =
__builtin_amdgcn_wmma_i32_16x16x16_iu8_w64_gfx12(true, xc, true, bfrag, zero, false);
w0c = w0n;
w1c = w1n;
sc = sn;
xc = xn;
if (g + 2 < groups) {
const int* xr = xi + (size_t)ra * x_words;
xn = ra < rows ? xr[(g + 2) * 4 + kh] : 0;
if (o_valid) {
const int* wp = wi + (size_t)ocol * w_words + (g + 2) * 2;
w0n = wp[0];
w1n = wp[1];
sn = s_rel[(size_t)ocol * groups + g + 2];
}
}
acc[0] = fmaf((float)dfrag.x, s, acc[0]);
acc[1] = fmaf((float)dfrag.y, s, acc[1]);
acc[2] = fmaf((float)dfrag.z, s, acc[2]);
acc[3] = fmaf((float)dfrag.w, s, acc[3]);
}
if (o_valid) {
#pragma unroll
for (uint32_t d = 0; d < 4; ++d) {
const uint32_t r = r_base + 4 * kh + d;
if (r < rows) {
float value = acc[d] * act_scales[r];
if (bias != nullptr) {
value += bias[ocol];
}
y[(size_t)r * n + ocol] = value;
}
}
}
}
#endif
static __global__ void __launch_bounds__(MUL_MAT_W4A8_BLOCK* MUL_MAT_W4A8_BLOCK) mul_mat_w4a8_convrot(
const char* __restrict__ w,
const char* __restrict__ x,
const float* __restrict__ codebook,
const float* __restrict__ s_channel,
const uint8_t* __restrict__ s_rel,
const float* __restrict__ act_scales,
const float* __restrict__ bias,
float* __restrict__ y,
const uint32_t n,
const uint32_t rows,
const uint32_t k) {
#if defined(SD_W4_WMMA_GFX11) || defined(SD_W4_WMMA_GFX12)
// Retain the 32-row launch grid shared with DP4A. Each WMMA wave
// computes a 16-row tile; the barrier protects the reused LUTs.
for (uint32_t tile = 0; tile < 2; ++tile) {
#if defined(SD_W4_WMMA_GFX12)
mul_mat_w4a8_convrot_wmma_gfx12(w, x, codebook, s_channel, s_rel, act_scales, bias, y, n, rows, k,
blockIdx.y * MUL_MAT_W4A8_ROWS + tile * MUL_MAT_W4A8_BLOCK);
#else
mul_mat_w4a8_convrot_wmma(w, x, codebook, s_channel, s_rel, act_scales, bias, y, n, rows, k,
blockIdx.y * MUL_MAT_W4A8_ROWS + tile * MUL_MAT_W4A8_BLOCK);
#endif
__syncthreads();
}
#else
const uint32_t o_base = blockIdx.x * MUL_MAT_W4A8_OUT;
const uint32_t r0 = blockIdx.y * MUL_MAT_W4A8_ROWS + threadIdx.y;
const uint32_t r1 = r0 + MUL_MAT_W4A8_BLOCK;
const uint32_t lx = threadIdx.x;
const uint32_t ly = threadIdx.y;
const uint32_t idx = ly * MUL_MAT_W4A8_BLOCK + lx;
const uint32_t dc = idx & (MUL_MAT_W4A8_OUT - 1);
const uint32_t dw = idx >> 6;
__shared__ int w_dec[2][MUL_MAT_W4A8_SLOTS * MUL_MAT_W4A8_OUT];
__shared__ int x_tile[2][MUL_MAT_W4A8_ROWS * MUL_MAT_W4A8_SLOTS];
__shared__ float s_dec[2][MUL_MAT_W4A8_GPS * MUL_MAT_W4A8_OUT];
__shared__ __align__(4) int8_t cb8[16];
__shared__ float s_cb;
__shared__ int lut[256];
const uint32_t w_words = k / 8;
const uint32_t x_words = k / 4;
const uint32_t groups = k / 16;
const int* wi = (const int*)w;
const int* xi = (const int*)x;
if (ly == 0 && lx == 0) {
float amax = 0.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
amax = fmaxf(amax, fabsf(codebook[i]));
}
s_cb = amax / 127.0f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
const int v = s_cb == 0.f ? 0 : __float2int_rn(codebook[i] / s_cb);
cb8[i] = (int8_t)(v < -127 ? -127 : (v > 127 ? 127 : v));
}
}
__syncthreads();
lut[idx] = (cb8[idx & 0xF] & 0xFF) | ((cb8[idx >> 4] & 0xFF) << 8);
__syncthreads();
#pragma unroll
for (uint32_t j = 0; j < 2; ++j) {
const uint32_t pw = dw * 2 + j;
const uint32_t ocol = o_base + dc;
const int wv = (ocol < n && pw < w_words) ? wi[(size_t)ocol * w_words + pw] : 0;
w_dec[0][(pw * 2 + 0) * MUL_MAT_W4A8_OUT + dc] = (lut[wv & 0xFF] & 0xFFFF) | ((lut[(wv >> 8) & 0xFF] & 0xFFFF) << 16);
w_dec[0][(pw * 2 + 1) * MUL_MAT_W4A8_OUT + dc] = (lut[(wv >> 16) & 0xFF] & 0xFFFF) | ((lut[(wv >> 24) & 0xFF] & 0xFFFF) << 16);
}
{
const uint32_t ocol = o_base + dc;
float s = 0.0f;
if (ocol < n && dw < groups) {
s = s_channel[ocol] * fp8_e4m3(s_rel[(size_t)ocol * groups + dw]);
}
s_dec[0][dw * MUL_MAT_W4A8_OUT + dc] = s_cb * s;
}
if (lx < 16) {
const uint32_t aidx = lx;
x_tile[0][ly * MUL_MAT_W4A8_SLOTS + lx] =
(r0 < rows && aidx < x_words) ? xi[(size_t)r0 * x_words + aidx] : 0;
x_tile[0][(MUL_MAT_W4A8_BLOCK + ly) * MUL_MAT_W4A8_SLOTS + lx] =
(r1 < rows && aidx < x_words) ? xi[(size_t)r1 * x_words + aidx] : 0;
}
__syncthreads();
float acc0 = 0.0f;
float acc1 = 0.0f;
float acc2 = 0.0f;
float acc3 = 0.0f;
float acc4 = 0.0f;
float acc5 = 0.0f;
float acc6 = 0.0f;
float acc7 = 0.0f;
for (uint32_t gs = 0; gs < groups; gs += MUL_MAT_W4A8_GPS) {
const uint32_t buf = (gs >> 2) & 1;
if (gs + MUL_MAT_W4A8_GPS < groups) {
const uint32_t nbuf = buf ^ 1;
const uint32_t ngs = gs + MUL_MAT_W4A8_GPS;
#pragma unroll
for (uint32_t j = 0; j < 2; ++j) {
const uint32_t pw = dw * 2 + j;
const uint32_t ocol = o_base + dc;
const uint32_t widx = ngs * 2 + pw;
const int wv = (ocol < n && widx < w_words) ? wi[(size_t)ocol * w_words + widx] : 0;
w_dec[nbuf][(pw * 2 + 0) * MUL_MAT_W4A8_OUT + dc] = (lut[wv & 0xFF] & 0xFFFF) | ((lut[(wv >> 8) & 0xFF] & 0xFFFF) << 16);
w_dec[nbuf][(pw * 2 + 1) * MUL_MAT_W4A8_OUT + dc] = (lut[(wv >> 16) & 0xFF] & 0xFFFF) | ((lut[(wv >> 24) & 0xFF] & 0xFFFF) << 16);
}
{
const uint32_t ocol = o_base + dc;
float s = 0.0f;
if (ocol < n && ngs + dw < groups) {
s = s_channel[ocol] * fp8_e4m3(s_rel[(size_t)ocol * groups + ngs + dw]);
}
s_dec[nbuf][dw * MUL_MAT_W4A8_OUT + dc] = s_cb * s;
}
if (lx < 16) {
const uint32_t aidx = ngs * 4 + lx;
x_tile[nbuf][ly * MUL_MAT_W4A8_SLOTS + lx] =
(r0 < rows && aidx < x_words) ? xi[(size_t)r0 * x_words + aidx] : 0;
x_tile[nbuf][(MUL_MAT_W4A8_BLOCK + ly) * MUL_MAT_W4A8_SLOTS + lx] =
(r1 < rows && aidx < x_words) ? xi[(size_t)r1 * x_words + aidx] : 0;
}
}
#pragma unroll
for (uint32_t gl = 0; gl < MUL_MAT_W4A8_GPS; ++gl) {
const int u0[4] = {
x_tile[buf][ly * MUL_MAT_W4A8_SLOTS + gl * 4 + 0],
x_tile[buf][ly * MUL_MAT_W4A8_SLOTS + gl * 4 + 1],
x_tile[buf][ly * MUL_MAT_W4A8_SLOTS + gl * 4 + 2],
x_tile[buf][ly * MUL_MAT_W4A8_SLOTS + gl * 4 + 3],
};
const int u1[4] = {
x_tile[buf][(MUL_MAT_W4A8_BLOCK + ly) * MUL_MAT_W4A8_SLOTS + gl * 4 + 0],
x_tile[buf][(MUL_MAT_W4A8_BLOCK + ly) * MUL_MAT_W4A8_SLOTS + gl * 4 + 1],
x_tile[buf][(MUL_MAT_W4A8_BLOCK + ly) * MUL_MAT_W4A8_SLOTS + gl * 4 + 2],
x_tile[buf][(MUL_MAT_W4A8_BLOCK + ly) * MUL_MAT_W4A8_SLOTS + gl * 4 + 3],
};
int accg0 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + lx], u0[0], 0);
accg0 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + lx], u0[1], accg0);
accg0 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + lx], u0[2], accg0);
accg0 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + lx], u0[3], accg0);
int accg1 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + 16 + lx], u0[0], 0);
accg1 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + 16 + lx], u0[1], accg1);
accg1 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + 16 + lx], u0[2], accg1);
accg1 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + 16 + lx], u0[3], accg1);
int accg2 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + 32 + lx], u0[0], 0);
accg2 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + 32 + lx], u0[1], accg2);
accg2 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + 32 + lx], u0[2], accg2);
accg2 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + 32 + lx], u0[3], accg2);
int accg3 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + 48 + lx], u0[0], 0);
accg3 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + 48 + lx], u0[1], accg3);
accg3 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + 48 + lx], u0[2], accg3);
accg3 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + 48 + lx], u0[3], accg3);
int accg4 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + lx], u1[0], 0);
accg4 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + lx], u1[1], accg4);
accg4 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + lx], u1[2], accg4);
accg4 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + lx], u1[3], accg4);
int accg5 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + 16 + lx], u1[0], 0);
accg5 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + 16 + lx], u1[1], accg5);
accg5 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + 16 + lx], u1[2], accg5);
accg5 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + 16 + lx], u1[3], accg5);
int accg6 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + 32 + lx], u1[0], 0);
accg6 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + 32 + lx], u1[1], accg6);
accg6 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + 32 + lx], u1[2], accg6);
accg6 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + 32 + lx], u1[3], accg6);
int accg7 = dot4(w_dec[buf][(gl * 4 + 0) * MUL_MAT_W4A8_OUT + 48 + lx], u1[0], 0);
accg7 = dot4(w_dec[buf][(gl * 4 + 1) * MUL_MAT_W4A8_OUT + 48 + lx], u1[1], accg7);
accg7 = dot4(w_dec[buf][(gl * 4 + 2) * MUL_MAT_W4A8_OUT + 48 + lx], u1[2], accg7);
accg7 = dot4(w_dec[buf][(gl * 4 + 3) * MUL_MAT_W4A8_OUT + 48 + lx], u1[3], accg7);
acc0 = fmaf((float)accg0, s_dec[buf][gl * MUL_MAT_W4A8_OUT + lx], acc0);
acc1 = fmaf((float)accg1, s_dec[buf][gl * MUL_MAT_W4A8_OUT + 16 + lx], acc1);
acc2 = fmaf((float)accg2, s_dec[buf][gl * MUL_MAT_W4A8_OUT + 32 + lx], acc2);
acc3 = fmaf((float)accg3, s_dec[buf][gl * MUL_MAT_W4A8_OUT + 48 + lx], acc3);
acc4 = fmaf((float)accg4, s_dec[buf][gl * MUL_MAT_W4A8_OUT + lx], acc4);
acc5 = fmaf((float)accg5, s_dec[buf][gl * MUL_MAT_W4A8_OUT + 16 + lx], acc5);
acc6 = fmaf((float)accg6, s_dec[buf][gl * MUL_MAT_W4A8_OUT + 32 + lx], acc6);
acc7 = fmaf((float)accg7, s_dec[buf][gl * MUL_MAT_W4A8_OUT + 48 + lx], acc7);
}
__syncthreads();
}
const float accv[8] = {acc0, acc1, acc2, acc3, acc4, acc5, acc6, acc7};
#pragma unroll
for (uint32_t t = 0; t < 2; ++t) {
const uint32_t rt = t == 0 ? r0 : r1;
if (rt < rows) {
#pragma unroll
for (uint32_t j = 0; j < 4; ++j) {
const uint32_t oj = o_base + j * 16 + lx;
if (oj < n) {
float value = accv[t * 4 + j] * act_scales[rt];
if (bias != nullptr) {
value += bias[oj];
}
y[(size_t)rt * n + oj] = value;
}
}
}
}
#endif
}
static __global__ void dequantize(const int32_t* accum, const float* xs, const float* ws, const float* bias, float* dst, int64_t n, int64_t total) {
const int64_t i = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (i < total) {
@ -854,7 +303,7 @@ namespace SD_CUDA_NAMESPACE {
*state = plan;
size_t gemm_bytes = 0;
#ifdef SD_CUDA_W4_CUTLASS
if (plan->mma && op.kind == SDW4Kind::W4A4) {
if (plan->mma) {
if (!op.bias && aligned(dst, 16) && aligned(op.weight_scale, 16))
plan->gemm = sd_cuda_i8_gemm_prepare(ggml_backend_get_device(backend), ggml_nrows(dst), dst->ne[0], op.input->ne[0], SDI8GemmActivation::None, &gemm_bytes, true);
plan->mma = plan->gemm != nullptr;
@ -862,7 +311,7 @@ namespace SD_CUDA_NAMESPACE {
gemm_bytes = 256;
}
#endif
const size_t tensor_bytes = ggml_nbytes(dst) * ((op.kind == SDW4Kind::W4A4 && !plan->mma ? 1 : 0) + (may_alias ? 1 : 0));
const size_t tensor_bytes = ggml_nbytes(dst) * ((!plan->mma ? 1 : 0) + (may_alias ? 1 : 0));
plan->gemm_offset = (tensor_bytes + 255) / 256 * 256;
*bytes = plan->gemm_offset + gemm_bytes;
return GGML_STATUS_SUCCESS;
@ -894,28 +343,18 @@ namespace SD_CUDA_NAMESPACE {
const dim3 grid(unsigned((n + 63) / 64), unsigned((rows + 31) / 32)), block(16, 16);
#ifdef SD_CUDA_W4_CUTLASS
auto* plan = static_cast<Plan*>(state);
if (plan->mma) {
if (plan->gemm) {
auto* workspace = scratch ? reinterpret_cast<char*>(scratch) + plan->gemm_offset : nullptr;
if (sd_cuda_i8_gemm_execute(plan->gemm, reinterpret_cast<const int8_t*>(x), reinterpret_cast<const int8_t*>(w), xs, ws, output, workspace, stream) != GGML_STATUS_SUCCESS)
return GGML_STATUS_FAILED;
} else {
const dim3 tiles(unsigned((n + 63) / 64), unsigned((rows + 127) / 128));
sd_w4_mma::w4a8<128, 64, 128><<<tiles, 256, 0, stream>>>(reinterpret_cast<const uint8_t*>(w), reinterpret_cast<const int8_t*>(x), xs, ws,
static_cast<const float*>(op.s_channel->data), static_cast<const uint8_t*>(op.s_rel->data), bias, output, int(rows), int(n), int(k));
}
if (plan->gemm) {
auto* workspace = scratch ? reinterpret_cast<char*>(scratch) + plan->gemm_offset : nullptr;
if (sd_cuda_i8_gemm_execute(plan->gemm, reinterpret_cast<const int8_t*>(x), reinterpret_cast<const int8_t*>(w), xs, ws, output, workspace, stream) != GGML_STATUS_SUCCESS)
return GGML_STATUS_FAILED;
} else
#endif
if (op.kind == SDW4Kind::W4A4) {
{
auto* accum = reinterpret_cast<int32_t*>(scratch + (alias ? ggml_nelements(dst) : 0));
mul_mat_w4a4_convrot_dp4a<<<grid, block, 0, stream>>>(w, x, accum, uint32_t(n), uint32_t(rows), uint32_t(k / 2));
if (cuda_last_error() != cuda_success)
return GGML_STATUS_FAILED;
dequantize<<<unsigned((n * rows + 255) / 256), 256, 0, stream>>>(accum, xs, ws, bias, output, n, n * rows);
} else {
mul_mat_w4a8_convrot<<<grid, block, 0, stream>>>(w, x, ws,
static_cast<const float*>(op.s_channel->data), static_cast<const uint8_t*>(op.s_rel->data),
xs, bias, output, uint32_t(n), uint32_t(rows), uint32_t(k));
}
auto error = cuda_last_error();
if (error == cuda_success && alias)

View file

@ -1,138 +0,0 @@
#ifndef __SD_CORE_CUDA_W4_MMA_H__
#define __SD_CORE_CUDA_W4_MMA_H__
#include <cuda_runtime.h>
#include <cutlass/arch/mma_sm80.h>
#include <cstdint>
namespace sd_w4_mma {
static __device__ __forceinline__ float fp8_e4m3(uint8_t v) {
const int exponent = (v >> 3) & 15, mantissa = v & 7;
const float result = exponent == 15 && mantissa == 7 ? __int_as_float(0x7fc00000) : exponent == 0 ? ldexpf(float(mantissa), -9)
: ldexpf(1.f + float(mantissa) / 8.f, exponent - 7);
return v & 128 ? -result : result;
}
template <int M, int N, int K>
static __global__ void __launch_bounds__(256) w4a8(
const uint8_t* __restrict__ w,
const int8_t* __restrict__ x,
const float* __restrict__ xs,
const float* __restrict__ codebook,
const float* __restrict__ channel,
const uint8_t* __restrict__ relative,
const float* __restrict__ bias,
float* __restrict__ dst,
int rows,
int n,
int k) {
const int row_base = blockIdx.y * M, col_base = blockIdx.x * N;
const int tid = threadIdx.x, lane = tid % 32, warp = tid / 32;
__shared__ int cb[16];
__shared__ float cbscale;
if (tid == 0) {
float amax = 0.f;
#pragma unroll
for (int i = 0; i < 16; ++i)
amax = fmaxf(amax, fabsf(codebook[i]));
cbscale = amax / 127.f;
#pragma unroll
for (int i = 0; i < 16; ++i) {
const int value = cbscale == 0.f ? 0 : __float2int_rn(codebook[i] / cbscale);
cb[i] = max(-127, min(127, value));
}
}
__syncthreads();
#if __CUDA_ARCH__ >= 800
constexpr int stride = K / 4 + 4;
__shared__ __align__(16) uint32_t a[M][stride], b[N][stride];
__shared__ uint32_t lut[256];
__shared__ float scales[K / 16][N];
lut[tid] = (cb[tid & 15] & 255) | ((cb[tid >> 4] & 255) << 8);
__syncthreads();
constexpr int warp_cols = N / 32;
constexpr int row_tiles = M / (16 * (8 / warp_cols));
const int wr = (warp / warp_cols) * 16 * row_tiles, wc = (warp % warp_cols) * 32;
float acc[row_tiles][4][4] = {};
for (int base = 0; base < k; base += K) {
for (int i = tid; i < M * K / 16; i += 256) {
const int r = i / (K / 16), t = (i % (K / 16)) * 16;
const int4 value = row_base + r < rows && base + t < k ? *reinterpret_cast<const int4*>(x + int64_t(row_base + r) * k + base + t) : make_int4(0, 0, 0, 0);
*reinterpret_cast<int4*>(&a[r][t / 4]) = value;
}
for (int i = tid; i < N * K / 8; i += 256) {
const int c = i / (K / 8), t = i % (K / 8);
const uint32_t value = col_base + c < n && base + t * 8 < k ? *reinterpret_cast<const uint32_t*>(w + int64_t(col_base + c) * (k / 2) + base / 2 + t * 4) : 0;
b[c][2 * t] = lut[value & 255] | (lut[(value >> 8) & 255] << 16);
b[c][2 * t + 1] = lut[(value >> 16) & 255] | (lut[value >> 24] << 16);
}
for (int i = tid; i < N * K / 16; i += 256) {
const int c = i % N, g = i / N;
scales[g][c] = col_base + c < n && base + g * 16 < k ? cbscale * (channel[col_base + c] * fp8_e4m3(relative[int64_t(col_base + c) * (k / 16) + base / 16 + g])) : 0.f;
}
__syncthreads();
#pragma unroll
for (int g = 0; g < K / 16; ++g) {
#pragma unroll
for (int r = 0; r < row_tiles; ++r) {
const int ar = wr + r * 16 + lane / 4, ac = g * 4 + lane % 4;
const uint32_t a0 = a[ar][ac], a1 = a[ar + 8][ac];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint32_t b0 = b[wc + j * 8 + lane / 4][ac];
using Mma = cutlass::arch::Mma<cutlass::gemm::GemmShape<16, 8, 16>, 32,
int8_t, cutlass::layout::RowMajor, int8_t, cutlass::layout::ColumnMajor,
int, cutlass::layout::RowMajor, cutlass::arch::OpMultiplyAddSaturate>;
Mma::FragmentA af;
Mma::FragmentB bf;
Mma::FragmentC d;
reinterpret_cast<uint32_t*>(&af)[0] = a0;
reinterpret_cast<uint32_t*>(&af)[1] = a1;
reinterpret_cast<uint32_t*>(&bf)[0] = b0;
d.clear();
// Each K=16 MMA has its own scale; combining groups before
// dequantization would change the W4A8 representation.
Mma{}(d, af, bf, d);
const float s0 = scales[g][wc + j * 8 + (lane % 4) * 2], s1 = scales[g][wc + j * 8 + (lane % 4) * 2 + 1];
#pragma unroll
for (int v = 0; v < 4; ++v)
acc[r][j][v] = fmaf(float(d[v]), v % 2 ? s1 : s0, acc[r][j][v]);
}
}
}
__syncthreads();
}
#pragma unroll
for (int r = 0; r < row_tiles; ++r) {
#pragma unroll
for (int j = 0; j < 4; ++j) {
#pragma unroll
for (int v = 0; v < 4; ++v) {
const int row = row_base + wr + r * 16 + lane / 4 + (v / 2) * 8;
const int col = col_base + wc + j * 8 + (lane % 4) * 2 + v % 2;
if (row < rows && col < n)
dst[int64_t(row) * n + col] = __fmul_rn(acc[r][j][v], xs[row]) + (bias ? bias[col] : 0.f);
}
}
}
#else
for (int i = tid; i < M * N; i += 256) {
const int row = row_base + i / N, col = col_base + i % N;
if (row < rows && col < n) {
float sum = 0.f;
for (int g = 0; g < k / 16; ++g) {
int d = 0;
for (int j = 0; j < 16; ++j) {
const int t = g * 16 + j;
d += cb[(w[int64_t(col) * (k / 2) + t / 2] >> (4 * (t % 2))) & 15] * int(x[int64_t(row) * k + t]);
}
sum = fmaf(float(d), cbscale * (channel[col] * fp8_e4m3(relative[int64_t(col) * (k / 16) + g])), sum);
}
dst[int64_t(row) * n + col] = __fmul_rn(sum, xs[row]) + (bias ? bias[col] : 0.f);
}
}
#endif
}
}
#endif

View file

@ -978,10 +978,10 @@ namespace sd {
const auto budget_bytes = available.available_budget_bytes == SIZE_MAX
? std::string("unlimited")
: sd_format("%.2f MB", available.available_budget_bytes / (1024.0 * 1024.0));
auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
ggml_backend_name(request.compute_backend),
available.required_device_bytes / (1024.0 * 1024.0),
available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
ggml_backend_name(request.compute_backend),
available.required_device_bytes / (1024.0 * 1024.0),
available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
LOG_WARN("%s", message.c_str());
if (device_memory_error != nullptr && available.valid) {
*device_memory_error = std::move(message);

View file

@ -858,9 +858,11 @@ ggml_tensor* ggml_ext_mul_mat_i8_tensorwise(GGMLRunnerContext* runner_ctx,
ggml_tensor* ws,
ggml_tensor* bias,
int group,
ggml_tensor* xs) {
ggml_tensor* xs,
ggml_tensor* codebook,
ggml_tensor* relative_scale) {
auto ctx = runner_ctx->ggml_ctx;
if (!w || !x)
if (!w || !x || (codebook == nullptr) != (relative_scale == nullptr))
return nullptr;
const auto* logical = x;
if (x->type == GGML_TYPE_I8 && !xs) {
@ -870,7 +872,7 @@ ggml_tensor* ggml_ext_mul_mat_i8_tensorwise(GGMLRunnerContext* runner_ctx,
logical = x->src[0];
}
SDI8Attributes attr = {{logical->ne[1], logical->ne[2], logical->ne[3]}, group, logical != x ? SD_I8_PACKED : 0};
ggml_tensor* inputs[5] = {w, x};
ggml_tensor* inputs[7] = {w, x};
int count = 2;
if (xs) {
attr.flags |= SD_I8_INPUT_SCALE;
@ -884,6 +886,11 @@ ggml_tensor* ggml_ext_mul_mat_i8_tensorwise(GGMLRunnerContext* runner_ctx,
attr.flags |= SD_I8_BIAS;
inputs[count++] = bias;
}
if (codebook) {
attr.flags |= SD_I8_WEIGHT_W4;
inputs[count++] = codebook;
inputs[count++] = relative_scale;
}
return ggml_ext_op_create(ctx, sd_ggml_i8_op(), inputs, count, &attr);
}
@ -902,39 +909,6 @@ ggml_tensor* ggml_ext_quantize_i8_convrot(GGMLRunnerContext* runner_ctx, ggml_te
return result;
}
ggml_tensor* ggml_ext_mul_mat_w4_convrot(GGMLRunnerContext* runner_ctx,
ggml_tensor* w,
ggml_tensor* x,
ggml_tensor* ws,
ggml_tensor* sc,
ggml_tensor* sr,
ggml_tensor* bias,
SDW4Kind kind,
int group) {
auto ctx = runner_ctx->ggml_ctx;
if (!w || !x || group < 0 || (group && !sd_ggml_valid_convrot_group(group)))
return nullptr;
const int quant_group = group ? group : 1;
if (x->type == GGML_TYPE_F32)
x = ggml_ext_quantize_i8_convrot(runner_ctx, x, quant_group);
int packed_group;
if (!sd_ggml_convrot_describe(x, &packed_group) || packed_group != quant_group)
return nullptr;
const auto* logical = x->src[0];
SDW4Attributes attr = {{logical->ne[1], logical->ne[2], logical->ne[3]}, kind, bias ? 1 : 0};
ggml_tensor* inputs[6] = {w, x, ws};
int count = 3;
if (kind == SDW4Kind::W4A8) {
inputs[count++] = sc;
inputs[count++] = sr;
} else if (sc || sr) {
return nullptr;
}
if (bias)
inputs[count++] = bias;
return ggml_ext_op_create(ctx, sd_ggml_w4_op(), inputs, count, &attr);
}
ggml_tensor* ggml_ext_sage_attn(GGMLRunnerContext* runner_ctx,
ggml_tensor* q,
ggml_tensor* k,
@ -1170,18 +1144,32 @@ ggml_tensor* ggml_ext_linear_w4_convrot(GGMLRunnerContext* runner_ctx,
ggml_tensor* x,
ggml_tensor* w,
ggml_tensor* ws,
ggml_tensor* sc,
ggml_tensor* sr,
ggml_tensor* bias,
SDW4Kind kind,
int group,
float scale) {
float scale,
ggml_tensor* codebook,
ggml_tensor* s_rel) {
auto ctx = runner_ctx->ggml_ctx;
x = ggml_ext_prepare_i8_input(runner_ctx, x);
if (scale != 1.f) {
x = ggml_ext_scale(runner_ctx, x, scale);
}
auto out = ggml_ext_mul_mat_w4_convrot(runner_ctx, w, x, ws, sc, sr, scale == 1.f ? bias : nullptr, kind, group);
group = group ? group : 1;
if (x->type == GGML_TYPE_F32) {
x = ggml_ext_quantize_i8_convrot(runner_ctx, x, group);
}
int packed_group;
GGML_ASSERT(sd_ggml_convrot_describe(x, &packed_group) && packed_group == group);
ggml_tensor* fused_bias = scale == 1.f ? bias : nullptr;
ggml_tensor* out;
if (codebook) {
out = ggml_ext_mul_mat_i8_tensorwise(runner_ctx, w, x, ws, fused_bias, group, nullptr, codebook, s_rel);
} else {
const auto* logical = x->src[0];
SDW4Attributes attr = {{logical->ne[1], logical->ne[2], logical->ne[3]}, fused_bias ? 1 : 0};
ggml_tensor* inputs[] = {w, x, ws, fused_bias};
out = ggml_ext_op_create(ctx, sd_ggml_w4_op(), inputs, fused_bias ? 4 : 3, &attr);
}
GGML_ASSERT(out);
if (scale != 1.f) {
out = ggml_ext_scale(runner_ctx, out, 1.f / scale);

View file

@ -212,22 +212,12 @@ ggml_tensor* ggml_ext_mul_mat_i8_tensorwise(GGMLRunnerContext* runner_ctx,
ggml_tensor* weight_scale,
ggml_tensor* bias,
int group_size,
ggml_tensor* input_scale = nullptr);
ggml_tensor* input_scale = nullptr,
ggml_tensor* codebook = nullptr,
ggml_tensor* relative_scale = nullptr);
ggml_tensor* ggml_ext_quantize_i8_convrot(GGMLRunnerContext* runner_ctx, ggml_tensor* input, int group_size);
// Packed I8 [K/2, N], low nibble first. W4A8 uses a 16-entry F32 codebook
// and F8_E4M3 [K/16, N] relative scales. F32 inputs get an explicit quantize node.
ggml_tensor* ggml_ext_mul_mat_w4_convrot(GGMLRunnerContext* runner_ctx,
ggml_tensor* weight,
ggml_tensor* input,
ggml_tensor* weight_scale,
ggml_tensor* s_channel,
ggml_tensor* s_rel,
ggml_tensor* bias,
SDW4Kind kind,
int group_size);
// Q/K: contiguous F32 [D, tokens, heads, batch], V: contiguous F16 in the same layout.
// Output: F32 [D, query heads, query tokens, batch]. CUDA-only, unmasked inference.
ggml_tensor* ggml_ext_sage_attn(GGMLRunnerContext* runner_ctx,
@ -292,12 +282,11 @@ ggml_tensor* ggml_ext_linear_w4_convrot(GGMLRunnerContext* runner_ctx,
ggml_tensor* x,
ggml_tensor* w,
ggml_tensor* ws,
ggml_tensor* sc,
ggml_tensor* sr,
ggml_tensor* bias,
SDW4Kind kind,
int group,
float scale = 1.f);
float scale,
ggml_tensor* codebook = nullptr,
ggml_tensor* s_rel = nullptr);
#endif
ggml_tensor* ggml_ext_conv_2d_grouped(GGMLRunnerContext* runner_ctx,

View file

@ -177,8 +177,8 @@ static bool i8_shape(const SDI8Operation& op, const int64_t* shape) {
const auto* w = op.weight;
const auto* x = op.input;
if (!w || !x || w->type != GGML_TYPE_I8 || w->ne[2] != 1 || w->ne[3] != 1 ||
!ggml_is_contiguous(w) || !ggml_is_contiguous(x) || x->ne[0] != w->ne[0] ||
(op.group_size != 0 && (!sd_ggml_valid_convrot_group(op.group_size) || w->ne[0] % op.group_size)))
!ggml_is_contiguous(w) || !ggml_is_contiguous(x) ||
(op.group_size != 0 && (!sd_ggml_valid_convrot_group(op.group_size) || op.k() % op.group_size)))
return false;
int64_t rows = 1;
for (int i = 0; i < 3; ++i) {
@ -186,11 +186,21 @@ static bool i8_shape(const SDI8Operation& op, const int64_t* shape) {
return false;
rows *= shape[i];
}
const int64_t k = w->ne[0], n = w->ne[1];
const int64_t k = op.k(), n = w->ne[1];
int64_t height;
if (n <= 0 || n > (i8_size_limit - 4) / 4 || k <= 0 || k > i8_size_limit - 4 - n * 4 ||
rows > (i8_size_limit - 3) / (k + 4 + n * 4) || !packed_height(k, rows, &height))
return false;
if (op.codebook) {
const auto* scales = op.relative_scale;
if (k % 16 || w->ne[0] != k / 2 || k > i8_size_limit / n || !op.weight_scale ||
!scale_matches(op.codebook, 16) || scales->type != GGML_TYPE_F8_E4M3 ||
!ggml_is_contiguous(scales) || ggml_n_dims(scales) > 2 ||
scales->ne[0] != k / 16 || scales->ne[1] != n)
return false;
} else if (w->ne[0] != k) {
return false;
}
if (op.packed) {
if (x->type != GGML_TYPE_I8 || !sd_ggml_valid_convrot_group(op.group_size) || op.input_scale ||
x->ne[1] != height || x->ne[2] != 1 || x->ne[3] != 1)
@ -207,21 +217,34 @@ static bool i8_shape(const SDI8Operation& op, const int64_t* shape) {
return scale_matches(op.input_scale, rows) && scale_matches(op.weight_scale, w->ne[1]) && scale_matches(op.bias, w->ne[1]);
}
static bool i8_infer(ggml_tensor* const* inputs, int count, const void* attributes, ggml_ext_tensor_desc* output) {
SDI8Attributes attr;
std::memcpy(&attr, attributes, sizeof(attr));
if (count < 2 || (attr.flags & ~15))
static constexpr int i8_flags = SD_I8_PACKED | SD_I8_INPUT_SCALE | SD_I8_WEIGHT_SCALE | SD_I8_BIAS | SD_I8_WEIGHT_W4;
static bool i8_operands(ggml_tensor* const* inputs, int count, const SDI8Attributes& attr, SDI8Operation* op) {
if (count < 2 || (attr.flags & ~i8_flags))
return false;
SDI8Operation op = {inputs[0], inputs[1], nullptr, nullptr, nullptr, attr.group_size, (attr.flags & SD_I8_PACKED) != 0};
int index = 2;
for (auto entry : {std::make_pair(SD_I8_INPUT_SCALE, &op.input_scale), std::make_pair(SD_I8_WEIGHT_SCALE, &op.weight_scale), std::make_pair(SD_I8_BIAS, &op.bias)}) {
*op = {inputs[0], inputs[1], nullptr, nullptr, nullptr, attr.group_size, (attr.flags & SD_I8_PACKED) != 0, nullptr, nullptr};
int index = 2;
for (auto entry : {std::make_pair(SD_I8_INPUT_SCALE, &op->input_scale), std::make_pair(SD_I8_WEIGHT_SCALE, &op->weight_scale), std::make_pair(SD_I8_BIAS, &op->bias)}) {
if (attr.flags & entry.first) {
if (index >= count)
if (index >= count || !inputs[index])
return false;
*entry.second = inputs[index++];
}
}
if (index != count || !i8_shape(op, attr.shape))
if (attr.flags & SD_I8_WEIGHT_W4) {
if (count - index != 2 || !inputs[index] || !inputs[index + 1])
return false;
op->codebook = inputs[index++];
op->relative_scale = inputs[index++];
}
return index == count && i8_shape(*op, attr.shape);
}
static bool i8_infer(ggml_tensor* const* inputs, int count, const void* attributes, ggml_ext_tensor_desc* output) {
SDI8Attributes attr;
std::memcpy(&attr, attributes, sizeof(attr));
SDI8Operation op;
if (!i8_operands(inputs, count, attr, &op))
return false;
output->type = GGML_TYPE_F32;
output->ne[0] = op.weight->ne[1];
@ -256,28 +279,16 @@ ggml_ext_op_t sd_ggml_convrot_op() {
}
bool sd_ggml_i8_describe(const ggml_tensor* node, SDI8Operation* op) {
if (!node || node->type != GGML_TYPE_F32 || !ggml_is_contiguous(node))
if (!node || node->type != GGML_TYPE_F32 || !ggml_is_contiguous(node) || ggml_ext_op_get(node) != sd_ggml_i8_op())
return false;
*op = {node->src[0], node->src[1], nullptr, nullptr, nullptr, 0, false};
if (ggml_ext_op_get(node) == sd_ggml_i8_op()) {
SDI8Attributes attr;
std::memcpy(&attr, ggml_ext_op_attributes(node), sizeof(attr));
if (attr.flags & ~15 || std::memcmp(attr.shape, node->ne + 1, sizeof(attr.shape)))
return false;
op->group_size = attr.group_size;
op->packed = (attr.flags & SD_I8_PACKED) != 0;
int index = 2;
if (attr.flags & SD_I8_INPUT_SCALE)
op->input_scale = node->src[index++];
if (attr.flags & SD_I8_WEIGHT_SCALE)
op->weight_scale = node->src[index++];
if (attr.flags & SD_I8_BIAS)
op->bias = node->src[index++];
if (((attr.flags & SD_I8_INPUT_SCALE) && !op->input_scale) || ((attr.flags & SD_I8_WEIGHT_SCALE) && !op->weight_scale) || ((attr.flags & SD_I8_BIAS) && !op->bias))
return false;
} else
SDI8Attributes attr;
std::memcpy(&attr, ggml_ext_op_attributes(node), sizeof(attr));
if (std::memcmp(attr.shape, node->ne + 1, sizeof(attr.shape)))
return false;
return i8_shape(*op, node->ne + 1) && node->ne[0] == op->weight->ne[1];
int count = 0;
while (count < GGML_MAX_SRC && node->src[count])
++count;
return i8_operands(node->src, count, attr, op) && node->ne[0] == op->weight->ne[1];
}
bool sd_ggml_convrot_describe(const ggml_tensor* node, int* group) {
@ -344,9 +355,7 @@ static bool w4_infer(ggml_tensor* const* inputs, int count, const void* attribut
return false;
SDW4Attributes attr;
std::memcpy(&attr, attributes, sizeof(attr));
const bool codebook = attr.kind == SDW4Kind::W4A8;
if ((!codebook && attr.kind != SDW4Kind::W4A4) || (attr.has_bias != 0 && attr.has_bias != 1) ||
count != (codebook ? 5 : 3) + attr.has_bias)
if ((attr.has_bias != 0 && attr.has_bias != 1) || count != 3 + attr.has_bias)
return false;
for (int i = 0; i < count; ++i)
if (!inputs[i] || !ggml_is_contiguous(inputs[i]))
@ -366,12 +375,9 @@ static bool w4_infer(ggml_tensor* const* inputs, int count, const void* attribut
int64_t height;
if (!packed_height(k, rows, &height) || n > i8_size_limit / 4 / rows ||
x->type != GGML_TYPE_I8 || x->ne[0] != k || x->ne[1] != height || x->ne[2] != 1 || x->ne[3] != 1 ||
!scale_matches(inputs[2], codebook ? 16 : n) ||
!scale_matches(inputs[2], n) ||
(attr.has_bias && !scale_matches(inputs[count - 1], n)))
return false;
if (codebook && (k % 16 || !scale_matches(inputs[3], n) || inputs[4]->type != GGML_TYPE_F8_E4M3 ||
inputs[4]->ne[0] != k / 16 || inputs[4]->ne[1] != n || inputs[4]->ne[2] != 1 || inputs[4]->ne[3] != 1))
return false;
out->type = GGML_TYPE_F32;
out->ne[0] = n;
std::memcpy(out->ne + 1, attr.shape, sizeof(attr.shape));
@ -393,14 +399,12 @@ bool sd_ggml_w4_describe(const ggml_tensor* node, SDW4Operation* op) {
return false;
SDW4Attributes attr;
std::memcpy(&attr, ggml_ext_op_attributes(node), sizeof(attr));
const bool codebook = attr.kind == SDW4Kind::W4A8;
const int count = (codebook ? 5 : 3) + (attr.has_bias != 0);
const int count = 3 + (attr.has_bias != 0);
ggml_ext_tensor_desc out;
if (!w4_infer(node->src, count, &attr, &out) || node->type != out.type ||
std::memcmp(node->ne, out.ne, sizeof(out.ne)))
return false;
*op = {node->src[0], node->src[1], node->src[2], codebook ? node->src[3] : nullptr,
codebook ? node->src[4] : nullptr, attr.has_bias ? node->src[count - 1] : nullptr, attr.kind};
*op = {node->src[0], node->src[1], node->src[2], attr.has_bias ? node->src[3] : nullptr};
return true;
}

View file

@ -27,7 +27,8 @@ struct SDI8Attributes {
enum SDI8Flags { SD_I8_PACKED = 1,
SD_I8_INPUT_SCALE = 2,
SD_I8_WEIGHT_SCALE = 4,
SD_I8_BIAS = 8 };
SD_I8_BIAS = 8,
SD_I8_WEIGHT_W4 = 16 };
struct SDI8Operation {
const ggml_tensor* weight;
@ -37,6 +38,11 @@ struct SDI8Operation {
const ggml_tensor* bias;
int group_size;
bool packed;
const ggml_tensor* codebook;
const ggml_tensor* relative_scale;
int64_t k() const { return input->ne[0]; }
size_t decoded_weight_bytes() const { return codebook ? size_t(k()) * weight->ne[1] : 0; }
};
bool sd_ggml_valid_convrot_group(int group);
@ -74,12 +80,8 @@ struct SDI8LoRAMerge {
ggml_ext_op_t sd_ggml_i8_lora_merge_op();
bool sd_ggml_i8_lora_merge_describe(const ggml_tensor* node, SDI8LoRAMerge* op);
enum class SDW4Kind : int32_t { W4A4 = 1,
W4A8 = 2 };
struct SDW4Attributes {
int64_t shape[3];
SDW4Kind kind;
int32_t has_bias;
};
@ -87,10 +89,7 @@ struct SDW4Operation {
const ggml_tensor* weight;
const ggml_tensor* input;
const ggml_tensor* weight_scale;
const ggml_tensor* s_channel;
const ggml_tensor* s_rel;
const ggml_tensor* bias;
SDW4Kind kind;
};
ggml_ext_op_t sd_ggml_w4_op();

View file

@ -164,6 +164,26 @@ kernel void sd_i8_lora_quantize(device const char* weight [[buffer(0)]],
}
}
kernel void sd_i8_decode_w4a8(device const uchar* packed [[buffer(0)]],
device const float* codebook [[buffer(1)]],
device const uchar* scales [[buffer(2)]],
device char* decoded [[buffer(3)]],
constant uint& groups [[buffer(4)]],
uint group [[thread_position_in_grid]]) {
if (group >= groups)
return;
const uint bits = scales[group];
const uint exponent = (bits >> 3) & 15, mantissa = bits & 7;
const float magnitude = exponent == 0 ? float(mantissa) * (1.f / 512.f)
: as_type<float>(((exponent + 120) << 23) | (mantissa << 20));
const float relative = bits & 128 ? -magnitude : magnitude;
for (uint i = 0; i < 16; ++i) {
const uint code = (packed[group * 8 + i / 2] >> (4 * (i % 2))) & 15;
const float value = codebook[code] * relative;
decoded[group * 16 + i] = (bits & 127) == 127 || isnan(value) ? 0 : char(rint(clamp(value, -127.f, 127.f)));
}
}
struct MatParams {
uint k;
uint n;

View file

@ -17,6 +17,7 @@ namespace sd_metal {
id<MTLComputePipelineState> quantize = nil;
id<MTLComputePipelineState> multiply = nil;
id<MTLComputePipelineState> multiply_mpp = nil;
id<MTLComputePipelineState> decode_w4a8 = nil;
id<MTLComputePipelineState> lora_stats = nil;
id<MTLComputePipelineState> lora_summary = nil;
id<MTLComputePipelineState> lora_quant = nil;
@ -28,6 +29,7 @@ namespace sd_metal {
[quantize release];
[multiply release];
[multiply_mpp release];
[decode_w4a8 release];
[lora_stats release];
[lora_summary release];
[lora_quant release];
@ -78,10 +80,15 @@ namespace sd_metal {
return node->ne[0] <= INT_MAX && ggml_nrows(node) <= INT_MAX;
}
static bool supports_i8(ggml_backend_dev_t, const ggml_tensor* node, void*) {
static bool supports_i8(ggml_backend_dev_t, const ggml_tensor* node, void* user_data) {
SDI8Operation op;
return sd_ggml_i8_describe(node, &op) && dimensions(node) && dimensions(op.weight) &&
uint64_t(op.weight->ne[0]) * ggml_nrows(node) <= UINT32_MAX;
if (!sd_ggml_i8_describe(node, &op) || !dimensions(node) || op.k() > INT_MAX ||
uint64_t(op.k()) * ggml_nrows(node) > UINT32_MAX)
return false;
const auto decode = static_cast<Kernels*>(user_data)->decode_w4a8;
return !op.codebook || (decode.maxTotalThreadsPerThreadgroup >= 128 &&
op.decoded_weight_bytes() <= UINT32_MAX &&
op.decoded_weight_bytes() <= decode.device.maxBufferLength);
}
static bool supports_convrot(ggml_backend_dev_t, const ggml_tensor* node, void*) {
@ -111,6 +118,8 @@ namespace sd_metal {
return GGML_STATUS_FAILED;
}
*bytes = aligned(sd_ggml_modulate_workspace_size(node));
if (linear)
*bytes += aligned(op.decoded_weight_bytes());
if (input->type == GGML_TYPE_F32) {
if (group > 1)
*bytes += aligned(ggml_nbytes(input));
@ -194,6 +203,25 @@ namespace sd_metal {
if (e.linear) {
if (!bind_tensor(kernels, e.op.weight, w))
return GGML_STATUS_FAILED;
if (e.op.codebook) {
ggml_ext_metal_buffer codebook, scales, decoded;
if (!bind_tensor(kernels, e.op.codebook, codebook) ||
!bind_tensor(kernels, e.op.relative_scale, scales) ||
!scratch(e.op.decoded_weight_bytes(), decoded))
return GGML_STATUS_FAILED;
const auto groups = uint32_t(ggml_nelements(e.op.relative_scale));
id<MTLComputeCommandEncoder> encoder = [command computeCommandEncoder];
[encoder setComputePipelineState:kernels->decode_w4a8];
set_buffer(encoder, w, 0);
set_buffer(encoder, codebook, 1);
set_buffer(encoder, scales, 2);
set_buffer(encoder, decoded, 3);
[encoder setBytes:&groups length:sizeof(groups) atIndex:4];
[encoder dispatchThreadgroups:MTLSizeMake((groups + 127) / 128, 1, 1)
threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
[encoder endEncoding];
w = decoded;
}
ws = bias = xs;
if (e.op.weight_scale && !bind_tensor(kernels, e.op.weight_scale, ws))
return GGML_STATUS_FAILED;
@ -327,6 +355,7 @@ void sd_ggml_register_metal_i8(ggml_backend_dev_t device) {
kernels->rotate = pipeline(@"sd_i8_rotate");
kernels->quantize = pipeline(@"sd_i8_quantize");
kernels->multiply = pipeline(@"sd_i8_multiply");
kernels->decode_w4a8 = pipeline(@"sd_i8_decode_w4a8");
kernels->lora_stats = pipeline(@"sd_i8_lora_stats");
kernels->lora_summary = pipeline(@"sd_i8_lora_summary");
kernels->lora_quant = pipeline(@"sd_i8_lora_quantize");

View file

@ -4,6 +4,7 @@
#include <cstdint>
void pretty_progress(int step, int steps, float time);
void pretty_console_progress(int step, int steps, float time);
void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds);
namespace sd {

View file

@ -592,14 +592,17 @@ static void print_progress_line(int step, int steps, const std::string& speed_te
fflush(stdout); // for linux
}
static int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show
static float passed_time = 0.f;
void pretty_progress(int step, int steps, float time) {
if (sd_progress_cb) {
sd_progress_cb(step, steps, time, sd_progress_cb_data);
return;
}
pretty_console_progress(step, steps, time);
}
void pretty_console_progress(int step, int steps, float time) {
static thread_local int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show
static thread_local float passed_time = 0.f;
if (step == 0) {
show_eta = -1; // reinitialize for batch generations
passed_time = 0.f;
@ -654,7 +657,7 @@ void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float
if (!byte_progress_console)
return;
}
if (sd_progress_cb) {
if (!byte_progress_console && sd_progress_cb) {
float time = elapsed_seconds / (step + 1e-6f);
sd_progress_cb(step, steps, time, sd_progress_cb_data);
return;

View file

@ -56,10 +56,9 @@ sd_vulkan_shader(quantize_i8_convrot quantize_i8_convrot ${SD_VK_DOT} -O)
sd_vulkan_shader(quantize_i8_convrot_h64 quantize_i8_convrot_h64 ${SD_VK_DOT} -O -DGROUP_SIZE=64)
sd_vulkan_shader(i8_lora_merge i8_lora_merge ON -O)
sd_vulkan_shader(mul_mat_w4a4_convrot mul_mat_w4a4_convrot ${SD_VK_DOT} -O)
sd_vulkan_shader(mul_mat_w4a8_convrot mul_mat_w4a8_convrot ${SD_VK_DOT} -O)
sd_vulkan_shader(decode_w4a8 decode_w4a8 ON -O)
sd_vulkan_shader(mul_mat_w4a4_convrot_cm2 mul_mat_w4a4_convrot_cm2 ${SD_VK_CM2} -O)
sd_vulkan_shader(mul_mat_w4a4_convrot_decode_cm2 mul_mat_w4a4_convrot_decode_cm2 ${SD_VK_CM2} -O)
sd_vulkan_shader(mul_mat_w4a8_convrot_cm2 mul_mat_w4a8_convrot_cm2 ${SD_VK_CM2} -O)
sd_vulkan_shader(quantize_i8_convrot_subgroup quantize_i8_convrot_subgroup ${SD_VK_DOT} -O)
sd_vulkan_shader(quantize_i8_convrot_register quantize_i8_convrot_subgroup ${SD_VK_DOT} -O -DSINGLE_PASS=1)
sd_vulkan_shader(swiglu_quantize_i8_convrot quantize_i8_convrot_subgroup ${SD_VK_DOT} -O -DSWIGLU=1)

View file

@ -5,6 +5,7 @@
#include <cstring>
#include <vector>
#include "core/ggml_extensions.h"
#include "decode_w4a8.h"
#include "ggml-ext-vulkan.h"
#include "i8_lora_merge.h"
#include "modulate_convrot.h"
@ -16,8 +17,6 @@
#include "mul_mat_w4a4_convrot.h"
#include "mul_mat_w4a4_convrot_cm2.h"
#include "mul_mat_w4a4_convrot_decode_cm2.h"
#include "mul_mat_w4a8_convrot.h"
#include "mul_mat_w4a8_convrot_cm2.h"
#include "quantize_i8_convrot.h"
#include "quantize_i8_convrot_h64.h"
#include "quantize_i8_convrot_register.h"
@ -31,14 +30,12 @@ namespace sd_vulkan_i8 {
// Keep these budgets in sync with the cooperative matrix shader tile layouts.
static constexpr uint32_t w4a4_shared = 2 * (64 + 64) * (64 / 4 + 4) * 4;
static constexpr uint32_t w4a4_large_shared = 2 * (64 + 128) * (64 / 4 + 4) * 4;
static constexpr uint32_t w4a8_shared = (64 * (64 / 2 + 4) + 64 * (64 / 16) + 64 * (64 / 4 + 4) + 256 + 256 + 16 + 1) * 4;
static constexpr uint32_t w4a8_large_shared = (64 * (64 / 2 + 4) + 64 * (64 / 16) + 128 * (64 / 4 + 4) + 256 + 256 + 16 + 1) * 4;
struct Device {
const ggml_ext_vulkan_api* api;
ggml_ext_vulkan_device_info info;
ggml_ext_vulkan_compute_info compute;
bool subgroup, cm2, cm2_small;
bool w4a4_cm2, w4a8_cm2;
bool w4a4_cm2;
uint32_t cm_m, cm_n, cm_k;
};
static bool device_info(ggml_backend_dev_t dev, Device& d) {
@ -68,7 +65,6 @@ namespace sd_vulkan_i8 {
}
if (prop.flexible && prop.workgroup_scope && prop.invocations == 256 && d.info.max_group_size[0] >= 256 && 64 % prop.m == 0 && 64 % prop.n == 0) {
d.w4a4_cm2 |= d.compute.shared_memory >= w4a4_shared && 64 % prop.k == 0 && sizeof(sd_vulkan_shaders::mul_mat_w4a4_convrot_cm2) > 4;
d.w4a8_cm2 |= d.compute.shared_memory >= w4a8_shared && 32 % prop.k == 0 && sizeof(sd_vulkan_shaders::mul_mat_w4a8_convrot_cm2) > 4;
}
}
return d.info.integer_dot_product && sizeof(sd_vulkan_shaders::mul_mat_i8_tensorwise) > 4;
@ -117,24 +113,41 @@ namespace sd_vulkan_i8 {
const auto* x = dst->src[0];
return x->ne[0] <= UINT32_MAX && ggml_nrows(x) <= UINT32_MAX && d.info.max_group_invocations >= 256 && d.info.max_group_size[0] >= 256;
}
static uint64_t w4a8_chunk_cols(const Device& d, const SDI8Operation& op) {
const auto max_bytes = std::min<uint64_t>(UINT32_MAX, d.info.max_buffer_range);
if (op.decoded_weight_bytes() <= max_bytes)
return op.weight->ne[1];
// Complete GEMM tiles also keep the packed weights, group scales, and channel vectors aligned.
const auto alignment = std::max<uint64_t>(128, d.info.buffer_alignment / sizeof(float));
return max_bytes / op.k() / alignment * alignment;
}
static bool is_unchunked_matmul(const Device& d, const ggml_tensor* mat) {
SDI8Operation op;
// SwiGLU and residual epilogues index full-width projections.
return sd_ggml_i8_describe(mat, &op) &&
(!op.codebook || w4a8_chunk_cols(d, op) == uint64_t(op.weight->ne[1]));
}
static bool can_matmul(const Device& d, const ggml_tensor* dst) {
SDI8Operation op;
if (!sd_ggml_i8_describe(dst, &op) || !op.packed || op.group_size != 256 || !op.weight_scale || !bounded(d, dst))
if (!sd_ggml_i8_describe(dst, &op) || !op.packed || !op.weight_scale || !bounded(d, dst))
return false;
for (auto* t : {op.weight, op.input, op.weight_scale, op.bias})
if (t && !bounded(d, t))
return false;
const uint64_t cols = op.weight->ne[1], rows = ggml_nrows(dst);
return op.weight->ne[0] % 256 == 0 && op.weight->ne[0] <= UINT32_MAX && cols <= UINT32_MAX && rows <= UINT32_MAX &&
(cols + 15) / 16 <= d.info.max_group_count[0] && (rows + 15) / 16 <= d.info.max_group_count[1] &&
if (op.codebook && (!bounded(d, op.codebook) || !bounded(d, op.relative_scale) || !w4a8_chunk_cols(d, op)))
return false;
const uint64_t k = op.k(), cols = op.weight->ne[1], rows = ggml_nrows(dst);
return k % 64 == 0 && k <= UINT32_MAX && ggml_nelements(dst) <= UINT32_MAX &&
(k * ((rows + 3) / 4 * 4)) % d.info.buffer_alignment == 0 &&
(cols + 63) / 64 <= d.info.max_group_count[0] && (rows + 31) / 32 <= d.info.max_group_count[1] &&
d.info.max_group_invocations >= 256 && d.info.max_group_size[0] >= 16 && d.info.max_group_size[1] >= 16;
}
static bool w4_supports(ggml_backend_dev_t dev, const ggml_tensor* dst, void*) {
Device d;
SDW4Operation op;
if (!device_info(dev, d) || !sd_ggml_w4_describe(dst, &op) || !bounded(d, dst) ||
sizeof(sd_vulkan_shaders::mul_mat_w4a4_convrot) <= 4 || sizeof(sd_vulkan_shaders::mul_mat_w4a8_convrot) <= 4 ||
d.compute.shared_memory < (op.kind == SDW4Kind::W4A8 ? 16452u : 13312u) || d.info.max_push_constants < 16)
sizeof(sd_vulkan_shaders::mul_mat_w4a4_convrot) <= 4 ||
d.compute.shared_memory < 13312 || d.info.max_push_constants < 16)
return false;
for (auto* t : dst->src)
if (t && (!bounded(d, t) || ggml_nbytes(t) > UINT32_MAX))
@ -310,7 +323,9 @@ namespace sd_vulkan_i8 {
}
const ggml_tensor* gate = glu->src[0];
const ggml_tensor* up = glu->src[1];
if (gate == up || gate->src[1] != up->src[1] || !ggml_are_same_shape(gate, up)) {
SDI8Operation gate_op, up_op;
if (gate == up || !sd_ggml_i8_describe(gate, &gate_op) || !sd_ggml_i8_describe(up, &up_op) ||
gate_op.codebook || up_op.codebook || gate_op.input != up_op.input || !ggml_are_same_shape(gate, up)) {
return false;
}
for (auto mat : {gate, up}) {
@ -344,7 +359,7 @@ namespace sd_vulkan_i8 {
}
const ggml_tensor* mat = node(graph, i);
const ggml_tensor* glu = node(graph, i + 1);
return is_mat(mat) && can_matmul(device, mat) &&
return is_unchunked_matmul(device, mat) && can_matmul(device, mat) &&
mat->view_src == nullptr && mat->src[3] == nullptr && mat->ne[0] % 256 == 0 &&
glu->op == GGML_OP_GLU && ggml_get_glu_op(glu) == GGML_GLU_OP_SWIGLU &&
param_i32(glu, 1) == 0 && glu->src[0] == mat && glu->src[1] == nullptr &&
@ -367,7 +382,7 @@ namespace sd_vulkan_i8 {
const ggml_tensor* scaled_mat = mul->src[0];
const bool scaled = scaled_mat->op == GGML_OP_SCALE;
const ggml_tensor* mat = scaled ? scaled_mat->src[0] : scaled_mat;
if (!is_mat(mat) || !can_matmul(device, mat) || mat->src[3] != nullptr ||
if (!is_unchunked_matmul(device, mat) || !can_matmul(device, mat) || mat->src[3] != nullptr ||
(scaled && param_f32(scaled_mat, 1) != 0.0f)) {
return 0;
}
@ -475,9 +490,9 @@ namespace sd_vulkan_i8 {
struct MatParameters {
uint32_t n, rows, k, has_bias, row_offset;
float output_scale;
uint32_t group_cols;
uint32_t group_cols, output_stride, output_col;
};
static_assert(sizeof(QuantParameters) == 8 && sizeof(ModulateParameters) == 28 && sizeof(MatParameters) == 28, "INT8 push constant layout mismatch");
static_assert(sizeof(QuantParameters) == 8 && sizeof(ModulateParameters) == 28 && sizeof(MatParameters) == 36, "INT8 push constant layout mismatch");
template <size_t N>
static ggml_ext_vulkan_pipeline shader(const char* name, const uint32_t (&spirv)[N], uint32_t bindings, uint32_t constants) {
return {name, spirv, sizeof(spirv), bindings, constants, nullptr, 0, 0, false};
@ -628,9 +643,13 @@ namespace sd_vulkan_i8 {
SDI8Operation op, up;
if (!sd_ggml_i8_describe(mat, &op) || (up_mat && !sd_ggml_i8_describe(up_mat, &up)))
return GGML_STATUS_FAILED;
const uint32_t k = uint32_t(op.weight->ne[0]), n = uint32_t(op.weight->ne[1]), rows = uint32_t(ggml_nrows(mat));
const uint32_t k = uint32_t(op.k()), n = uint32_t(op.weight->ne[1]), rows = uint32_t(ggml_nrows(mat));
const size_t scale_offset = size_t(k) * ((uint64_t(rows) + 3) / 4 * 4);
std::vector<ggml_ext_vulkan_binding> inputs = {{op.weight}, {op.input}, {op.weight_scale}, {op.bias ? op.bias : op.weight_scale}};
if (op.codebook) {
inputs.push_back({op.codebook});
inputs.push_back({op.relative_scale});
}
if (gate) {
inputs.push_back({gate});
inputs.push_back({residual});
@ -645,47 +664,90 @@ namespace sd_vulkan_i8 {
bool alias;
if (!output_binding(e, d, output, inputs, dst, alias, concat ? nullptr : residual))
return GGML_STATUS_FAILED;
auto destination = concat ? range(dst, ggml_nbytes(concat->src[0]), ggml_nbytes(tail)) : dst;
const uint32_t chunk_cols = op.codebook ? uint32_t(w4a8_chunk_cols(d, op)) : n;
if (!chunk_cols)
return GGML_STATUS_FAILED;
if (op.codebook && alias)
dst.offset = GGML_PAD(size_t(chunk_cols) * k, d.info.buffer_alignment);
const auto destination = concat ? range(dst, ggml_nbytes(concat->src[0]), ggml_nbytes(tail)) : dst;
const uint32_t output_stride = uint32_t(tail->ne[0]);
ggml_ext_vulkan_binding bindings[] = {{op.weight}, {op.input, nullptr, 0, scale_offset}, {op.weight_scale}, {op.input, nullptr, scale_offset, size_t(rows) * 4}, {op.bias ? op.bias : op.weight_scale}, destination, {up_mat ? up.weight : gate}, {up_mat ? up.weight_scale : residual}};
auto dispatch = [&](ggml_ext_vulkan_pipeline pipeline, uint32_t tile_cols, uint32_t tile_rows,
std::initializer_list<uint32_t> constants, uint32_t row_offset, uint32_t dispatch_rows) {
if (!dispatch_rows)
return GGML_STATUS_SUCCESS;
const uint32_t cols = glu ? uint32_t(glu->ne[0]) : n;
MatParameters pc = {n * (up_mat ? 2u : 1u), rows, k, op.bias ? 1u : 0u, row_offset, output_scale, group_columns(cols, k, tile_cols, glu != nullptr)};
pipeline.constants = constants.begin();
pipeline.constant_count = uint32_t(constants.size());
const uint32_t groups[] = {(cols + tile_cols - 1) / tile_cols, (dispatch_rows + tile_rows - 1) / tile_rows, 1};
return d.api->dispatch(e->backend, &pipeline, bindings, &pc, groups);
auto multiply_chunk = [&](uint32_t first, uint32_t cols) {
const uint32_t output_cols = glu ? uint32_t(glu->ne[0]) : cols;
auto dispatch = [&](ggml_ext_vulkan_pipeline pipeline, uint32_t tile_cols, uint32_t tile_rows,
std::initializer_list<uint32_t> constants, uint32_t row_offset, uint32_t dispatch_rows) {
if (!dispatch_rows)
return GGML_STATUS_SUCCESS;
MatParameters pc = {cols * (up_mat ? 2u : 1u), rows, k, op.bias ? 1u : 0u, row_offset, output_scale,
group_columns(output_cols, k, tile_cols, glu != nullptr), output_stride, first};
pipeline.constants = constants.begin();
pipeline.constant_count = uint32_t(constants.size());
const uint32_t groups[] = {(output_cols + tile_cols - 1) / tile_cols, (dispatch_rows + tile_rows - 1) / tile_rows, 1};
return d.api->dispatch(e->backend, &pipeline, bindings, &pc, groups);
};
ggml_status status = GGML_STATUS_SUCCESS;
if (d.cm2) {
const bool large_k = k % 4096 == 0 || (rows >= cols && k >= cols);
// The aligned store uses a row stride rounded down to 128 columns.
const bool aligned_output = cols % 128 == 0 && output_stride % 128 == 0;
const uint32_t full_rows = (glu || aligned_output) ? rows / 128 * 128 : 0;
auto pipeline = residual ? SD_VK_PIPELINE(mul_mat_i8_residual_cm2, 8, MatParameters) : up_mat ? SD_VK_PIPELINE(mul_mat_i8_swiglu_split_cm2, 8, MatParameters)
: SD_VK_PIPELINE(mul_mat_i8_tensorwise_cm2, 6, MatParameters);
const uint32_t tile_cols = glu ? 64 : 128;
const uint32_t full_k = (glu || large_k) && k % 128 == 0 ? 128u : 64u;
status = dispatch(pipeline, tile_cols, 128, {128, 1, glu ? 1u : 0u, tile_cols, full_k}, 0, full_rows);
if (status == GGML_STATUS_SUCCESS) {
const bool small = d.cm2_small && (glu || aligned_output) && rows - full_rows <= 32;
const uint32_t tail_cols = small || glu ? 64 : 128, tail_rows = small ? 32 : glu ? 128
: 64;
const uint32_t tail_k = small && k % 256 == 0 ? 256u : 64u;
status = dispatch(pipeline, tail_cols, tail_rows, {tail_rows, small ? 2u : 0u, glu ? 1u : 0u, tail_cols, tail_k}, full_rows, rows - full_rows);
}
} else {
uint32_t coop_rows = 0;
if (d.cm_m && k % d.cm_k == 0 && cols % (4 * d.cm_n) == 0 &&
cols / (4 * d.cm_n) <= d.info.max_group_count[0] && rows / (4 * d.cm_m) <= d.info.max_group_count[1]) {
const uint32_t tile_rows = 4 * d.cm_m;
coop_rows = rows / tile_rows * tile_rows;
auto pipeline = SD_VK_PIPELINE(mul_mat_i8_tensorwise_cm1, 6, MatParameters);
pipeline.full_subgroups = d.info.full_subgroups;
pipeline.required_subgroup_size = d.info.subgroup_size_control ? d.info.subgroup_size : 0;
status = dispatch(pipeline, 4 * d.cm_n, tile_rows, {d.info.subgroup_size, d.cm_m, d.cm_n, d.cm_k}, 0, coop_rows);
}
if (status == GGML_STATUS_SUCCESS)
status = dispatch(SD_VK_PIPELINE(mul_mat_i8_tensorwise, 6, MatParameters), 64, 32, {}, coop_rows, rows - coop_rows);
}
return status;
};
ggml_status status = GGML_STATUS_SUCCESS;
if (d.cm2) {
const bool large_k = k % 4096 == 0 || (rows >= n && k >= n);
const uint32_t full_rows = (glu || n % 128 == 0) ? rows / 128 * 128 : 0;
auto pipeline = residual ? SD_VK_PIPELINE(mul_mat_i8_residual_cm2, 8, MatParameters) : up_mat ? SD_VK_PIPELINE(mul_mat_i8_swiglu_split_cm2, 8, MatParameters)
: SD_VK_PIPELINE(mul_mat_i8_tensorwise_cm2, 6, MatParameters);
const uint32_t tile_cols = glu ? 64 : 128;
status = dispatch(pipeline, tile_cols, 128, {128, 1, glu ? 1u : 0u, tile_cols, glu || large_k ? 128u : 64u}, 0, full_rows);
if (status == GGML_STATUS_SUCCESS) {
const bool small = d.cm2_small && (glu || n % 128 == 0) && rows - full_rows <= 32;
const uint32_t tail_cols = small || glu ? 64 : 128, tail_rows = small ? 32 : glu ? 128
: 64;
status = dispatch(pipeline, tail_cols, tail_rows, {tail_rows, small ? 2u : 0u, glu ? 1u : 0u, tail_cols, small ? 256u : 64u}, full_rows, rows - full_rows);
for (uint32_t first = 0; first < n;) {
const uint32_t cols = std::min(chunk_cols, n - first);
if (op.codebook) {
const size_t packed_row = op.weight->nb[1], scale_row = op.relative_scale->nb[1];
bindings[0] = {nullptr, e->workspace, 0, size_t(cols) * k};
bindings[2] = range({op.weight_scale}, size_t(first) * sizeof(float), size_t(cols) * sizeof(float));
bindings[4] = op.bias ? range({op.bias}, size_t(first) * sizeof(float), size_t(cols) * sizeof(float)) : bindings[2];
const ggml_ext_vulkan_binding decode_inputs[] = {
range({op.weight}, first * packed_row, cols * packed_row),
{op.codebook},
range({op.relative_scale}, first * scale_row, cols * scale_row),
bindings[0],
};
const uint32_t groups_count = cols * (k / 16);
const uint32_t groups[] = {std::min((groups_count + 127) / 128, d.info.max_group_count[0]), 1, 1};
const auto pipeline = SD_VK_PIPELINE(decode_w4a8, 4, uint32_t);
const auto status = d.api->dispatch(e->backend, &pipeline, decode_inputs, &groups_count, groups);
if (status != GGML_STATUS_SUCCESS)
return status;
}
} else {
uint32_t coop_rows = 0;
if (d.cm_m && k % d.cm_k == 0 && n % (4 * d.cm_n) == 0) {
const uint32_t tile_rows = 4 * d.cm_m;
coop_rows = rows / tile_rows * tile_rows;
auto pipeline = SD_VK_PIPELINE(mul_mat_i8_tensorwise_cm1, 6, MatParameters);
pipeline.full_subgroups = d.info.full_subgroups;
pipeline.required_subgroup_size = d.info.subgroup_size_control ? d.info.subgroup_size : 0;
status = dispatch(pipeline, 4 * d.cm_n, tile_rows, {d.info.subgroup_size, d.cm_m, d.cm_n, d.cm_k}, 0, coop_rows);
}
if (status == GGML_STATUS_SUCCESS)
status = dispatch(SD_VK_PIPELINE(mul_mat_i8_tensorwise, 6, MatParameters), 16, 16, {}, coop_rows, rows - coop_rows);
const auto status = multiply_chunk(first, cols);
if (status != GGML_STATUS_SUCCESS)
return status;
first += cols;
}
if (status == GGML_STATUS_SUCCESS && concat && ggml_nbytes(concat->src[0])) {
ggml_status status = GGML_STATUS_SUCCESS;
if (concat && ggml_nbytes(concat->src[0])) {
ggml_ext_vulkan_binding src = {concat->src[0]}, prefix = range(dst, 0, ggml_nbytes(concat->src[0]));
status = d.api->copy(e->backend, &src, &prefix);
}
@ -699,10 +761,6 @@ namespace sd_vulkan_i8 {
const size_t scale_offset = size_t(k) * ((uint64_t(rows) + 3) / 4 * 4);
const ggml_ext_vulkan_binding xs = {op.input, nullptr, scale_offset, size_t(rows) * 4};
std::vector<ggml_ext_vulkan_binding> bindings = {{op.weight}, {op.input, nullptr, 0, scale_offset}, {op.weight_scale}};
if (op.kind == SDW4Kind::W4A8) {
bindings.push_back({op.s_channel});
bindings.push_back({op.s_rel});
}
bindings.push_back(xs);
bindings.push_back({op.bias ? op.bias : op.weight_scale});
ggml_ext_vulkan_binding dst;
@ -714,17 +772,15 @@ namespace sd_vulkan_i8 {
uint32_t n, rows, k, bias;
};
const Parameters pc = {n, rows, k, op.bias ? 1u : 0u};
auto pipeline = op.kind == SDW4Kind::W4A4 ? SD_VK_PIPELINE(mul_mat_w4a4_convrot, 6, Parameters) : SD_VK_PIPELINE(mul_mat_w4a8_convrot, 8, Parameters);
auto pipeline = SD_VK_PIPELINE(mul_mat_w4a4_convrot, 6, Parameters);
uint32_t tile_cols = 64, tile_rows = 32;
const bool large_w4a4 = op.kind == SDW4Kind::W4A4 && rows >= 512 && d.compute.shared_memory >= w4a4_large_shared;
const bool large_w4a8 = op.kind == SDW4Kind::W4A8 && rows >= 512 && d.compute.shared_memory >= w4a8_large_shared;
const bool decode_w4a4 = op.kind == SDW4Kind::W4A4 && d.w4a4_cm2 && k % 256 == 0 && n % 64 == 0 && rows >= 128 &&
const bool large_w4a4 = rows >= 512 && d.compute.shared_memory >= w4a4_large_shared;
const bool decode_w4a4 = d.w4a4_cm2 && k % 256 == 0 && n % 64 == 0 && rows >= 128 &&
aligned(op.weight, 16) && sizeof(sd_vulkan_shaders::mul_mat_w4a4_convrot_decode_cm2) > 4;
const uint32_t constants[] = {64, large_w4a4 || large_w4a8 ? 128u : 64u, 64};
const uint32_t constants[] = {64, large_w4a4 ? 128u : 64u, 64};
const char* force_dp4a = std::getenv("GGML_VK_W4_FORCE_DP4A");
if (!(force_dp4a && std::atoi(force_dp4a)) && aligned(op.input, 16) &&
(op.kind == SDW4Kind::W4A4 ? d.w4a4_cm2 : d.w4a8_cm2 && aligned(op.weight, 8))) {
pipeline = op.kind == SDW4Kind::W4A4 ? SD_VK_PIPELINE(mul_mat_w4a4_convrot_cm2, 6, Parameters) : SD_VK_PIPELINE(mul_mat_w4a8_convrot_cm2, 8, Parameters);
if (!(force_dp4a && std::atoi(force_dp4a)) && aligned(op.input, 16) && d.w4a4_cm2) {
pipeline = SD_VK_PIPELINE(mul_mat_w4a4_convrot_cm2, 6, Parameters);
if (decode_w4a4) {
struct DecodeParameters {
uint32_t n, rows, k, bias, row_offset;
@ -834,7 +890,7 @@ namespace sd_vulkan_i8 {
const auto src = reinterpret_cast<uintptr_t>(input->data) + offset;
return dst < src + size && src < dst + ggml_nbytes(output);
}
static ggml_status prepare(ggml_backend_t, ggml_tensor* const* nodes, int count, void**, size_t* bytes, void*) {
static ggml_status prepare(ggml_backend_t backend, ggml_tensor* const* nodes, int count, void**, size_t* bytes, void*) {
const auto* output = nodes[count - 1];
// Fresh outputs cannot alias external inputs except the residual's elementwise reuse.
const bool fresh = !output->data && !output->view_src &&
@ -850,6 +906,13 @@ namespace sd_vulkan_i8 {
if (!alias)
*bytes = 0;
}
SDI8Operation op;
if (sd_ggml_i8_describe(nodes[0], &op) && op.codebook) {
Device d;
if (!device_info(ggml_backend_get_device(backend), d))
return GGML_STATUS_FAILED;
*bytes += GGML_PAD(w4a8_chunk_cols(d, op) * op.k(), d.info.buffer_alignment);
}
return GGML_STATUS_SUCCESS;
}
static void destroy(void*, void*) {}

View file

@ -0,0 +1,39 @@
#version 450
layout(local_size_x = 128) in;
layout(push_constant) uniform Parameters {
uint groups;
}
p;
layout(binding = 0, std430) readonly buffer Packed {
uint packed[];
};
layout(binding = 1, std430) readonly buffer Codebook {
float codebook[];
};
layout(binding = 2, std430) readonly buffer Scales {
uint scales[];
};
layout(binding = 3, std430) writeonly buffer Decoded {
uint decoded[];
};
void main() {
for (uint group = gl_GlobalInvocationID.x; group < p.groups; group += gl_NumWorkGroups.x * gl_WorkGroupSize.x) {
const uint bits = (scales[group / 4] >> (8 * (group % 4))) & 255u;
const uint exponent = (bits >> 3) & 15u;
const uint mantissa = bits & 7u;
const float magnitude = exponent == 0 ? float(mantissa) / 512.0 : uintBitsToFloat(((exponent + 120) << 23) | (mantissa << 20));
const float relative = (bits & 128u) != 0 ? -magnitude : magnitude;
for (uint i = 0; i < 4; ++i) {
const uint codes = packed[group * 2 + i / 2] >> (16 * (i % 2));
uint word = 0;
for (uint j = 0; j < 4; ++j) {
const float value = codebook[(codes >> (4 * j)) & 15u] * relative;
const int q = (bits & 127u) == 127u || isnan(value) ? 0 : int(roundEven(clamp(value, -127.0, 127.0)));
word |= (uint(q) & 255u) << (8 * j);
}
decoded[group * 4 + i] = word;
}
}
}

View file

@ -11,6 +11,8 @@ layout(push_constant) uniform parameter {
uint k;
uint has_bias;
uint row_offset;
layout(offset = 28) uint output_stride;
uint output_col;
}
p;
@ -33,42 +35,54 @@ layout(binding = 5, std430) writeonly buffer D {
float data_d[];
};
shared int weights[16 * 8];
shared int activations[16 * 8];
shared int weights[64][8];
shared int activations[32][8];
void main() {
const uint output_index = gl_WorkGroupID.x * 16 + gl_LocalInvocationID.x;
const uint row = p.row_offset + gl_WorkGroupID.y * 16 + gl_LocalInvocationID.y;
const uint lx = gl_LocalInvocationID.x;
const uint ly = gl_LocalInvocationID.y;
const uint k_packed = p.k / 4;
int sum = 0;
const uint col_base = gl_WorkGroupID.x * 64;
const uint row_base = p.row_offset + gl_WorkGroupID.y * 32;
const uint lx = gl_LocalInvocationID.x;
const uint ly = gl_LocalInvocationID.y;
const uint load_row = gl_LocalInvocationIndex / 8;
const uint load_word = gl_LocalInvocationIndex % 8;
const uint k_packed = p.k / 4;
int sum[2][4];
[[unroll]] for (uint r = 0; r < 2; ++r)
[[unroll]]
for (uint c = 0; c < 4; ++c)
sum[r][c] = 0;
for (uint k_base = 0; k_base < k_packed; k_base += 8) {
if (ly < 8) {
weights[lx * 8 + ly] = output_index < p.n
? data_w[output_index * k_packed + k_base + ly]
: 0;
}
if (lx < 8) {
activations[ly * 8 + lx] = row < p.rows
? data_a[row * k_packed + k_base + lx]
: 0;
const uint word = k_base + load_word;
const uint row = row_base + load_row;
activations[load_row][load_word] = row < p.rows ? data_a[row * k_packed + word] : 0;
[[unroll]] for (uint j = 0; j < 2; ++j) {
const uint offset = load_row + j * 32;
const uint col = col_base + offset;
weights[offset][load_word] = col < p.n ? data_w[col * k_packed + word] : 0;
}
barrier();
[[unroll]]
for (uint i = 0; i < 8; ++i) {
sum += dotPacked4x8EXT(weights[lx * 8 + i], activations[ly * 8 + i]);
[[unroll]] for (uint i = 0; i < 8; ++i) {
[[unroll]] for (uint r = 0; r < 2; ++r) {
const int act = activations[ly + 16 * r][i];
[[unroll]] for (uint c = 0; c < 4; ++c)
sum[r][c] += dotPacked4x8EXT(weights[lx + 16 * c][i], act);
}
}
barrier();
}
if (output_index < p.n && row < p.rows) {
float value = float(sum) * data_as[row] * data_ws[output_index];
if (p.has_bias != 0) {
value += data_b[output_index];
[[unroll]] for (uint r = 0; r < 2; ++r) {
const uint row = row_base + ly + 16 * r;
[[unroll]] for (uint c = 0; c < 4; ++c) {
const uint col = col_base + lx + 16 * c;
if (col < p.n && row < p.rows) {
float value = float(sum[r][c]) * data_as[row] * data_ws[col];
if (p.has_bias != 0)
value += data_b[col];
data_d[row * p.output_stride + p.output_col + col] = value;
}
}
data_d[row * p.n + output_index] = value;
}
}

View file

@ -23,6 +23,8 @@ layout(push_constant) uniform parameter {
uint k;
uint has_bias;
uint row_offset;
layout(offset = 28) uint output_stride;
uint output_col;
}
p;
@ -97,7 +99,7 @@ void main() {
if (p.has_bias != 0) {
value += data_b[output_index];
}
data_d[row * p.n + output_index] = value;
data_d[row * p.output_stride + p.output_col + output_index] = value;
}
controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup,
gl_StorageSemanticsShared, gl_SemanticsAcquireRelease);

View file

@ -22,6 +22,8 @@ layout(push_constant) uniform parameter {
uint row_offset;
float output_scale;
uint group_cols;
uint output_stride;
uint output_col;
}
p;
@ -94,13 +96,13 @@ int32_t dequantize_swiglu(const in uint row, const in uint col, const in int32_t
}
void main() {
const uint k_size = p.k & ~255u;
const uint k_size = p.k & ~63u;
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> a_layout = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> w_layout = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> d_layout = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
a_layout = setTensorLayoutDimensionNV(a_layout, p.rows, k_size);
w_layout = setTensorLayoutDimensionNV(w_layout, p.n, k_size);
d_layout = setTensorLayoutDimensionNV(d_layout, p.rows, SWIGLU ? p.n / 2 : p.n);
d_layout = setTensorLayoutDimensionNV(d_layout, p.rows, p.output_stride);
tensorViewNV<2, false, 1, 0> transpose = createTensorViewNV(2, false, 1, 0);
// Keep a weight panel in L2 while visiting the activation tiles.
const uint col_tiles = gl_NumWorkGroups.x;
@ -164,9 +166,9 @@ void main() {
// The aligned dispatch contains only complete tiles and a 128-aligned output width.
if (ALIGNMENT == 1) {
tensorLayoutNV<2> d_full = createTensorLayoutNV(2);
d_full = setTensorLayoutDimensionNV(d_full, p.rows, (SWIGLU ? p.n / 2 : p.n) & ~127u);
coopMatStoreTensorNV(sum, data_d, 0, sliceTensorLayoutNV(d_full, row, BN, col, BM), transpose);
d_full = setTensorLayoutDimensionNV(d_full, p.rows, p.output_stride & ~127u);
coopMatStoreTensorNV(sum, data_d, 0, sliceTensorLayoutNV(d_full, row, BN, p.output_col + col, BM), transpose);
} else {
coopMatStoreTensorNV(sum, data_d, 0, sliceTensorLayoutNV(d_layout, row, BN, col, BM), transpose);
coopMatStoreTensorNV(sum, data_d, 0, sliceTensorLayoutNV(d_layout, row, BN, p.output_col + col, BM), transpose);
}
}

View file

@ -1,244 +0,0 @@
#version 460
#extension GL_EXT_control_flow_attributes : require
#extension GL_EXT_integer_dot_product : require
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
layout(push_constant) uniform parameter {
uint n;
uint rows;
uint k;
uint has_bias;
}
p;
layout(binding = 0, std430) readonly buffer W {
int data_w[];
};
layout(binding = 1, std430) readonly buffer A {
int data_a[];
};
layout(binding = 2, std430) readonly buffer CB {
float data_cb[];
};
layout(binding = 3, std430) readonly buffer SC {
float data_sc[];
};
layout(binding = 4, std430) readonly buffer SR {
uint data_sr[];
};
layout(binding = 5, std430) readonly buffer AS {
float data_as[];
};
layout(binding = 6, std430) readonly buffer B {
float data_b[];
};
layout(binding = 7, std430) writeonly buffer D {
float data_d[];
};
shared int w_dec[2][16 * 64];
shared int x_tile[2][32 * 16];
shared float s_dec[2][4 * 64];
shared int lut[256];
shared float s_lut[256];
shared int cb8s[16];
shared float s_cb;
float f8_e4m3_to_f32(uint v) {
const uint sign = (v >> 7) & 1u;
const uint exp = (v >> 3) & 0xFu;
const uint man = v & 0x7u;
float result;
if (exp == 0xFu && man == 0x7u) {
result = uintBitsToFloat(0x7FC00000u);
} else if (exp == 0u) {
result = ldexp(float(man), -9);
} else {
result = ldexp(1.0 + float(man) / 8.0, int(exp) - 7);
}
return sign != 0u ? -result : result;
}
void main() {
const uint out_base = gl_WorkGroupID.x * 64u;
const uint lx = gl_LocalInvocationID.x;
const uint ly = gl_LocalInvocationID.y;
const uint row0 = gl_WorkGroupID.y * 32u + ly;
const uint row1 = row0 + 16u;
const uint idx = gl_LocalInvocationIndex;
const uint w_words = p.k / 8u;
const uint a_words = p.k / 4u;
const uint groups = p.k / 16u;
const uint sr_words = groups / 4u;
const uint dc = idx & 63u;
const uint dw = idx >> 6u;
const uint ocol = out_base + dc;
float sum0 = 0.0;
float sum1 = 0.0;
float sum2 = 0.0;
float sum3 = 0.0;
float sum4 = 0.0;
float sum5 = 0.0;
float sum6 = 0.0;
float sum7 = 0.0;
if (idx == 0u) {
float amax = 0.0;
for (uint i = 0; i < 16; ++i) {
amax = max(amax, abs(data_cb[i]));
}
s_cb = amax / 127.0;
for (uint i = 0; i < 16; ++i) {
const int v = (s_cb == 0.0 ? 0 : int(roundEven(data_cb[i] / s_cb)));
cb8s[i] = v < -127 ? -127 : (v > 127 ? 127 : v);
}
}
barrier();
lut[idx] = (cb8s[idx & 0xFu] & 0xFF) | (cb8s[idx >> 4] << 8);
s_lut[idx] = f8_e4m3_to_f32(idx);
barrier();
{
[[unroll]] for (uint j = 0; j < 2; ++j) {
const uint pw = dw * 2 + j;
const uint widx = pw;
const uint wv = ocol < p.n && widx < w_words
? uint(data_w[ocol * w_words + widx])
: 0u;
w_dec[0][(pw * 2 + 0) * 64 + dc] = int((uint(lut[wv & 0xFFu] & 0xFFFF)) | (uint(lut[(wv >> 8) & 0xFFu] & 0xFFFF) << 16));
w_dec[0][(pw * 2 + 1) * 64 + dc] = int((uint(lut[(wv >> 16) & 0xFFu] & 0xFFFF)) | (uint(lut[(wv >> 24) & 0xFFu] & 0xFFFF) << 16));
}
{
const uint g = dw;
float s = 0.0;
if (ocol < p.n && g < groups) {
const uint sr_word = data_sr[ocol * sr_words + g / 4u];
s = data_sc[ocol] * s_lut[(sr_word >> (8u * (g % 4u))) & 0xFFu];
}
s_dec[0][dw * 64 + dc] = s_cb * s;
}
if (lx < 16u) {
const uint aidx = lx;
x_tile[0][ly * 16 + lx] = row0 < p.rows && aidx < a_words
? data_a[row0 * a_words + aidx]
: 0;
x_tile[0][(16u + ly) * 16 + lx] = row1 < p.rows && aidx < a_words
? data_a[row1 * a_words + aidx]
: 0;
}
}
barrier();
for (uint gs = 0; gs < groups; gs += 4) {
const uint buf = (gs >> 2) & 1u;
if (gs + 4 < groups) {
const uint nbuf = buf ^ 1u;
const uint ngs = gs + 4;
[[unroll]] for (uint j = 0; j < 2; ++j) {
const uint pw = dw * 2 + j;
const uint widx = ngs * 2 + pw;
const uint wv = ocol < p.n && widx < w_words
? uint(data_w[ocol * w_words + widx])
: 0u;
w_dec[nbuf][(pw * 2 + 0) * 64 + dc] = int((uint(lut[wv & 0xFFu] & 0xFFFF)) | (uint(lut[(wv >> 8) & 0xFFu] & 0xFFFF) << 16));
w_dec[nbuf][(pw * 2 + 1) * 64 + dc] = int((uint(lut[(wv >> 16) & 0xFFu] & 0xFFFF)) | (uint(lut[(wv >> 24) & 0xFFu] & 0xFFFF) << 16));
}
{
const uint g = ngs + dw;
float s = 0.0;
if (ocol < p.n && g < groups) {
const uint sr_word = data_sr[ocol * sr_words + g / 4u];
s = data_sc[ocol] * s_lut[(sr_word >> (8u * (g % 4u))) & 0xFFu];
}
s_dec[nbuf][dw * 64 + dc] = s_cb * s;
}
if (lx < 16u) {
const uint aidx = ngs * 4 + lx;
x_tile[nbuf][ly * 16 + lx] = row0 < p.rows && aidx < a_words
? data_a[row0 * a_words + aidx]
: 0;
x_tile[nbuf][(16u + ly) * 16 + lx] = row1 < p.rows && aidx < a_words
? data_a[row1 * a_words + aidx]
: 0;
}
}
float partial0 = 0.0;
float partial1 = 0.0;
float partial2 = 0.0;
float partial3 = 0.0;
float partial4 = 0.0;
float partial5 = 0.0;
float partial6 = 0.0;
float partial7 = 0.0;
{
[[unroll]] for (uint gl = 0; gl < 4; ++gl) {
int accg0 = 0;
int accg1 = 0;
int accg2 = 0;
int accg3 = 0;
int accg4 = 0;
int accg5 = 0;
int accg6 = 0;
int accg7 = 0;
[[unroll]] for (uint q = 0; q < 4; ++q) {
const int a0 = x_tile[buf][ly * 16 + gl * 4 + q];
const int a1 = x_tile[buf][(16u + ly) * 16 + gl * 4 + q];
accg0 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + lx], a0));
accg1 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + 16u + lx], a0));
accg2 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + 32u + lx], a0));
accg3 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + 48u + lx], a0));
accg4 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + lx], a1));
accg5 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + 16u + lx], a1));
accg6 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + 32u + lx], a1));
accg7 += int(dotPacked4x8EXT(w_dec[buf][(gl * 4 + q) * 64 + 48u + lx], a1));
}
const float s0 = s_dec[buf][gl * 64 + lx];
const float s1 = s_dec[buf][gl * 64 + 16u + lx];
const float s2 = s_dec[buf][gl * 64 + 32u + lx];
const float s3 = s_dec[buf][gl * 64 + 48u + lx];
partial0 += float(accg0) * s0;
partial1 += float(accg1) * s1;
partial2 += float(accg2) * s2;
partial3 += float(accg3) * s3;
partial4 += float(accg4) * s0;
partial5 += float(accg5) * s1;
partial6 += float(accg6) * s2;
partial7 += float(accg7) * s3;
}
}
sum0 += partial0;
sum1 += partial1;
sum2 += partial2;
sum3 += partial3;
sum4 += partial4;
sum5 += partial5;
sum6 += partial6;
sum7 += partial7;
barrier();
}
const float sumv[8] = {sum0, sum1, sum2, sum3, sum4, sum5, sum6, sum7};
[[unroll]] for (uint t = 0; t < 2u; ++t) {
const uint rt = t == 0u ? row0 : row1;
if (rt < p.rows) {
[[unroll]] for (uint j = 0; j < 4; ++j) {
const uint oj = out_base + j * 16u + lx;
if (oj < p.n) {
float value = sumv[t * 4u + j] * data_as[rt];
if (p.has_bias != 0) {
value += data_b[oj];
}
data_d[rt * p.n + oj] = value;
}
}
}
}
}

View file

@ -1,164 +0,0 @@
#version 460
#extension GL_EXT_shader_explicit_arithmetic_types_int8 : require
#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require
#extension GL_KHR_cooperative_matrix : require
#extension GL_NV_cooperative_matrix2 : require
#extension GL_KHR_memory_scope_semantics : require
#extension GL_EXT_control_flow_attributes : require
layout(local_size_x = 256) in;
layout(constant_id = 0) const uint BM = 64;
layout(constant_id = 1) const uint BN = 64;
layout(constant_id = 2) const uint BK = 64;
const uint STRIDE = BK / 2 + 4;
layout(push_constant) uniform parameter {
uint n;
uint rows;
uint k;
uint has_bias;
}
p;
layout(binding = 0, std430) readonly buffer W {
uvec2 data_w[];
};
layout(binding = 1, std430) readonly buffer A {
uvec4 data_a[];
};
layout(binding = 2, std430) readonly buffer CB {
float data_cb[];
};
layout(binding = 3, std430) readonly buffer SC {
float data_sc[];
};
layout(binding = 4, std430) readonly buffer SR {
uint data_sr[];
};
layout(binding = 5, std430) readonly buffer AS {
float data_as[];
};
layout(binding = 6, std430) readonly buffer B {
float data_b[];
};
layout(binding = 7, std430) writeonly buffer D {
int32_t data_d[];
};
shared uint lut[256];
shared int cb[16];
shared float cb_scale;
shared float relative[256];
shared float scales[BK / 16 * BM];
float fp8_e4m3(uint v) {
const uint exponent = (v >> 3) & 15u, mantissa = v & 7u;
const float value = exponent == 15u && mantissa == 7u ? uintBitsToFloat(0x7fc00000u) : exponent == 0u ? ldexp(float(mantissa), -9)
: ldexp(1.0 + float(mantissa) / 8.0, int(exponent) - 7);
return (v & 128u) != 0u ? -value : value;
}
int32_t accumulate_group(const in uint row, const in uint col, const in int32_t value, const in int32_t previous, const in uint group) {
return floatBitsToInt(fma(float(value), scales[group * BM + row], intBitsToFloat(previous)));
}
shared uint weights[BM * STRIDE];
const uint A_STRIDE = BK / 4 + 4;
shared uint activations[BN * A_STRIDE];
int32_t dequantize(const in uint row, const in uint col, const in int32_t acc, const in uint row_base, const in uint col_base) {
const uint r = row_base + col, c = col_base + row;
if (r >= p.rows || c >= p.n) {
return 0;
}
precise float value = intBitsToFloat(acc) * data_as[r];
if (p.has_bias != 0) {
value += data_b[c];
}
return floatBitsToInt(value);
}
void main() {
const uint tid = gl_LocalInvocationIndex;
const uint cols = gl_NumWorkGroups.x, rows = gl_NumWorkGroups.y;
const uint linear = gl_WorkGroupID.y * cols + gl_WorkGroupID.x;
// Reuse weight panels across activation tiles when the output expands.
const uint panel = p.n > p.k ? 16u : cols;
const uint first_col = (linear / (panel * rows)) * panel;
const uint group_cols = min(panel, cols - first_col);
const uint within = linear - first_col * rows;
const uint col_base = (first_col + within % group_cols) * BM, row_base = (within / group_cols) * BN;
tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> d_layout = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
d_layout = setTensorLayoutDimensionNV(d_layout, p.rows, p.n);
tensorViewNV<2, false, 1, 0> transpose = createTensorViewNV(2, false, 1, 0);
coopmat<int32_t, gl_ScopeWorkgroup, BM, BN, gl_MatrixUseAccumulator> sum = coopmat<int32_t, gl_ScopeWorkgroup, BM, BN, gl_MatrixUseAccumulator>(0);
if (tid == 0) {
float amax = 0.0;
for (uint i = 0; i < 16; ++i) {
amax = max(amax, abs(data_cb[i]));
}
cb_scale = amax / 127.0;
for (uint i = 0; i < 16; ++i) {
cb[i] = cb_scale == 0.0 ? 0 : clamp(int(roundEven(data_cb[i] / cb_scale)), -127, 127);
}
}
relative[tid] = fp8_e4m3(tid);
barrier();
for (uint i = tid; i < 256; i += 256) {
lut[i] = uint(cb[i & 15u] & 255) | (uint(cb[i >> 4] & 255) << 8);
}
barrier();
for (uint base = 0; base < p.k; base += BK) {
for (uint i = tid; i < BN * BK / 16; i += 256) {
const uint r = i / (BK / 16), t = i % (BK / 16);
const uvec4 value = row_base + r < p.rows ? data_a[(row_base + r) * (p.k / 16) + base / 16 + t] : uvec4(0);
const uint offset = r * A_STRIDE + t * 4;
activations[offset] = value.x;
activations[offset + 1] = value.y;
activations[offset + 2] = value.z;
activations[offset + 3] = value.w;
}
for (uint i = tid; i < BM * BK / 16; i += 256) {
const uint c = i / (BK / 16), part = i % (BK / 16);
const uvec2 packed = col_base + c < p.n ? data_w[(col_base + c) * (p.k / 16) + base / 16 + part] : uvec2(0);
// Complementary zero halves let adjacent groups reuse one activation fragment.
const uint odd = part % 2;
const uint offset = c * STRIDE + part * 8 + odd * 4;
const uint zero_offset = c * STRIDE + part * 8 + (1 - odd) * 4;
for (uint j = 0; j < 2; ++j) {
const uint v = packed[j];
weights[offset + 2 * j] = lut[v & 255u] | (lut[(v >> 8) & 255u] << 16);
weights[offset + 2 * j + 1] = lut[(v >> 16) & 255u] | (lut[v >> 24] << 16);
weights[zero_offset + 2 * j] = 0u;
weights[zero_offset + 2 * j + 1] = 0u;
}
}
for (uint i = tid; i < BM * BK / 16; i += 256) {
const uint c = i / (BK / 16), g = i % (BK / 16);
float scale = 0.0;
if (col_base + c < p.n) {
const uint packed = data_sr[(col_base + c) * (p.k / 64) + base / 64 + g / 4];
scale = cb_scale * (data_sc[col_base + c] * relative[(packed >> (8 * (g % 4))) & 255u]);
}
scales[g * BM + c] = scale;
}
barrier();
// The relative scale changes every 16 input values, so each group
// needs its own integer MMA and floating-point accumulation. Pad the
// weights with zeros to satisfy the device's K=32 matrix granularity.
[[unroll]] for (uint g = 0; g < BK / 16; g += 2) {
coopmat<int8_t, gl_ScopeWorkgroup, 32, BN, gl_MatrixUseB> a;
coopMatLoad(a, activations, g * 4, A_STRIDE, gl_CooperativeMatrixLayoutColumnMajor);
[[unroll]] for (uint j = 0; j < 2; ++j) {
coopmat<int8_t, gl_ScopeWorkgroup, BM, 32, gl_MatrixUseA> w;
coopmat<int32_t, gl_ScopeWorkgroup, BM, BN, gl_MatrixUseAccumulator> part = coopmat<int32_t, gl_ScopeWorkgroup, BM, BN, gl_MatrixUseAccumulator>(0);
coopMatLoad(w, weights, (g + j) * 8, STRIDE, gl_CooperativeMatrixLayoutRowMajor);
part = coopMatMulAdd(w, a, part);
coopMatPerElementNV(sum, part, accumulate_group, sum, g + j);
}
}
barrier();
}
coopMatPerElementNV(sum, sum, dequantize, row_base, col_base);
coopMatStoreTensorNV(sum, data_d, 0, sliceTensorLayoutNV(d_layout, row_base, BN, col_base, BM), transpose);
}

View file

@ -132,6 +132,9 @@ namespace sd::dgl {
if (!parse_strict_bool(value, enabled))
throw std::runtime_error("batched_cfg expects a boolean");
batched_cfg = enabled;
} else if (key == "console_progress") {
if (!parse_strict_bool(value, callbacks.console_progress))
throw std::runtime_error("console_progress expects a boolean");
} else if (key == "max_vram") {
ggml_graph_cut::MaxVramAssignment limit;
std::string error;

View file

@ -202,8 +202,8 @@ namespace sd::dgl::models {
return decoded;
}
if (!sd::backend_fit::prepare_vae_decode_retry_tiling(tiling_params, prefer_temporal_tiling,
first_stage_model->last_compute_status(),
tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) {
first_stage_model->last_compute_status(),
tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) {
break;
}
}

View file

@ -1,5 +1,7 @@
#include "run_events.h"
#include <cstdio>
#include "diagnostic.h"
namespace sd::dgl {
@ -43,29 +45,48 @@ namespace sd::dgl {
run.progress_.report("loading", "", completed, total, "tensors");
}
void RunEvents::render_sample_progress(int completed, int total_steps, float time) {
const bool console_only = forces_console_progress();
const bool renders_line = console_only || !sd_get_progress_callback();
if (console_only)
pretty_console_progress(completed, total_steps, time);
else
pretty_progress(completed, total_steps, time);
sample_line_open_ = renders_line && completed > 0 && completed < total_steps;
}
void RunEvents::begin_sample(int total_steps) {
check_cancelled();
finish_sample_line();
++preview_info_.sample_pass;
preview_info_.total_steps = total_steps;
if (legacy_preview_)
sd_begin_preview_pass(total_steps);
last_progress_us_ = ggml_time_us();
if (legacy_progress_ || !callbacks_.progress)
pretty_progress(0, total_steps, 0.f);
if (uses_console_progress())
render_sample_progress(0, total_steps, 0.f);
progress_.begin_sample(total_steps, "");
check_cancelled();
}
void RunEvents::sample_step(int completed, int total_steps) {
if (legacy_progress_ || !callbacks_.progress) {
if (uses_console_progress()) {
const auto now = ggml_time_us();
pretty_progress(completed, total_steps, (now - last_progress_us_) / 1000000.f);
render_sample_progress(completed, total_steps, (now - last_progress_us_) / 1000000.f);
last_progress_us_ = now;
}
progress_.report_sample(completed, total_steps);
check_cancelled();
}
void RunEvents::finish_sample_line() {
if (sample_line_open_) {
std::fputc('\n', stdout);
std::fflush(stdout);
sample_line_open_ = false;
}
}
void RunEvents::preview_bridge(int step, int frame_count, const sd_tensor_t* const* frames, bool noisy, void* userdata) {
auto& run = *static_cast<RunEvents*>(userdata);
if (run.cancelled())
@ -78,11 +99,12 @@ namespace sd::dgl {
RunEventsScope::RunEventsScope(RunEvents& events)
: previous_(active_events),
byte_progress_(events.uses_legacy_progress() ? nullptr : RunEvents::report_loading, &events),
console_progress_(events.uses_legacy_progress() || !events.callbacks().progress) {
byte_progress_(!events.uses_legacy_progress() && events.callbacks().progress ? RunEvents::report_loading : nullptr, &events),
console_progress_(events.forces_console_progress()) {
active_events = &events;
}
RunEventsScope::~RunEventsScope() {
active_events->finish_sample_line();
active_events = previous_;
}

View file

@ -17,6 +17,7 @@ namespace sd::dgl {
int interval = 0;
bool denoised = false;
bool noisy = false;
bool console_progress = false;
};
class RunEvents {
@ -28,8 +29,10 @@ namespace sd::dgl {
void* legacy_preview_data_ = nullptr;
bool legacy_progress_ = false;
int64_t last_progress_us_ = 0;
bool sample_line_open_ = false;
static void preview_bridge(int step, int frame_count, const sd_tensor_t* const* frames, bool noisy, void* userdata);
void render_sample_progress(int completed, int total_steps, float time);
public:
RunEvents(const RunCallbacks& callbacks, bool legacy_callbacks);
@ -41,8 +44,11 @@ namespace sd::dgl {
void report_frames(const char* stage, int completed, int total) const;
static void report_loading(int completed, int total, void* data);
bool uses_legacy_progress() const { return legacy_progress_; }
bool forces_console_progress() const { return !legacy_progress_ && callbacks_.console_progress; }
bool uses_console_progress() const { return legacy_progress_ || !callbacks_.progress || forces_console_progress(); }
void begin_sample(int total_steps);
void sample_step(int completed, int total_steps);
void finish_sample_line();
const RunCallbacks& callbacks() const { return callbacks_; }
const sd_preview_info_t& preview_info() const { return preview_info_; }
bool uses_legacy_preview() const { return legacy_preview_ != nullptr; }

View file

@ -262,10 +262,10 @@ public:
#ifndef SD_USE_UPSTREAM_GGML
if (w4_convrot_kind) {
out = ggml_ext_linear_w4_convrot(ctx, x, w,
w4_convrot_kind == 2 ? params["weight_codebook"] : weight_scale,
w4_convrot_kind == 2 ? params["weight_s_channel"] : nullptr,
w4_convrot_kind == 2 ? params["weight_s_rel"] : nullptr,
b, static_cast<SDW4Kind>(w4_convrot_kind), int8_convrot ? int8_convrot_group_size : 0, scale);
w4_convrot_kind == 2 ? params["weight_s_channel"] : weight_scale,
b, int8_convrot ? int8_convrot_group_size : 0, scale,
w4_convrot_kind == 2 ? params["weight_codebook"] : nullptr,
w4_convrot_kind == 2 ? params["weight_s_rel"] : nullptr);
} else
#endif
out = ggml_ext_linear_i8_tensorwise(ctx,

View file

@ -15,6 +15,7 @@ namespace Flux3 {
int depth = 5;
int single_depth = 28;
bool flow_map = false;
bool fused_qkv = false;
static Flux3Config detect_from_weights(const String2TensorStorage& tensors, const std::string& prefix) {
Flux3Config config;
@ -33,6 +34,8 @@ namespace Flux3 {
config.channels = tensor.logical_ne0();
} else if (key == "single_blocks.0.mlp_out.weight") {
config.mlp_dim = tensor.logical_ne0();
} else if (key == "single_blocks.0.qkv.weight") {
config.fused_qkv = true;
} else if (key == "ref_time_in.in_layer.weight") {
config.flow_map = true;
}
@ -62,15 +65,21 @@ namespace Flux3 {
struct Block : public GGMLBlock {
int heads;
bool fused_qkv;
Block(const Flux3Config& config)
: heads(config.heads) {
for (const auto* name : {"q_proj", "k_proj", "v_proj", "attn_out"}) {
blocks[name] = std::make_shared<Linear>(config.hidden_size, config.hidden_size, false);
: heads(config.heads), fused_qkv(config.fused_qkv) {
if (fused_qkv) {
blocks["qkv"] = std::make_shared<Linear>(config.hidden_size, 3 * config.hidden_size, false);
} else {
for (const auto* name : {"q_proj", "k_proj", "v_proj"}) {
blocks[name] = std::make_shared<Linear>(config.hidden_size, config.hidden_size, false);
}
}
blocks["mlp_in"] = std::make_shared<Linear>(config.hidden_size, 2 * config.mlp_dim, false);
blocks["mlp_out"] = std::make_shared<Linear>(config.mlp_dim, config.hidden_size, false);
blocks["norm"] = std::make_shared<Flux::QKNorm>(config.hidden_size / heads);
blocks["attn_out"] = std::make_shared<Linear>(config.hidden_size, config.hidden_size, false);
blocks["mlp_in"] = std::make_shared<Linear>(config.hidden_size, 2 * config.mlp_dim, false);
blocks["mlp_out"] = std::make_shared<Linear>(config.mlp_dim, config.hidden_size, false);
blocks["norm"] = std::make_shared<Flux::QKNorm>(config.hidden_size / heads);
}
ggml_tensor* linear(GGMLRunnerContext* ctx, const std::string& name, ggml_tensor* x) {
@ -87,13 +96,28 @@ namespace Flux3 {
x_mod = x_mod ? ggml_concat(gc, x_mod, part, 1) : part;
offset += lengths[i];
}
auto split = [&](ggml_tensor* v) {
return ggml_reshape_4d(gc, v, x->ne[0] / heads, heads, x->ne[1], x->ne[2]);
};
const int64_t head_dim = x->ne[0] / heads;
ggml_tensor *q, *k, *v;
if (fused_qkv) {
auto qkv = linear(ctx, "qkv", x_mod);
auto select = [&](int i) {
return ggml_view_4d(gc, qkv, head_dim, heads, qkv->ne[1], qkv->ne[2],
head_dim * qkv->nb[0], qkv->nb[1], qkv->nb[2], i * x->ne[0] * qkv->nb[0]);
};
q = select(0);
k = select(1);
v = select(2);
} else {
auto reshape = [&](ggml_tensor* projected) {
return ggml_reshape_4d(gc, projected, head_dim, heads, projected->ne[1], projected->ne[2]);
};
q = reshape(linear(ctx, "q_proj", x_mod));
k = reshape(linear(ctx, "k_proj", x_mod));
v = reshape(linear(ctx, "v_proj", x_mod));
}
auto norm = std::dynamic_pointer_cast<Flux::QKNorm>(blocks["norm"]);
auto q = norm->query_norm(ctx, split(linear(ctx, "q_proj", x_mod)));
auto k = norm->key_norm(ctx, split(linear(ctx, "k_proj", x_mod)));
auto v = split(linear(ctx, "v_proj", x_mod));
q = norm->query_norm(ctx, q);
k = norm->key_norm(ctx, k);
auto attn = Rope::attention(ctx, q, k, v, pe, nullptr);
auto mlp = ggml_ext_silu_act(ctx, linear(ctx, "mlp_in", x_mod));
auto update = ggml_add(gc, linear(ctx, "attn_out", attn), linear(ctx, "mlp_out", mlp));

View file

@ -466,7 +466,7 @@ namespace LingBotVideo {
ggml_tensor* temb6,
ggml_tensor* pe,
ggml_tensor* attention_mask = nullptr) {
// x: [N, tokens, hidden_size], temb6: [N, tokens, 6 * hidden_size]
// x: [N, tokens, hidden_size], temb6: [N, 1, 6 * hidden_size]
auto norm1 = std::dynamic_pointer_cast<RMSNorm>(blocks["norm1"]);
auto attn = std::dynamic_pointer_cast<LingBotVideoAttention>(blocks["attn"]);
auto norm_post_attn = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_post_attn"]);
@ -488,12 +488,12 @@ namespace LingBotVideo {
auto attn_in = Flux::modulate(ctx, norm1->forward(ctx, x), shift_msa, scale_msa, true);
auto attn_out = attn->forward(ctx, attn_in, pe, attention_mask);
attn_out = norm_post_attn->forward(ctx, attn_out);
x = ggml_add(ctx->ggml_ctx, x, ggml_mul(ctx->ggml_ctx, gate_msa, attn_out));
x = ggml_add(ctx->ggml_ctx, x, ggml_mul(ctx->ggml_ctx, attn_out, gate_msa));
auto ffn_in = Flux::modulate(ctx, norm2->forward(ctx, x), shift_mlp, scale_mlp, true);
auto ffn_out = ffn->forward(ctx, ffn_in);
ffn_out = norm_post_ffn->forward(ctx, ffn_out);
x = ggml_add(ctx->ggml_ctx, x, ggml_mul(ctx->ggml_ctx, gate_mlp, ffn_out));
x = ggml_add(ctx->ggml_ctx, x, ggml_mul(ctx->ggml_ctx, ffn_out, gate_mlp));
return x;
}
};
@ -568,11 +568,10 @@ namespace LingBotVideo {
10000,
1.0f);
auto t_emb = time_embedder->forward(ctx, timestep_proj);
auto temb_template = ggml_new_tensor_3d(ctx->ggml_ctx, t_emb->type, t_emb->ne[0], hidden_states->ne[1], t_emb->ne[1]);
auto temb_tokens = ggml_repeat(ctx->ggml_ctx,
ggml_reshape_3d(ctx->ggml_ctx, t_emb, t_emb->ne[0], 1, t_emb->ne[1]),
temb_template);
auto temb_tokens = ggml_reshape_3d(ctx->ggml_ctx, t_emb, t_emb->ne[0], 1, t_emb->ne[1]);
auto temb6 = time_modulation->forward(ctx, ggml_silu(ctx->ggml_ctx, temb_tokens));
// Keep timestep embedding ops out of the first RMSNorm fusion pattern.
ctx->expand_graph(temb6);
sd::ggml_graph_cut::mark_graph_cut(hidden_states, "lingbot_video.prelude", "hidden_states");
@ -664,7 +663,7 @@ namespace LingBotVideo {
return sd::Tensor<float>({2, 2, config.axes_dim_sum / 2, pos_len}, std::move(pe_vec));
}));
auto runner_ctx = get_context();
auto runner_ctx = get_context(gf);
ggml_tensor* out = lingbot_video.forward(&runner_ctx, x, timesteps, context, pe);
ggml_build_forward_expand(gf, out);
return gf;

View file

@ -555,26 +555,19 @@ namespace LTXV {
int64_t a_dim;
bool cross_attention_adaln;
void init_params(ggml_context* ctx,
const String2TensorStorage& tensor_storage_map = {},
const std::string prefix = "") override {
void init_params(ggml_context* ctx, const String2TensorStorage& = {}, const std::string = "") override {
// The tables determine the type of the modulation values applied to F32 activations.
int64_t coeff = cross_attention_adaln ? 9 : 6;
ggml_type vw = get_type(prefix + "scale_shift_table", tensor_storage_map, GGML_TYPE_F32);
ggml_type aw = get_type(prefix + "audio_scale_shift_table", tensor_storage_map, GGML_TYPE_F32);
params["scale_shift_table"] = ggml_new_tensor_2d(ctx, vw, v_dim, coeff);
params["audio_scale_shift_table"] = ggml_new_tensor_2d(ctx, aw, a_dim, coeff);
params["scale_shift_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, v_dim, coeff);
params["audio_scale_shift_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, a_dim, coeff);
if (cross_attention_adaln) {
ggml_type vpw = get_type(prefix + "prompt_scale_shift_table", tensor_storage_map, GGML_TYPE_F32);
ggml_type apw = get_type(prefix + "audio_prompt_scale_shift_table", tensor_storage_map, GGML_TYPE_F32);
params["prompt_scale_shift_table"] = ggml_new_tensor_2d(ctx, vpw, v_dim, 2);
params["audio_prompt_scale_shift_table"] = ggml_new_tensor_2d(ctx, apw, a_dim, 2);
params["prompt_scale_shift_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, v_dim, 2);
params["audio_prompt_scale_shift_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, a_dim, 2);
}
ggml_type avw = get_type(prefix + "scale_shift_table_a2v_ca_audio", tensor_storage_map, GGML_TYPE_F32);
ggml_type vaw = get_type(prefix + "scale_shift_table_a2v_ca_video", tensor_storage_map, GGML_TYPE_F32);
params["scale_shift_table_a2v_ca_audio"] = ggml_new_tensor_2d(ctx, avw, a_dim, 5);
params["scale_shift_table_a2v_ca_video"] = ggml_new_tensor_2d(ctx, vaw, v_dim, 5);
params["scale_shift_table_a2v_ca_audio"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, a_dim, 5);
params["scale_shift_table_a2v_ca_video"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, v_dim, 5);
}
BasicAVTransformerBlock(int64_t v_dim,
@ -768,22 +761,12 @@ namespace LTXV {
struct LTXAVModelBlock : public GGMLBlock {
LTXAVConfig config;
void init_params(ggml_context* ctx,
const String2TensorStorage& tensor_storage_map = {},
const std::string prefix = "") override {
params["scale_shift_table"] = ggml_new_tensor_2d(ctx,
get_type(prefix + "scale_shift_table", tensor_storage_map, GGML_TYPE_F32),
config.hidden_size,
2);
params["audio_scale_shift_table"] = ggml_new_tensor_2d(ctx,
get_type(prefix + "audio_scale_shift_table", tensor_storage_map, GGML_TYPE_F32),
config.audio_hidden_size,
2);
void init_params(ggml_context* ctx, const String2TensorStorage& = {}, const std::string = "") override {
params["scale_shift_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, config.hidden_size, 2);
params["audio_scale_shift_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, config.audio_hidden_size, 2);
if (config.use_keyframes_abs_pos_embedding) {
params["keyframes_abs_pos_embedding"] = ggml_new_tensor_2d(ctx,
get_type(prefix + "keyframes_abs_pos_embedding", tensor_storage_map, GGML_TYPE_F32),
config.hidden_size,
1);
// Added to f32 activations, and backends without BF16 support (e.g. Vulkan on RADV) can't add a BF16 tensor.
params["keyframes_abs_pos_embedding"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, config.hidden_size, 1);
}
}

View file

@ -87,19 +87,19 @@ namespace RelayVSR {
}
ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* context, ggml_tensor* query_rope, ggml_tensor* key_rope, const VSR::LocalAttention* local, const std::string& cut_group, const std::string& attention_name) {
auto to_q = std::dynamic_pointer_cast<Linear>(blocks["to_q"]);
auto to_k = std::dynamic_pointer_cast<Linear>(blocks["to_k"]);
auto to_v = std::dynamic_pointer_cast<Linear>(blocks["to_v"]);
auto to_out_0 = std::dynamic_pointer_cast<Linear>(blocks["to_out.0"]);
auto norm_q = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_q"]);
auto norm_k = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_k"]);
auto c = ctx->ggml_ctx;
auto q = norm_q->forward(ctx, to_q->forward(ctx, x));
auto to_q = std::dynamic_pointer_cast<Linear>(blocks["to_q"]);
auto to_k = std::dynamic_pointer_cast<Linear>(blocks["to_k"]);
auto to_v = std::dynamic_pointer_cast<Linear>(blocks["to_v"]);
auto to_out_0 = std::dynamic_pointer_cast<Linear>(blocks["to_out.0"]);
auto norm_q = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_q"]);
auto norm_k = std::dynamic_pointer_cast<RMSNorm>(blocks["norm_k"]);
auto c = ctx->ggml_ctx;
auto q = norm_q->forward(ctx, to_q->forward(ctx, x));
const auto cache_name = cut_group + "." + attention_name;
auto past_k = ctx->get_cache_tensor(cache_name + ".key");
auto past_v = ctx->get_cache_tensor(cache_name + ".value");
ggml_tensor* k = nullptr;
ggml_tensor* v = nullptr;
auto past_k = ctx->get_cache_tensor(cache_name + ".key");
auto past_v = ctx->get_cache_tensor(cache_name + ".value");
ggml_tensor* k = nullptr;
ggml_tensor* v = nullptr;
if (context && past_k) {
k = past_k;
v = past_v;

View file

@ -4,35 +4,105 @@
#include "core/ggml_runner.h"
#include "model/common/ggml_block.hpp"
struct MLP : public UnaryBlock {
MLP(int64_t input_dim, int64_t hidden_dim, int64_t output_dim) {
blocks["0"] = std::shared_ptr<GGMLBlock>(new Linear(input_dim, hidden_dim));
blocks["2"] = std::shared_ptr<GGMLBlock>(new Linear(hidden_dim, output_dim));
}
ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) {
auto layer0 = std::dynamic_pointer_cast<Linear>(blocks["0"]);
auto layer2 = std::dynamic_pointer_cast<Linear>(blocks["2"]);
x = layer0->forward(ctx, x);
x = ggml_ext_gelu(ctx, x, true);
x = layer2->forward(ctx, x);
return x;
}
};
struct ClipProjConnector : public UnaryBlock {
int64_t input_dim = 2560;
int64_t output_dim = 5120;
bool has_linear = true;
bool has_mlp = false;
bool has_sink = true;
ClipProjConnector(int64_t input_dim = 2560, int64_t output_dim = 5120) : input_dim(input_dim), output_dim(output_dim) {}
int64_t mlp_hidden = 0;
void config_from_weights(const String2TensorStorage& tensor_storage_map = {}) {
static constexpr const char* prefix = "text_encoders.connector";
has_linear = false;
has_mlp = false;
has_sink = false;
for (const auto& [name, tensor_storage] : tensor_storage_map) {
if (!starts_with(name, prefix)) {
continue;
}
if (name.find("W") != std::string::npos) {
has_linear = true;
}
if (name.find("mlp.0.bias") != std::string::npos) {
has_mlp = true;
mlp_hidden = tensor_storage.ne[0];
}
// optional in the original code, but always present in the model weights...
if (name.find("sink_out") != std::string::npos) {
has_sink = true;
}
}
}
ClipProjConnector(int64_t input_dim = 2560, int64_t output_dim = 5120, const String2TensorStorage& tensor_storage_map = {}) : input_dim(input_dim), output_dim(output_dim) {
config_from_weights(tensor_storage_map);
if (has_mlp) {
if (mlp_hidden <= 0) {
throw std::runtime_error("Cannot find hidden size for ClipProj mlp");
}
blocks["mlp"] = std::shared_ptr<GGMLBlock>(new MLP(input_dim, mlp_hidden, output_dim));
}
}
void init_params(ggml_context* ctx,
const String2TensorStorage& tensor_storage_map = {},
const std::string prefix = "") override {
params["W"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, output_dim, input_dim);
if (has_linear) {
params["W"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, output_dim, input_dim);
}
for (const auto* name : {"mean_in", "std_in"}) {
params[name] = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, input_dim);
}
for (const auto* name : {"mean_out", "std_out", "sink_out"}) {
for (const auto* name : {"mean_out", "std_out"}) {
params[name] = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, output_dim);
}
if (has_sink) {
params["sink_out"] = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, output_dim);
}
}
ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) override {
auto projW = params["W"];
projW = ggml_cont(ctx->ggml_ctx, ggml_transpose(ctx->ggml_ctx, projW));
x = ggml_div(ctx->ggml_ctx, ggml_sub(ctx->ggml_ctx, x, params["mean_in"]), params["std_in"]);
x = ggml_mul_mat(ctx->ggml_ctx, projW, x);
x = ggml_add(ctx->ggml_ctx, ggml_mul(ctx->ggml_ctx, x, params["std_out"]), params["mean_out"]);
auto sink = ggml_repeat(ctx->ggml_ctx, params["sink_out"], ggml_ext_slice(ctx, x, 1, 0, 1));
if (x->ne[1] == 1) {
return sink;
auto x_std = ggml_div(ctx->ggml_ctx, ggml_sub(ctx->ggml_ctx, x, params["mean_in"]), params["std_in"]);
if (has_linear) {
auto projW = params["W"];
projW = ggml_cont(ctx->ggml_ctx, ggml_transpose(ctx->ggml_ctx, projW));
x = ggml_mul_mat(ctx->ggml_ctx, projW, x_std);
}
if (has_mlp) {
auto mlp = std::dynamic_pointer_cast<MLP>(blocks["mlp"]);
auto x_mlp = mlp->forward(ctx, x_std);
x = has_linear ? ggml_add_inplace(ctx->ggml_ctx, x, x_mlp) : x_mlp;
}
x = ggml_add(ctx->ggml_ctx, ggml_mul(ctx->ggml_ctx, x, params["std_out"]), params["mean_out"]);
if (has_sink) {
auto sink = ggml_repeat(ctx->ggml_ctx, params["sink_out"], ggml_ext_slice(ctx, x, 1, 0, 1));
if (x->ne[1] == 1) {
return sink;
}
return ggml_concat(ctx->ggml_ctx, sink, ggml_ext_slice(ctx, x, 1, 1, x->ne[1]), 1);
} else {
return x;
}
return ggml_concat(ctx->ggml_ctx, sink, ggml_ext_slice(ctx, x, 1, 1, x->ne[1]), 1);
}
};
@ -42,9 +112,10 @@ struct ClipProjConnectorRunner : public GGMLRunner {
ClipProjConnectorRunner(ggml_backend_t backend,
int64_t input_dim,
int64_t output_dim,
const String2TensorStorage& tensor_storage_map,
std::shared_ptr<RunnerWeightManager> weight_manager = nullptr)
: GGMLRunner(backend, weight_manager), model(input_dim) {
: GGMLRunner(backend, weight_manager), model(input_dim, output_dim, tensor_storage_map) {
model.init(params_ctx, tensor_storage_map, prefix);
}

View file

@ -140,13 +140,12 @@ static bool read_comfy_quant_config(std::ifstream& file,
const nlohmann::json json = nlohmann::json::parse(data.data(), data.data() + size);
config.format = json.value("format", "");
config.convrot = json.value("convrot", false);
config.group_size = json.value("convrot_groupsize", 0);
config.weight_group_size = json.value("group_size", 0);
if (config.format == "convrot_w4a4" || config.format == "asym_w4a8_int8") {
// Packed W4 formats imply rotation, including exports without the INT8 convrot flag.
config.convrot = true;
config.group_size = json.value("convrot_groupsize", 256);
config.convrot = true;
}
config.group_size = json.value("convrot_groupsize", config.convrot ? 256 : 0);
config.weight_group_size = json.value("group_size", 0);
if (config.format == "asym_w4a8_int8") {
// ComfyUI defaults the W4A8 weight group size to 16 when the key is missing.
config.weight_group_size = json.value("group_size", 16);

View file

@ -462,8 +462,10 @@ SDVersion ModelLoader::get_sd_version() const {
return VERSION_FIBO2;
}
if (tensor_storage_map.find("model.diffusion_model.emb_in.image.weight") != tensor_storage_map.end() &&
tensor_storage_map.find("model.diffusion_model.txt_mode_blocks.0.q_proj.weight") != tensor_storage_map.end()) {
if (tensor_storage_map.count("model.diffusion_model.emb_in.image.weight") &&
(tensor_storage_map.count("model.diffusion_model.txt_mode_blocks.0.q_proj.weight") ||
tensor_storage_map.count("model.diffusion_model.single_blocks.0.qkv.weight") ||
tensor_storage_map.count("model.diffusion_model.single_transformer_blocks.0.qkv.weight"))) {
return VERSION_FLUX3;
}

View file

@ -758,6 +758,8 @@ static std::string convert_diffusers_dit_to_original_flux3(std::string name) {
{".attn.to_k.", ".k_proj."},
{".attn.to_v.", ".v_proj."},
{".attn.to_out.0.", ".attn_out."},
{".norm.query_norm.weight", ".norm.query_norm.scale"},
{".norm.key_norm.weight", ".norm.key_norm.scale"},
{".ff.linear_in.", ".mlp_in."},
{".ff.linear_out.", ".mlp_out."},
};

View file

@ -6216,7 +6216,7 @@ inline bool range_error(Request &req, Response &res) {
}
if (first_pos == -1) {
first_pos = content_len - last_pos;
first_pos = content_len - (std::min)(content_len, last_pos);
last_pos = content_len - 1;
}