diff --git a/examples/cli/dgl.cpp b/examples/cli/dgl.cpp index d10273bd3..e7e89d7df 100644 --- a/examples/cli/dgl.cpp +++ b/examples/cli/dgl.cpp @@ -241,7 +241,12 @@ class DownloadDisplay { } }; -int DGLModeParams::run(const SDContextParams& options, bool embed_metadata, sd_generation_progress_cb_t callback, void* userdata, const sd_progress_options_t& progress) 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 LogCallbackRegistration& log_callback) const { try { if (script_path.empty()) { const auto* catalog = sd_dgl_builtin_catalog(); @@ -302,7 +307,9 @@ int DGLModeParams::run(const SDContextParams& options, bool embed_metadata, sd_g if (!max_ram.empty()) check_dgl(sd_dgl_ctx_set(context.get(), "max_ram", max_ram.c_str())); sd_dgl_result_t* raw_result = nullptr; - check_dgl(sd_dgl_run(context.get(), source.c_str(), nullptr, 0, &raw_result) == SD_STATUS_OK); + const auto status = sd_dgl_run(context.get(), source.c_str(), nullptr, 0, &raw_result); + log_callback.flush(); + check_dgl(status == SD_STATUS_OK); std::unique_ptr result(raw_result, sd_dgl_result_free); for (const auto& [name, output_path] : tensor_paths) { auto tensor = sd_dgl_result_tensor(result.get(), name.c_str()); diff --git a/examples/cli/dgl.h b/examples/cli/dgl.h index f4893d6d5..5aa485efc 100644 --- a/examples/cli/dgl.h +++ b/examples/cli/dgl.h @@ -13,6 +13,7 @@ struct ArgOptions; struct SDContextParams; +class LogCallbackRegistration; using DGLScriptArgs = std::map>; @@ -33,7 +34,12 @@ struct DGLModeParams { ArgOptions get_options(); bool has_options() const; bool validate() const; - int run(const SDContextParams& options, bool embed_metadata, sd_generation_progress_cb_t callback, void* userdata, const sd_progress_options_t& progress) const; + int run(const SDContextParams& options, + bool embed_metadata, + sd_generation_progress_cb_t callback, + void* userdata, + const sd_progress_options_t& progress, + const LogCallbackRegistration& log_callback) const; }; #endif // __EXAMPLES_CLI_DGL_H__ diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index 63f64719e..e8b31bc79 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -571,8 +571,8 @@ int main(int argc, const char* argv[]) { SDGenerationParams gen_params; gen_params.seed = 42; - sd_set_log_callback(sd_log_cb, (void*)&cli_params); parse_args(argc, argv, cli_params, ctx_params, gen_params); + const LogCallbackRegistration log_callback(sd_log_cb, &cli_params); const bool preview_enabled = cli_params.preview_method != "none" && cli_params.preview_method != "off"; sd_progress_options_t progress_options{ @@ -583,7 +583,7 @@ int main(int argc, const char* argv[]) { // A decoder supplied by the script takes precedence over projection. progress_options.preview.mode = "tae"; return cli_params.dgl.run(ctx_params, gen_params.embed_image_metadata, - preview_enabled ? preview_progress : nullptr, &cli_params, progress_options); + preview_enabled ? preview_progress : nullptr, &cli_params, progress_options, log_callback); } if (cli_params.mode == METADATA) { @@ -647,6 +647,7 @@ int main(int argc, const char* argv[]) { ctx_params.n_threads.value_or(0), loras.empty() ? nullptr : loras.data(), (int)loras.size()); + log_callback.flush(); if (!success) { LOG_ERROR("convert '%s'/'%s' to '%s' failed", ctx_params.model_path.c_str(), @@ -766,6 +767,7 @@ int main(int argc, const char* argv[]) { SDCtxPtr sd_ctx(create_sd_context(sd_ctx_params)); if (sd_ctx == nullptr) { + log_callback.flush(); LOG_INFO("sd_ctx_create failed"); return 1; } @@ -828,6 +830,7 @@ int main(int argc, const char* argv[]) { } if (!results) { + log_callback.flush(); LOG_ERROR("generate failed: %s", sd_get_last_error()); return 1; } @@ -869,6 +872,7 @@ int main(int argc, const char* argv[]) { if (!video_info.empty() && results.count() > 0) video_info = results.generation_info(0); + log_callback.flush(); if (!save_results(cli_params, ctx_params, gen_params, results, num_results, generated_audio, video_info)) { free_sd_audio(generated_audio); return 1; diff --git a/examples/common/log.h b/examples/common/log.h index fd5bd4cff..acf007657 100644 --- a/examples/common/log.h +++ b/examples/common/log.h @@ -20,6 +20,23 @@ extern sd_log_level_t log_level; extern bool log_color; extern FILE* log_stream; +class LogCallbackRegistration { + sd_log_cb_t callback_; + void* data_; + +public: + LogCallbackRegistration(sd_log_cb_t callback, void* data) + : callback_(callback), data_(data) { + sd_set_log_callback(callback_, data_); + } + ~LogCallbackRegistration() { sd_set_log_callback(nullptr, nullptr); } + LogCallbackRegistration(const LogCallbackRegistration&) = delete; + LogCallbackRegistration& operator=(const LogCallbackRegistration&) = delete; + + // Re-registering the callback waits for output queued by the previous phase. + void flush() const { sd_set_log_callback(callback_, data_); } +}; + std::string sd_basename(const std::string& path); void print_utf8(FILE* stream, const char* utf8); const char* log_level_name(sd_log_level_t level); diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 0d08c9ae4..d495d2afc 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -81,8 +81,8 @@ int main(int argc, const char** argv) { ctx_params.lora_model_dir.clear(); SDGenerationParams default_gen_params; - sd_set_log_callback(sd_log_cb, (void*)&svr_params); parse_args(argc, argv, svr_params, ctx_params, default_gen_params); + const LogCallbackRegistration log_callback(sd_log_cb, &svr_params); LOG_VERBOSE("version: %s", version_string().c_str()); LOG_VERBOSE("%s", sd_get_system_info()); diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 27a52af2c..88019e1a6 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -280,7 +280,9 @@ enum sd_log_level_t { SD_LOG_ERROR }; +// Log callbacks run on the library's output thread. Keep data valid until the callback is cleared or replaced. typedef void (*sd_log_cb_t)(enum sd_log_level_t level, const char* text, void* data); +// Calls from application threads wait for queued output. Call outside locks the previous callback may need. SD_API void sd_set_log_callback(sd_log_cb_t sd_log_cb, void* data); typedef struct { diff --git a/src/convert.cpp b/src/convert.cpp index 2e2317ecf..b1a434908 100644 --- a/src/convert.cpp +++ b/src/convert.cpp @@ -320,7 +320,7 @@ static bool stream_tensor_data(ModelLoader& model_loader, for (auto& worker : workers) { worker.join(); } - printf("\n"); + sd::console_progress_newline(); if (failed) { if (error != nullptr) { *error = failure; diff --git a/src/core/console_output.cpp b/src/core/console_output.cpp new file mode 100644 index 000000000..dea6c23dd --- /dev/null +++ b/src/core/console_output.cpp @@ -0,0 +1,681 @@ +#include "core/console_output.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core/progress.h" +#include "core/util.h" + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#include +#endif + +static constexpr int console_progress_width = 50; + +static int console_columns() { +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO info{}; + if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info)) + return info.srWindow.Right - info.srWindow.Left + 1; +#else + const char* term = std::getenv("TERM"); + winsize size{}; + if (term && std::strcmp(term, "dumb") != 0 && ioctl(fileno(stdout), TIOCGWINSZ, &size) == 0) + return size.ws_col; +#endif + return 0; +} + +static int fit_progress_bar(const sd::ConsoleProgressLine& line, int columns) { + // Keep the counter, speed and ETA on narrow terminals by shortening the bar. + return columns > 0 ? std::clamp(columns - 5 - static_cast(line.suffix.size()), 1, console_progress_width) + : console_progress_width; +} + +static std::string build_progress_bar(int step, int steps, char progress_char, bool show_head, int width) { + std::string progress = " |"; + int current = 0; + if (steps > 0) { + current = static_cast(std::clamp(step, 0, steps) * 1.f * width / steps); + } + int head_length = current == width ? 0 : 1; + progress += std::string(current, progress_char) + std::string(head_length, show_head ? '>' : progress_char) + std::string(width - current - head_length, ' ') + "|"; + return progress; +} + +static std::string progress_suffix(int step, int steps, const std::string& speed, const std::string& eta = "") { + const auto digits = static_cast(std::to_string(steps).size()); + return sd_format(" %*i/%i - %10s%s%s", digits, step, steps, speed.c_str(), eta.empty() ? "" : " - ETA ", eta.c_str()); +} + +struct ConsoleLine { + sd::ConsoleProgressLine line; + char progress_char; + bool show_head; + std::thread::id sampler; +}; + +struct SegmentConsoleFrame { + std::thread::id owner; + size_t total; + size_t weights_ready = 0; + size_t computed = 0; + std::shared_ptr sampling; +}; + +struct ConsoleLog { + sd_log_level_t level; + std::string message; +}; + +struct ConsoleLogCallback { + sd_log_cb_t callback = nullptr; + void* data = nullptr; +}; + +struct ConsoleNewline {}; + +using ConsoleClock = std::chrono::steady_clock; + +struct ConsoleSampleBegin { + std::thread::id owner; + int steps; + ConsoleClock::time_point started; +}; + +struct ConsoleSampleEnd { + std::thread::id owner; + bool newline; +}; + +using ConsoleEvent = std::variant; + +class SamplingCursor { + std::thread::id owner_; +#ifdef _WIN32 + HANDLE console_ = INVALID_HANDLE_VALUE; + CONSOLE_CURSOR_INFO original_{}; +#endif + +public: + ~SamplingCursor() { + restore(owner_); + } + + void hide(std::thread::id owner, int columns) { + if (owner_ != std::thread::id{} || columns <= 0) + return; +#ifdef _WIN32 + const auto output = GetStdHandle(STD_OUTPUT_HANDLE); + if (!GetConsoleCursorInfo(output, &original_)) + return; + auto hidden = original_; + hidden.bVisible = FALSE; + if (original_.bVisible && !SetConsoleCursorInfo(output, &hidden)) + return; + console_ = output; +#else + std::fputs("\033[?25l", stdout); +#endif + owner_ = owner; + } + + void restore(std::thread::id owner) { + if (owner_ == std::thread::id{} || owner_ != owner) + return; +#ifdef _WIN32 + if (original_.bVisible) + SetConsoleCursorInfo(console_, &original_); +#else + std::fputs("\033[?25h", stdout); + std::fflush(stdout); +#endif + owner_ = {}; + } +}; + +class SegmentConsole { + std::string segment_rows_; + std::string sampling_row_; + int drawn_rows_ = 0; +#ifdef _WIN32 + HANDLE console_ = INVALID_HANDLE_VALUE; + DWORD original_mode_ = 0; +#endif + + bool enable_cursor_movement() { +#ifdef _WIN32 + if (console_ == INVALID_HANDLE_VALUE) { + const auto output = GetStdHandle(STD_OUTPUT_HANDLE); + DWORD mode; + if (!GetConsoleMode(output, &mode) || !SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) + return false; + console_ = output; + original_mode_ = mode; + } +#endif + return true; + } + + static std::string format_bar(const char* label, size_t completed, size_t total) { + constexpr size_t width = 20; + const size_t filled = width * completed / total; + char bar[width + 1] = {}; + std::fill_n(bar, filled, '#'); + std::fill(bar + filled, bar + width, ' '); + return sd_format("\r%-16s [%s] %zu/%zu\033[K", label, bar, completed, total); + } + +public: + ~SegmentConsole() { + clear(); +#ifdef _WIN32 + if (console_ != INVALID_HANDLE_VALUE) + SetConsoleMode(console_, original_mode_); +#endif + } + + void clear() { + if (drawn_rows_ == 0) + return; + for (; drawn_rows_ > 1; --drawn_rows_) + std::fputs("\r\033[2K\033[1A", stdout); + std::fputs("\r\033[2K", stdout); + std::fflush(stdout); + drawn_rows_ = 0; + } + + bool update(const SegmentConsoleFrame& progress, const sd::ConsoleProgressLine* sampling, SamplingCursor& cursor) { + const int width = console_columns(); + if (width <= 0 || (progress.total && width < 52) || !enable_cursor_movement()) { + clear(); + return false; + } + + std::string rows; + if (progress.total) { + rows = format_bar("Weights ready", progress.weights_ready, progress.total); + rows += '\n'; + rows += format_bar("Compute done", progress.computed, progress.total); + } + std::string sample_row; + if (sampling) { + sample_row = "\r"; + sample_row += build_progress_bar(sampling->completed, sampling->total, '=', true, fit_progress_bar(*sampling, width)); + sample_row += sampling->suffix; + sample_row += "\033[K"; + cursor.hide(progress.owner, width); + } + const int row_count = (progress.total ? 2 : 0) + (sampling ? 1 : 0); + if (drawn_rows_ != row_count) { + clear(); + std::fputs(rows.c_str(), stdout); + if (sampling) { + if (progress.total) + std::fputc('\n', stdout); + std::fputs(sample_row.c_str(), stdout); + } + } else if (rows != segment_rows_) { + std::fprintf(stdout, "\033[%dA%s", row_count - 1, rows.c_str()); + if (sampling) { + if (sample_row == sampling_row_) { + std::fputs("\033[1B", stdout); + } else { + std::fputc('\n', stdout); + std::fputs(sample_row.c_str(), stdout); + } + } + } else if (sample_row != sampling_row_) { + std::fputs(sample_row.c_str(), stdout); + } else { + return true; + } + std::fflush(stdout); + segment_rows_ = std::move(rows); + sampling_row_ = std::move(sample_row); + drawn_rows_ = row_count; + return true; + } +}; + +static std::atomic console_log_enabled{false}; + +class ConsoleWriter { + struct FirstSample { + ConsoleSampleBegin sample; + sd::ConsoleProgressLine line; + ConsoleClock::time_point next_refresh; + }; + + SamplingCursor sampling_cursor_; + SegmentConsole segment_; + std::optional frame_; + std::optional first_sample_; + ConsoleLogCallback sink_; + std::vector deferred_debug_; + bool frame_dirty_ = false; + + void deliver(const ConsoleLog& log) const noexcept { + if (sink_.callback) { + try { + sink_.callback(log.level, log.message.c_str(), sink_.data); + } catch (...) { + // A diagnostic callback must not stop the output worker. + } + } + } + + void split_output() { + segment_.clear(); + frame_dirty_ = frame_.has_value(); + const auto deferred = std::exchange(deferred_debug_, {}); + for (const auto& log : deferred) + deliver(log); + } + + bool end_first_sample(std::thread::id owner) { + if (!first_sample_ || first_sample_->sample.owner != owner) + return false; + first_sample_.reset(); + return true; + } + +public: + void write(ConsoleSampleBegin sample) { + if (!first_sample_ && console_columns() > 0) { + first_sample_ = FirstSample{ + sample, {0, sample.steps, progress_suffix(0, sample.steps, "first step 0s")}, sample.started + std::chrono::seconds(1)}; + } + } + + void write(SegmentConsoleFrame frame) { + if (frame_ && frame_->owner != frame.owner) + return; + if (frame.total != 0) { + frame_ = std::move(frame); + frame_dirty_ = true; + } else if (frame_ && (!frame_->sampling || frame_->computed != frame_->total)) { + split_output(); + frame_.reset(); + } + } + + void write(ConsoleLog log) { + if (!sink_.callback) + return; + if (frame_ && log.level == SD_LOG_DEBUG) { + deferred_debug_.push_back(std::move(log)); + } else { + split_output(); + deliver(log); + } + } + + void write(ConsoleLogCallback sink) { + split_output(); + sink_ = sink; + console_log_enabled.store(sink.callback != nullptr, std::memory_order_relaxed); + } + + void write(ConsoleLine output) { + const bool sampling = output.sampler != std::thread::id{}; + if (sampling) + end_first_sample(output.sampler); + if (sampling && frame_ && frame_->sampling && frame_->owner == output.sampler) { + if (output.line.completed < output.line.total) { + frame_->sampling = std::make_shared(output.line); + if (segment_.update(*frame_, frame_->sampling.get(), sampling_cursor_)) { + frame_dirty_ = false; + return; + } + } + frame_.reset(); + } + split_output(); + const auto& line = output.line; + const bool finished = line.completed == line.total; + const int columns = sampling ? console_columns() : 0; + const auto progress = build_progress_bar(line.completed, line.total, output.progress_char, output.show_head, + fit_progress_bar(line, columns)); + if (sampling && !finished) + sampling_cursor_.hide(output.sampler, columns); + std::printf("\r%s%s\033[K%s", progress.c_str(), line.suffix.c_str(), finished ? "\n" : ""); + std::fflush(stdout); + if (sampling && finished) + sampling_cursor_.restore(output.sampler); + } + + void write(ConsoleNewline) { + split_output(); + std::fputc('\n', stdout); + std::fflush(stdout); + } + + void write(ConsoleSampleEnd end) { + const bool ended_first_sample = end_first_sample(end.owner); + if (frame_ && frame_->owner == end.owner && frame_->sampling) { + split_output(); + frame_.reset(); + } else if (end.newline) { + write(ConsoleNewline{}); + } else if (ended_first_sample && !frame_) { + split_output(); + } + sampling_cursor_.restore(end.owner); + } + + std::optional next_refresh() const { + if (first_sample_) + return first_sample_->next_refresh; + return std::nullopt; + } + + void paint() { + bool refresh = false; + if (first_sample_) { + const auto now = ConsoleClock::now(); + if (now >= first_sample_->next_refresh) { + const auto elapsed = std::chrono::duration_cast(now - first_sample_->sample.started); + first_sample_->line.suffix = progress_suffix(0, first_sample_->line.total, + sd_format("first step %llds", static_cast(elapsed.count()))); + first_sample_->next_refresh = first_sample_->sample.started + elapsed + std::chrono::seconds(1); + refresh = true; + } + } + + const bool frame_dirty = std::exchange(frame_dirty_, false); + if (frame_ && (frame_dirty || refresh)) { + const auto* sampling = frame_->sampling.get(); + if (sampling && sampling->completed == 0 && first_sample_ && first_sample_->sample.owner == frame_->owner) + sampling = &first_sample_->line; + if (segment_.update(*frame_, sampling, sampling_cursor_)) + return; + } + if (refresh && (!frame_ || frame_->owner == first_sample_->sample.owner)) + segment_.update(SegmentConsoleFrame{first_sample_->sample.owner, 0}, &first_sample_->line, sampling_cursor_); + } +}; + +static thread_local ConsoleWriter* current_console_writer = nullptr; + +class ConsoleOutput { + std::mutex mutex_; + std::condition_variable ready_; + std::condition_variable completed_; + std::deque events_; + std::thread worker_; + size_t submitted_ = 0; + size_t written_ = 0; + bool stopping_ = false; + + static bool can_replace(const ConsoleEvent& previous, const ConsoleEvent& next) { + if (const auto* frame = std::get_if(&previous)) { + const auto* newer = std::get_if(&next); + return newer && frame->total && newer->total && frame->owner == newer->owner; + } + if (const auto* line = std::get_if(&previous)) { + const auto* newer = std::get_if(&next); + return newer && line->progress_char == '#' && newer->progress_char == '#' && + line->line.completed < line->line.total && newer->line.completed < newer->line.total; + } + return false; + } + + void run() { + ConsoleWriter writer; + current_console_writer = &writer; + std::deque batch; + std::unique_lock lock(mutex_); + for (;;) { + const auto ready = [&] { return stopping_ || !events_.empty(); }; + if (const auto refresh = writer.next_refresh()) + ready_.wait_until(lock, *refresh, ready); + else + ready_.wait(lock, ready); + if (stopping_ && events_.empty()) + break; + const auto end = submitted_; + events_.swap(batch); + lock.unlock(); + + // Paint only the latest segment snapshot from this batch. + for (auto& event : batch) { + try { + std::visit([&](auto& item) { writer.write(std::move(item)); }, event); + } catch (...) { + // Output is best effort even if formatting or buffering fails. + } + } + try { + writer.paint(); + } catch (...) { + } + batch.clear(); + + lock.lock(); + if (written_ != end) { + written_ = end; + completed_.notify_all(); + } + } + lock.unlock(); + current_console_writer = nullptr; + } + +public: + ~ConsoleOutput() { + { + std::lock_guard lock(mutex_); + stopping_ = true; + } + ready_.notify_one(); + if (worker_.joinable()) + worker_.join(); + } + + size_t submit(ConsoleEvent event) noexcept { + try { + std::lock_guard lock(mutex_); + if (stopping_) + return 0; + if (!worker_.joinable()) + worker_ = std::thread([this] { run(); }); + if (!events_.empty() && can_replace(events_.back(), event)) { + events_.back() = std::move(event); + } else { + events_.push_back(std::move(event)); + } + ready_.notify_one(); + return ++submitted_; + } catch (...) { + return 0; + } + } + + void wait_until_written(size_t end) { + std::unique_lock lock(mutex_); + completed_.wait(lock, [&] { return written_ >= end; }); + } +}; + +static ConsoleOutput& console_output() { + static ConsoleOutput output; + return output; +} + +static void print_progress_line(sd::ConsoleProgressLine line, char progress_char = '=', bool show_head = true, bool sampling = false) { + console_output().submit(ConsoleLine{ + std::move(line), progress_char, show_head, sampling ? std::this_thread::get_id() : std::thread::id{}}); +} + +bool sd::render_segment_progress(const SegmentProgress* progress, const ConsoleProgressLine* sampling) { + static thread_local std::optional interactive; + static thread_local std::shared_ptr sampling_snapshot; + const auto owner = std::this_thread::get_id(); + if (!progress) { + if (interactive.value_or(false)) + console_output().submit(SegmentConsoleFrame{owner, 0}); + interactive.reset(); + sampling_snapshot.reset(); + return false; + } + if (!interactive) { + interactive = console_columns() >= 52; + if (*interactive && sampling) + sampling_snapshot = std::make_shared(*sampling); + } + return *interactive && console_output().submit(SegmentConsoleFrame{ + owner, progress->total, progress->weights_ready, progress->computed, sampling_snapshot}) != 0; +} + +void sd::console_progress_newline() { + console_output().submit(ConsoleNewline{}); +} + +void sd::finish_console_sampling(bool newline) { + console_output().submit(ConsoleSampleEnd{std::this_thread::get_id(), newline}); +} + +void pretty_console_progress(int step, int steps, float time, sd::ConsoleProgressLine* line) { + static thread_local int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show + static thread_local float passed_time = 0.f; + if (step == 0) { + show_eta = -1; // reinitialize for batch generations + passed_time = 0.f; + if (line) { + *line = {step, steps, progress_suffix(step, steps, "first step")}; + if (steps > 0) + console_output().submit(ConsoleSampleBegin{std::this_thread::get_id(), steps, ConsoleClock::now()}); + } + return; + } + std::string remainder_text = ""; + if (show_eta && step < steps) { // if timer is not disabled and bar is not filled, + if (show_eta == -1 && step) // estimate the total time once, then + show_eta = (std::abs(time * steps / step) < 15.f) ? 0 : 1; // hide the timer if total is less than 15 seconds + if (show_eta) { + unsigned remainder = (passed_time += time) / step * (steps - step); // average speed; time*(steps-step) for current + remainder_text = remainder < 3600 ? sd_format("%02u:%02u", remainder / 60, remainder % 60) + : sd_format("%u:%02u:%02u", remainder / 3600, (remainder / 60) % 60, remainder % 60); + } + } + const char* unit = "s/it"; + float speed = time; + if (speed < 1.0f && speed > 0.f) { + speed = 1.0f / speed; + unit = "it/s"; + } + sd::ConsoleProgressLine progress{step, steps, progress_suffix(step, steps, sd_format("%.2f%s", speed, unit), remainder_text)}; + if (line) + *line = progress; + print_progress_line(std::move(progress), '=', true, line != nullptr); +} + +void pretty_console_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds) { + if (step == 0) { + return; + } + + double bytes_per_second = 0.0; + if (elapsed_seconds > 0.0f) { + bytes_per_second = bytes_processed / (double)elapsed_seconds; + } + + double speed_mb = bytes_per_second / (1024.0 * 1024.0); + if (speed_mb >= 1024.0) { + print_progress_line({step, steps, progress_suffix(step, steps, sd_format("%.2fGB/s", speed_mb / 1024.0))}, '#', false); + } else { + print_progress_line({step, steps, progress_suffix(step, steps, sd_format("%.2fMB/s", speed_mb))}, '#', false); + } +} + +static std::string sd_basename(const std::string& path) { + size_t pos = path.find_last_of('/'); + if (pos != std::string::npos) { + return path.substr(pos + 1); + } + pos = path.find_last_of('\\'); + if (pos != std::string::npos) { + return path.substr(pos + 1); + } + return path; +} + +static void sd_log_dispatch(sd_log_level_t level, const std::string& origin, const std::string& text) { + if (!console_log_enabled.load(std::memory_order_relaxed)) + return; + std::string message = text; + while (!message.empty() && (message.back() == '\n' || message.back() == '\r')) { + message.pop_back(); + } + if (origin == "ggml") { + message = origin + ": " + message + '\n'; + } else { + message += " --- " + origin + '\n'; + } + console_output().submit(ConsoleLog{level, std::move(message)}); +} + +void log_printf(sd_log_level_t level, const char* file, int line, const char* format, ...) { + va_list args; + va_start(args, format); + std::string message = sd_vformat(format, args); + va_end(args); + std::string origin = sd_format("%s:%d", sd_basename(file).c_str(), line); + sd_log_dispatch(level, origin, message); +} + +void sd_ggml_log_callback(ggml_log_level level, const char* text, void*) { + sd_log_level_t sd_level = SD_LOG_VERBOSE; + switch (level) { + case GGML_LOG_LEVEL_DEBUG: + sd_level = SD_LOG_VERBOSE; + break; + case GGML_LOG_LEVEL_INFO: + sd_level = SD_LOG_INFO; + break; + case GGML_LOG_LEVEL_WARN: + sd_level = SD_LOG_WARN; + break; + case GGML_LOG_LEVEL_ERROR: + sd_level = SD_LOG_ERROR; + break; + default: + sd_level = SD_LOG_VERBOSE; + break; + } + sd_log_dispatch(sd_level, "ggml", text); +} + +void sd_set_log_callback(sd_log_cb_t cb, void* data) { + const ConsoleLogCallback callback{cb, data}; + if (current_console_writer) { + current_console_writer->write(callback); + } else { + auto& output = console_output(); + const auto update = output.submit(callback); + if (update) + output.wait_until_written(update); + } +} diff --git a/src/core/console_output.h b/src/core/console_output.h new file mode 100644 index 000000000..330d43883 --- /dev/null +++ b/src/core/console_output.h @@ -0,0 +1,36 @@ +#ifndef __SD_CORE_CONSOLE_OUTPUT_H__ +#define __SD_CORE_CONSOLE_OUTPUT_H__ + +#include +#include + +#include "ggml.h" +#include "stable-diffusion.h" + +void log_printf(sd_log_level_t level, const char* file, int line, const char* format, ...); +void sd_ggml_log_callback(ggml_log_level level, const char* text, void*); + +#define LOG_DEBUG(format, ...) log_printf(SD_LOG_DEBUG, __FILE__, __LINE__, format, ##__VA_ARGS__) +#define LOG_VERBOSE(format, ...) log_printf(SD_LOG_VERBOSE, __FILE__, __LINE__, format, ##__VA_ARGS__) +#define LOG_INFO(format, ...) log_printf(SD_LOG_INFO, __FILE__, __LINE__, format, ##__VA_ARGS__) +#define LOG_WARN(format, ...) log_printf(SD_LOG_WARN, __FILE__, __LINE__, format, ##__VA_ARGS__) +#define LOG_ERROR(format, ...) log_printf(SD_LOG_ERROR, __FILE__, __LINE__, format, ##__VA_ARGS__) + +namespace sd { + struct SegmentProgress; + + struct ConsoleProgressLine { + int completed = 0; + int total = 0; + std::string suffix; + }; + + bool render_segment_progress(const SegmentProgress* progress, const ConsoleProgressLine* sampling = nullptr); + void console_progress_newline(); + void finish_console_sampling(bool newline); +} // namespace sd + +void pretty_console_progress(int step, int steps, float time, sd::ConsoleProgressLine* line = nullptr); +void pretty_console_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds); + +#endif // __SD_CORE_CONSOLE_OUTPUT_H__ diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp index c04d4d218..0da8bb2fc 100644 --- a/src/core/execution_engine.cpp +++ b/src/core/execution_engine.cpp @@ -9,6 +9,7 @@ #include "core/ggml_extend_backend.h" #include "core/ggml_tensor_utils.h" #include "core/layer_split_partition.h" +#include "core/progress.h" #include "core/segment_graph_bindings.h" #include "core/segment_weight_pipeline.h" #include "core/tensor_ggml.hpp" @@ -601,9 +602,10 @@ namespace sd { segment.input_refs.push_back(input); } } - const auto& plan = segmented ? cached_plan : monolithic_plan; + const auto& plan = segmented ? cached_plan : monolithic_plan; + SegmentProgressScope segment_progress(task_.description.c_str(), plan.segments.size(), segmented); const bool segments_changed = plan.segments.size() != session_.logged_segment_count_; - if (segments_changed && (segmented || session_.logged_segment_count_ > 1)) { + if (!segment_progress.active() && segments_changed && (segmented || session_.logged_segment_count_ > 1)) { LOG_VERBOSE("%s using %zu segment%s", task_.description.c_str(), plan.segments.size(), plan.segments.size() == 1 ? "" : "s"); } @@ -711,6 +713,7 @@ namespace sd { if (!weights.segment_start(index, ensure_capacity)) { return fail_segment("weight preparation"); } + segment_progress.weights_ready(index + 1); // Preparing weights can execute LoRA graphs and reclaim an idle workspace. if (!session_.workspace_.prepare(measurement)) { last_compute_status_ = GGML_STATUS_ALLOC_FAILED; @@ -786,6 +789,7 @@ namespace sd { last_compute_status_ = GGML_STATUS_FAILED; return fail_segment("workspace synchronization"); } + segment_progress.computed(index + 1); // Final outputs and callbacks can still refer to cuts until this point. if (last) { session_.cut_cache_.prune(segment.future_cut_names); @@ -801,6 +805,7 @@ namespace sd { session_.logged_compute_bytes_ = std::move(peak_compute_bytes); session_.logged_segment_count_ = plan.segments.size(); } + segment_progress.finish(); return true; } diff --git a/src/core/progress.h b/src/core/progress.h index 390f1c202..dc57f8fab 100644 --- a/src/core/progress.h +++ b/src/core/progress.h @@ -1,19 +1,73 @@ #ifndef __SD_CORE_PROGRESS_H__ #define __SD_CORE_PROGRESS_H__ +#include +#include #include +#include + +struct ggml_tensor; void report_tile_progress(int completed, int total, float seconds); -void pretty_console_progress(int step, int steps, float time); void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds); -void pretty_console_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds); namespace sd { + struct SegmentProgress { + const char* model; + size_t total; + size_t weights_ready = 0; + size_t computed = 0; + }; + + struct SegmentTransferStats { + std::atomic file_bytes{0}; + std::atomic upload_bytes{0}; + }; + + struct SegmentSummary { + uint64_t file_bytes; + uint64_t upload_bytes; + }; + + bool compact_segment_logs(); + const std::shared_ptr& segment_transfer_stats(); + void record_weight_upload(const ggml_tensor* source, const ggml_tensor* destination); + + class SegmentTransferScope { + std::shared_ptr previous_; + + public: + explicit SegmentTransferScope(std::shared_ptr stats); + ~SegmentTransferScope(); + SegmentTransferScope(const SegmentTransferScope&) = delete; + SegmentTransferScope& operator=(const SegmentTransferScope&) = delete; + }; + + class SegmentProgressScope { + SegmentProgress progress_; + bool active_ = false; + std::shared_ptr transfers_; + + void notify(const SegmentProgress* progress, const SegmentSummary* summary = nullptr) const noexcept; + + public: + SegmentProgressScope(const char* model, size_t total, bool segmented); + ~SegmentProgressScope(); + SegmentProgressScope(const SegmentProgressScope&) = delete; + SegmentProgressScope& operator=(const SegmentProgressScope&) = delete; + + bool active() const { return active_; } + void weights_ready(size_t completed); + void computed(size_t completed); + void finish(); + }; + class ProgressScope { public: struct Callbacks { void (*tiles)(int completed, int total, float seconds, void* data); void (*loading)(int completed, int total, uint64_t bytes, float seconds, void* data); + void (*segments)(const SegmentProgress* progress, const SegmentSummary* summary, void* data); void* data; }; @@ -26,6 +80,6 @@ namespace sd { ProgressScope(const ProgressScope&) = delete; ProgressScope& operator=(const ProgressScope&) = delete; }; -} +} // namespace sd -#endif +#endif // __SD_CORE_PROGRESS_H__ diff --git a/src/core/util.cpp b/src/core/util.cpp index a06e6078d..3bc28169e 100644 --- a/src/core/util.cpp +++ b/src/core/util.cpp @@ -4,17 +4,20 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #include #include #include #include +#include #include #include "core/ggml_tensor_utils.h" #include "core/option_types.h" @@ -25,11 +28,6 @@ #include #endif -#if !defined(_WIN32) -#include -#include -#endif - #include "ggml-backend.h" #include "ggml.h" #include "stable-diffusion.h" @@ -79,7 +77,7 @@ std::string escape_newlines(const std::string& text) { return escaped; } -static std::string sd_vformat(const char* fmt, va_list ap) { +std::string sd_vformat(const char* fmt, va_list ap) { char small[128]; va_list ap2; va_copy(ap2, ap); @@ -392,18 +390,6 @@ std::u32string unicode_value_to_utf32(int unicode_value) { return utf32_string; } -static std::string sd_basename(const std::string& path) { - size_t pos = path.find_last_of('/'); - if (pos != std::string::npos) { - return path.substr(pos + 1); - } - pos = path.find_last_of('\\'); - if (pos != std::string::npos) { - return path.substr(pos + 1); - } - return path; -} - std::string path_join(const std::string& p1, const std::string& p2) { if (p1.empty()) { return p2; @@ -557,31 +543,85 @@ bool parse_strict_bool(const std::string& text, bool& value) { return false; } -static std::string build_progress_bar(int step, int steps, char progress_char = '=', bool show_head = true) { - std::string progress = " |"; - constexpr int max_progress = 50; - int32_t current = 0; - if (steps > 0) { - current = (int32_t)(std::clamp(step, 0, steps) * 1.f * max_progress / steps); +static thread_local sd::ProgressScope::Callbacks progress_callbacks{}; +static thread_local bool segment_progress_active = false; +static thread_local std::shared_ptr segment_transfers; + +bool sd::compact_segment_logs() { + return segment_progress_active; +} + +const std::shared_ptr& sd::segment_transfer_stats() { + return segment_transfers; +} + +void sd::record_weight_upload(const ggml_tensor* source, const ggml_tensor* destination) { + if (segment_transfers && source->buffer && destination->buffer && + ggml_backend_buffer_is_host(source->buffer) && + !ggml_backend_buffer_is_host(destination->buffer)) { + segment_transfers->upload_bytes.fetch_add(ggml_nbytes(destination), std::memory_order_relaxed); + } +} + +sd::SegmentTransferScope::SegmentTransferScope(std::shared_ptr stats) + : previous_(std::exchange(segment_transfers, std::move(stats))) {} + +sd::SegmentTransferScope::~SegmentTransferScope() { + segment_transfers = std::move(previous_); +} + +sd::SegmentProgressScope::SegmentProgressScope(const char* model, size_t total, bool segmented) + : progress_{model, total} { + if (segmented && !segment_progress_active && progress_callbacks.segments) { + try { + transfers_ = std::make_shared(); + } catch (const std::bad_alloc&) { + return; + } + segment_transfers = transfers_; + active_ = segment_progress_active = true; + notify(&progress_); } - int head_length = (current == max_progress) ? 0 : 1; - progress += std::string(current, progress_char) + std::string(head_length, show_head ? '>' : progress_char) + std::string(max_progress - current - head_length, ' ') + "|"; - return progress; } -static void print_progress_line(int step, int steps, const std::string& speed_text, char progress_char = '=', bool show_head = true, const std::string& eta_text = "") { - if (step == 0) { - return; +sd::SegmentProgressScope::~SegmentProgressScope() { + if (active_) { + notify(nullptr); + segment_transfers.reset(); + segment_progress_active = false; } - std::string progress = build_progress_bar(step, steps, progress_char, show_head); - int step_width = static_cast(std::to_string(steps).size()); - const char* lf = (step == steps ? "\n" : ""); - printf("\r%s %*i/%i - %10s%s%s\033[K%s", progress.c_str(), step_width, step, steps, speed_text.c_str(), - eta_text.empty() ? "" : " - ETA ", eta_text.c_str(), lf); - fflush(stdout); // for linux } -static thread_local sd::ProgressScope::Callbacks progress_callbacks{}; +void sd::SegmentProgressScope::notify(const SegmentProgress* progress, const SegmentSummary* summary) const noexcept { + try { + progress_callbacks.segments(progress, summary, progress_callbacks.data); + } catch (...) { + // A console or summary failure must not interrupt graph execution. + } +} + +void sd::SegmentProgressScope::weights_ready(size_t completed) { + if (active_) { + progress_.weights_ready = completed; + notify(&progress_); + } +} + +void sd::SegmentProgressScope::computed(size_t completed) { + if (active_) { + progress_.computed = completed; + notify(&progress_); + } +} + +void sd::SegmentProgressScope::finish() { + if (active_) { + const SegmentSummary summary{ + transfers_->file_bytes.load(std::memory_order_relaxed), + transfers_->upload_bytes.load(std::memory_order_relaxed)}; + notify(&progress_, &summary); + } +} void report_tile_progress(int completed, int total, float seconds) { if (progress_callbacks.tiles) @@ -590,33 +630,6 @@ void report_tile_progress(int completed, int total, float seconds) { pretty_console_progress(completed, total, seconds); } -void pretty_console_progress(int step, int steps, float time) { - static thread_local int show_eta = -1; // -1 - estimate duration, 0 - hide, 1 - show - static thread_local float passed_time = 0.f; - if (step == 0) { - show_eta = -1; // reinitialize for batch generations - passed_time = 0.f; - return; - } - std::string remainder_text = ""; - if (show_eta && step < steps) { // if timer is not disabled and bar is not filled, - if (show_eta == -1 && step) // estimate the total time once, then - show_eta = (std::abs(time * steps / step) < 15.f) ? 0 : 1; // hide the timer if total is less than 15 seconds - if (show_eta) { - unsigned remainder = (passed_time += time) / step * (steps - step); // average speed; time*(steps-step) for current - remainder_text = remainder < 3600 ? sd_format("%02u:%02u", remainder / 60, remainder % 60) - : sd_format("%u:%02u:%02u", remainder / 3600, (remainder / 60) % 60, remainder % 60); - } - } - const char* unit = "s/it"; - float speed = time; - if (speed < 1.0f && speed > 0.f) { - speed = 1.0f / speed; - unit = "it/s"; - } - print_progress_line(step, steps, sd_format("%.2f%s", speed, unit), '=', true, remainder_text); -} - sd::ProgressScope::ProgressScope(Callbacks callbacks) : previous_(progress_callbacks) { progress_callbacks = callbacks; @@ -629,28 +642,10 @@ sd::ProgressScope::~ProgressScope() { void pretty_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds) { if (progress_callbacks.loading) progress_callbacks.loading(step, steps, bytes_processed, elapsed_seconds, progress_callbacks.data); - else + else if (!sd::compact_segment_logs()) pretty_console_bytes_progress(step, steps, bytes_processed, elapsed_seconds); } -void pretty_console_bytes_progress(int step, int steps, uint64_t bytes_processed, float elapsed_seconds) { - if (step == 0) { - return; - } - - double bytes_per_second = 0.0; - if (elapsed_seconds > 0.0f) { - bytes_per_second = bytes_processed / (double)elapsed_seconds; - } - - double speed_mb = bytes_per_second / (1024.0 * 1024.0); - if (speed_mb >= 1024.0) { - print_progress_line(step, steps, sd_format("%.2fGB/s", speed_mb / 1024.0), '#', false); - } else { - print_progress_line(step, steps, sd_format("%.2fMB/s", speed_mb), '#', false); - } -} - std::string ltrim(const std::string& s) { auto it = std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); @@ -669,59 +664,6 @@ std::string trim(const std::string& s) { return rtrim(ltrim(s)); } -static sd_log_cb_t sd_log_cb = nullptr; -void* sd_log_cb_data = nullptr; - -static void sd_log_dispatch(sd_log_level_t level, const std::string& origin, const std::string& text) { - if (sd_log_cb == nullptr) - return; - std::string message = text; - while (!message.empty() && (message.back() == '\n' || message.back() == '\r')) { - message.pop_back(); - } - if (origin == "ggml") { - message = origin + ": " + message + '\n'; - } else { - message += " --- " + origin + '\n'; - } - sd_log_cb(level, message.c_str(), sd_log_cb_data); -} - -void log_printf(sd_log_level_t level, const char* file, int line, const char* format, ...) { - va_list args; - va_start(args, format); - std::string message = sd_vformat(format, args); - va_end(args); - std::string origin = sd_format("%s:%d", sd_basename(file).c_str(), line); - sd_log_dispatch(level, origin, message); -} - -void sd_ggml_log_callback(ggml_log_level level, const char* text, void*) { - sd_log_level_t sd_level = SD_LOG_VERBOSE; - switch (level) { - case GGML_LOG_LEVEL_DEBUG: - sd_level = SD_LOG_VERBOSE; - break; - case GGML_LOG_LEVEL_INFO: - sd_level = SD_LOG_INFO; - break; - case GGML_LOG_LEVEL_WARN: - sd_level = SD_LOG_WARN; - break; - case GGML_LOG_LEVEL_ERROR: - sd_level = SD_LOG_ERROR; - break; - default: - sd_level = SD_LOG_VERBOSE; - break; - } - sd_log_dispatch(sd_level, "ggml", text); -} - -void sd_set_log_callback(sd_log_cb_t cb, void* data) { - sd_log_cb = cb; - sd_log_cb_data = data; -} void sd_set_backend_eval_callback(sd_graph_eval_callback_t cb, void* data) { sd_backend_eval_cb = cb; sd_backend_eval_cb_data = data; diff --git a/src/core/util.h b/src/core/util.h index 44a7d07f2..816e4c997 100644 --- a/src/core/util.h +++ b/src/core/util.h @@ -3,12 +3,14 @@ #include "core/media.h" +#include #include #include #include #include #include +#include "core/console_output.h" #include "core/option_types.h" #include "core/progress.h" #include "core/tensor.hpp" @@ -31,6 +33,7 @@ bool starts_with(const std::string& str, const std::string& start); bool contains(const std::string& str, const std::string& substr); std::string sd_format(const char* fmt, ...); +std::string sd_vformat(const char* fmt, va_list ap); void replace_all_chars(std::string& str, char target, char replacement); std::string escape_newlines(const std::string& text); @@ -43,7 +46,6 @@ bool is_directory(const std::string& path); std::u32string utf8_to_utf32(const std::string& utf8_str); std::string utf32_to_utf8(const std::u32string& utf32_str); std::u32string unicode_value_to_utf32(int unicode_value); -// std::string sd_basename(const std::string& path); sd::Image tensor_to_sd_image(const sd::Tensor& tensor, int frame_index = 0); @@ -88,9 +90,6 @@ bool parse_strict_float(const std::string& text, float& value); bool parse_strict_int(const std::string& text, int& value); bool parse_strict_bool(const std::string& text, bool& value); -void log_printf(sd_log_level_t level, const char* file, int line, const char* format, ...); -void sd_ggml_log_callback(ggml_log_level level, const char* text, void*); - ggml_type sd_type_to_ggml_type(sd_type_t sdtype); bool validate_tensor_types(sd_type_t type, const char* tensor_type_rules); @@ -106,9 +105,4 @@ void* sd_get_backend_eval_callback_data(); // test if the backend is a specific one, e.g. "CUDA", "ROCm", "Vulkan" etc. bool sd_backend_is(ggml_backend_t backend, const std::string& name); -#define LOG_DEBUG(format, ...) log_printf(SD_LOG_DEBUG, __FILE__, __LINE__, format, ##__VA_ARGS__) -#define LOG_VERBOSE(format, ...) log_printf(SD_LOG_VERBOSE, __FILE__, __LINE__, format, ##__VA_ARGS__) -#define LOG_INFO(format, ...) log_printf(SD_LOG_INFO, __FILE__, __LINE__, format, ##__VA_ARGS__) -#define LOG_WARN(format, ...) log_printf(SD_LOG_WARN, __FILE__, __LINE__, format, ##__VA_ARGS__) -#define LOG_ERROR(format, ...) log_printf(SD_LOG_ERROR, __FILE__, __LINE__, format, ##__VA_ARGS__) #endif // __SD_CORE_UTIL_H__ diff --git a/src/dgl/run_events.cpp b/src/dgl/run_events.cpp index 5e511b0de..4d36573fc 100644 --- a/src/dgl/run_events.cpp +++ b/src/dgl/run_events.cpp @@ -1,8 +1,8 @@ #include "run_events.h" -#include #include +#include "core/util.h" #include "diagnostic.h" #include "ggml.h" @@ -43,16 +43,34 @@ namespace sd::dgl { if (run.cancelled()) return; const sd_loading_progress_t loading{bytes, seconds}; - if (run.uses_console_progress() && completed > 0) { + if (run.uses_console_progress() && completed > 0 && !compact_segment_logs()) { pretty_console_bytes_progress(completed, total, loading.bytes_processed, loading.elapsed_seconds); run.progress_line_open_ = completed > 0 && completed < total; } run.emit({"loading", "", "tensors", completed, total, &loading}); } - void RunEvents::render_step(int completed, int total, float seconds) { + void RunEvents::report_segments(const SegmentProgress* progress, const SegmentSummary* summary, void* data) { + auto& run = *static_cast(data); + if (summary) { + if (run.reported_segment_models_.emplace(progress->model).second) { + constexpr double mib = 1024.0 * 1024.0; + LOG_VERBOSE( + "%s segmented execution (first graph, %zu segments), " + "%.2f MiB read from model files, %.2f MiB uploaded", + progress->model, progress->total, summary->file_bytes / mib, summary->upload_bytes / mib); + } + return; + } + const auto& sampling = run.sampling_line_; + if (run.uses_console_progress() && + render_segment_progress(progress, sampling.completed < sampling.total ? &sampling : nullptr)) + run.progress_line_open_ = false; + } + + void RunEvents::render_step(int completed, int total, float seconds, ConsoleProgressLine* line) { if (uses_console_progress()) { - pretty_console_progress(completed, total, seconds); + pretty_console_progress(completed, total, seconds, line); progress_line_open_ = completed > 0 && completed < total; } } @@ -68,7 +86,7 @@ namespace sd::dgl { check_cancelled(); finish_progress_line(); ++sample_pass_; - render_step(0, total_steps, 0.f); + render_step(0, total_steps, 0.f, &sampling_line_); const sd_sampling_progress_t sampling{sample_pass_, 0.f, {}, {}}; emit({"sampling", "", "steps", 0, total_steps, &sampling}); check_cancelled(); @@ -81,18 +99,20 @@ namespace sd::dgl { const auto noisy = std::exchange(noisy_, {}); const sd_sampling_progress_t sampling{ sample_pass_, (ggml_time_us() - last_progress_us_) / 1000000.f, denoised.view(), noisy.view()}; - render_step(completed, total_steps, sampling.step_seconds); + render_step(completed, total_steps, sampling.step_seconds, &sampling_line_); emit({"sampling", "", "steps", completed, total_steps, &sampling}); check_cancelled(); last_progress_us_ = ggml_time_us(); } void RunEvents::finish_progress_line() { - if (progress_line_open_) { - std::fputc('\n', stdout); - std::fflush(stdout); - progress_line_open_ = false; + if (sampling_line_.completed < sampling_line_.total) { + finish_console_sampling(progress_line_open_); + } else if (progress_line_open_) { + console_progress_newline(); } + sampling_line_ = {}; + progress_line_open_ = false; } void RunEvents::set_preview(const std::vector& images, bool noisy) { @@ -111,7 +131,10 @@ namespace sd::dgl { RunEventsScope::RunEventsScope(RunEvents& events) : previous_(active_events), - progress_({RunEvents::report_tiles, RunEvents::report_loading, &events}) { + progress_({RunEvents::report_tiles, + RunEvents::report_loading, + RunEvents::report_segments, + &events}) { active_events = &events; } RunEventsScope::~RunEventsScope() { diff --git a/src/dgl/run_events.h b/src/dgl/run_events.h index 6ce927054..dd7337a55 100644 --- a/src/dgl/run_events.h +++ b/src/dgl/run_events.h @@ -2,8 +2,11 @@ #define __SD_DGL_RUN_EVENTS_H__ #include +#include +#include #include "api/tensor.h" +#include "core/console_output.h" #include "core/option_types.h" #include "core/progress.h" @@ -36,12 +39,15 @@ namespace sd::dgl { int64_t last_progress_us_ = 0; bool executing_reported_ = false; bool progress_line_open_ = false; + ConsoleProgressLine sampling_line_; + std::set reported_segment_models_; bool uses_console_progress() const { return !callbacks_.progress || callbacks_.console_progress; } void emit(const sd_generation_progress_t& progress) const; - void render_step(int completed, int total, float seconds); + void render_step(int completed, int total, float seconds, ConsoleProgressLine* line = nullptr); static void report_tiles(int completed, int total, float seconds, void* data); static void report_loading(int completed, int total, uint64_t bytes, float seconds, void* data); + static void report_segments(const SegmentProgress* progress, const SegmentSummary* summary, void* data); friend class RunEventsScope; public: diff --git a/src/model_loader.cpp b/src/model_loader.cpp index 6eee683bb..442bd12c5 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -1148,6 +1148,9 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, } process_model_files(enable_mmap, false); + const bool compact_logs = sd::compact_segment_logs(); + const auto transfer_stats = sd::segment_transfer_stats(); + const auto log_level = compact_logs ? SD_LOG_DEBUG : SD_LOG_INFO; std::atomic read_time_ms(0); std::atomic memcpy_time_ms(0); std::atomic copy_to_backend_time_ms(0); @@ -1206,10 +1209,8 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, } sd::require_file_access(file_path, SD_DGL_FILE_READ_MODEL); if (log_progress) { - LOG_INFO("loading %zu/%zu tensors from %s", - tensors_to_process.size(), - file_tensors.size(), - file_path.c_str()); + log_printf(log_level, __FILE__, __LINE__, "loading %zu/%zu tensors from %s", + tensors_to_process.size(), file_tensors.size(), file_path.c_str()); } bool is_zip = fdata.is_zip; @@ -1419,6 +1420,8 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, std::lock_guard lock(backend_tensor_set_mutex); ggml_backend_tensor_set(dst_tensor, convert_buf, 0, ggml_nbytes(dst_tensor)); + if (transfer_stats) + transfer_stats->upload_bytes.fetch_add(ggml_nbytes(dst_tensor), std::memory_order_relaxed); t1 = ggml_time_ms(); copy_to_backend_time_ms.fetch_add(t1 - t0); @@ -1461,19 +1464,22 @@ bool ModelLoader::load_tensors(on_new_tensor_cb_t on_new_tensor_cb, bytes_processed.load(), (ggml_time_ms() - t_start) / 1000.0f); } - if (log_progress && total_tensors_processed < total_tensors_to_process && total_tensors_to_process > 0) { - printf("\n"); + if (log_progress && !compact_logs && total_tensors_processed < total_tensors_to_process && total_tensors_to_process > 0) { + sd::console_progress_newline(); } } int64_t end_time = ggml_time_ms(); + if (transfer_stats) + transfer_stats->file_bytes.fetch_add(bytes_processed.load(), std::memory_order_relaxed); if (log_progress) { - LOG_INFO("loading tensors completed, taking %.2fs (read: %.2fs, memcpy: %.2fs, convert: %.2fs, copy_to_backend: %.2fs)", - (end_time - start_time) / 1000.f, - (read_time_ms.load() / (float)last_n_threads) / 1000.f, - (memcpy_time_ms.load() / (float)last_n_threads) / 1000.f, - (convert_time_ms.load() / (float)last_n_threads) / 1000.f, - (copy_to_backend_time_ms.load() / (float)last_n_threads) / 1000.f); + log_printf(log_level, __FILE__, __LINE__, + "loading tensors completed, taking %.2fs (read: %.2fs, memcpy: %.2fs, convert: %.2fs, copy_to_backend: %.2fs)", + (end_time - start_time) / 1000.f, + (read_time_ms.load() / (float)last_n_threads) / 1000.f, + (memcpy_time_ms.load() / (float)last_n_threads) / 1000.f, + (convert_time_ms.load() / (float)last_n_threads) / 1000.f, + (copy_to_backend_time_ms.load() / (float)last_n_threads) / 1000.f); } return success && validate_sources(target_tensor_names); } diff --git a/src/model_manager.cpp b/src/model_manager.cpp index 36664ee4c..a4855436e 100644 --- a/src/model_manager.cpp +++ b/src/model_manager.cpp @@ -753,11 +753,12 @@ bool ModelManager::load_tensors_to_params_backend(const std::vector shared_groups; @@ -1111,10 +1112,12 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vectorparam_source() != ParamSource::ModelFile || reusable_lora_weight(*state)) continue; - if (const auto* source = prefetched_file_tensor(prefetch_owner, *state)) + if (const auto* source = prefetched_file_tensor(prefetch_owner, *state)) { ggml_backend_tensor_copy(source, staging_tensor); - else + sd::record_weight_upload(source, staging_tensor); + } else { file_reads.push_back(read_target(*state, staging_tensor)); + } } if (!file_reads.empty() && !sd::weights::read_weights(file_reads)) { ggml_backend_buffer_free(compute_buffer); @@ -1131,9 +1134,11 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vectortensor, staging_tensor); + sd::record_weight_upload(&cached->tensor, staging_tensor); epoch = cached->lora_epoch; } else if (state->param_source() != ParamSource::ModelFile) { ggml_backend_tensor_copy(managed_tensor, staging_tensor); + sd::record_weight_upload(managed_tensor, staging_tensor); epoch = state->storage_epoch(); } std::swap(managed_tensor->buffer, staging_tensor->buffer); @@ -1182,12 +1187,11 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector& states, for (auto* state : states) { if (!state) continue; - if (const auto* source = writable.count(state) ? prefetched_file_tensor(prefetch_owner, *state) : nullptr) + if (const auto* source = writable.count(state) ? prefetched_file_tensor(prefetch_owner, *state) : nullptr) { ggml_backend_tensor_copy(source, state->tensor); - else + sd::record_weight_upload(source, state->tensor); + } else { targets.push_back(read_target(*state, state->tensor)); + } } if (!sd::weights::read_weights(targets)) return false; diff --git a/src/model_manager_prefetch.cpp b/src/model_manager_prefetch.cpp index b85ae1932..b573a7874 100644 --- a/src/model_manager_prefetch.cpp +++ b/src/model_manager_prefetch.cpp @@ -404,7 +404,8 @@ std::unique_ptr ModelManager::prepare_file_prefetch( const bool restrict_access = sd::active_file_access.callback != nullptr; auto read = [this, job = file.get(), readers = std::move(readers), sources = std::move(sources), targets = std::move(targets), paths = std::move(authorized_paths), restrict_access, - copies = std::move(copies)]() mutable { + copies = std::move(copies), stats = sd::segment_transfer_stats()]() mutable { + const sd::SegmentTransferScope transfer_scope(std::move(stats)); // Only the execution thread calls the application policy. The worker checks those paths. const sd::FileAccessPolicy authorized{ [](const char* path, sd_dgl_file_access_t access, void* data) { diff --git a/src/weights/weight_reader.cpp b/src/weights/weight_reader.cpp index bc0dcc56a..e70a8687f 100644 --- a/src/weights/weight_reader.cpp +++ b/src/weights/weight_reader.cpp @@ -7,6 +7,8 @@ #include #include +#include "core/progress.h" + namespace sd::weights { namespace { using ReadGroup = std::tuple; @@ -36,8 +38,10 @@ namespace sd::weights { auto* first = entry.second.front(); for (auto* tensor : entry.second) { // File mappings already contain the weight and may be read-only. - if (tensor != first && !loader->is_mmap_buffer(tensor->buffer)) + if (tensor != first && !loader->is_mmap_buffer(tensor->buffer)) { ggml_backend_tensor_copy(first, tensor); + record_weight_upload(first, tensor); + } } } return true; @@ -69,6 +73,8 @@ namespace sd::weights { if (!read_batch({target.loader, target.file, target.version, target.use_mmap}, batch, false)) return false; ggml_backend_tensor_set(target.destination, buffer.data(), 0, size); + if (const auto& stats = segment_transfer_stats()) + stats->upload_bytes.fetch_add(size, std::memory_order_relaxed); return true; } } diff --git a/src/weights/weight_transfer.cpp b/src/weights/weight_transfer.cpp index 7d54ae740..d526246ba 100644 --- a/src/weights/weight_transfer.cpp +++ b/src/weights/weight_transfer.cpp @@ -29,6 +29,7 @@ namespace sd::weights { } else { ggml_backend_tensor_copy_async(copy.source_backend, queue, const_cast(copy.source), copy.destination); } + record_weight_upload(copy.source, copy.destination); } ggml_backend_t WeightTransfer::queue_for(ggml_backend_t compute_backend) { @@ -117,6 +118,7 @@ namespace sd::weights { used += GGML_PAD(chunk, copy_alignment); offset += chunk; } + record_weight_upload(copy.source, copy.destination); } // The last batch event protects both the slot and the destination tensors. pending.event = finish_batch();