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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions docs/dgl-builtins.md

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions docs/dgl.md
Original file line number Diff line number Diff line change
Expand Up @@ -1735,8 +1735,9 @@ sd_dgl_result_free(result);
### Context execution settings

Set these options with `sd_dgl_ctx_set` while the context is idle or use the
corresponding `sd-cli` and `sd-server` flags. All models in the context use the
same settings.
corresponding `sd-cli` and `sd-server` flags. The settings apply throughout the
context. A `linear_type` context setting overrides the loader's `linear_type`
argument for each selected module.

| Context key | CLI and server flag | Default |
| --- | --- | --- |
Expand All @@ -1748,6 +1749,7 @@ same settings.
| `eager_load` | `--eager-load` | Off |
| `disable_prefetch` | `--disable-prefetch` | Off |
| `disable_segmented_compute` | `--disable-segmented-compute` | Off |
| `linear_type` | `--linear-type` with `auto\|i8\|raw` or module assignments such as `dit=i8` | `auto` (currently equivalent to `raw`) |

The context accepts a thread count from 1 to 4096 and boolean strings such as
`"on"` and `"off"`. Changing threading, placement or weight-loading options
Expand Down
1 change: 1 addition & 0 deletions docs/guides/c_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,7 @@ For SDXL's bundled VAE (no `vae_path`), generation emits
| `image` | `tensor` | upscale |
| `init_image` | `tensor` | image, video |
| `linear_scale` | `float` | context |
| `linear_type` | `string` | context, upscaler. `auto` (default), `i8`, `raw`, or module assignments such as `dit=i8,te=raw` |
| `llm_path` | `string` | context |
| `llm_vision_path` | `string` | context |
| `lora_apply_mode` | `string` | context |
Expand Down
36 changes: 35 additions & 1 deletion docs/guides/int8_convrot.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ The packed runtime activation tensor contains the I8 activation rows and their f
- 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`.
- 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.
- Vulkan supports unrotated rowwise, H64, and H256 activation quantization and packed-activation INT8 matrix multiplication with input widths divisible by 64. It requires integer dot product support and uses cooperative matrices when available. Unsupported configurations use the scheduler's CPU fallback.

`--lora-apply-mode auto` selects immediate merging for INT8 tensorwise models
on the compute backend without row splitting. Use `--lora-apply-mode at_runtime`
Expand Down Expand Up @@ -164,6 +164,40 @@ and logical weight dimensions. Packed weights and their codebook/scale tensors
are excluded from weight type conversion. `SD_USE_UPSTREAM_GGML` builds reject
these formats because they require the application extension API.

## Runtime requantization to INT8

Use `--linear-type i8` to run eligible Q8_0 linear layers through INT8 GEMM on
CUDA, HIP, MUSA, and Vulkan. A bare mode applies to all models in the context,
including diffusion models and text encoders loaded with `--llm`. The default
is `auto`, which currently behaves like `raw`. With `--linear-type raw`, each
layer uses its original execution path. Native INT8 weights use their INT8
path in all three modes.

Use module assignments to apply a mode selectively. For example,
`--linear-type dit=i8` selects runtime conversion for the diffusion module.
The text encoder and other modules use `auto`. Use `--linear-type i8,te=raw` to
enable conversion globally while keeping the text encoders on their original
paths. Module names and aliases are shared with [backend selection](backend.md).
Module assignments override the default regardless of their order. Within
the same string, the last value for a module or the default wins.

Runtime conversion uses H256 for weights and activations. Eligible linear
layers have an input width divisible by 256. Vulkan also requires integer
dot products and compatible storage buffer sizes and alignment. The C API option is
`linear_type`. In DGL, set the mode on a model loader, for example
`load_dit(path, linear_type = "i8")`. To override loader settings by module,
use `sd_dgl_ctx_set(ctx, "linear_type", "dit=i8")` or pass
`--linear-type dit=i8` when running the script from the CLI.

At runtime, sd.cpp dequantizes the Q8_0 blocks, rotates the weights, and
requantizes them to INT8 with one scale per output channel. It applies the
same rotation to the activations before quantizing each input row. The
converted matrix uses temporary GPU memory and feeds the standard INT8 kernels
and their fusions. The checkpoint file stays in its original format.
Requantization changes numerical results, and conversion overhead depends on
matrix shape. Row-split models and unsupported layers use the standard Q8_0
path.

## Example

ComfyUI INT8 convrot safetensors can be passed to `--diffusion-model` without conversion:
Expand Down
3 changes: 2 additions & 1 deletion examples/cli/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,8 @@ int main(int argc, const char* argv[]) {
ctx_params.n_threads,
gen_params.upscale_tile_size,
ctx_params.effective_backend.c_str(),
ctx_params.effective_params_backend.c_str()));
ctx_params.effective_params_backend.c_str(),
ctx_params.linear_type));

if (upscaler_ctx == nullptr) {
LOG_ERROR("sd_upscaler_create failed");
Expand Down
19 changes: 19 additions & 0 deletions examples/common/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,22 @@ ArgOptions SDContextParams::get_options() {
vae_conv_direct = true;
return 0;
}},
{"",
"--linear-type",
"auto|i8|raw or module assignments, e.g. dit=i8 or i8,te=raw. Default: auto (currently equivalent to raw)",
[this](int argc, const char** argv, int index) {
if (++index >= argc || argv[index][0] == '\0') {
LOG_ERROR("--linear-type requires auto, i8, raw, or module assignments");
return -1;
}
SDOptPtr validation(sd_ctx_opt_create());
if (sd_opt_set_string(validation.get(), "linear_type", argv[index]) != SD_STATUS_OK) {
LOG_ERROR("--linear-type: %s", sd_get_last_error());
return -1;
}
linear_type = argv[index];
return 1;
}},
{"",
"--conv-direct",
"on|off|auto or diffusion/vae/controlnet assignments (default: auto), e.g. auto,vae=off. Overrides legacy convolution flags",
Expand Down Expand Up @@ -948,6 +964,7 @@ std::string SDContextParams::to_string() const {
<< " flash_attn_mode: " << flash_attn_mode << ",\n"
<< " conv_direct_mode: " << conv_direct_mode << ",\n"
<< " sage_attn: " << sage_attn << ",\n"
<< " linear_type: " << linear_type.value_or("auto") << ",\n"
<< " linear_scale: " << linear_scale << ",\n"
<< " attn_scale: " << attn_scale << ",\n"
<< " diffusion_conv_direct: " << diffusion_conv_direct << ",\n"
Expand All @@ -965,6 +982,7 @@ bool SDContextParams::configure_dgl(sd_dgl_ctx_t* ctx) const {
return !option || sd_dgl_ctx_set(ctx, key, std::to_string(*option).c_str());
};
return (!max_vram || sd_dgl_ctx_set(ctx, "max_vram", max_vram->c_str())) &&
(!linear_type || sd_dgl_ctx_set(ctx, "linear_type", linear_type->c_str())) &&
set("auto_fit", auto_fit) &&
set("conditioning_cache_size", conditioning_cache_size) &&
set("batched_cfg", batched_cfg) &&
Expand Down Expand Up @@ -1025,6 +1043,7 @@ SDOptPtr SDContextParams::to_context_opt() {
opt.set_string("flash_attn_mode", flash_attn_mode);
opt.set_string("conv_direct_mode", conv_direct_mode);
opt.set_bool("sage_attn", sage_attn);
opt.set_string("linear_type", linear_type);
opt.set_float("linear_scale", linear_scale);
opt.set_float("attn_scale", attn_scale);
opt.set_bool("tae_preview_only", taesd_preview_only);
Expand Down
1 change: 1 addition & 0 deletions examples/common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ struct SDContextParams {
std::optional<std::string> flash_attn_mode;
std::optional<std::string> conv_direct_mode;
std::optional<bool> sage_attn;
std::optional<std::string> linear_type;
std::optional<bool> diffusion_conv_direct;
std::optional<bool> vae_conv_direct;
std::optional<bool> taesd_preview_only;
Expand Down
5 changes: 3 additions & 2 deletions examples/common/resource_owners.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -324,14 +324,15 @@ static inline bool generate_sd_video(sd_ctx_t* ctx, const SDOptPtr& opt, sd_resu
return opt && sd_generate_video(ctx, opt.get(), result) == SD_STATUS_OK;
}

static inline sd_upscaler_t* create_sd_upscaler(const char* path, std::optional<bool> direct, std::optional<int> threads, std::optional<int> tile, const char* backend, const char* params_backend) {
static inline sd_upscaler_t* create_sd_upscaler(const char* path, std::optional<bool> direct, std::optional<int> threads, std::optional<int> tile, const char* backend, const char* params_backend, const std::optional<std::string>& linear_type) {
SDOptPtr opt(sd_upscaler_opt_create());
if (!opt || sd_opt_set_string(opt.get(), "model_path", path) != SD_STATUS_OK ||
(direct && sd_opt_set_bool(opt.get(), "conv_direct", *direct) != SD_STATUS_OK) ||
(tile && sd_opt_set_int(opt.get(), "tile_size", *tile) != SD_STATUS_OK) ||
(threads && sd_opt_set_int(opt.get(), "n_threads", *threads) != SD_STATUS_OK) ||
(backend && sd_opt_set_string(opt.get(), "backend", backend) != SD_STATUS_OK) ||
(params_backend && sd_opt_set_string(opt.get(), "params_backend", params_backend) != SD_STATUS_OK))
(params_backend && sd_opt_set_string(opt.get(), "params_backend", params_backend) != SD_STATUS_OK) ||
(linear_type && sd_opt_set_string(opt.get(), "linear_type", linear_type->c_str()) != SD_STATUS_OK))
return nullptr;
sd_upscaler_t* result = nullptr;
sd_upscaler_create(opt.get(), &result);
Expand Down
2 changes: 2 additions & 0 deletions src/api/generation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ namespace sd::api {
: model(copy_options(source), purpose) {
const auto& settings = model.config.context;
execution.set("n_threads", std::to_string(settings.n_threads));
if (settings.linear_type)
execution.set("linear_type", settings.linear_type);
execution.set("conditioning_cache_size", std::to_string(settings.conditioning_cache_size));
for (const auto& [key, enabled] : std::map<std::string, bool>{
{"auto_fit", settings.auto_fit}, {"batched_cfg", settings.batched_cfg}, {"enable_mmap", settings.enable_mmap}, {"eager_load", settings.eager_load}, {"disable_prefetch", settings.disable_prefetch}, {"disable_segmented_compute", settings.disable_segmented_compute}})
Expand Down
9 changes: 9 additions & 0 deletions src/api/options.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "options.h"
#include "core/ggml_extend_backend.h"
#include "core/option_types.h"
#include "core/util.h"
#include "tensor.h"
Expand Down Expand Up @@ -337,6 +338,14 @@ static void add_context_specs(std::vector<ParamSpec>& specs) {
specs.push_back(parameter<std::string>("conv_direct_mode", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.conv_direct_mode = value.c_str(); }));
specs.push_back(parameter<std::string>("diffusion_model_path", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.diffusion_model_path = value.c_str(); }));
specs.push_back(parameter<std::string>("flash_attn_mode", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.flash_attn_mode = value.c_str(); }));
auto linear_type = parameter<std::string>(
"linear_type", ParamType::String, Context | Upscaler, [](const std::string& value, sd::OptConfig& config) { config.context.linear_type = value.c_str(); });
linear_type.valid = [](const ParamValue& value) {
SDBackendAssignment assignment;
return sd_parse_linear_type_assignment(std::get<std::string>(value), &assignment, nullptr);
};
linear_type.invalid_reason = "expected auto, i8, raw, or module assignments such as dit=i8";
specs.push_back(std::move(linear_type));
specs.push_back(integer_parameter(
"n_threads", Context | Upscaler, [](const int64_t& value, sd::OptConfig& config) { config.context.n_threads = static_cast<int>(value); }, 1, INT32_MAX));
specs.push_back(parameter<std::string>("params_backend", ParamType::String, Context | Upscaler, [](const std::string& value, sd::OptConfig& config) { config.context.params_backend = value.c_str(); }));
Expand Down
Loading
Loading