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
1 change: 1 addition & 0 deletions examples/cli/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ add_executable(${TARGET}
../common/media_io.cpp
main.cpp
dgl.cpp
dgl_args.cpp
media_input.cpp
)
if(APPLE)
Expand Down
15 changes: 15 additions & 0 deletions examples/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ before execution at debug level (`--log-level debug`).

Run a [DGL program](../../docs/dgl.md) with `sd-cli -M dgl --script program.dgl`.
DGL mode accepts the same logging options and sends logs to stderr.

Use `--dgl-arg NAME=VALUE` to override a variable declared in the script's
`var` block for one invocation. Repeat the option for different variables.

```sh
sd-cli -M dgl --script workflow.dgl --dgl-arg seed=123 --dgl-arg 'prompt=a mountain lake' --dgl-arg 'size=[768,1024]'
```

Strings use the text passed by the shell, so `--dgl-arg prompt=` sets an empty
string. Other values use DGL literal syntax and must match the default's type.
For example, use `7.0` for a floating-point value and `'{width=768, height=1024}'`
for a dictionary. Lists and dictionaries are replaced in full. Unknown and
duplicate variable names are errors. `--check` validates the script with the
same overrides used for execution.

Weight loading displays a progress bar with transfer speed; sampling displays
its step progress. Context progress callbacks remain active during loading.
`--run-once on|off` controls model release after last use and defaults to `on`.
Expand Down
25 changes: 23 additions & 2 deletions examples/cli/dgl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ ArgOptions DGLModeParams::get_options() {
{"", "--list-builtins", "print the DGL built-in catalog", true, &list_builtins},
};
options.manual_options = {
{"", "--dgl-arg", "override a DGL var value (NAME=VALUE, repeatable)",
[this](int argc, const char** argv, int index) {
const auto arg = index + 1 < argc ? argv_to_utf8(index + 1, argv) : std::string{};
const auto equal = arg.find('=');
if (equal == std::string::npos || equal == 0) {
LOG_ERROR("--dgl-arg requires NAME=VALUE");
return -1;
}
const auto name = arg.substr(0, equal);
if (!script_args.emplace(name, arg.substr(equal + 1)).second) {
LOG_ERROR("duplicate --dgl-arg '%s'", name.c_str());
return -1;
}
return 1;
}},
{"", "--run-once", "on|off (default: on). Release DGL models after their last use when on",
[this](int argc, const char** argv, int index) {
const std::string_view value = index + 1 < argc ? argv[index + 1] : "";
Expand All @@ -46,10 +61,14 @@ ArgOptions DGLModeParams::get_options() {

bool DGLModeParams::has_options() const {
return !script_path.empty() || !write_builtins_path.empty() || !check_builtins_path.empty() ||
!tensor_paths.empty() || !max_ram.empty() || check_only || run_once.has_value() || list_builtins;
!tensor_paths.empty() || !script_args.empty() || !max_ram.empty() || check_only || run_once.has_value() || list_builtins;
}

bool DGLModeParams::validate() const {
if (script_path.empty() && !script_args.empty()) {
LOG_ERROR("--dgl-arg requires --script");
return false;
}
const int actions = int(!script_path.empty()) + int(!write_builtins_path.empty()) + int(!check_builtins_path.empty()) + int(list_builtins);
if (actions != 1) {
LOG_ERROR("DGL mode requires exactly one of --script, --list-builtins, --write-builtins and --check-builtins");
Expand Down Expand Up @@ -96,7 +115,9 @@ int DGLModeParams::run(const SDContextParams& options, bool embed_metadata) cons
std::ifstream file(path, std::ios::binary);
if (!file)
throw std::runtime_error("cannot open program file");
const std::string source{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
std::string source{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
if (!script_args.empty())
apply_dgl_args(source, script_args);
if (check_only) {
check_dgl(sd_dgl_check(source.c_str(), false) == SD_STATUS_OK);
std::cout << "DGL syntax and types are valid. Models were not loaded.\n";
Expand Down
6 changes: 6 additions & 0 deletions examples/cli/dgl.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef __EXAMPLES_CLI_DGL_H__
#define __EXAMPLES_CLI_DGL_H__

#include <map>
#include <optional>
#include <string>
#include <utility>
Expand All @@ -9,12 +10,17 @@
struct ArgOptions;
struct SDContextParams;

using DGLScriptArgs = std::map<std::string, std::string, std::less<>>;

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

struct DGLModeParams {
std::string script_path;
std::string write_builtins_path;
std::string check_builtins_path;
std::string max_ram;
std::vector<std::pair<std::string, std::string>> tensor_paths;
DGLScriptArgs script_args;
bool check_only = false;
std::optional<bool> run_once;
bool list_builtins = false;
Expand Down
234 changes: 234 additions & 0 deletions examples/cli/dgl_args.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
#include "dgl.h"

#include <cctype>
#include <set>
#include <stdexcept>
#include <string_view>

#include "json.hpp"

namespace {

bool is_name_start(char c) {
return std::isalpha(static_cast<unsigned char>(c)) || c == '_';
}

bool is_digit(char c) {
return c >= '0' && c <= '9';
}

struct Literal {
size_t begin;
size_t end;
std::string_view type;
};

// Scan value boundaries for substitution. The DGL compiler validates each value's grammar.
class VarScanner {
std::string_view source_;
size_t offset_;

char current() const {
return offset_ < source_.size() ? source_[offset_] : '\0';
}

char peek() {
while (offset_ < source_.size()) {
if (std::isspace(static_cast<unsigned char>(current()))) {
++offset_;
} else if (current() == '#' || source_.substr(offset_, 2) == "//") {
const auto newline = source_.find('\n', offset_);
offset_ = newline == std::string_view::npos ? source_.size() : newline;
} else {
break;
}
}
return current();
}

void skip_string() {
++offset_;
while (offset_ < source_.size()) {
const char c = source_[offset_++];
if (c == '"')
return;
if (c == '\\' && offset_ < source_.size())
++offset_;
}
throw std::runtime_error("unterminated DGL string");
}

void skip_container() {
std::string closing;
do {
const char c = peek();
switch (c) {
case '[':
closing.push_back(']');
break;
case '{':
closing.push_back('}');
break;
case '(':
closing.push_back(')');
break;
case ']':
case '}':
case ')':
if (c != closing.back())
throw std::runtime_error("mismatched DGL literal delimiters");
closing.pop_back();
break;
case '"':
skip_string();
continue;
case '\0':
throw std::runtime_error("unterminated DGL literal");
default:
break;
}
++offset_;
} while (!closing.empty());
}

void digits() {
if (!is_digit(current()))
throw std::runtime_error("expected a digit in DGL number");
do {
++offset_;
} while (is_digit(current()));
}

std::string_view number() {
if (current() == '+' || current() == '-') {
++offset_;
peek();
}
digits();
bool floating = false;
if (current() == '.') {
floating = true;
++offset_;
digits();
}
if (current() == 'e' || current() == 'E') {
floating = true;
++offset_;
if (current() == '+' || current() == '-')
++offset_;
digits();
}
return floating ? "float" : "integer";
}

public:
explicit VarScanner(std::string_view source, size_t offset = 0)
: source_(source), offset_(offset) {}

bool take(char c) {
if (peek() != c)
return false;
++offset_;
return true;
}

bool done() {
peek();
return offset_ == source_.size();
}

std::string_view name() {
if (!is_name_start(peek()))
return {};
const size_t begin = offset_++;
while (is_name_start(current()) || is_digit(current()))
++offset_;
return source_.substr(begin, offset_ - begin);
}

Literal literal() {
peek();
const size_t begin = offset_;
size_t groups = 0;
while (take('('))
++groups;

const char c = peek();
std::string_view type;
if (c == '"') {
skip_string();
type = "string";
} else if (c == '[' || c == '{') {
skip_container();
type = c == '[' ? "list" : "dict";
} else if (is_digit(c) || c == '+' || c == '-') {
type = number();
} else {
const auto word = name();
if (word != "true" && word != "false")
throw std::runtime_error("expected a DGL literal");
type = "boolean";
}
for (; groups > 0; --groups) {
if (!take(')'))
throw std::runtime_error("expected ')' after DGL literal");
}
return {begin, offset_, type};
}
};

std::string override_value(const std::string& value, std::string_view type) {
if (type == "string")
return nlohmann::json(value).dump();
VarScanner scanner(value);
const auto literal = scanner.literal();
if (!scanner.done())
throw std::runtime_error("expected a single DGL literal");
if (literal.type != type)
throw std::runtime_error("expected a DGL " + std::string(type) + " literal");
return value.substr(literal.begin, literal.end - literal.begin);
}

} // namespace

void apply_dgl_args(std::string& source, const DGLScriptArgs& args) {
struct Replacement {
Literal literal;
std::string value;
};
const size_t bom = source.compare(0, 3, "\xef\xbb\xbf") == 0 ? 3 : 0;
VarScanner script(source, bom);
std::vector<Replacement> replacements;
std::set<std::string_view> matched;
if (script.name() == "var") {
if (!script.take('{'))
throw std::runtime_error("expected '{' after DGL var");
while (!script.take('}')) {
const auto name = script.name();
if (name.empty() || !script.take('='))
throw std::runtime_error("expected NAME=VALUE or '}' in DGL var block");
auto literal = script.literal();
script.take(';');

const auto arg = args.find(name);
if (arg == args.end() || !matched.insert(name).second)
continue;
try {
auto value = override_value(arg->second, literal.type);
// A closing parenthesis in the original value can separate it from the next name.
if (literal.end < source.size() && is_name_start(source[literal.end]))
value += ' ';
replacements.push_back({literal, std::move(value)});
} catch (const std::exception& error) {
throw std::runtime_error("invalid --dgl-arg '" + arg->first + "': " + error.what());
}
}
}
for (const auto& arg : args) {
if (!matched.count(arg.first))
throw std::runtime_error("unknown --dgl-arg '" + arg.first + "' in DGL var block");
}
for (auto it = replacements.rbegin(); it != replacements.rend(); ++it) {
source.replace(it->literal.begin, it->literal.end - it->literal.begin, it->value);
}
}
Loading