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: 4 additions & 0 deletions examples/server/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1841,6 +1841,10 @@ the working directory's ./dgl directory unless --dgl-dir is set.
| GET /sdcpp/v1/dgl/jobs/{id} | Returns the job status, error or result with tensor descriptions and inline encoded media |
| GET /sdcpp/v1/dgl/jobs/{id}/outputs/{index}?frame=0 | Returns a PNG of an image output or a video frame. Output and frame indexes start at zero. |

Failed jobs report `error.code` and `error.message`. When execution reports
`out_of_memory`, the message includes the memory failure details available
from the runtime.

Scripts share the component cache and execution settings used for generation.
Model reads are restricted to the configured model directories. Script writes
are restricted to output/ in the server's working directory.
Expand Down
28 changes: 17 additions & 11 deletions examples/server/async_jobs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -679,28 +679,29 @@ void configure_server_file_access(ServerModels& models, const SDSvrParams& param
throw std::runtime_error(sd_get_last_error());
}

static bool execute_dgl_job(ServerRuntime& runtime,
AsyncGenerationJob& job,
std::shared_ptr<sd_dgl_result_t>& result,
json& result_info,
std::string& error_message) {
static sd_status_t execute_dgl_job(ServerRuntime& runtime,
AsyncGenerationJob& job,
std::shared_ptr<sd_dgl_result_t>& result,
json& result_info,
std::string& error_message) {
try {
auto source = std::move(job.dgl_source);
sd_dgl_result_t* raw_result = nullptr;
{
std::lock_guard<std::mutex> lock(*runtime.sd_ctx_mutex);
update_job_progress(job, "executing", "dgl");
if (sd_dgl_run(sd_ctx_get_dgl_ctx(runtime.sd_ctx), source.c_str(), nullptr, 0, &raw_result) != SD_STATUS_OK) {
const auto status = sd_dgl_run(sd_ctx_get_dgl_ctx(runtime.sd_ctx), source.c_str(), nullptr, 0, &raw_result);
if (status != SD_STATUS_OK) {
error_message = sd_dgl_error();
return false;
return status;
}
}
result.reset(raw_result, sd_dgl_result_free);
result_info = describe_dgl_result(result.get());
return true;
return SD_STATUS_OK;
} catch (const std::exception& error) {
error_message = error.what();
return false;
return SD_STATUS_GENERATION_FAILED;
}
}

Expand Down Expand Up @@ -785,6 +786,7 @@ void async_job_worker(ServerRuntime& runtime) {
std::shared_ptr<sd_dgl_result_t> dgl_result;
json dgl_result_info;
std::string error_message;
const char* error_code = "generation_failed";
bool ok = false;

if (job->kind == AsyncJobKind::ImgGen) {
Expand All @@ -799,7 +801,11 @@ void async_job_worker(ServerRuntime& runtime) {
output_info,
error_message);
} else if (job->kind == AsyncJobKind::Dgl) {
ok = execute_dgl_job(runtime, *job, dgl_result, dgl_result_info, error_message);
const auto status = execute_dgl_job(runtime, *job, dgl_result, dgl_result_info, error_message);
ok = status == SD_STATUS_OK;
if (status == SD_STATUS_OUT_OF_MEMORY) {
error_code = "out_of_memory";
}
} else {
error_message = "unsupported job kind";
}
Expand Down Expand Up @@ -832,7 +838,7 @@ void async_job_worker(ServerRuntime& runtime) {
job->error_message.clear();
} else {
job->status = AsyncJobStatus::Failed;
job->error_code = "generation_failed";
job->error_code = error_code;
job->error_message = error_message.empty() ? "unknown generation error" : error_message;
job->result_images_b64.clear();
job->result_generation_info = nullptr;
Expand Down
30 changes: 20 additions & 10 deletions src/core/execution_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ namespace sd {
std::unordered_set<const ggml_tensor*> params_tensor_set_;
ggml_status last_compute_status_ = GGML_STATUS_FAILED;
Tensor<float> output_;
std::string device_memory_error_;

using GraphCutPlan = ggml_graph_cut::Plan;
ggml_tensor* canonical_param_tensor(ggml_tensor* tensor);
Expand Down Expand Up @@ -73,9 +74,9 @@ namespace sd {

ComputeResult run() {
if (!execute_graph(task_.graph, task_.n_threads, task_.no_return, task_.read_outputs)) {
return {last_compute_status_, {}};
return {last_compute_status_, {}, std::move(device_memory_error_)};
}
return {GGML_STATUS_SUCCESS, std::move(output_)};
return {GGML_STATUS_SUCCESS, std::move(output_), {}};
}
};

Expand Down Expand Up @@ -602,8 +603,12 @@ namespace sd {
const auto& segment = plan.segments[index];
const bool last = index + 1 == plan.segments.size();
auto fail_segment = [&](const char* phase) {
LOG_ERROR("%s segment %zu/%zu (%s) failed during %s", task_.description.c_str(),
index + 1, plan.segments.size(), segment.group_name.c_str(), phase);
auto message = sd_format("%s segment %zu/%zu (%s) failed during %s", task_.description.c_str(),
index + 1, plan.segments.size(), segment.group_name.c_str(), phase);
LOG_ERROR("%s", message.c_str());
if (!device_memory_error_.empty()) {
device_memory_error_ = message + ": " + device_memory_error_;
}
return false;
};
session_.cut_cache_.prune(segment.live_cut_names);
Expand Down Expand Up @@ -658,7 +663,7 @@ namespace sd {
sync_runtime_residency();
requests = memory_requests(measurement.buffers, new_cache_bytes);
}
const bool ready = weights.ensure_segment_capacity(index, requests);
const bool ready = weights.ensure_segment_capacity(index, requests, &device_memory_error_);
if (!ready && manager != nullptr) {
last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
}
Expand Down Expand Up @@ -880,7 +885,8 @@ namespace sd {
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params) {
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error) {
GGML_ASSERT(&manager == manager_);
auto capacity = [&]() { return manager.inspect_compute_backend_capacity(request, required_params); };
const auto initial = capacity();
Expand Down Expand Up @@ -972,10 +978,14 @@ namespace sd {
const auto budget_bytes = available.available_budget_bytes == SIZE_MAX
? std::string("unlimited")
: sd_format("%.2f MB", available.available_budget_bytes / (1024.0 * 1024.0));
LOG_WARN("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
ggml_backend_name(request.compute_backend),
available.required_device_bytes / (1024.0 * 1024.0),
available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
ggml_backend_name(request.compute_backend),
available.required_device_bytes / (1024.0 * 1024.0),
available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
LOG_WARN("%s", message.c_str());
if (device_memory_error != nullptr && available.valid) {
*device_memory_error = std::move(message);
}
return false;
}

Expand Down
4 changes: 3 additions & 1 deletion src/core/execution_engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ namespace sd {
struct ComputeResult {
ggml_status status = GGML_STATUS_FAILED;
Tensor<float> output;
std::string device_memory_error;
};

class ExecutionSession {
Expand Down Expand Up @@ -100,7 +101,8 @@ namespace sd {
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params);
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error = nullptr);
// Graphs, input data and output callbacks remain borrowed until execute returns.
ComputeResult execute(ExecutionSession& session, const ComputeTask& task);
};
Expand Down
2 changes: 2 additions & 0 deletions src/core/ggml_runner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ std::optional<sd::Tensor<float>> GGMLRunner::compute(get_graph_cb_t get_graph,
bool no_return,
const std::function<bool()>& read_outputs) {
last_compute_status_ = GGML_STATUS_FAILED;
clear_device_memory_error();
if (graph_active_) {
LOG_ERROR("%s does not support reentrant graph execution", get_desc().c_str());
return std::nullopt;
Expand Down Expand Up @@ -317,6 +318,7 @@ std::optional<sd::Tensor<float>> GGMLRunner::compute(get_graph_cb_t get_graph,
task.read_outputs = read_outputs;
auto result = execution_engine_->execute(execution_session_, task);
last_compute_status_ = result.status;
device_memory_error_ = std::move(result.device_memory_error);
success = result.status == GGML_STATUS_SUCCESS;
if (success) {
return std::move(result.output);
Expand Down
3 changes: 3 additions & 0 deletions src/core/ggml_runner.h
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ struct GGMLRunner {
std::shared_ptr<sd::ExecutionEngine> execution_engine_;
sd::ExecutionSession& execution_session_;
ggml_status last_compute_status_ = GGML_STATUS_SUCCESS;
std::string device_memory_error_;

protected:
typedef std::function<ggml_cgraph*()> get_graph_cb_t;
Expand Down Expand Up @@ -301,6 +302,8 @@ struct GGMLRunner {
const std::function<bool()>& read_outputs = {});

ggml_status last_compute_status() const { return last_compute_status_; }
const std::string& device_memory_error() const { return device_memory_error_; }
void clear_device_memory_error() { device_memory_error_.clear(); }

void set_flash_attention_enabled(bool enabled) {
flash_attn_enabled = enabled;
Expand Down
5 changes: 3 additions & 2 deletions src/core/segment_weight_pipeline.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ namespace sd {

bool SegmentWeightPipeline::ensure_segment_capacity(
size_t segment_index,
const std::vector<DeviceMemoryRequest>& requests) {
const std::vector<DeviceMemoryRequest>& requests,
std::string* device_memory_error) {
if (segment_index >= segment_params_.size()) {
return false;
}
Expand All @@ -94,7 +95,7 @@ namespace sd {
protected_params.insert(protected_params.end(), queued_params_.begin(), queued_params_.end());
for (const auto& request : requests) {
if (!manager->ensure_compute_backend_capacity(request, segment_params_[segment_index],
preferred_eviction_order(), protected_params)) {
preferred_eviction_order(), protected_params, device_memory_error)) {
return false;
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/core/segment_weight_pipeline.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>

Expand Down Expand Up @@ -50,7 +51,8 @@ namespace sd {

const std::vector<ggml_tensor*>& params(size_t index) const { return segment_params_[index]; }
bool ensure_segment_capacity(size_t segment_index,
const std::vector<DeviceMemoryRequest>& requests);
const std::vector<DeviceMemoryRequest>& requests,
std::string* device_memory_error);
bool segment_start(size_t segment_index, const std::function<bool()>& ensure_capacity);
void segment_end();
// Prefetch is best effort; segment_start falls back to synchronous loading.
Expand Down
4 changes: 3 additions & 1 deletion src/device_residency_manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>

#include "ggml-backend.h"
Expand Down Expand Up @@ -104,7 +105,8 @@ struct DeviceResidencyManager {
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params) = 0;
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error = nullptr) = 0;
virtual DeviceMemoryCapacity inspect_compute_backend_capacity(
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& params,
Expand Down
9 changes: 9 additions & 0 deletions src/dgl/models/dit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "conditioning/conditioner.hpp"
#include "core/ggml_tensor_utils.h"
#include "core/util.h"
#include "dgl/diagnostic.h"
#include "dgl/models/component_builders.h"
#include "dgl/models/component_sources.h"
#include "dgl/models/control.h"
Expand Down Expand Up @@ -406,7 +407,15 @@ namespace sd::dgl::models {
z_image_controls.push_back(binding->model->z_image_input(*binding, input));
params.extra = ZImageDiffusionExtra{nullptr, 1.f, &z_image_controls};
}
diffusion_model->clear_device_memory_error();
auto result = diffusion_model->compute(n_threads, params);
if (result.empty()) {
const auto& error = diffusion_model->device_memory_error();
if (!error.empty()) {
throw Error(SD_STATUS_OUT_OF_MEMORY, error);
}
throw std::runtime_error("diffusion compute failed");
}
if (result.shape() != shape) {
throw std::runtime_error("diffusion output shape " + sd::tensor_shape_to_string(result.shape()) +
" does not match input " + sd::tensor_shape_to_string(shape));
Expand Down
24 changes: 19 additions & 5 deletions src/dgl/models/vae.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "core/ggml_tensor_utils.h"
#include "core/image_geometry.h"
#include "core/util.h"
#include "dgl/diagnostic.h"
#include "dgl/models/component_builders.h"
#include "dgl/models/component_sources.h"
#include "dgl/run_events.h"
Expand Down Expand Up @@ -152,8 +153,13 @@ namespace sd::dgl::models {
input = &adjusted;
}
}
first_stage_model->clear_device_memory_error();
auto latents = first_stage_model->encode(n_threads, *input, vae_tiling_params, circular_x, circular_y);
if (latents.empty()) {
const auto& error = first_stage_model->device_memory_error();
if (!error.empty()) {
throw Error(SD_STATUS_OUT_OF_MEMORY, error);
}
return {};
}
return first_stage_model->vae_output_to_latents(latents, rng,
Expand All @@ -175,6 +181,7 @@ namespace sd::dgl::models {

sd::Tensor<float> VAE::decode_vae_latents(const sd::Tensor<float>& latents, bool decode_video) {
report_run_progress("vae_decode");
first_stage_model->clear_device_memory_error();
auto tiling_params = first_stage_model->resolve_tiling_params(vae_tiling_params);
const bool prefer_temporal_tiling = decode_video && latents.dim() == 5 && latents.shape()[2] > 1 &&
first_stage_model->can_temporal_tile_decode();
Expand All @@ -185,19 +192,26 @@ namespace sd::dgl::models {
if (tiling_params.enabled &&
!first_stage_model->get_tile_sizes(tile_size_w, tile_size_h, tile_overlap, tiling_params,
latents.shape()[0], latents.shape()[1])) {
return {};
break;
}
auto decoded = first_stage_model->decode(n_threads, latents, tiling_params, decode_video, circular_x, circular_y);
if (sd_version_is_minimax_h3_image(version()) && !decoded.empty() && decoded.dim() == 5) {
decoded = decoded.squeeze(2);
}
if (!decoded.empty() ||
!sd::backend_fit::prepare_vae_decode_retry_tiling(tiling_params, prefer_temporal_tiling,
first_stage_model->last_compute_status(),
tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) {
if (!decoded.empty()) {
return decoded;
}
if (!sd::backend_fit::prepare_vae_decode_retry_tiling(tiling_params, prefer_temporal_tiling,
first_stage_model->last_compute_status(),
tile_size_w, tile_size_h, first_stage_model->get_scale_factor())) {
break;
}
}
const auto& error = first_stage_model->device_memory_error();
if (!error.empty()) {
throw Error(SD_STATUS_OUT_OF_MEMORY, error);
}
return {};
}

} // namespace sd::dgl::models
Loading
Loading