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
4 changes: 3 additions & 1 deletion docs/development/c_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ copying tensor payloads. DGL outputs are adapted at the result boundary.
Internal producers with an `sd::Tensor<T>` can
move it directly into a handle. Video results keep per-frame tensors and assemble
a contiguous video tensor only when requested. Cached assembly is synchronized.
Preview tensors are independent snapshots and may be retained by callbacks.
Generation shares the DGL context's progress registration and keeps one progress
dispatcher across the DGL programs in a batch. Preview tensors in a sampling
event are independent snapshots and may be retained by the callback.
Results retain the exact compiled DGL source. WebUI conversion and media metadata
embedding are separate from inference and never rebuild the execution program.
`src/api/generation_metadata.cpp` parses the source once to produce image
Expand Down
6 changes: 4 additions & 2 deletions docs/development/dgl.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ The first two statements describe which model and conditions to evaluate and how
to combine the predictions. They keep the model reachable. The sampling
operation drives the solver and evaluates that predictor at each required
step. The resource plan therefore accounts for diffusion weights during
`sample`. Each sampling call owns its own prediction history and progress state.
`sample`. Each sampling call owns its prediction history and reports sampling
events through the run's shared progress dispatcher.

## What the context retains

Expand All @@ -71,6 +72,7 @@ context can release it after its last use. Releasing a script binding and
evicting cached weights are therefore separate lifetime decisions.

One context runs one program at a time. Each run gets a fresh placement plan
and its own progress, preview and cancellation state. Two runs of the same
and its own progress and cancellation state. The active sampling pass sends
its selected previews with the completed step event. Two runs of the same
source can choose different weight placement as cached resources or available
memory change. See [context execution settings](../dgl.md#context-execution-settings).
38 changes: 20 additions & 18 deletions docs/dgl.md
Original file line number Diff line number Diff line change
Expand Up @@ -1004,14 +1004,14 @@ observer = preview(decoder = tae)
latent = sample(start, sigmas, predict = guided, rng = rng, observer = observer)
```

`preview()` needs no decoder for latent projection. The context's preview
callback selects the mode, interval and noisy or denoised previews. A sampling
`preview()` needs no decoder for latent projection. The context's progress
options select the mode, interval and noisy or denoised previews. A sampling
call without an observer uses a shared projection preview observer. Without a
decoder, preview falls back to projection. An explicit observer is only needed
to supply a decoder or custom preview settings. An observer can be reused
across sampling calls; each call has its own observation state. The observer
retains its decoder, and decoding resources are acquired only for a selected
preview and released afterwards. Without an enabled preview callback, it
preview and released afterwards. With previews disabled, it
performs no preview decoding.

### Media dimensions
Expand Down Expand Up @@ -1826,8 +1826,10 @@ the capacity changes.

### File access and memory budgets

Install a file access callback with `sd_dgl_ctx_set_file_access_callback` before
running scripts in a context. The callback receives a UTF-8 path and an access
Install a file access callback with `sd_dgl_ctx_set_file_access_callback` on an
idle context. The setter returns `sd_status_t`. A DGL context borrowed from
`sd_ctx_get_dgl_ctx()` shares its file access policy with generation and model
probing. The callback receives a UTF-8 path and an access
type for input reads, model reads or writes. Returning false ends the run with a
file access error. Keep its user data valid throughout the run. Model reads
include checkpoints, referenced shards and external tokenizers. Without a
Expand Down Expand Up @@ -1898,7 +1900,7 @@ Each run prepares one weight-placement plan for the graph, including models
already cached in the context. Compilation tracks actual model use separately
from metadata queries and model captures. For example, `latent_shape` does not
need VAE weights, while a VAE preview observer keeps the decoder in the sampling
working set when VAE/TAE preview callbacks are enabled. Unrelated scalar
working set when the progress options enable VAE/TAE previews. Unrelated scalar
operations do not change the model-use phases.
If a loader omits `backend`, the run compares available GPU budgets before
Expand All @@ -1925,24 +1927,24 @@ allocation checks.
### Progress, preview and cancellation
Register callbacks on an idle context with `sd_dgl_ctx_set_progress_callback`
and `sd_dgl_ctx_set_preview_callback`. They run synchronously on the executing
thread and receive events for that context's current run. A null callback
clears the registration. The sampling pass counter starts at one on each
run. Progress can report model loading in tensors, sampling in steps, video
upscaling in frames, or a stage with no known total.
Without a progress callback, the DGL execution layer displays sampling and
weight-loading progress bars. Set `sd_dgl_ctx_set(ctx, "console_progress", "on")`
on an idle context to display those bars alongside a progress callback.
Register a callback on an idle context with `sd_dgl_ctx_set_progress_callback`.
It uses the same event and options as the [generation C API](guides/c_api.md#progress-and-previews).
It runs synchronously on the executing thread. A null callback clears the
registration. Progress can report model loading in tensors, sampling in steps,
tiling in tiles, video upscaling in frames, or a stage with no known total.
Without a callback, DGL displays its built-in progress bars.
Set `sd_progress_options_t.console_progress` to display the bars alongside a callback.
The default observer handles previews. Preview mode `proj` uses latent projection. Modes `tae` and `vae`
use the decoder supplied to `preview(decoder=...)`, falling back to projection. A positive interval
previews each matching completed logical step. Intermediate model evaluations,
such as Heun's first evaluation, do not produce duplicate previews or progress
events. Zero previews the final step of the first sampling pass.
A negative interval selects the step at its absolute value. The callback
receives the pass number, total steps and borrowed frame tensors. Use
`sd_tensor_retain` if a frame must outlive the callback.
A negative interval selects the step at its absolute value. Each completed
step emits one sampling event. Its `sd_sampling_progress_t` payload contains
the pass number and any selected denoised and noisy frame tensors. Passes
start at one on each run. Use `sd_tensor_retain` if a frame must outlive
the callback.
`sd_dgl_ctx_cancel` can be called from a callback or another thread. An
idle context accepts the call without queuing a cancellation. The current
Expand Down
2 changes: 1 addition & 1 deletion docs/dgl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,4 @@ and [NumPy tensor files](../dgl.md#tensor-files).
| [PuLID-Flux](../models/pulid.md) | [Identity-guided generation](pulid/pulid-flux1-schnell.dgl) |
| [RelayVSR](../models/relay_vsr.md) | [Upscale a video](relay_vsr/relayvsr-x2-video-upscale.dgl) · [Upscale an image](relay_vsr/relayvsr-x2-image-upscale.dgl) |
| [SeedVR2](../models/seedvr2.md) | [Upscale an image](seedvr2/seedvr2-3b-image-upscale.dgl) · [Upscale a video](seedvr2/seedvr2-3b-video-upscale.dgl) |
| [TAESD](../models/taesd.md) | [SD 1.5 decoding with TAESD](taesd/sd1-5-taesd-preview.dgl). The CLI writes the final PNG. Intermediate previews require a [host preview callback](../dgl.md#progress-preview-and-cancellation) in `tae` mode. |
| [TAESD](../models/taesd.md) | [SD 1.5 decoding with TAESD](taesd/sd1-5-taesd-preview.dgl). The CLI writes the final PNG. For intermediate previews, pass `--preview on` or register a [progress callback](../dgl.md#progress-preview-and-cancellation) with preview mode `tae`. |
69 changes: 57 additions & 12 deletions docs/guides/c_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,14 @@ preserves the current configuration. Model setters return `SD_STATUS_BUSY`
while model probing is in progress, including from file-access callbacks.
The execution settings and component cache continue to serve generation and the
DGL context borrowed through `sd_ctx_get_dgl_ctx()`. The borrowed pointer stays
valid until `sd_ctx_free()`. Run scripts and generation calls one at a time. Set
file-access callbacks for generated programs and scripts through
`sd_ctx_set_file_access_callback()` and `sd_dgl_ctx_set_file_access_callback()`
respectively.
valid until `sd_ctx_free()`. Run scripts and generation calls one at a time.
Register a file access callback once with `sd_ctx_set_file_access_callback()`
or `sd_dgl_ctx_set_file_access_callback()` on the borrowed context. Both setters
return `sd_status_t` and update the same policy for generation, model probing
and DGL scripts. Passing a null callback clears the registration. Both setters
return `SD_STATUS_BUSY` during generation, DGL execution or model probing.
Use a separately created DGL context when a script needs an independent policy.
Use `sd_dgl_ctx_unload_models()` to release cached model components and reload
them on demand. It clears idle buffer caches on supported backends and returns
Expand Down Expand Up @@ -175,18 +179,46 @@ The bundled CLI and server retain these modes as strings and pass them directly
to setters. Enum parsers, enum name helpers, parameter configuration layouts and
name tables are internal and are not exported by the shared library.

Preview registration also uses strings:
## Progress and previews

Register a progress callback on an idle context. Both context types use the
same event and options. A DGL context borrowed from `sd_ctx_get_dgl_ctx()`
shares the registration with its owning context.

```c
sd_status_t status = sd_set_preview_callback(callback, "proj", 5,
true, false, user_data);
/* Disable registration when the context is idle. */
sd_set_preview_callback(NULL, "none", 1, false, false, NULL);
const sd_progress_options_t options = {
.console_progress = true,
.preview = { .mode = "proj", .interval = 5, .denoised = true },
};
sd_status_t status = sd_ctx_set_progress_callback(ctx, callback, user_data, &options);
/* For a DGL context, call sd_dgl_ctx_set_progress_callback with the same options. */
/* Clear registration when idle. */
sd_ctx_set_progress_callback(ctx, NULL, NULL, NULL);
```
Preview modes are `none`, `proj`, `tae` and `vae`. A null or unknown mode returns
`SD_STATUS_INVALID_ARGUMENT` and preserves the previous registration. See the
public header for interval, noisy/denoised and callback lifetime semantics.
With a callback registered, set `console_progress` to keep the library's
progress bars visible. A null options pointer subscribes to progress with
previews and console output disabled. Passing a null callback clears the
registration, ignores the options, and restores console progress.
The event's `stage` is a string. On `sampling`, cast `stage_data` to
`const sd_sampling_progress_t*` for the sampling pass, step time and optional
frames. On counted `loading` events, it points to `sd_loading_progress_t` with
bytes processed and elapsed seconds. Other stages can be displayed using the
common fields. A `total` of zero means the total is unknown.
Sampling emits one event at the start of each pass and one per completed
logical step. A step can carry both denoised and noisy frames. A positive
preview interval selects every Nth step, a negative interval selects one
step by its absolute value, and zero selects the last step of the first
pass. Pass numbers start at one for each request and continue across the
images of a batch. Preview modes are `none`, `proj`, `tae` and `vae`. A null
preview mode disables previews. An unknown mode preserves the previous
registration and returns `SD_STATUS_INVALID_ARGUMENT`.
Events run synchronously on the executing thread. Callbacks must not throw.
Data is borrowed for the duration of the callback. Use `sd_tensor_retain()`
to keep an individual frame.
## Tensor data
Expand Down Expand Up @@ -523,6 +555,19 @@ their initialization/formatting helpers, `new_sd_ctx()`, `free_sd_ctx()`,
have been removed. Applications and bindings must migrate and rebuild; no
compatibility layer is provided.

`sd_dgl_ctx_set_file_access_callback()` now returns `sd_status_t`. Success is
`SD_STATUS_OK` (`0`). Replace boolean checks with an explicit status check.

```c
if (sd_dgl_ctx_set_file_access_callback(ctx, callback, userdata) != SD_STATUS_OK) {
/* Handle registration failure. */
}
```

Register or clear the policy through either handle when the DGL context is
borrowed from `sd_ctx_get_dgl_ctx()`. To keep separate policies, create a
standalone DGL context for scripts.

Create context/image/video options with the corresponding constructor, populate
them through the shared typed setters, and use `sd_ctx_create()`,
`sd_generate_image()` and `sd_generate_video()`. Read or retain outputs through
Expand Down
5 changes: 3 additions & 2 deletions docs/models/taesd.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,9 @@ tiny autoencoder matching that model. See [Web UI guide](../../examples/server/R

The [SD 1.5 example](../dgl/taesd/sd1-5-taesd-preview.dgl) uses TAESD to
decode the final image and passes the same decoder to `preview(decoder = vae)`.
Running it with `sd-cli -M dgl` writes the final PNG. To receive intermediate
images, run it in a host that registers a DGL preview callback in `"tae"` mode.
Running it with `sd-cli -M dgl` writes the final PNG. Add `--preview on` for
intermediate images. Applications can receive them by registering a DGL
progress callback with preview mode `"tae"`.
See [progress and previews](../dgl.md#progress-preview-and-cancellation).

#### Run a script
Expand Down
8 changes: 3 additions & 5 deletions examples/cli/dgl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ class DownloadDisplay {
}
};

int DGLModeParams::run(const SDContextParams& options, bool embed_metadata, const DGLPreviewOptions& preview) const {
int DGLModeParams::run(const SDContextParams& options, bool embed_metadata, sd_generation_progress_cb_t callback, void* userdata, const sd_progress_options_t& progress) const {
try {
if (script_path.empty()) {
const auto* catalog = sd_dgl_builtin_catalog();
Expand Down Expand Up @@ -295,10 +295,8 @@ int DGLModeParams::run(const SDContextParams& options, bool embed_metadata, cons
check_dgl(raw_context != nullptr);
std::unique_ptr<sd_dgl_ctx_t, decltype(&sd_dgl_ctx_free)> context(raw_context, sd_dgl_ctx_free);
check_dgl(options.configure_dgl(context.get()));
if (preview.callback) {
// Decoder-based mode so the script's preview(decoder = ...) argument, not the host,
// selects between projection and decoding; tae and vae behave identically with a decoder.
check_dgl(sd_dgl_ctx_set_preview_callback(context.get(), preview.callback, "tae", preview.interval, preview.denoised, preview.noisy, preview.data) == SD_STATUS_OK);
if (callback) {
check_dgl(sd_dgl_ctx_set_progress_callback(context.get(), callback, userdata, &progress) == SD_STATUS_OK);
}
check_dgl(sd_dgl_ctx_set(context.get(), "embed_metadata", embed_metadata ? "on" : "off"));
if (!max_ram.empty())
Expand Down
10 changes: 1 addition & 9 deletions examples/cli/dgl.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,6 @@ using DGLScriptArgs = std::map<std::string, std::string, std::less<>>;

void apply_dgl_args(std::string& source, const DGLScriptArgs& args);

struct DGLPreviewOptions {
sd_dgl_preview_cb_t callback = nullptr;
int interval = 0;
bool denoised = false;
bool noisy = false;
void* data = nullptr;
};

struct DGLModeParams {
std::string script_path;
std::string write_builtins_path;
Expand All @@ -41,7 +33,7 @@ struct DGLModeParams {
ArgOptions get_options();
bool has_options() const;
bool validate() const;
int run(const SDContextParams& options, bool embed_metadata, const DGLPreviewOptions& preview) const;
int run(const SDContextParams& options, bool embed_metadata, sd_generation_progress_cb_t callback, void* userdata, const sd_progress_options_t& progress) const;
};

#endif // __EXAMPLES_CLI_DGL_H__
Loading
Loading