| Type: | Package |
| Title: | Stable Diffusion Image Generation |
| Version: | 0.2.3 |
| Description: | Provides Stable Diffusion image generation using the 'ggmlR' library, with no 'Python' or external API dependencies. Supports text-to-image and image-to-image generation for SD 1.x, SD 2.x, 'SDXL', Flux, 'FLUX.2' and 'FLUX.3'. A single sd_generate() function handles the entire pipeline, including sampling and high-resolution output; composable node graphs (encode, sample, decode, masks, inpainting, 'ControlNet', image operations) run with result caching and can be saved to and loaded from JSON. Background removal and depth estimation run on 'ggmlR' 'ONNX' models. Features multi-GPU support, a 'Shiny' GUI, and runs on CPU or 'Vulkan' GPU across Linux, macOS, and Windows. |
| SystemRequirements: | GNU make, curl or wget (for downloading vocabulary files during installation) |
| License: | MIT + file LICENSE |
| URL: | https://github.com/Zabis13/sd2R |
| BugReports: | https://github.com/Zabis13/sd2R/issues |
| Depends: | R (≥ 4.1.0) |
| Encoding: | UTF-8 |
| Imports: | Rcpp (≥ 1.0.0), ggmlR (≥ 0.8.8), shiny, base64enc, jsonlite, later, png |
| LinkingTo: | Rcpp, ggmlR |
| Suggests: | testthat (≥ 3.0.0), callr, plumber, drogonR, withr |
| RoxygenNote: | 7.3.3 |
| Config/testthat/edition: | 3 |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-28 06:37:17 UTC; yuri |
| Author: | Yuri Baramykov |
| Maintainer: | Yuri Baramykov <lbsbmsu@mail.ru> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-28 11:30:19 UTC |
Build JSON error response
Description
Build JSON error response
Usage
.api_error(res, status, message)
Convert R array [H, W, 3] to sd_image list
Description
Convert R array [H, W, 3] to sd_image list
Usage
.array_to_sd_image(arr)
Arguments
arr |
3D numeric array [height, width, channels] in [0, 1] |
Value
SD image list (width, height, channel, data)
Decode base64 PNG to sd_image
Description
Decode base64 PNG to sd_image
Usage
.base64_to_image(b64)
Arguments
b64 |
Base64-encoded PNG string |
Value
sd_image list
Build linear blend mask for a patch
Description
Build linear blend mask for a patch
Usage
.blend_mask(h, w, overlap, is_left, is_top, is_right, is_bottom)
Arguments
h |
Patch height |
w |
Patch width |
overlap |
Overlap in pixels |
is_left, is_top, is_right, is_bottom |
Whether patch is at canvas edge |
Value
Matrix [h, w] with blend weights in [0, 1]
Build plumber router with sd2R endpoints
Description
Creates and configures a plumber router. Called internally by
sd_api_start.
Usage
.build_router()
Value
A plumber router object
Check LoRA application after a generation
Description
Check LoRA application after a generation
Usage
.check_lora_stats(ctx, loras)
Arguments
ctx |
SD context |
loras |
Resolved loras (list(path, multiplier, is_high_noise)) or NULL |
Value
The stats data.frame (invisibly), or NULL without loras
Compute patch grid positions
Description
Compute patch grid positions
Usage
.compute_patch_grid(width, height, tile_size, overlap_px)
Arguments
width |
Target width |
height |
Target height |
tile_size |
Tile size in pixels |
overlap_px |
Overlap in pixels |
Value
Data frame with columns x, y (0-based top-left of each patch)
Detect model type from a sibling config.json (diffusers-style layout)
Description
Looks for config.json next to the model file and maps its
model_type / architectures[1] / _class_name fields onto
sd2R's type vocabulary. Pure R, no weights read.
Usage
.detect_model_type_config(path)
Arguments
path |
Path to the model file |
Value
Model type string, or NULL if not detectable
Detect model type from a GGUF file's KV metadata (header-only probe)
Description
Reads general.architecture (and a few related KV keys) from a GGUF
header WITHOUT loading tensor weights, via
ggmlR::gguf_load(path, meta_only = TRUE) (no_alloc header read). Cheap
even on multi-GB Flux models.
Usage
.detect_model_type_gguf(path)
Arguments
path |
Path to a .gguf file |
Details
Note: stable-diffusion.cpp itself detects the version from tensor
names/shapes, not from general.architecture, so many diffusion
GGUFs (e.g. quantized Flux converters) leave that field empty or set it to a
sub-component name (e.g. "t5" for a packed text encoder). This probe
is therefore best-effort: it returns a concrete type only on a confident
match and otherwise NULL, so the caller falls through to
config.json / filename detection.
Value
Model type string, or NULL if unavailable / inconclusive
Estimate peak VAE VRAM usage in bytes
Description
Analytic upper bound on the peak compute-buffer size of the VAE decoder.
The peak occurs in the ResNet block that runs at full pixel resolution
(W x H) with the decoder's base channel width. The per-pixel cost is
derived from architecture (base channels x dtype bytes); the only
empirical constant is live_tensors — how many such full-res
tensors ggml's graph allocator keeps alive simultaneously. That value
is calibrated against an observed Flux failure: a 2048x1024 decode
requested 19238223904 bytes, i.e. 19238223904 / (2048*1024) ~= 9175
B/px, and 9175 / (128 ch * 4 B) ~= 17.9 live full-res tensors. We round
up to 18 for a safe over-estimate (tiling should engage rather than OOM).
Usage
.estimate_vae_vram(width, height, model_type = "sd1", batch = 1L)
Arguments
width |
Image width in pixels |
height |
Image height in pixels |
model_type |
Model type string ("sd1", "sd2", "sdxl", "flux", etc.) |
batch |
Batch size (default 1) |
Value
Estimated peak VRAM in bytes
Find least recently used model id
Description
Find least recently used model id
Usage
.find_lru()
Get model context by name (or default)
Description
Get model context by name (or default)
Usage
.get_ctx(model_id = NULL)
Guess component role from filename
Description
Guess component role from filename
Usage
.guess_component(filename)
Arguments
filename |
File basename |
Value
Character: "diffusion", "vae", "llm", "clip_l", "clip_g", "t5xxl", "taesd", or "unknown"
Guess model type from filename
Description
Guess model type from filename
Usage
.guess_model_type(filename)
Arguments
filename |
File basename |
Value
Character: "flux3", "flux2", "flux", "sdxl", "sd1", "sd2", "sd3", or "unknown"
Encode sd_image list to base64 PNG strings
Description
Encode sd_image list to base64 PNG strings
Usage
.images_to_base64(images)
Arguments
images |
List of sd_image objects |
Value
Character vector of base64-encoded PNG strings
Get native latent tile size for a model type
Description
Get native latent tile size for a model type
Usage
.native_latent_tile_size(model_type)
Arguments
model_type |
One of "sd1", "sd2", "sdxl", "flux", "flux2", "flux3", "sd3" |
Value
Integer tile size in latent pixels
Get native tile size for a model type
Description
Get native tile size for a model type
Usage
.native_tile_size(model_type)
Arguments
model_type |
One of "sd1", "sd2", "sdxl", "flux", "flux2", "flux3", "sd3" |
Value
Integer tile size in pixels
Extract <lora:name:weight> tags from a prompt
Description
Extract <lora:name:weight> tags from a prompt
Usage
.parse_lora_tags(prompt)
Arguments
prompt |
Prompt string |
Value
list(prompt = prompt without tags, loras = named numeric vector)
Pick the LLM text encoder for FLUX.2 / FLUX.3
Description
FLUX.3 uses Qwen3-VL, FLUX.2 Klein uses plain Qwen3 (full FLUX.2: Mistral). Prefers a "vl" file for flux3 and a non-"vl" file for flux2; falls back to any candidate when no preferred one exists.
Usage
.pick_llm(files, model_type)
Arguments
files |
Candidate LLM file paths |
model_type |
"flux2" or "flux3" |
Value
A single path, or NULL when there are no candidates
Bilinear resize of an SD image
Description
Bilinear resize of an SD image
Usage
.resize_sd_image(image, target_w, target_h)
Arguments
image |
SD image list |
target_w |
Target width |
target_h |
Target height |
Value
Resized SD image
Resolve device layout preset to concrete GPU indices
Description
Resolve device layout preset to concrete GPU indices
Usage
.resolve_device_layout(
layout,
diffusion_gpu,
clip_gpu,
vae_gpu,
keep_clip_on_cpu,
keep_vae_on_cpu
)
Arguments
layout |
One of "mono", "split_encoders", "split_vae", "encoders_cpu" |
diffusion_gpu |
Manual override (-1 = use layout) |
clip_gpu |
Manual override (-1 = use layout) |
vae_gpu |
Manual override (-1 = use layout) |
keep_clip_on_cpu |
Existing keep_clip_on_cpu flag |
keep_vae_on_cpu |
Existing keep_vae_on_cpu flag |
Value
List with diffusion, clip, vae (GPU indices), clip_on_cpu, vae_on_cpu
Resolve a LoRA name to an existing file
Description
Resolve a LoRA name to an existing file
Usage
.resolve_lora_path(name, dir)
Arguments
name |
Path or name (without the |high_noise| prefix) |
dir |
lora_model_dir or NULL |
Value
Normalized path; errors if not found
Merge prompt tags and explicit loras, resolve paths
Description
Merge prompt tags and explicit loras, resolve paths
Usage
.resolve_loras(ctx, prompt, loras = NULL)
Arguments
ctx |
SD context (attribute lora_model_dir) |
prompt |
Prompt string (tags are removed) |
loras |
Named numeric vector or NULL |
Value
list(prompt, loras = NULL or list(path, multiplier, is_high_noise))
Resolve model_type, including the "auto" detection hierarchy
Description
When model_type == "auto", tries, in order: GGUF KV metadata
(.detect_model_type_gguf, header-only probe), a sibling
config.json (.detect_model_type_config), then the
filename heuristic (.guess_model_type). If all fail it errors
with a hint to set model_type explicitly rather than guessing.
Usage
.resolve_model_type(model_type, path)
Arguments
model_type |
User-supplied model type ("auto" triggers detection) |
path |
Path used for detection (model_path or diffusion_model_path) |
Value
A concrete model type string
Resolve VAE tiling mode to boolean
Description
In "auto" mode, queries free VRAM from the Vulkan backend and
compares against .estimate_vae_vram. Falls back to the
pixel-area vae_auto_threshold when VRAM query is unavailable.
Usage
.resolve_vae_tiling(
vae_mode,
vae_tiling,
width,
height,
vae_auto_threshold,
ctx = NULL,
batch = 1L,
system_reserve = 50 * 1024^2
)
Arguments
vae_mode |
One of "normal", "tiled", "auto" |
vae_tiling |
Deprecated boolean flag (NULL if not set) |
width |
Image width in pixels |
height |
Image height in pixels |
vae_auto_threshold |
Pixel area threshold — fallback for auto mode when VRAM query fails |
ctx |
SD context (used to read device index and model_type). NULL disables VRAM-aware logic. |
batch |
Batch size for VRAM estimation (default 1) |
system_reserve |
Bytes to keep free as safety margin (default 50 MB) |
Value
Logical, TRUE if tiling should be enabled
Build an executable step plan for sd_generate (async orchestration)
Description
Mirrors the routing logic of sd_generate (cfg auto-1.0 for
guidance-distilled Flux/Flux.2, strategy selection, VAE tiling resolution)
but instead of running the pipeline, returns a list of steps. Each
step is one of:
-
type = "gen"— a singlesd_generate_async()call. Carries a ready-to-useparamslist,width/height, alabel, anduses_init(whether it consumes the previous step's image asinit_image). -
type = "upscale"— a synchronous R-side resize/ESRGAN step run between two gen steps. Carrieswidth/height,upscaler,upscale_factor.
The final step (the image returned to the caller) has final = TRUE.
Usage
.sd_generate_plan(
ctx,
prompt,
negative_prompt = "",
width = 512L,
height = 512L,
init_image = NULL,
strength = 0.75,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
batch_count = 1L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
eta = 0,
flow_shift = NULL,
hr_strength = 0.4,
hr_steps = NULL,
upscaler = NULL,
upscale_factor = 4L,
vae_mode = "auto",
vae_auto_threshold = 1048576L,
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
cache_mode = c("off", "easy", "ucache"),
cache_config = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt describing desired image |
negative_prompt |
Negative prompt (default "") |
width |
Image width in pixels (default 512) |
height |
Image height in pixels (default 512) |
init_image |
Optional init image for img2img. If provided, runs img2img
instead of txt2img. Requires |
strength |
Denoising strength for img2img (default 0.75). Ignored for txt2img. |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Random seed (-1 for random) |
batch_count |
Number of images to generate (default 1) |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
eta |
Eta parameter for DDIM-like samplers |
flow_shift |
Flow shift for flow-matching models (Flux, SD3). |
hr_strength |
Denoising strength for highres fix refinement pass (default 0.4). Only used when auto-routing selects highres fix. |
vae_mode |
VAE processing mode: |
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512); converted internally to latent cells with the model's VAE scale factor (8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent cells (default 64); values below 128 give a warning. |
vae_tile_overlap |
Overlap for VAE tiling (default 0.25) |
cache_mode |
Step caching mode: |
cache_config |
Optional fine-tuned cache config from
|
Details
This lets the Shiny GUI drive the multi-step highres-fix pipeline through the single-shot async engine: run a gen step, poll it, feed its result into the next step, all without blocking the R session.
Value
List of step descriptors (see above).
Run one generation with LoRA resolution and the post-generation check
Description
Run one generation with LoRA resolution and the post-generation check
Usage
.sd_generate_with_loras(ctx, params, loras = NULL)
Arguments
ctx |
SD context |
params |
Params list for sd_generate_image (prompt may contain tags) |
loras |
Named numeric vector or NULL |
Value
List of images
Select generation strategy based on resolution and VRAM
Description
Select generation strategy based on resolution and VRAM
Usage
.select_strategy(
width,
height,
ctx,
model_type,
is_img2img,
vae_decode_only = TRUE
)
Arguments
width |
Target width |
height |
Target height |
ctx |
SD context with VRAM attributes |
model_type |
Model type string |
is_img2img |
Whether this is an img2img call |
vae_decode_only |
Whether context has VAE encoder (FALSE = has encoder) |
Value
One of "direct", "tiled", "highres_fix"
Recursively unbox scalar values in nested lists for JSON serialization
Description
Recursively unbox scalar values in nested lists for JSON serialization
Usage
.unbox_scalars(x, keep_arrays = character(0))
Arguments
x |
List or atomic value |
Value
Same structure with scalars wrapped in jsonlite::unbox
LoRA apply modes
Description
LoRA apply modes
Usage
LORA_APPLY_MODE
Format
An object of class list of length 3.
Prediction types
Description
FLUX2_FLOW_PRED is kept as an alias of FLUX_FLOW_PRED: the
core no longer has a separate FLUX.2 prediction type.
Usage
PREDICTION
Format
An object of class list of length 9.
Preview decode modes
Description
Mode strings accepted by the preview callback (see
sd_preview_start). "proj" is a fast linear projection
of the latent (cheap, rough), "tae" uses the tiny autoencoder
(needs taesd_path), "vae" runs the full VAE (slow, accurate).
Usage
PREVIEW
Format
An object of class list of length 4.
RNG types
Description
RNG types
Usage
RNG_TYPE
Format
An object of class list of length 3.
Sampling methods
Description
Sampling methods
Usage
SAMPLE_METHOD
Format
An object of class list of length 21.
Schedulers
Description
Schedulers
Usage
SCHEDULER
Format
An object of class list of length 17.
Cache modes
Description
Cache modes
Usage
SD_CACHE_MODE
Format
An object of class list of length 7.
Weight types (ggml quantization types)
Description
Weight types (ggml quantization types)
Usage
SD_TYPE
Format
An object of class list of length 38.
Start sd2R REST API server
Description
Launches a plumber-based REST API for image generation. Optionally pre-loads a model at startup.
Usage
sd_api_start(
model_path = NULL,
model_type = "sd1",
model_id = NULL,
vae_decode_only = TRUE,
host = "0.0.0.0",
port = 8080L,
api_key = NULL,
...
)
Arguments
model_path |
Optional path to model file to load at startup |
model_type |
Model type for the pre-loaded model (default "sd1") |
model_id |
Identifier for the pre-loaded model (default: basename of model_path) |
vae_decode_only |
VAE decode only for the pre-loaded model (default TRUE) |
host |
Host to bind to (default "0.0.0.0") |
port |
Port to listen on (default 8080) |
api_key |
Optional API key string. When set, non-localhost requests
must include |
... |
Additional arguments passed to |
Value
Invisibly returns the plumber router object
Examples
## Not run:
# Start with a pre-loaded model
sd_api_start("model.safetensors", model_type = "flux", port = 8080)
# Start empty, load models via API
sd_api_start(port = 8080)
# With API key
sd_api_start("model.safetensors", api_key = "my-secret-key")
## End(Not run)
Stop sd2R REST API server
Description
Stops the running plumber server and unloads all models.
Usage
sd_api_stop()
Value
No return value, called for side effects.
Launch sd2R Shiny GUI
Description
Opens an interactive Shiny application for text-to-image generation. Requires the shiny and base64enc packages.
Usage
sd_app(model_dir = NULL, launch.browser = TRUE, port = NULL, ...)
Arguments
model_dir |
Path to folder with model files. If provided, the app scans the folder on startup and auto-assigns model roles. |
launch.browser |
Open in browser (default TRUE) |
port |
Port number (default NULL = random) |
... |
Additional arguments passed to |
Value
This function does not return; it runs the Shiny app until stopped.
Examples
## Not run:
sd_app()
sd_app(model_dir = "/path/to/models")
## End(Not run)
Create a pipeline execution cache
Description
A cache keeps node results between sd_run_pipeline calls:
on the next run, a node whose type, parameters and inputs are unchanged
returns its stored result without running, and so do not need to run the
nodes it depends on. Pass the same cache object to every run; it can be
shared between different pipelines.
Usage
sd_cache(max_entries = 32L, max_mb = NULL)
Arguments
max_entries |
Maximum number of stored node results (LRU eviction). Default 32. |
max_mb |
Memory budget in megabytes for the stored results
(estimated with |
Details
A node's key is computed before anything runs from its type, its
parameters, the keys of the nodes linked to its inputs, and the model
context (each sd_ctx gets its own generation number, so a
new context never reuses old results). Node ids are not part of the key:
renaming a node or moving it to another pipeline keeps its cached result.
For nodes that read a file (load_image, load_mask, the
remove_background model), the file's size and modification time
are part of the key, so a rewritten file is read again (like
make; changes within the file system's time resolution may go
unnoticed).
What is cached: the expensive nodes encode_text,
encode_image, sample, txt2img, img2img and
remove_background. Other nodes (decode, loading, image and
mask operations) always run, but their keys still let the nodes after
them hit the cache. save and save_mask always run (the file
must exist after the run), taking their inputs from the cache.
Not cached, together with every node after them: txt2img and
img2img with a random seed (seed < 0), upscale (its
model is passed separately and has no identity in the key), and all
nodes when ctx was not created by sd_ctx().
Run-time inputs (input_* nodes) are keyed by a hash of their
content, so the same input value keeps the nodes after it cacheable.
Results are kept in R memory (not on the GPU). When more than
max_entries results, or more than max_mb megabytes, are
stored, the least recently used ones are dropped (a single result larger
than max_mb is not kept). Large data (arrays) should reach a node through its inputs, not
its parameters: parameters are compared in full on every run.
Value
An environment of class "sd_cache".
See Also
sd_cache_clear, sd_run_pipeline
Examples
## Not run:
cache <- sd_cache()
sd_run_pipeline(pipe, ctx, cache = cache) # runs everything
pipe$nodes[[4]]$params$path <- "other.png"
sd_run_pipeline(pipe, ctx, cache = cache) # encode/sample from cache
## End(Not run)
Clear a pipeline execution cache
Description
Drops all stored results and resets the hit/miss counters.
Usage
sd_cache_clear(cache)
Arguments
cache |
An |
Value
The cache, invisibly.
Create cache configuration for step caching
Description
Constructs a list of cache parameters for fine-tuning step caching behavior.
Pass the result as cache_config to generation functions.
Usage
sd_cache_params(
mode = SD_CACHE_MODE$EASYCACHE,
threshold = 1,
start_percent = 0.15,
end_percent = 0.95
)
Arguments
mode |
Cache mode integer from |
threshold |
Reuse threshold (default 1.0). Lower = more aggressive caching |
start_percent |
Start caching after this fraction of steps (default 0.15) |
end_percent |
Stop caching after this fraction of steps (default 0.95) |
Value
Named list of cache parameters
Canny edge map for ControlNet
Description
Computes a Canny edge map with the stable-diffusion.cpp core (the same code
as its --canny option): grayscale, Gaussian blur, Sobel gradients,
non-maximum suppression and hysteresis thresholding.
Usage
sd_canny(
image,
high_threshold = 0.08,
low_threshold = 0.08,
weak = 0.8,
strong = 1,
inverse = FALSE
)
Arguments
image |
SD image (list with |
high_threshold, low_threshold |
Hysteresis thresholds on the normalized gradient, in [0, 1] (defaults 0.08, as in sd.cpp). |
weak, strong |
Output values for weak and strong edges, in [0, 1] (defaults 0.8 and 1). |
inverse |
If |
Value
An SD image with the same size and channels as the input, the edge map in every colour channel (alpha is kept).
Examples
## Not run:
edges <- sd_canny("photo.png")
sd_save_image(edges, "edges.png")
## End(Not run)
Convert model to different quantization format
Description
Convert model to different quantization format
Usage
sd_convert(
input_path,
output_path,
output_type = SD_TYPE$F16,
vae_path = NULL,
tensor_type_rules = NULL
)
Arguments
input_path |
Path to input model file |
output_path |
Path for output model file |
output_type |
Target quantization type (see |
vae_path |
Optional path to separate VAE model |
tensor_type_rules |
Optional tensor type rules string |
Value
TRUE on success
Create a Stable Diffusion context
Description
Loads a model and creates a context for image generation.
Usage
sd_ctx(
model_path = NULL,
vae_path = NULL,
taesd_path = NULL,
clip_l_path = NULL,
clip_g_path = NULL,
t5xxl_path = NULL,
llm_path = NULL,
diffusion_model_path = NULL,
control_net_path = NULL,
n_threads = 0L,
wtype = SD_TYPE$COUNT,
tensor_type_rules = NULL,
vae_decode_only = TRUE,
free_params_immediately = FALSE,
keep_clip_on_cpu = FALSE,
keep_vae_on_cpu = FALSE,
offload_params_to_cpu = FALSE,
max_vram = 0,
stream_layers = FALSE,
enable_mmap = FALSE,
eager_load = TRUE,
vae_conv_direct = TRUE,
diffusion_conv_direct = FALSE,
diffusion_flash_attn = TRUE,
rng_type = RNG_TYPE$CUDA,
prediction = NULL,
lora_apply_mode = LORA_APPLY_MODE$AUTO,
lora_model_dir = NULL,
model_type = "sd1",
vram_gb = NULL,
device_layout = "mono",
diffusion_gpu = -1L,
clip_gpu = -1L,
vae_gpu = -1L,
meta_backend = FALSE,
verbose = FALSE
)
Arguments
model_path |
Path to the model file (safetensors, gguf, or checkpoint) |
vae_path |
Optional path to a separate VAE model |
taesd_path |
Optional path to TAESD model for preview |
clip_l_path |
Optional path to CLIP-L model |
clip_g_path |
Optional path to CLIP-G model |
t5xxl_path |
Optional path to T5-XXL model |
llm_path |
Optional path to an LLM text encoder (Qwen3 / Mistral-Small).
Required for models that use an LLM conditioner, e.g. FLUX.2 Klein (Qwen3),
FLUX.2 (Mistral-Small), Z-Image and Qwen-Image. Loaded into the
|
diffusion_model_path |
Optional path to separate diffusion model |
control_net_path |
Optional path to ControlNet model |
n_threads |
Number of CPU threads (0 = auto-detect) |
wtype |
Weight type for quantization (see |
tensor_type_rules |
Optional per-component weight type override, as a
comma-separated string of
Type names match ggml type names ( |
vae_decode_only |
If TRUE, only load VAE decoder (saves memory) |
free_params_immediately |
Free model params after first computation. If TRUE, the context can only be used for a single generation — subsequent calls will crash. Set to TRUE only when you need to save memory and will not reuse the context. Default is FALSE. |
keep_clip_on_cpu |
Keep CLIP model on CPU even when using GPU |
keep_vae_on_cpu |
Keep VAE on CPU even when using GPU |
offload_params_to_cpu |
Keep model weights in CPU RAM and stream them to the GPU on demand during compute (default FALSE). Lowers VRAM usage at the cost of CPU<->GPU transfers each step. Use when the model does not fit in GPU memory. |
max_vram |
GiB budget for graph-cut segmented parameter offload
(default 0 = disabled). A positive value caps GPU memory used by the compute
graph; |
stream_layers |
Enable residency + prefetch streaming of layers on top of
|
enable_mmap |
Memory-map model weights from disk instead of reading them into a malloc'd buffer (default FALSE). Lowers RAM footprint for large models (e.g. Flux); pages are loaded on demand by the OS and shared across processes. Ignored for zip-archived weights. May slow the first generation slightly as pages fault in. |
eager_load |
Load all model weights in |
vae_conv_direct |
Use direct Conv2d implementation in VAE (default TRUE). Faster on GPU; skips im2col and uses direct convolution kernels. |
diffusion_conv_direct |
Use direct Conv2d in diffusion model (default FALSE). |
diffusion_flash_attn |
Enable flash attention for diffusion model (default TRUE). Set to FALSE if you experience issues with specific GPU drivers or backends. |
rng_type |
RNG type (see |
prediction |
Prediction type override (see |
lora_apply_mode |
LoRA application mode (see |
lora_model_dir |
Directory searched for LoRA names given without a
path (in |
model_type |
Model architecture hint: |
vram_gb |
Override available VRAM in GB. When set, disables auto-detection
and uses this value for strategy routing. Default |
device_layout |
GPU layout preset for multi-GPU systems. One of:
Ignored when |
diffusion_gpu |
Vulkan GPU device index for the diffusion model.
Default |
clip_gpu |
Vulkan GPU device index for CLIP/T5 text encoders.
Default |
vae_gpu |
Vulkan GPU device index for VAE encoder/decoder.
Default |
meta_backend |
Logical flag to run the diffusion model through the ggml
meta backend ("second path", multi-GPU tensor split across all available
GPUs). Requires meta-backend support compiled in at install time (ggmlR
>= 0.7.8 exporting |
verbose |
If |
Value
An external pointer to the SD context (class "sd_ctx") with
attributes model_type, vae_decode_only, vram_gb,
vram_total_gb, and vram_device.
Examples
## Not run:
ctx <- sd_ctx("model.safetensors")
imgs <- sd_txt2img(ctx, "a cat sitting on a chair")
sd_save_image(imgs[[1]], "cat.png")
## End(Not run)
Decode a latent into a pixel image (low-level VAE decode)
Description
Decode a latent into a pixel image (low-level VAE decode)
Usage
sd_decode_latent(ctx, latent)
Arguments
ctx |
SD context |
latent |
An sd_tensor list (e.g. the output of |
Value
An sd_image list (width, height, channel,
data). For a batch latent (ne[4] = N > 1, see the
batch argument of sd_sample) the elements are
decoded one by one and returned as one image with batch = N
and the N images' data one after another; split it with
sd_unbatch.
See Also
Default generation parameters
Description
Returns a named list of all per-generation defaults used by
sd_generate. Edit the returned list and pass it back via the
params argument to set a reusable baseline; any explicit argument to
sd_generate() overrides the matching field.
Usage
sd_default_params()
Details
This is the R-level analogue of IRIS_PARAMS_DEFAULT. It covers
generation knobs only; context-construction options (model paths, devices,
offload, etc.) belong to sd_ctx.
Value
A named list with fields: negative_prompt, width,
height, strength, sample_method, sample_steps,
cfg_scale, seed, batch_count, scheduler,
clip_skip, eta, hr_strength, vae_mode,
vae_tile_size, vae_tile_overlap, cache_mode,
cache_config.
See Also
Examples
p <- sd_default_params()
p$sample_steps <- 30
p$cfg_scale <- 4.0
## Not run:
ctx <- sd_ctx("model.safetensors", model_type = "auto")
imgs <- sd_generate(ctx, "a cat", params = p)
## End(Not run)
Run a single denoise step (low-level)
Description
Runs the diffusion model once on x at sigma and returns the
denoised x_0 estimate. The Euler update of x is done by the caller
(see sd_sample_stepwise for the full loop). Must be called
between sd_sampler_begin and sd_sampler_end.
Usage
sd_denoise_step(
ctx,
x,
sigma,
cond,
uncond = list(crossattn = NULL, vector = NULL, concat = NULL),
cfg_scale = 7,
step = 1L,
total_steps = 1L,
sigma_next = NULL
)
Arguments
ctx |
SD context |
x |
Current latent sd_tensor |
sigma |
Current sigma (scalar) |
cond |
Positive conditioning from |
uncond |
Negative conditioning; empty (all |
cfg_scale |
CFG scale (1 disables CFG) |
step, total_steps |
1-based step index / total, for progress hooks |
sigma_next |
Next sigma of the schedule (0 on the last step). Required
for FLUX.3 (flow-map target timestep); ignored by other models.
|
Value
An sd_tensor list — the denoised x_0 estimate.
See Also
Load a depth estimation model (ONNX)
Description
Loads a monocular depth model through ggmlR's ONNX runtime. The defaults
fit Depth Anything V2 (input 518 x 518, ImageNet normalization, output
relative inverse depth); size, mean and std can be
changed for other models of the same kind (e.g. MiDaS / DPT: 384, mean
and std 0.5).
Usage
sd_depth_load(
path,
device = NULL,
dtype = "f32",
size = 518L,
mean = c(0.485, 0.456, 0.406),
std = c(0.229, 0.224, 0.225)
)
Arguments
path |
Path to the |
device |
ggmlR device ( |
dtype |
Weight type for ggmlR (default |
size |
Square input size in pixels (a multiple of 14 for Depth Anything). Default 518. |
mean, std |
Per-channel (RGB) normalization of the [0, 1] input. |
Value
An object of class "sd_depth".
See Also
Release a stable diffusion context and free its VRAM
Description
Immediately destroys an sd_ctx object created by sd_ctx,
freeing the GPU memory held by its model weights and compute buffers. Use this
before loading a different model so the two models do not pile up in VRAM.
Usage
sd_destroy_context(ctx)
Arguments
ctx |
An |
Details
The context's external pointer also has a finalizer that frees it during R's
garbage collection, but that is non-deterministic and may not run promptly —
on a memory-constrained GPU, loading a second model before the first is
collected can exhaust VRAM and make the next Vulkan device init fail. Calling
sd_destroy_context() makes the release deterministic.
After this call the ctx object is dead; do not pass it to
sd_generate or other functions. Calling it twice on the same
object, or on an already-finalized one, is a safe no-op.
Value
NULL, invisibly.
See Also
Examples
## Not run:
ctx <- sd_ctx("flux1.safetensors", model_type = "flux")
img <- sd_generate(ctx, "a cat")
sd_destroy_context(ctx) # free VRAM before the next model
ctx <- sd_ctx("flux2.safetensors", model_type = "flux2")
## End(Not run)
Download a Stable Diffusion model from Kaggle Models
Description
Downloads a model bundle from the public Kaggle Models registry and unpacks
it into dest. Mirrors the behaviour of the Python kagglehub
package (kagglehub.model_download("owner/model/framework/variation"))
but uses only base R – no Python dependency.
Usage
sd_download_model(
handle = "lbsbmsu/flux-2/gguf/default",
dest,
version = NULL,
files = NULL,
verbose = FALSE
)
Arguments
handle |
Model handle in kagglehub form
|
dest |
Destination directory for the unpacked files. Created if it does not exist. Required. |
version |
Integer version number. If |
files |
Optional character vector of file names to extract from the
bundle. If |
verbose |
Logical; print progress messages. Defaults to |
Details
Kaggle serves each model version as a single .tar.gz bundle; the whole
bundle is downloaded even when only some files are needed. Only public models
are supported.
Value
The path to dest (invisibly), containing the model files.
Encode an image into a latent (low-level VAE encode)
Description
Encode an image into a latent (low-level VAE encode)
Usage
sd_encode_image(ctx, image)
Arguments
ctx |
SD context (must be built with |
image |
An sd_image list ( |
Value
An sd_tensor list (type, ne, data) — the latent.
See Also
Encode a text prompt into conditioning (low-level)
Description
Runs only the text-encoder stage of the pipeline, returning the
conditioning tensors (analogue of SDCondition). Building block for
custom pipelines; most users want sd_generate.
Usage
sd_encode_text(ctx, prompt, clip_skip = -1L, width = -1L, height = -1L)
Arguments
ctx |
SD context from |
prompt |
Text prompt |
clip_skip |
CLIP layers to skip (-1 = model default) |
width, height |
Intended generation size (affects size-conditioning for some models, e.g. SDXL). -1 lets the model decide. |
Value
A conditioning list with elements crossattn, vector,
concat; each is an sd_tensor list (type, ne,
data) or NULL when the model does not produce it.
See Also
Depth map for ControlNet
Description
Estimates relative depth with a model loaded by sd_depth_load
and returns it as a hint image for depth ControlNets: near = white, far =
black, min-max normalized per image, resized back to the input size
(bilinear).
Usage
sd_estimate_depth(image, model)
Arguments
image |
SD image or a path to a PNG file. |
model |
An |
Value
A 3-channel SD image of the input size (gray depth in every channel).
Examples
## Not run:
depth <- sd_depth_load("depth_anything_v2_small.onnx")
sd_save_image(sd_estimate_depth("photo.png", depth), "depth.png")
## End(Not run)
Euler update of a latent (low-level)
Description
Computes x + (x - denoised) / sigma * (sigma_next - sigma) in float,
exactly as the built-in Euler sampler, so an R sampling loop built from
sd_denoise_step + sd_euler_step matches
sd_sample bit-for-bit.
Usage
sd_euler_step(x, denoised, sigma, sigma_next)
Arguments
x |
Current latent sd_tensor |
denoised |
Denoised x_0 estimate from |
sigma |
Current sigma |
sigma_next |
Next sigma of the schedule (0 on the last step) |
Value
An sd_tensor list — the updated latent.
See Also
sd_denoise_step, sd_sample_stepwise
Generate images (unified entry point)
Description
Automatically selects the best generation strategy based on output resolution
and available VRAM (set via vram_gb in sd_ctx). For
txt2img, routes between direct generation, tiled sampling (MultiDiffusion),
or highres fix. For img2img (when init_image is provided), routes
between direct and tiled img2img.
Usage
sd_generate(
ctx,
prompt,
negative_prompt = "",
width = 512L,
height = 512L,
init_image = NULL,
strength = 0.75,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
batch_count = 1L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
eta = 0,
flow_shift = NULL,
hr_strength = 0.4,
vae_mode = "auto",
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
cache_mode = c("off", "easy", "ucache"),
cache_config = NULL,
params = NULL,
preview = FALSE,
preview_path = NULL,
preview_mode = PREVIEW$PROJ,
preview_interval = 1L,
loras = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt describing desired image |
negative_prompt |
Negative prompt (default "") |
width |
Image width in pixels (default 512) |
height |
Image height in pixels (default 512) |
init_image |
Optional init image for img2img. If provided, runs img2img
instead of txt2img. Requires |
strength |
Denoising strength for img2img (default 0.75). Ignored for txt2img. |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Random seed (-1 for random) |
batch_count |
Number of images to generate (default 1) |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
eta |
Eta parameter for DDIM-like samplers |
flow_shift |
Flow shift for flow-matching models (Flux, SD3). |
hr_strength |
Denoising strength for highres fix refinement pass (default 0.4). Only used when auto-routing selects highres fix. |
vae_mode |
VAE processing mode: |
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512); converted internally to latent cells with the model's VAE scale factor (8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent cells (default 64); values below 128 give a warning. |
vae_tile_overlap |
Overlap for VAE tiling (default 0.25) |
cache_mode |
Step caching mode: |
cache_config |
Optional fine-tuned cache config from
|
params |
Optional baseline list from |
preview |
If |
preview_path |
File path for the preview PPM. Defaults to a tempfile
when |
preview_mode |
Preview decode mode (see |
preview_interval |
Emit a preview every N steps (default 1). |
loras |
LoRA weights: named numeric vector |
Details
When vram_gb is not set on the context, defaults to direct generation
(equivalent to calling sd_txt2img or sd_img2img
directly).
Value
List of SD images (or single image for highres fix path).
Examples
## Not run:
# Simple — auto-routes based on detected VRAM
ctx <- sd_ctx("model.safetensors", model_type = "sd1",
vae_decode_only = FALSE)
imgs <- sd_generate(ctx, "a cat", width = 2048, height = 2048)
# Manual override — force 4 GB VRAM limit
ctx4 <- sd_ctx("model.safetensors", model_type = "sd1",
vram_gb = 4, vae_decode_only = FALSE)
imgs <- sd_generate(ctx4, "a cat", width = 2048, height = 2048)
## End(Not run)
Parallel generation across multiple GPUs
Description
Distributes prompts across available Vulkan GPUs, running one process per
GPU via callr. Each process creates its own sd_ctx and
calls sd_generate. Requires the callr package.
Usage
sd_generate_multi_gpu(
model_path = NULL,
prompts,
negative_prompt = "",
devices = NULL,
seeds = NULL,
width = 512L,
height = 512L,
model_type = "sd1",
vram_gb = NULL,
vae_decode_only = TRUE,
progress = TRUE,
diffusion_model_path = NULL,
vae_path = NULL,
clip_l_path = NULL,
t5xxl_path = NULL,
llm_path = NULL,
...
)
Arguments
model_path |
Path to the model file (single-file models like SD 1.x/2.x/SDXL) |
prompts |
Character vector of prompts (one image per prompt) |
negative_prompt |
Negative prompt applied to all images (default "") |
devices |
Integer vector of Vulkan device indices (0-based). Default
|
seeds |
Integer vector of seeds, same length as |
width |
Image width (default 512) |
height |
Image height (default 512) |
model_type |
Model type (default "sd1") |
vram_gb |
VRAM per GPU for auto-routing (default NULL) |
vae_decode_only |
VAE decode only (default TRUE) |
progress |
Print progress messages (default TRUE) |
diffusion_model_path |
Path to diffusion model (Flux/multi-file models) |
vae_path |
Path to VAE model |
clip_l_path |
Path to CLIP-L model |
t5xxl_path |
Path to T5-XXL model |
llm_path |
Path to an LLM text encoder (Qwen3 / Mistral), e.g. FLUX.2 |
... |
Additional arguments passed to |
Value
List of SD images, one per prompt, in original order.
Note
Release any existing SD context (rm(ctx); gc()) before calling
this function. Holding a Vulkan context in the main process while
subprocesses try to use the same GPU can produce corrupted (grey) images.
Examples
## Not run:
# Single-file model (SD 1.x/2.x/SDXL)
imgs <- sd_generate_multi_gpu(
"model.safetensors",
prompts = c("a cat", "a dog", "a bird", "a fish"),
devices = 0:1
)
# Multi-file model (Flux)
imgs <- sd_generate_multi_gpu(
diffusion_model_path = "flux1-dev-Q4_K_S.gguf",
vae_path = "ae.safetensors",
clip_l_path = "clip_l.safetensors",
t5xxl_path = "t5-v1_1-xxl-encoder-Q5_K_M.gguf",
prompts = c("a cat", "a dog"),
model_type = "flux", devices = 0:1
)
## End(Not run)
Generate an image conditioned on multiple reference images
Description
Runs generation with one or more reference images, as used by edit /
reference-conditioned models (e.g. Qwen-Image, FLUX control/edit variants).
The references are passed straight through to the underlying
generate_image C-API (ref_images); the active model decides how
to use them, so this only has effect on models that support reference
conditioning.
Usage
sd_generate_multiref(
ctx,
prompt,
refs,
negative_prompt = "",
width = 512L,
height = 512L,
auto_resize_ref_image = TRUE,
increase_ref_index = FALSE,
sample_method = SAMPLE_METHOD$EULER,
scheduler = SCHEDULER$DISCRETE,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
clip_skip = -1L,
eta = 0,
batch_count = 1L,
loras = NULL
)
Arguments
ctx |
SD context from |
prompt |
Text prompt |
refs |
A list of sd_image lists (each with |
negative_prompt |
Negative prompt (default "") |
width, height |
Output size in pixels |
auto_resize_ref_image |
If |
increase_ref_index |
If |
sample_method, scheduler |
Sampler / scheduler (name or enum value) |
sample_steps, cfg_scale, seed, clip_skip, eta |
Standard sampling controls |
batch_count |
Number of images (default 1) |
loras |
LoRA weights: named numeric vector |
Value
List of sd_image lists.
See Also
High-resolution image generation (Highres Fix)
Description
Two-pass generation: first creates a base image at native model resolution, then upscales and refines with tiled img2img to produce a high-resolution result with coherent global composition.
Usage
sd_highres_fix(
ctx,
prompt,
negative_prompt = "",
width = 2048L,
height = 2048L,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
eta = 0,
flow_shift = NULL,
hr_strength = 0.4,
hr_steps = NULL,
sample_tile_size = NULL,
sample_tile_overlap = 0.25,
upscaler = NULL,
upscale_factor = 4L,
vae_mode = "auto",
vae_auto_threshold = 1048576L,
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
cache_mode = c("off", "easy", "ucache"),
cache_config = NULL,
loras = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt describing desired image |
negative_prompt |
Negative prompt (default "") |
width |
Target output width in pixels (default 2048) |
height |
Target output height in pixels (default 2048) |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Random seed (-1 for random) |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
eta |
Eta parameter for DDIM-like samplers |
flow_shift |
Flow shift for flow-matching models (Flux, SD3). |
hr_strength |
Denoising strength for the refinement pass (0.0-1.0, default 0.4). Lower = more faithful to base, higher = more detail/change. |
hr_steps |
Sample steps for refinement pass (default same as sample_steps) |
sample_tile_size |
Tile size in latent pixels for refinement (default auto) |
sample_tile_overlap |
Tile overlap fraction (default 0.25) |
upscaler |
Path to ESRGAN model for upscaling. If NULL, uses bilinear. |
upscale_factor |
ESRGAN upscale factor (default 4, only used with upscaler) |
vae_mode |
VAE processing mode: |
vae_auto_threshold |
Pixel area fallback threshold for
|
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512);
converted internally to latent cells with the model's VAE scale factor
(8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent
cells (default 64); values below 128 give a warning.
Ignored when |
vae_tile_overlap |
Overlap ratio between tiles, 0.0-0.5 (default 0.25) |
cache_mode |
Step caching mode: |
cache_config |
Optional fine-tuned cache config from
|
loras |
LoRA weights: named numeric vector |
Value
SD image (single image, not list)
Convert SD image to R numeric array
Description
Converts the raw uint8 SD image format to a [height, width, channels] numeric array with values in [0, 1] suitable for R image processing.
Usage
sd_image_to_array(image)
Arguments
image |
SD image list (width, height, channel, data) |
Value
3D numeric array [height, width, channels] in [0, 1]
Generate images with img2img
Description
Generate images with img2img
Usage
sd_img2img(
ctx,
prompt,
init_image,
negative_prompt = "",
mask = NULL,
width = NULL,
height = NULL,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
batch_count = 1L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
strength = 0.75,
eta = 0,
flow_shift = NULL,
vae_mode = "auto",
vae_auto_threshold = 1048576L,
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
vae_tile_rel_x = NULL,
vae_tile_rel_y = NULL,
vae_tiling = NULL,
cache_mode = c("off", "easy", "ucache"),
cache_config = NULL,
loras = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt describing desired image |
init_image |
Init image in sd_image format. Use |
negative_prompt |
Negative prompt (default "") |
mask |
Optional inpainting mask. A PNG file path, a numeric matrix
|
width |
Image width in pixels (default 512) |
height |
Image height in pixels (default 512) |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Random seed (-1 for random) |
batch_count |
Number of images to generate (default 1) |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
strength |
Denoising strength (0.0 = no change, 1.0 = full denoise, default 0.75) |
eta |
Eta parameter for DDIM-like samplers |
flow_shift |
Flow shift for flow-matching models (Flux, SD3). |
vae_mode |
VAE processing mode: |
vae_auto_threshold |
Pixel area fallback threshold for
|
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512);
converted internally to latent cells with the model's VAE scale factor
(8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent
cells (default 64); values below 128 give a warning.
Ignored when |
vae_tile_overlap |
Overlap ratio between tiles, 0.0-0.5 (default 0.25) |
vae_tile_rel_x |
Relative tile width as fraction of latent width (0-1)
or number of tiles (>1). NULL = use |
vae_tile_rel_y |
Relative tile height as fraction of latent height (0-1)
or number of tiles (>1). NULL = use |
vae_tiling |
Deprecated. Use |
cache_mode |
Step caching mode: |
cache_config |
Optional fine-tuned cache config from
|
loras |
LoRA weights: named numeric vector |
Value
List of SD images
Tiled img2img (MultiDiffusion with init image)
Description
Runs img2img with tiled sampling: at each denoising step the latent is split into overlapping tiles, each denoised independently, then merged. The init image provides global composition; tiles add detail.
Usage
sd_img2img_tiled(
ctx,
prompt,
init_image,
negative_prompt = "",
width = NULL,
height = NULL,
sample_tile_size = NULL,
sample_tile_overlap = 0.25,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
batch_count = 1L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
strength = 0.5,
eta = 0,
flow_shift = NULL,
vae_mode = "auto",
vae_auto_threshold = 1048576L,
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
cache_mode = c("off", "easy", "ucache"),
cache_config = NULL,
loras = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt describing desired image |
init_image |
Init image in sd_image format. Use |
negative_prompt |
Negative prompt (default "") |
width |
Image width in pixels (default 512) |
height |
Image height in pixels (default 512) |
sample_tile_size |
Tile size in latent pixels (default auto from model) |
sample_tile_overlap |
Overlap fraction 0.0-0.5 (default 0.25) |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Random seed (-1 for random) |
batch_count |
Number of images to generate (default 1) |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
strength |
Denoising strength (0.0 = no change, 1.0 = full denoise, default 0.75) |
eta |
Eta parameter for DDIM-like samplers |
flow_shift |
Flow shift for flow-matching models (Flux, SD3). |
vae_mode |
VAE processing mode: |
vae_auto_threshold |
Pixel area fallback threshold for
|
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512);
converted internally to latent cells with the model's VAE scale factor
(8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent
cells (default 64); values below 128 give a warning.
Ignored when |
vae_tile_overlap |
Overlap ratio between tiles, 0.0-0.5 (default 0.25) |
cache_mode |
Step caching mode: |
cache_config |
Optional fine-tuned cache config from
|
loras |
LoRA weights: named numeric vector |
Value
List of SD images
Undo final-step latent scaling (low-level)
Description
Applies the denoiser's inverse noise scaling after the last step. A no-op for discrete CompVis denoisers (SD1/SD2/SDXL).
Usage
sd_inverse_noise_scale(ctx, x, sigma_last)
Arguments
ctx |
SD context |
x |
Latent sd_tensor after the last step |
sigma_last |
Last sigma of the schedule (typically 0) |
Value
An sd_tensor.
List registered models
Description
Returns a data frame of all models recorded in the sd2R model registry, with a column indicating which are currently loaded in memory.
Usage
sd_list_models()
Value
Data frame with columns: id, model_type, loaded, diffusion_path
Load image from file as SD image
Description
Reads a PNG file and converts it to the SD image format (list with width, height, channel, data) suitable for img2img.
Usage
sd_load_image(path, channels = 3L)
Arguments
path |
Path to image file (PNG) |
channels |
Number of output channels (3 for RGB, default) |
Value
SD image list (width, height, channel, data as raw vector)
Load a mask from a PNG file as a 1-channel SD image
Description
Reads a PNG and reduces it to a single grayscale channel suitable for inpainting. RGB(A) inputs are averaged across the colour channels; the alpha channel (if any) is ignored.
Usage
sd_load_mask(path)
Arguments
path |
Path to a PNG file. |
Details
Mask semantics match the engine: white (255) = generate (the inpainted region), black (0) = keep the original pixels.
Value
SD image list (width, height, channel = 1, data as raw vector).
Load a registered model
Description
Loads a model by its registry id. Returns a cached context if already
loaded, otherwise creates a new sd_ctx. Additional
arguments override registry defaults.
Usage
sd_load_model(id, ...)
Arguments
id |
Model identifier from registry |
... |
Additional arguments passed to |
Details
Before loading, the estimated VRAM need (on-disk weight size times a
headroom factor plus a reserve) is compared against free GPU memory; if it
would not fit, least-recently-used models are unloaded first. If loading
still fails due to insufficient VRAM, the LRU model is unloaded and the load
is retried once. VRAM estimation/eviction is skipped when GPU memory cannot
be queried (e.g. CPU backend). Tunable via environment variables
SD2R_VRAM_HEADROOM (default 1.2) and SD2R_VRAM_RESERVE_MB
(default 512).
Value
SD context (external pointer)
Examples
## Not run:
ctx <- sd_load_model("flux-dev")
imgs <- sd_txt2img(ctx, "a cat in space")
# Override defaults
ctx <- sd_load_model("flux-dev", vae_decode_only = FALSE, verbose = TRUE)
## End(Not run)
Load pipeline from JSON
Description
Load pipeline from JSON
Usage
sd_load_pipeline(path)
Arguments
path |
Path to a JSON file saved by |
Value
An sd_pipeline object.
Loopback: feed a pipeline's output back into its input
Description
Runs pipeline n times; the output from of iteration
i becomes the run-time input to of iteration i + 1 (the first
iteration gets init). Typical use: repeated img2img with a
decaying strength.
Usage
sd_loopback(
pipeline,
ctx,
n,
from,
to,
init,
vary = NULL,
seed_mode = c("fixed", "increment"),
keep = c("last", "all"),
inputs = NULL,
cache = sd_cache(),
on_event = NULL,
upscaler_ctx = NULL,
verbose = FALSE
)
Arguments
pipeline |
An |
ctx |
Model context. |
n |
Number of iterations (>= 1). |
from |
Output fed back: |
to |
Id of the run-time input node that receives it. |
init |
Value of |
vary |
Per-iteration parameters (vectors of length |
seed_mode |
|
keep |
|
inputs |
Other fixed run-time inputs. |
cache |
An |
on_event |
Event handler; events get an extra field |
upscaler_ctx, verbose |
As in |
Details
Parameters change per iteration through vary: a list named by node
id of named lists of vectors of length n, e.g.
list(lat = list(strength = seq(0.6, 0.3, length.out = n))). Seeds
follow seed_mode unless varied. Side-effect nodes need a
{i} placeholder (iteration number) in their path, or a varied
path, so iterations do not overwrite each other.
Value
The value of from after the last iteration, or (with
keep = "all") a list of the values of all iterations.
Examples
## Not run:
pipe <- sd_pipeline(
sd_node("input_image", id = "src"),
sd_node("img2img", id = "out", image = "src", prompt = "a castle"),
sd_node("save", image = "out", path = "loop_{i}.png"))
sd_loopback(pipe, ctx, n = 4, from = "out", to = "src",
init = sd_load_image("start.png"),
vary = list(out = list(strength = c(0.6, 0.5, 0.4, 0.3))))
## End(Not run)
LoRA in sd2R
Description
LoRA adapters are passed per generation, either explicitly or as webui-style tags in the prompt. Both forms can be mixed.
Details
Explicit: loras = c("style.safetensors" = 0.8, "detail" = 0.5)
– a named numeric vector, names are paths or names, values are weights.
Prompt tags: "a cat <lora:style:0.8>". Tags are removed from
the prompt before encoding. The name may contain spaces and colons (e.g.
Windows paths C:\loras\style.safetensors); the weight is the part
after the last colon.
Path resolution (same for both forms):
an existing file path is used as is (no directory search);
otherwise the name is looked up in
lora_model_dir(seesd_ctx), first as given, then with the extensions.safetensors,.gguf,.pt,.ckptin this order.
A LoRA that cannot be found is an error. This deliberately differs from the stable-diffusion.cpp CLI, which only warns and silently generates without it.
A name prefixed with |high_noise| targets the high-noise expert of
two-expert video models (Wan 2.2), as in the CLI.
Repeated LoRA: weights of the same file are summed (as in the CLI), and a message reports the sum.
Application check: after generation the number of LoRA tensors that
were actually applied is queried from the core (sd_lora_stats).
A LoRA with less than getOption("sd2R.lora_min_applied", 0.5) of its
compatible tensors applied (e.g. trained for another architecture whose
block names partly coincide, such as a FLUX.1 LoRA on FLUX.2) is an error and
no image is returned; partial application above that share gives a warning
with the counts (legitimate for LoRAs that touch only some blocks). Set the
option lower (e.g. 0) to accept such LoRAs. The check runs after the
generation, so a wrong LoRA costs one full generation.
Apply modes (lora_apply_mode in sd_ctx):
AT_RUNTIMEbase weights stay untouched; the low-rank delta is added during every forward pass. Exact for quantized models, slightly slower.
IMMEDIATELYthe delta is merged into the weights once. For quantized weights this is dequantize -> add -> requantize, so part of the (small) LoRA delta is lost to quantization – the usual reason for "LoRA looks weaker / worse than expected". Not available for INT8 tensorwise weights, row-split tensors, or weight types the backend cannot write back to (Vulkan: K-quants and most IQ types); then the whole context falls back to at_runtime with a logged warning. The mode in effect is reported by
sd_lora_apply_mode.AUTO(default) at_runtime if the model has quantized weights, weights are offloaded to CPU/disk or row-split is active; immediately otherwise.
Effective LoRA apply mode of a context
Description
The mode actually used by ctx: AUTO resolved, and
IMMEDIATELY replaced by AT_RUNTIME when the backend cannot
merge into the model's weight type (e.g. Vulkan with K-quants; a warning is
logged). Decided when the model is loaded, i.e. in sd_ctx with
eager_load = TRUE (default), otherwise at the first generation.
Usage
sd_lora_apply_mode(ctx)
Arguments
ctx |
SD context from |
Value
"immediately" or "at_runtime".
See Also
sd_lora, LORA_APPLY_MODE
LoRA application statistics of the last generation
Description
Number of LoRA tensors that target the model, were applied, or were skipped
as incompatible (shape mismatch), per LoRA file, for the last generation on
ctx. Same counting as the "(applied / total) LoRA tensors" log line
of stable-diffusion.cpp.
Usage
sd_lora_stats(ctx)
Arguments
ctx |
SD context from |
Value
data.frame with columns path, total, applied,
skipped. A LoRA none of whose tensors target the model has no row.
See Also
Create a pipeline node
Description
Create a pipeline node
Usage
sd_node(type, ..., id = NULL)
Arguments
type |
Node type. High-level: |
... |
Parameters for the node (passed to the corresponding function).
Arguments named after one of the node's inputs ( |
id |
Optional node id, used to link other nodes to this one. Assigned
automatically by |
Details
Slots read -> written, and parameters of the low-level nodes:
- encode_text
->
cond,uncond.prompt(required),negative_prompt(default""),clip_skip,width,height; seesd_encode_text.- load_image
->
image.path(required),channels; seesd_load_image.- encode_image
image->latent; seesd_encode_image.- sample
cond[+uncond,latent] ->latent. Other parameters go tosd_sample(sample_steps,cfg_scale,strength,seed, ...). Without an input latent the noise shape isc(width, height) / vae_scale_factorbylatent_channels, both read from the model;width/heightdefault to 512, andvae_scale_factor,latent_channelsor a fulllatent_shapecan be given to override. With an input latent (img2img) its shape is used; setstrengthbelow 1. Optional inputs, linked explicitly only (never the nearest node):mask(inpainting; needslatent; not for inpainting checkpoints yet) andcontrol(an image: ControlNet hint; needs a context withcontrol_net_path, checked before the run; strength viacontrol_strength, in [0, 2], default 0.9). Both must have the generation size in pixels (else an error: useresize/resize_mask).- decode
latent->image; seesd_decode_latent.- upscale_latent
latent->latent, resized in latent space:scale, orwidthandheightin pixels (multiples of the VAE scale factor);methodas forresize. Only plain 4- or 16-channel latents (SD1/2/XL, SD3/FLUX.1); FLUX.2/3 latents pack 2x2 sub-pixels into 128 channels and are refused. A quick option: re-sample with a highstrength(about 0.5-0.7), and expect lower quality than upscaling the image.
Highres fix: generate at the model's native size, upscale, then refine
with img2img. Upscaling the image works for every model and gives the
best quality (use an "upscale" node with ESRGAN instead of
"resize" for sharper detail):
sd_pipeline(
sd_node("encode_text", id = "txt", prompt = "a castle",
width = 1024L, height = 1024L),
sd_node("sample", id = "base", cond = "txt", width = 512L, height = 512L),
sd_node("decode", id = "small", latent = "base"),
sd_node("resize", id = "big", image = "small", width = 1024L),
sd_node("encode_image", id = "init", image = "big"),
sd_node("sample", id = "hr", cond = "txt", latent = "init",
strength = 0.45),
sd_node("decode", latent = "hr"),
sd_node("save", path = "castle.png")
)
For plain latents, decode -> resize -> encode_image can be replaced
by sd_node("upscale_latent", latent = "base", scale = 2) (skips the
VAE round trip; use a higher strength).
Run-time inputs: "input_image", "input_mask",
"input_latent" (no parameters) output the value given for their
id in sd_run_pipeline(inputs = ); the graph (and its JSON) holds
no data. Used by sd_run_batch and sd_loopback.
Masks are a separate type from images: a 1-channel image with values 0..255 ([0, 1] in R), white = regenerate, black = keep the original. A mask input accepts only a mask output, and only as a link to a node (not a file path).
- load_mask
->
mask.path(required); seesd_load_mask.- invert_mask
mask->mask(white <-> black).- save_mask
mask->mask(pass-through, always runs).path(required).- remove_background
image->mask(foreground is white),image(RGBA, or the mask ifoutput = "mask").
Image operations (pure R, run on the CPU):
- resize, resize_mask
image -> image/mask -> mask.widthand/orheight(a missing side keeps the aspect ratio) orscale(not both); the size is rounded to the nearest integer.method:"bilinear"(default, also for masks: keeps soft edges) or"nearest"(for binary masks).- crop, crop_mask
image -> image/mask -> mask.x,y(0-based offsets of the top-left corner, default 0),width,height(required). A region outside the input is an error.- composite
fg,bg(images),mask->image:fg * mask + bg * (1 - mask). All three inputs must be linked explicitly (no nearest-node default, so fg and bg cannot be swapped silently) and have the same size (else an error: useresize/resize_mask). fg and bg are used as RGB: an alpha channel is ignored, grayscale is expanded. The result has 3 channels.
To replace the background, invert the foreground mask and inpaint:
sd_pipeline(
sd_node("load_image", id = "src", path = "photo.png"),
sd_node("remove_background", id = "bg", image = "src",
model_path = "RMBG-1.4.onnx"),
sd_node("invert_mask", id = "back", mask = "bg$mask"),
sd_node("img2img", image = "src", mask = "back",
prompt = "on a beach", strength = 0.9),
sd_node("save", path = "beach.png")
)
Value
A list with class "sd_node".
Examples
## Not run:
pipe <- sd_pipeline(
sd_node("encode_text", prompt = "a cat", width = 768L, height = 768L),
sd_node("sample", width = 768L, height = 768L, sample_steps = 20L),
sd_node("decode"),
sd_node("save", path = "cat.png")
)
sd_run_pipeline(pipe, ctx)
## End(Not run)
Scale noise into the starting latent (low-level)
Description
Applies the denoiser's noise scaling for the first sigma, producing the
starting x for the sampling loop. For txt2img pass init_latent
= NULL.
Usage
sd_noise_scale(ctx, noise, sigma0, init_latent = NULL)
Arguments
ctx |
SD context |
noise |
Noise sd_tensor (defines geometry) |
sigma0 |
First sigma of the schedule |
init_latent |
Optional starting latent (img2img); |
Value
An sd_tensor — the scaled starting latent.
Create a pipeline from nodes
Description
Nodes run in the given order. Each input of a node is either linked
explicitly to an earlier node (sd_node("decode", latent = "s1"))
or, if not given, taken from the nearest earlier node that produces it.
Usage
sd_pipeline(...)
Arguments
... |
|
Details
Nodes without an id get one automatically
("<type>_<position>"). Ids must be unique.
Value
A list with class "sd_pipeline".
Cancel a running pipeline
Description
Call from an on_event handler of sd_run_pipeline to
stop the run. Signals an error of class "sd_pipeline_cancel", so a
cancel can be told apart from a failure:
tryCatch(..., sd_pipeline_cancel = function(c) ...).
Usage
sd_pipeline_cancel(message = "pipeline cancelled")
Arguments
message |
Reason shown in the error. |
Value
Does not return.
Enable live generation previews
Description
Installs the preview callback so that, during the next generation, the most
recent intermediate frame is written to path (a single PPM file,
updated atomically). Poll it with sd_read_preview. Call
sd_preview_stop when done.
Usage
sd_preview_start(path, mode = PREVIEW$PROJ, interval = 1L, denoised = TRUE)
Arguments
path |
File path for the preview PPM (e.g. a tempfile). |
mode |
Decode mode, one of |
interval |
Emit a preview every N sampling steps (default 1). |
denoised |
If |
Details
Most users pass preview = TRUE to sd_generate instead,
which wires this up automatically.
Value
Invisibly, path.
See Also
sd_read_preview, sd_preview_stop
Disable live generation previews
Description
Removes the preview callback and cleans up the temporary .tmp file.
Usage
sd_preview_stop()
Value
Invisibly NULL.
See Also
Get raw profile events
Description
Returns a data frame of captured events with columns stage,
kind ("start"/"end"), and timestamp_ms.
Usage
sd_profile_get()
Value
Data frame of profile events.
Start profiling
Description
Clears the event buffer and begins capturing stage timings from sd.cpp.
Usage
sd_profile_start()
Value
No return value, called for side effects.
Stop profiling
Description
Stops capturing stage events. Call sd_profile_get to retrieve.
Usage
sd_profile_stop()
Value
No return value, called for side effects.
Build a profile summary from raw events
Description
Matches start/end events by stage and computes durations.
Usage
sd_profile_summary(events)
Arguments
events |
Data frame from |
Value
Data frame with columns stage, start_ms,
end_ms, duration_ms, duration_s.
Has class "sd_profile" for pretty printing.
Read the current preview frame
Description
Reads the latest preview PPM written by the running generation and returns
it as an sd_image list. Returns NULL if no preview exists yet (e.g.
generation has not produced a frame). Optionally writes a PNG copy.
Usage
sd_read_preview(path, png_path = NULL)
Arguments
path |
The preview PPM path passed to |
png_path |
Optional path; if set, the frame is also written there as
PNG via |
Value
An sd_image list (width, height, channel,
data), or NULL if unavailable.
See Also
Register a model in the sd2R model registry
Description
Adds or updates a model entry in the sd2R model registry file. The
registry lives in tools::R_user_dir("sd2R", "config") by default
and can be overridden via the SD2R_REGISTRY_DIR environment
variable. The directory is created only when a model is actually
registered. Paths and defaults are stored for later use by
sd_load_model.
Usage
sd_register_model(id, model_type, paths, defaults = list(), overwrite = FALSE)
Arguments
id |
Unique model identifier (e.g. "flux-dev", "sd15-base") |
model_type |
Model architecture: "sd1", "sd2", "sdxl", "flux", "flux2", "flux3", "sd3" |
paths |
Named list of file paths. Recognized names:
|
defaults |
Named list of generation defaults (optional). Recognized:
|
overwrite |
If FALSE (default), error when id already exists |
Value
Invisible model id
Examples
## Not run:
sd_register_model(
id = "flux-dev",
model_type = "flux",
paths = list(
diffusion = "models/flux1-dev-Q4_K_S.gguf",
vae = "models/ae.safetensors",
clip_l = "models/clip_l.safetensors",
t5xxl = "models/t5xxl_fp16.safetensors"
),
defaults = list(steps = 25, cfg_scale = 3.5, width = 1024, height = 1024)
)
## End(Not run)
Remove the background from an image
Description
Runs RMBG-1.4: the image is resized to 1024x1024, normalized
(x / 255 - 0.5), and the predicted foreground mask is min-max
normalized and resized back to the original size.
Usage
sd_remove_background(
image,
model,
output = c("rgba", "mask"),
threshold = NULL
)
Arguments
image |
An SD image (list with |
model |
An |
output |
|
threshold |
Optional number in (0, 1): binarize the mask at this value instead of keeping soft edges. |
Value
An SD image: 4 channels for "rgba", 1 for "mask".
Save with sd_save_image.
Examples
## Not run:
rmbg <- sd_rmbg_load("models/RMBG-1.4.onnx")
cut <- sd_remove_background("cat.png", rmbg)
sd_save_image(cut, "cat_rgba.png")
## End(Not run)
Remove a model from the registry
Description
Removes the model entry from the sd2R model registry and unloads it from memory if loaded.
Usage
sd_remove_model(id)
Arguments
id |
Model identifier |
Value
No return value, called for side effects.
Load an RMBG background-removal model
Description
Loads an RMBG-1.4 ONNX model (model.onnx from the
briaai/RMBG-1.4 repository; download it yourself) with
ggmlR::onnx_load().
Usage
sd_rmbg_load(path, device = NULL, dtype = "f32")
Arguments
path |
Path to the |
device |
|
dtype |
Weight precision, |
Value
An object of class "sd_rmbg", for
sd_remove_background.
See Also
Run a pipeline several times with varying parameters or inputs
Description
Runs pipeline once per combination of the values in vary.
Nodes that do not change between runs are taken from cache. Every
variant is built and validated before the first run, so a typo fails at
once, not on run 5 of 20.
Usage
sd_run_batch(
pipeline,
ctx,
vary,
mode = c("zip", "grid"),
inputs = NULL,
outputs = NULL,
cache = sd_cache(),
on_error = c("stop", "continue"),
max_runs = 100L,
upscaler_ctx = NULL,
on_event = NULL,
verbose = FALSE
)
Arguments
pipeline |
An |
ctx |
Model context (see |
vary |
Named list of variations (see Details). |
mode |
|
inputs |
Fixed run-time inputs (named by input node id), used in every run unless varied. |
outputs, upscaler_ctx, verbose |
As in |
cache |
An |
on_error |
|
max_runs |
Upper limit on the number of runs (default 100), a guard against huge grids. |
on_event |
Event handler as in |
Details
vary is a list named by node id. For a parameter node, an element
is a named list of parameters, each a vector (or list) of values:
list(lat = list(seed = 1:4, cfg_scale = c(5, 7, 7, 9))). A varied
parameter must already be set on the node (its value there is the type
reference and guards against typos). For a run-time input node
(input_image, input_mask, input_latent) the element is
a list of values: list(src = list(img1, img2)).
Seeds change only if varied explicitly. Side-effect nodes (save,
save_mask) would overwrite their file on every run: give their path
a {i} placeholder (replaced by the run number) or vary it.
Value
An object of class "sd_batch": results (one
sd_run_pipeline result per run, or the error condition),
values (data frame, one row per run, the varied values; input
variations by index), failed (logical per run).
Examples
## Not run:
b <- sd_run_batch(pipe, ctx,
vary = list(lat = list(seed = 1:3, cfg_scale = c(4, 7)),
save_4 = list(path = "out_{i}.png")),
mode = "grid")
b$values
## End(Not run)
Run a pipeline
Description
Executes nodes in order. Data passes between nodes through typed outputs
(cond, uncond, latent, image): each node type
declares the inputs it reads and the outputs it writes. An input is
linked to an earlier node by id ("id", or "id$output" to
pick a specific output); without a link it reads the nearest earlier node
that produces it. With "id" alone, the output with the same name
as the input is used, or else the only output of a matching type
(cond and uncond are the same type).
Usage
sd_run_pipeline(
pipeline,
ctx,
upscaler_ctx = NULL,
outputs = NULL,
cache = NULL,
on_event = NULL,
verbose = FALSE,
inputs = NULL
)
Arguments
pipeline |
An |
ctx |
A Stable Diffusion context created by |
upscaler_ctx |
Optional upscaler context created by
|
outputs |
Which results to return. |
cache |
Optional |
on_event |
Optional function called with one argument, an event
list, as the run progresses (see Events). It only observes: its return
value is ignored. An error in it stops the run, naming the handler's
node and event; call |
verbose |
Logical. Print progress messages (via |
inputs |
Values for the run-time input nodes ( |
Details
The pipeline is validated before any node runs: every input must resolve
to an earlier node with a matching output, required parameters must be
set (txt2img and img2img need their own prompt; it is
not inherited from earlier nodes; save needs path), and
upscale needs upscaler_ctx. All problems are reported in one
error.
Only the nodes needed for the requested outputs run, plus save
nodes (side effects) and everything they depend on; other nodes are
skipped. Intermediate results are released as soon as their last
consumer has run, unless requested in outputs.
Value
With outputs = NULL, the last output of the last node (for
the current node types, an sd_image list). Otherwise a list named by
node id: for a node with one output, the value itself; for several
(encode_text), a list of them (res$txt$cond).
Events
Events, in order: "skipped" for every node removed by culling
(before anything runs), then per node to run either "cached"
(result taken from cache), or "start" followed by
"end" or "error" (the error is then re-raised). Fields:
- schema
Event format version, currently
1L. New fields may be added within a version; existing ones are not renamed.- event
One of the event names above.
- id, type, index
Node id, type and position in the pipeline.
- step, total
Position among the nodes that run (
NAfor"skipped") and their number.- elapsed
Seconds the node took (
"end","error";0for"cached";NAotherwise), measured withproc.time()(wall clock, not guaranteed monotonic).- outputs
For
"end"and"cached": per output, its metadata only (class, size:width/height/channelorne,bytes), never the value; get values withoutputs.- error
For
"error": the error message.
Run the sampling loop (low-level)
Description
Runs the full denoising loop given pre-computed conditioning and an explicit
noise tensor. Noise is supplied by the caller for determinism; use
seed to generate it reproducibly, or pass noise directly.
Usage
sd_sample(
ctx,
cond,
uncond = list(crossattn = NULL, vector = NULL, concat = NULL),
latent_shape = NULL,
init_latent = NULL,
noise = NULL,
strength = 1,
sample_method = SAMPLE_METHOD$EULER,
scheduler = SCHEDULER$DISCRETE,
sample_steps = 20L,
cfg_scale = 7,
eta = 0,
seed = 42L,
custom_sigmas = NULL,
mask = NULL,
control_image = NULL,
control_strength = 0.9,
batch = 1L
)
Arguments
ctx |
SD context |
cond |
Positive conditioning from |
uncond |
Negative conditioning from |
latent_shape |
Integer vector |
init_latent |
Optional starting latent for img2img (from
|
noise |
Optional explicit noise sd_tensor. When |
strength |
img2img denoising strength (ignored for txt2img) |
sample_method |
Sampling method (name or |
scheduler |
Scheduler (name or |
sample_steps |
Number of steps |
cfg_scale |
CFG scale |
eta |
Eta for DDIM-like samplers |
seed |
Seed for noise generation when |
custom_sigmas |
Optional explicit sigma schedule (overrides scheduler) |
mask |
Optional inpainting mask (needs |
control_image |
Optional ControlNet hint image (SD image or PNG
path) of the generation size in pixels; needs a context created with
|
control_strength |
ControlNet strength in |
batch |
Number of latents N sampled together (default 1). Element k
gets noise from |
Value
An sd_tensor list — the denoised latent x_0. Pass to
sd_decode_latent.
See Also
sd_encode_text, sd_decode_latent
Run the sampling loop step-by-step in R (low-level)
Description
Equivalent to sd_sample for the Euler / Euler-a samplers, but
runs the loop in R so a callback can observe or interrupt each step (e.g.
live preview). For Euler (no ancestral noise) the result is bit-for-bit equal
to sd_sample (the update runs in float via sd_euler_step);
Euler-a differs (R RNG vs ggml RNG for the ancestral
term). Other samplers are not supported here — use sd_sample.
Usage
sd_sample_stepwise(
ctx,
cond,
uncond = list(crossattn = NULL, vector = NULL, concat = NULL),
latent_shape = NULL,
init_latent = NULL,
noise = NULL,
width = 512L,
height = 512L,
sample_method = SAMPLE_METHOD$EULER,
scheduler = SCHEDULER$DISCRETE,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
custom_sigmas = NULL,
on_step = NULL
)
Arguments
ctx |
SD context |
cond |
Positive conditioning from |
uncond |
Negative conditioning; empty (all |
latent_shape |
Integer |
init_latent |
Optional starting latent (img2img); |
noise |
Optional explicit noise sd_tensor; generated from |
width, height |
Generation size in PIXELS (for the sigma schedule) |
sample_method |
|
scheduler |
Scheduler (name or |
sample_steps |
Number of steps |
cfg_scale |
CFG scale |
seed |
Seed for noise generation when |
custom_sigmas |
Optional explicit sigma schedule (overrides scheduler) |
on_step |
Optional callback |
Value
An sd_tensor — the denoised latent x_0.
See Also
Open / close a step-wise sampling window (low-level)
Description
Between begin and end the diffusion model keeps its GPU compute buffer alive
across sd_denoise_step calls, avoiding a large realloc per
step. Must be paired; sd_sampler_end frees the buffer. Not reentrant.
sd_sample_stepwise manages this for you.
Usage
sd_sampler_begin(ctx)
sd_sampler_end(ctx)
Arguments
ctx |
SD context |
Value
Invisibly NULL.
Sigma schedule for a sampler (low-level)
Description
Returns the sigma schedule that sd_sample_stepwise iterates
over, for a given scheduler / step count / generation size.
Usage
sd_sampler_sigmas(
ctx,
scheduler = SCHEDULER$DISCRETE,
sample_steps = 20L,
width = 512L,
height = 512L,
sample_method = SAMPLE_METHOD$EULER
)
Arguments
ctx |
SD context from |
scheduler |
Scheduler (name or |
sample_steps |
Number of steps |
width, height |
Generation size in PIXELS (same as passed to generation) |
sample_method |
Sampling method (name or |
Value
Numeric vector of length sample_steps + 1; the last value is 0.
See Also
sd_denoise_step, sd_sample_stepwise
Save SD image to PNG file
Description
Save SD image to PNG file
Usage
sd_save_image(image, path)
Arguments
image |
SD image (list with width, height, channel, data) as returned
by |
path |
Output file path (should end in .png) |
Value
The file path (invisibly).
Save pipeline to JSON
Description
Save pipeline to JSON
Usage
sd_save_pipeline(pipeline, path)
Arguments
pipeline |
An |
path |
File path (should end in |
Value
The file path, invisibly.
Scan a directory for models and register them
Description
Scans for .safetensors and .gguf files, guesses component
roles and model types from filenames, groups multi-file models (Flux),
and registers them.
Usage
sd_scan_models(dir, overwrite = FALSE, recursive = FALSE)
Arguments
dir |
Directory to scan |
overwrite |
If TRUE, overwrite existing entries (default FALSE) |
recursive |
Scan subdirectories (default FALSE) |
Details
Single-file models (SD 1.5, SDXL) are registered individually. Multi-file Flux models are grouped when diffusion + supporting files (VAE, CLIP, T5) are found in the same directory.
Value
Character vector of registered model ids (invisible)
Examples
## Not run:
sd_scan_models("/mnt/models/")
sd_list_models()
## End(Not run)
Does the loaded model support reference images?
Description
Reports whether the model in ctx consumes reference images (edit /
control / DiT families: Flux, Flux.2, SD3, Qwen-Image, Z-Image). Passing
refs to other models aborts inside ggml, so sd_generate_multiref
uses this to fail cleanly first.
Usage
sd_supports_ref_images(ctx)
Arguments
ctx |
SD context from |
Value
Logical scalar.
Get system information
Description
Returns information about the stable-diffusion.cpp backend.
Usage
sd_system_info()
Value
List with system info, version, and core count
Generate images from text prompt
Description
Generate images from text prompt
Usage
sd_txt2img(
ctx,
prompt,
negative_prompt = "",
width = 512L,
height = 512L,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
batch_count = 1L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
eta = 0,
flow_shift = NULL,
control_image = NULL,
control_strength = 0.9,
vae_mode = "auto",
vae_auto_threshold = 1048576L,
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
vae_tile_rel_x = NULL,
vae_tile_rel_y = NULL,
vae_tiling = NULL,
cache_mode = c("off", "easy", "ucache"),
cache_config = NULL,
loras = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt describing desired image |
negative_prompt |
Negative prompt (default "") |
width |
Image width in pixels (default 512) |
height |
Image height in pixels (default 512) |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Random seed (-1 for random) |
batch_count |
Number of images to generate (default 1) |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
eta |
Eta parameter for DDIM-like samplers |
flow_shift |
Flow shift for flow-matching models (Flux, SD3). |
control_image |
Optional control image for ControlNet (sd_image format) |
control_strength |
ControlNet strength (default 0.9) |
vae_mode |
VAE processing mode: |
vae_auto_threshold |
Pixel area fallback threshold for
|
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512);
converted internally to latent cells with the model's VAE scale factor
(8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent
cells (default 64); values below 128 give a warning.
Ignored when |
vae_tile_overlap |
Overlap ratio between tiles, 0.0-0.5 (default 0.25) |
vae_tile_rel_x |
Relative tile width as fraction of latent width (0-1)
or number of tiles (>1). NULL = use |
vae_tile_rel_y |
Relative tile height as fraction of latent height (0-1)
or number of tiles (>1). NULL = use |
vae_tiling |
Deprecated. Use |
cache_mode |
Step caching mode: |
cache_config |
Optional fine-tuned cache config from
|
loras |
LoRA weights: named numeric vector |
Value
List of SD images. Each image is a list with
width, height, channel, and data (raw vector of RGB pixels).
Use sd_save_image to save or sd_image_to_array to convert.
High-resolution image generation via patch-based pipeline
Description
Generates a large image by independently rendering overlapping patches at
the model's native resolution, then stitching them with linear blending.
An optional img2img harmonization pass can smooth seams further.
Usage
sd_txt2img_highres(
ctx,
prompt,
negative_prompt = "",
width = 2048L,
height = 2048L,
tile_size = NULL,
overlap = 0.125,
img2img_strength = NULL,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
eta = 0,
vae_mode = "auto",
vae_auto_threshold = 1048576L,
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
loras = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt |
negative_prompt |
Negative prompt (default "") |
width |
Target image width in pixels |
height |
Target image height in pixels |
tile_size |
Patch size in pixels. |
overlap |
Overlap between patches as fraction of |
img2img_strength |
If not |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Base random seed. Each patch gets |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
eta |
Eta parameter for DDIM-like samplers |
vae_mode |
VAE tiling mode for the harmonization pass
(default |
vae_auto_threshold |
Pixel area fallback threshold for auto VAE tiling when VRAM query is unavailable |
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512); converted internally to latent cells with the model's VAE scale factor (8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent cells (default 64); values below 128 give a warning. |
vae_tile_overlap |
Overlap for VAE tiling (default 0.25) |
loras |
LoRA weights: named numeric vector |
Value
SD image (list with width, height, channel, data)
Examples
## Not run:
ctx <- sd_ctx("sd15.safetensors", model_type = "sd1")
img <- sd_txt2img_highres(ctx, "a panoramic mountain landscape",
width = 2048, height = 1024)
sd_save_image(img, "panorama.png")
## End(Not run)
Tiled diffusion sampling (MultiDiffusion)
Description
Generates images at any resolution using tiled sampling: at each denoising step the latent is split into overlapping tiles, each tile is denoised independently by the UNet, and results are merged with Gaussian weighting. VRAM usage is bounded by tile size, not output resolution.
Usage
sd_txt2img_tiled(
ctx,
prompt,
negative_prompt = "",
width = 2048L,
height = 2048L,
sample_tile_size = NULL,
sample_tile_overlap = 0.25,
sample_method = SAMPLE_METHOD$EULER,
sample_steps = 20L,
cfg_scale = 7,
seed = 42L,
batch_count = 1L,
scheduler = SCHEDULER$DISCRETE,
clip_skip = -1L,
eta = 0,
flow_shift = NULL,
vae_mode = "auto",
vae_auto_threshold = 1048576L,
vae_tile_size = 512L,
vae_tile_overlap = 0.25,
vae_tile_rel_x = NULL,
vae_tile_rel_y = NULL,
cache_mode = c("off", "easy", "ucache"),
cache_config = NULL,
loras = NULL
)
Arguments
ctx |
SD context created by |
prompt |
Text prompt describing desired image |
negative_prompt |
Negative prompt (default "") |
width |
Target image width in pixels (can exceed model native resolution) |
height |
Target image height in pixels |
sample_tile_size |
Tile size in latent pixels (default |
sample_tile_overlap |
Overlap between tiles as fraction of tile size, 0.0-0.5 (default 0.25). |
sample_method |
Sampling method (see |
sample_steps |
Number of sampling steps (default 20) |
cfg_scale |
Classifier-free guidance scale (default 7.0) |
seed |
Random seed (-1 for random) |
batch_count |
Number of images to generate (default 1) |
scheduler |
Scheduler type (see |
clip_skip |
Number of CLIP layers to skip (-1 = auto) |
eta |
Eta parameter for DDIM-like samplers |
flow_shift |
Flow shift for flow-matching models (Flux, SD3). |
vae_mode |
VAE processing mode: |
vae_auto_threshold |
Pixel area fallback threshold for
|
vae_tile_size |
Tile size in image pixels for tiled VAE (default 512);
converted internally to latent cells with the model's VAE scale factor
(8 for SD/FLUX.1, 16 for FLUX.2/FLUX.3). Before sd2R 0.2.2 it was in latent
cells (default 64); values below 128 give a warning.
Ignored when |
vae_tile_overlap |
Overlap ratio between tiles, 0.0-0.5 (default 0.25) |
vae_tile_rel_x |
Relative tile width as fraction of latent width (0-1)
or number of tiles (>1). NULL = use |
vae_tile_rel_y |
Relative tile height as fraction of latent height (0-1)
or number of tiles (>1). NULL = use |
cache_mode |
Step caching mode: |
cache_config |
Optional fine-tuned cache config from
|
loras |
LoRA weights: named numeric vector |
Details
Requires tiled VAE (enabled automatically via vae_mode = "auto").
Value
List of SD images
Examples
## Not run:
ctx <- sd_ctx("sd15.safetensors", model_type = "sd1")
imgs <- sd_txt2img_tiled(ctx, "a vast mountain landscape",
width = 2048, height = 1024)
sd_save_image(imgs[[1]], "landscape.png")
## End(Not run)
Split a batch into its elements
Description
Splits a batch image (field batch = N, e.g. from
sd_decode_latent of a batch latent) or a batch latent
(ne[4] = N, from sd_sample(batch = N)) into a list of N
single elements. A single element gives a list of length 1.
Usage
sd_unbatch(x)
Arguments
x |
An SD image or an sd_tensor latent. |
Value
A list of SD images or latents.
Unload all models from memory
Description
Removes all cached contexts. Registry is preserved.
Usage
sd_unload_all()
Value
No return value, called for side effects.
Unload a model from memory
Description
Removes the cached context for the given model id. The model remains
in the registry and can be reloaded with sd_load_model.
Usage
sd_unload_model(id)
Arguments
id |
Model identifier |
Value
No return value, called for side effects.
Upscale an image using ESRGAN
Description
Upscale an image using ESRGAN
Usage
sd_upscale_image(esrgan_path, image, upscale_factor = 4L, n_threads = 0L)
Arguments
esrgan_path |
Path to ESRGAN model file |
image |
SD image to upscale (list with width, height, channel, data) |
upscale_factor |
Upscale factor (default 4) |
n_threads |
Number of CPU threads (0 = auto-detect) |
Value
Upscaled SD image
Get number of Vulkan GPU devices
Description
Returns the number of Vulkan-capable GPU devices available on the system.
Useful for deciding whether to use sd_generate_multi_gpu.
Usage
sd_vulkan_device_count()
Value
Integer, number of Vulkan devices (0 if Vulkan is not available)