preset.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. #include "arg.h"
  2. #include "preset.h"
  3. #include "peg-parser.h"
  4. #include "log.h"
  5. #include "download.h"
  6. #include <fstream>
  7. #include <sstream>
  8. #include <filesystem>
  9. static std::string rm_leading_dashes(const std::string & str) {
  10. size_t pos = 0;
  11. while (pos < str.size() && str[pos] == '-') {
  12. ++pos;
  13. }
  14. return str.substr(pos);
  15. }
  16. // only allow a subset of args for remote presets for security reasons
  17. // do not add more args unless absolutely necessary
  18. // args that output to files are strictly prohibited
  19. static std::set<std::string> get_remote_preset_whitelist(const std::map<std::string, common_arg> & key_to_opt) {
  20. static const std::set<std::string> allowed_options = {
  21. "model-url",
  22. "hf-repo",
  23. "hf-repo-draft",
  24. "hf-repo-v", // vocoder
  25. "hf-file-v", // vocoder
  26. "mmproj-url",
  27. "pooling",
  28. "jinja",
  29. "batch-size",
  30. "ubatch-size",
  31. "cache-reuse",
  32. // note: sampling params are automatically allowed by default
  33. // negated args will be added automatically
  34. };
  35. std::set<std::string> allowed_keys;
  36. for (const auto & it : key_to_opt) {
  37. const std::string & key = it.first;
  38. const common_arg & opt = it.second;
  39. if (allowed_options.find(key) != allowed_options.end() || opt.is_sparam) {
  40. allowed_keys.insert(key);
  41. // also add variant keys (args without leading dashes and env vars)
  42. for (const auto & arg : opt.get_args()) {
  43. allowed_keys.insert(rm_leading_dashes(arg));
  44. }
  45. for (const auto & env : opt.get_env()) {
  46. allowed_keys.insert(env);
  47. }
  48. }
  49. }
  50. return allowed_keys;
  51. }
  52. std::vector<std::string> common_preset::to_args(const std::string & bin_path) const {
  53. std::vector<std::string> args;
  54. if (!bin_path.empty()) {
  55. args.push_back(bin_path);
  56. }
  57. for (const auto & [opt, value] : options) {
  58. if (opt.is_preset_only) {
  59. continue; // skip preset-only options (they are not CLI args)
  60. }
  61. // use the last arg as the main arg (i.e. --long-form)
  62. args.push_back(opt.args.back());
  63. // handle value(s)
  64. if (opt.value_hint == nullptr && opt.value_hint_2 == nullptr) {
  65. // flag option, no value
  66. if (common_arg_utils::is_falsey(value)) {
  67. // use negative arg if available
  68. if (!opt.args_neg.empty()) {
  69. args.back() = opt.args_neg.back();
  70. } else {
  71. // otherwise, skip the flag
  72. // TODO: maybe throw an error instead?
  73. args.pop_back();
  74. }
  75. }
  76. }
  77. if (opt.value_hint != nullptr) {
  78. // single value
  79. args.push_back(value);
  80. }
  81. if (opt.value_hint != nullptr && opt.value_hint_2 != nullptr) {
  82. throw std::runtime_error(string_format(
  83. "common_preset::to_args(): option '%s' has two values, which is not supported yet",
  84. opt.args.back()
  85. ));
  86. }
  87. }
  88. return args;
  89. }
  90. std::string common_preset::to_ini() const {
  91. std::ostringstream ss;
  92. ss << "[" << name << "]\n";
  93. for (const auto & [opt, value] : options) {
  94. auto espaced_value = value;
  95. string_replace_all(espaced_value, "\n", "\\\n");
  96. ss << rm_leading_dashes(opt.args.back()) << " = ";
  97. ss << espaced_value << "\n";
  98. }
  99. ss << "\n";
  100. return ss.str();
  101. }
  102. void common_preset::set_option(const common_preset_context & ctx, const std::string & env, const std::string & value) {
  103. // try if option exists, update it
  104. for (auto & [opt, val] : options) {
  105. if (opt.env && env == opt.env) {
  106. val = value;
  107. return;
  108. }
  109. }
  110. // if option does not exist, we need to add it
  111. if (ctx.key_to_opt.find(env) == ctx.key_to_opt.end()) {
  112. throw std::runtime_error(string_format(
  113. "%s: option with env '%s' not found in ctx_params",
  114. __func__, env.c_str()
  115. ));
  116. }
  117. options[ctx.key_to_opt.at(env)] = value;
  118. }
  119. void common_preset::unset_option(const std::string & env) {
  120. for (auto it = options.begin(); it != options.end(); ) {
  121. const common_arg & opt = it->first;
  122. if (opt.env && env == opt.env) {
  123. it = options.erase(it);
  124. return;
  125. } else {
  126. ++it;
  127. }
  128. }
  129. }
  130. bool common_preset::get_option(const std::string & env, std::string & value) const {
  131. for (const auto & [opt, val] : options) {
  132. if (opt.env && env == opt.env) {
  133. value = val;
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. void common_preset::merge(const common_preset & other) {
  140. for (const auto & [opt, val] : other.options) {
  141. options[opt] = val; // overwrite existing options
  142. }
  143. }
  144. void common_preset::apply_to_params(common_params & params) const {
  145. for (const auto & [opt, val] : options) {
  146. // apply each option to params
  147. if (opt.handler_string) {
  148. opt.handler_string(params, val);
  149. } else if (opt.handler_int) {
  150. opt.handler_int(params, std::stoi(val));
  151. } else if (opt.handler_bool) {
  152. opt.handler_bool(params, common_arg_utils::is_truthy(val));
  153. } else if (opt.handler_str_str) {
  154. // not supported yet
  155. throw std::runtime_error(string_format(
  156. "%s: option with two values is not supported yet",
  157. __func__
  158. ));
  159. } else if (opt.handler_void) {
  160. opt.handler_void(params);
  161. } else {
  162. GGML_ABORT("unknown handler type");
  163. }
  164. }
  165. }
  166. static std::map<std::string, std::map<std::string, std::string>> parse_ini_from_file(const std::string & path) {
  167. std::map<std::string, std::map<std::string, std::string>> parsed;
  168. if (!std::filesystem::exists(path)) {
  169. throw std::runtime_error("preset file does not exist: " + path);
  170. }
  171. std::ifstream file(path);
  172. if (!file.good()) {
  173. throw std::runtime_error("failed to open server preset file: " + path);
  174. }
  175. std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  176. static const auto parser = build_peg_parser([](auto & p) {
  177. // newline ::= "\r\n" / "\n" / "\r"
  178. auto newline = p.rule("newline", p.literal("\r\n") | p.literal("\n") | p.literal("\r"));
  179. // ws ::= [ \t]*
  180. auto ws = p.rule("ws", p.chars("[ \t]", 0, -1));
  181. // comment ::= [;#] (!newline .)*
  182. auto comment = p.rule("comment", p.chars("[;#]", 1, 1) + p.zero_or_more(p.negate(newline) + p.any()));
  183. // eol ::= ws comment? (newline / EOF)
  184. auto eol = p.rule("eol", ws + p.optional(comment) + (newline | p.end()));
  185. // ident ::= [a-zA-Z_] [a-zA-Z0-9_.-]*
  186. auto ident = p.rule("ident", p.chars("[a-zA-Z_]", 1, 1) + p.chars("[a-zA-Z0-9_.-]", 0, -1));
  187. // value ::= (!eol-start .)*
  188. auto eol_start = p.rule("eol-start", ws + (p.chars("[;#]", 1, 1) | newline | p.end()));
  189. auto value = p.rule("value", p.zero_or_more(p.negate(eol_start) + p.any()));
  190. // header-line ::= "[" ws ident ws "]" eol
  191. auto header_line = p.rule("header-line", "[" + ws + p.tag("section-name", p.chars("[^]]")) + ws + "]" + eol);
  192. // kv-line ::= ident ws "=" ws value eol
  193. auto kv_line = p.rule("kv-line", p.tag("key", ident) + ws + "=" + ws + p.tag("value", value) + eol);
  194. // comment-line ::= ws comment (newline / EOF)
  195. auto comment_line = p.rule("comment-line", ws + comment + (newline | p.end()));
  196. // blank-line ::= ws (newline / EOF)
  197. auto blank_line = p.rule("blank-line", ws + (newline | p.end()));
  198. // line ::= header-line / kv-line / comment-line / blank-line
  199. auto line = p.rule("line", header_line | kv_line | comment_line | blank_line);
  200. // ini ::= line* EOF
  201. auto ini = p.rule("ini", p.zero_or_more(line) + p.end());
  202. return ini;
  203. });
  204. common_peg_parse_context ctx(contents);
  205. const auto result = parser.parse(ctx);
  206. if (!result.success()) {
  207. throw std::runtime_error("failed to parse server config file: " + path);
  208. }
  209. std::string current_section = COMMON_PRESET_DEFAULT_NAME;
  210. std::string current_key;
  211. ctx.ast.visit(result, [&](const auto & node) {
  212. if (node.tag == "section-name") {
  213. const std::string section = std::string(node.text);
  214. current_section = section;
  215. parsed[current_section] = {};
  216. } else if (node.tag == "key") {
  217. const std::string key = std::string(node.text);
  218. current_key = key;
  219. } else if (node.tag == "value" && !current_key.empty() && !current_section.empty()) {
  220. parsed[current_section][current_key] = std::string(node.text);
  221. current_key.clear();
  222. }
  223. });
  224. return parsed;
  225. }
  226. static std::map<std::string, common_arg> get_map_key_opt(common_params_context & ctx_params) {
  227. std::map<std::string, common_arg> mapping;
  228. for (const auto & opt : ctx_params.options) {
  229. for (const auto & env : opt.get_env()) {
  230. mapping[env] = opt;
  231. }
  232. for (const auto & arg : opt.get_args()) {
  233. mapping[rm_leading_dashes(arg)] = opt;
  234. }
  235. }
  236. return mapping;
  237. }
  238. static bool is_bool_arg(const common_arg & arg) {
  239. return !arg.args_neg.empty();
  240. }
  241. static std::string parse_bool_arg(const common_arg & arg, const std::string & key, const std::string & value) {
  242. // if this is a negated arg, we need to reverse the value
  243. for (const auto & neg_arg : arg.args_neg) {
  244. if (rm_leading_dashes(neg_arg) == key) {
  245. return common_arg_utils::is_truthy(value) ? "false" : "true";
  246. }
  247. }
  248. // otherwise, not negated
  249. return value;
  250. }
  251. common_preset_context::common_preset_context(llama_example ex, bool only_remote_allowed)
  252. : ctx_params(common_params_parser_init(default_params, ex)) {
  253. common_params_add_preset_options(ctx_params.options);
  254. key_to_opt = get_map_key_opt(ctx_params);
  255. // setup allowed keys if only_remote_allowed is true
  256. if (only_remote_allowed) {
  257. filter_allowed_keys = true;
  258. allowed_keys = get_remote_preset_whitelist(key_to_opt);
  259. }
  260. }
  261. common_presets common_preset_context::load_from_ini(const std::string & path, common_preset & global) const {
  262. common_presets out;
  263. auto ini_data = parse_ini_from_file(path);
  264. for (auto section : ini_data) {
  265. common_preset preset;
  266. if (section.first.empty()) {
  267. preset.name = COMMON_PRESET_DEFAULT_NAME;
  268. } else {
  269. preset.name = section.first;
  270. }
  271. LOG_DBG("loading preset: %s\n", preset.name.c_str());
  272. for (const auto & [key, value] : section.second) {
  273. LOG_DBG("option: %s = %s\n", key.c_str(), value.c_str());
  274. if (filter_allowed_keys && allowed_keys.find(key) == allowed_keys.end()) {
  275. throw std::runtime_error(string_format(
  276. "option '%s' is not allowed in remote presets",
  277. key.c_str()
  278. ));
  279. }
  280. if (key_to_opt.find(key) != key_to_opt.end()) {
  281. const auto & opt = key_to_opt.at(key);
  282. if (is_bool_arg(opt)) {
  283. preset.options[opt] = parse_bool_arg(opt, key, value);
  284. } else {
  285. preset.options[opt] = value;
  286. }
  287. LOG_DBG("accepted option: %s = %s\n", key.c_str(), preset.options[opt].c_str());
  288. } else {
  289. // TODO: maybe warn about unknown key?
  290. }
  291. }
  292. if (preset.name == "*") {
  293. // handle global preset
  294. global = preset;
  295. } else {
  296. out[preset.name] = preset;
  297. }
  298. }
  299. return out;
  300. }
  301. common_presets common_preset_context::load_from_cache() const {
  302. common_presets out;
  303. auto cached_models = common_list_cached_models();
  304. for (const auto & model : cached_models) {
  305. common_preset preset;
  306. preset.name = model.to_string();
  307. preset.set_option(*this, "LLAMA_ARG_HF_REPO", model.to_string());
  308. out[preset.name] = preset;
  309. }
  310. return out;
  311. }
  312. struct local_model {
  313. std::string name;
  314. std::string path;
  315. std::string path_mmproj;
  316. };
  317. common_presets common_preset_context::load_from_models_dir(const std::string & models_dir) const {
  318. if (!std::filesystem::exists(models_dir) || !std::filesystem::is_directory(models_dir)) {
  319. throw std::runtime_error(string_format("error: '%s' does not exist or is not a directory\n", models_dir.c_str()));
  320. }
  321. std::vector<local_model> models;
  322. auto scan_subdir = [&models](const std::string & subdir_path, const std::string & name) {
  323. auto files = fs_list(subdir_path, false);
  324. common_file_info model_file;
  325. common_file_info first_shard_file;
  326. common_file_info mmproj_file;
  327. for (const auto & file : files) {
  328. if (string_ends_with(file.name, ".gguf")) {
  329. if (file.name.find("mmproj") != std::string::npos) {
  330. mmproj_file = file;
  331. } else if (file.name.find("-00001-of-") != std::string::npos) {
  332. first_shard_file = file;
  333. } else {
  334. model_file = file;
  335. }
  336. }
  337. }
  338. // single file model
  339. local_model model{
  340. /* name */ name,
  341. /* path */ first_shard_file.path.empty() ? model_file.path : first_shard_file.path,
  342. /* path_mmproj */ mmproj_file.path // can be empty
  343. };
  344. if (!model.path.empty()) {
  345. models.push_back(model);
  346. }
  347. };
  348. auto files = fs_list(models_dir, true);
  349. for (const auto & file : files) {
  350. if (file.is_dir) {
  351. scan_subdir(file.path, file.name);
  352. } else if (string_ends_with(file.name, ".gguf")) {
  353. // single file model
  354. std::string name = file.name;
  355. string_replace_all(name, ".gguf", "");
  356. local_model model{
  357. /* name */ name,
  358. /* path */ file.path,
  359. /* path_mmproj */ ""
  360. };
  361. models.push_back(model);
  362. }
  363. }
  364. // convert local models to presets
  365. common_presets out;
  366. for (const auto & model : models) {
  367. common_preset preset;
  368. preset.name = model.name;
  369. preset.set_option(*this, "LLAMA_ARG_MODEL", model.path);
  370. if (!model.path_mmproj.empty()) {
  371. preset.set_option(*this, "LLAMA_ARG_MMPROJ", model.path_mmproj);
  372. }
  373. out[preset.name] = preset;
  374. }
  375. return out;
  376. }
  377. common_preset common_preset_context::load_from_args(int argc, char ** argv) const {
  378. common_preset preset;
  379. preset.name = COMMON_PRESET_DEFAULT_NAME;
  380. bool ok = common_params_to_map(argc, argv, ctx_params.ex, preset.options);
  381. if (!ok) {
  382. throw std::runtime_error("failed to parse CLI arguments into preset");
  383. }
  384. return preset;
  385. }
  386. common_presets common_preset_context::cascade(const common_presets & base, const common_presets & added) const {
  387. common_presets out = base; // copy
  388. for (const auto & [name, preset_added] : added) {
  389. if (out.find(name) != out.end()) {
  390. // if exists, merge
  391. common_preset & target = out[name];
  392. target.merge(preset_added);
  393. } else {
  394. // otherwise, add directly
  395. out[name] = preset_added;
  396. }
  397. }
  398. return out;
  399. }
  400. common_presets common_preset_context::cascade(const common_preset & base, const common_presets & presets) const {
  401. common_presets out;
  402. for (const auto & [name, preset] : presets) {
  403. common_preset tmp = base; // copy
  404. tmp.name = name;
  405. tmp.merge(preset);
  406. out[name] = std::move(tmp);
  407. }
  408. return out;
  409. }