preset.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. std::vector<std::string> common_preset::to_args(const std::string & bin_path) const {
  17. std::vector<std::string> args;
  18. if (!bin_path.empty()) {
  19. args.push_back(bin_path);
  20. }
  21. for (const auto & [opt, value] : options) {
  22. if (opt.is_preset_only) {
  23. continue; // skip preset-only options (they are not CLI args)
  24. }
  25. // use the last arg as the main arg (i.e. --long-form)
  26. args.push_back(opt.args.back());
  27. // handle value(s)
  28. if (opt.value_hint == nullptr && opt.value_hint_2 == nullptr) {
  29. // flag option, no value
  30. if (common_arg_utils::is_falsey(value)) {
  31. // use negative arg if available
  32. if (!opt.args_neg.empty()) {
  33. args.back() = opt.args_neg.back();
  34. } else {
  35. // otherwise, skip the flag
  36. // TODO: maybe throw an error instead?
  37. args.pop_back();
  38. }
  39. }
  40. }
  41. if (opt.value_hint != nullptr) {
  42. // single value
  43. args.push_back(value);
  44. }
  45. if (opt.value_hint != nullptr && opt.value_hint_2 != nullptr) {
  46. throw std::runtime_error(string_format(
  47. "common_preset::to_args(): option '%s' has two values, which is not supported yet",
  48. opt.args.back()
  49. ));
  50. }
  51. }
  52. return args;
  53. }
  54. std::string common_preset::to_ini() const {
  55. std::ostringstream ss;
  56. ss << "[" << name << "]\n";
  57. for (const auto & [opt, value] : options) {
  58. auto espaced_value = value;
  59. string_replace_all(espaced_value, "\n", "\\\n");
  60. ss << rm_leading_dashes(opt.args.back()) << " = ";
  61. ss << espaced_value << "\n";
  62. }
  63. ss << "\n";
  64. return ss.str();
  65. }
  66. void common_preset::set_option(const common_preset_context & ctx, const std::string & env, const std::string & value) {
  67. // try if option exists, update it
  68. for (auto & [opt, val] : options) {
  69. if (opt.env && env == opt.env) {
  70. val = value;
  71. return;
  72. }
  73. }
  74. // if option does not exist, we need to add it
  75. if (ctx.key_to_opt.find(env) == ctx.key_to_opt.end()) {
  76. throw std::runtime_error(string_format(
  77. "%s: option with env '%s' not found in ctx_params",
  78. __func__, env.c_str()
  79. ));
  80. }
  81. options[ctx.key_to_opt.at(env)] = value;
  82. }
  83. void common_preset::unset_option(const std::string & env) {
  84. for (auto it = options.begin(); it != options.end(); ) {
  85. const common_arg & opt = it->first;
  86. if (opt.env && env == opt.env) {
  87. it = options.erase(it);
  88. return;
  89. } else {
  90. ++it;
  91. }
  92. }
  93. }
  94. bool common_preset::get_option(const std::string & env, std::string & value) const {
  95. for (const auto & [opt, val] : options) {
  96. if (opt.env && env == opt.env) {
  97. value = val;
  98. return true;
  99. }
  100. }
  101. return false;
  102. }
  103. void common_preset::merge(const common_preset & other) {
  104. for (const auto & [opt, val] : other.options) {
  105. options[opt] = val; // overwrite existing options
  106. }
  107. }
  108. static std::map<std::string, std::map<std::string, std::string>> parse_ini_from_file(const std::string & path) {
  109. std::map<std::string, std::map<std::string, std::string>> parsed;
  110. if (!std::filesystem::exists(path)) {
  111. throw std::runtime_error("preset file does not exist: " + path);
  112. }
  113. std::ifstream file(path);
  114. if (!file.good()) {
  115. throw std::runtime_error("failed to open server preset file: " + path);
  116. }
  117. std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  118. static const auto parser = build_peg_parser([](auto & p) {
  119. // newline ::= "\r\n" / "\n" / "\r"
  120. auto newline = p.rule("newline", p.literal("\r\n") | p.literal("\n") | p.literal("\r"));
  121. // ws ::= [ \t]*
  122. auto ws = p.rule("ws", p.chars("[ \t]", 0, -1));
  123. // comment ::= [;#] (!newline .)*
  124. auto comment = p.rule("comment", p.chars("[;#]", 1, 1) + p.zero_or_more(p.negate(newline) + p.any()));
  125. // eol ::= ws comment? (newline / EOF)
  126. auto eol = p.rule("eol", ws + p.optional(comment) + (newline | p.end()));
  127. // ident ::= [a-zA-Z_] [a-zA-Z0-9_.-]*
  128. auto ident = p.rule("ident", p.chars("[a-zA-Z_]", 1, 1) + p.chars("[a-zA-Z0-9_.-]", 0, -1));
  129. // value ::= (!eol-start .)*
  130. auto eol_start = p.rule("eol-start", ws + (p.chars("[;#]", 1, 1) | newline | p.end()));
  131. auto value = p.rule("value", p.zero_or_more(p.negate(eol_start) + p.any()));
  132. // header-line ::= "[" ws ident ws "]" eol
  133. auto header_line = p.rule("header-line", "[" + ws + p.tag("section-name", p.chars("[^]]")) + ws + "]" + eol);
  134. // kv-line ::= ident ws "=" ws value eol
  135. auto kv_line = p.rule("kv-line", p.tag("key", ident) + ws + "=" + ws + p.tag("value", value) + eol);
  136. // comment-line ::= ws comment (newline / EOF)
  137. auto comment_line = p.rule("comment-line", ws + comment + (newline | p.end()));
  138. // blank-line ::= ws (newline / EOF)
  139. auto blank_line = p.rule("blank-line", ws + (newline | p.end()));
  140. // line ::= header-line / kv-line / comment-line / blank-line
  141. auto line = p.rule("line", header_line | kv_line | comment_line | blank_line);
  142. // ini ::= line* EOF
  143. auto ini = p.rule("ini", p.zero_or_more(line) + p.end());
  144. return ini;
  145. });
  146. common_peg_parse_context ctx(contents);
  147. const auto result = parser.parse(ctx);
  148. if (!result.success()) {
  149. throw std::runtime_error("failed to parse server config file: " + path);
  150. }
  151. std::string current_section = COMMON_PRESET_DEFAULT_NAME;
  152. std::string current_key;
  153. ctx.ast.visit(result, [&](const auto & node) {
  154. if (node.tag == "section-name") {
  155. const std::string section = std::string(node.text);
  156. current_section = section;
  157. parsed[current_section] = {};
  158. } else if (node.tag == "key") {
  159. const std::string key = std::string(node.text);
  160. current_key = key;
  161. } else if (node.tag == "value" && !current_key.empty() && !current_section.empty()) {
  162. parsed[current_section][current_key] = std::string(node.text);
  163. current_key.clear();
  164. }
  165. });
  166. return parsed;
  167. }
  168. static std::map<std::string, common_arg> get_map_key_opt(common_params_context & ctx_params) {
  169. std::map<std::string, common_arg> mapping;
  170. for (const auto & opt : ctx_params.options) {
  171. for (const auto & env : opt.get_env()) {
  172. mapping[env] = opt;
  173. }
  174. for (const auto & arg : opt.get_args()) {
  175. mapping[rm_leading_dashes(arg)] = opt;
  176. }
  177. }
  178. return mapping;
  179. }
  180. static bool is_bool_arg(const common_arg & arg) {
  181. return !arg.args_neg.empty();
  182. }
  183. static std::string parse_bool_arg(const common_arg & arg, const std::string & key, const std::string & value) {
  184. // if this is a negated arg, we need to reverse the value
  185. for (const auto & neg_arg : arg.args_neg) {
  186. if (rm_leading_dashes(neg_arg) == key) {
  187. return common_arg_utils::is_truthy(value) ? "false" : "true";
  188. }
  189. }
  190. // otherwise, not negated
  191. return value;
  192. }
  193. common_preset_context::common_preset_context(llama_example ex)
  194. : ctx_params(common_params_parser_init(default_params, ex)) {
  195. common_params_add_preset_options(ctx_params.options);
  196. key_to_opt = get_map_key_opt(ctx_params);
  197. }
  198. common_presets common_preset_context::load_from_ini(const std::string & path, common_preset & global) const {
  199. common_presets out;
  200. auto ini_data = parse_ini_from_file(path);
  201. for (auto section : ini_data) {
  202. common_preset preset;
  203. if (section.first.empty()) {
  204. preset.name = COMMON_PRESET_DEFAULT_NAME;
  205. } else {
  206. preset.name = section.first;
  207. }
  208. LOG_DBG("loading preset: %s\n", preset.name.c_str());
  209. for (const auto & [key, value] : section.second) {
  210. LOG_DBG("option: %s = %s\n", key.c_str(), value.c_str());
  211. if (key_to_opt.find(key) != key_to_opt.end()) {
  212. const auto & opt = key_to_opt.at(key);
  213. if (is_bool_arg(opt)) {
  214. preset.options[opt] = parse_bool_arg(opt, key, value);
  215. } else {
  216. preset.options[opt] = value;
  217. }
  218. LOG_DBG("accepted option: %s = %s\n", key.c_str(), preset.options[opt].c_str());
  219. } else {
  220. // TODO: maybe warn about unknown key?
  221. }
  222. }
  223. if (preset.name == "*") {
  224. // handle global preset
  225. global = preset;
  226. } else {
  227. out[preset.name] = preset;
  228. }
  229. }
  230. return out;
  231. }
  232. common_presets common_preset_context::load_from_cache() const {
  233. common_presets out;
  234. auto cached_models = common_list_cached_models();
  235. for (const auto & model : cached_models) {
  236. common_preset preset;
  237. preset.name = model.to_string();
  238. preset.set_option(*this, "LLAMA_ARG_HF_REPO", model.to_string());
  239. out[preset.name] = preset;
  240. }
  241. return out;
  242. }
  243. struct local_model {
  244. std::string name;
  245. std::string path;
  246. std::string path_mmproj;
  247. };
  248. common_presets common_preset_context::load_from_models_dir(const std::string & models_dir) const {
  249. if (!std::filesystem::exists(models_dir) || !std::filesystem::is_directory(models_dir)) {
  250. throw std::runtime_error(string_format("error: '%s' does not exist or is not a directory\n", models_dir.c_str()));
  251. }
  252. std::vector<local_model> models;
  253. auto scan_subdir = [&models](const std::string & subdir_path, const std::string & name) {
  254. auto files = fs_list(subdir_path, false);
  255. common_file_info model_file;
  256. common_file_info first_shard_file;
  257. common_file_info mmproj_file;
  258. for (const auto & file : files) {
  259. if (string_ends_with(file.name, ".gguf")) {
  260. if (file.name.find("mmproj") != std::string::npos) {
  261. mmproj_file = file;
  262. } else if (file.name.find("-00001-of-") != std::string::npos) {
  263. first_shard_file = file;
  264. } else {
  265. model_file = file;
  266. }
  267. }
  268. }
  269. // single file model
  270. local_model model{
  271. /* name */ name,
  272. /* path */ first_shard_file.path.empty() ? model_file.path : first_shard_file.path,
  273. /* path_mmproj */ mmproj_file.path // can be empty
  274. };
  275. if (!model.path.empty()) {
  276. models.push_back(model);
  277. }
  278. };
  279. auto files = fs_list(models_dir, true);
  280. for (const auto & file : files) {
  281. if (file.is_dir) {
  282. scan_subdir(file.path, file.name);
  283. } else if (string_ends_with(file.name, ".gguf")) {
  284. // single file model
  285. std::string name = file.name;
  286. string_replace_all(name, ".gguf", "");
  287. local_model model{
  288. /* name */ name,
  289. /* path */ file.path,
  290. /* path_mmproj */ ""
  291. };
  292. models.push_back(model);
  293. }
  294. }
  295. // convert local models to presets
  296. common_presets out;
  297. for (const auto & model : models) {
  298. common_preset preset;
  299. preset.name = model.name;
  300. preset.set_option(*this, "LLAMA_ARG_MODEL", model.path);
  301. if (!model.path_mmproj.empty()) {
  302. preset.set_option(*this, "LLAMA_ARG_MMPROJ", model.path_mmproj);
  303. }
  304. out[preset.name] = preset;
  305. }
  306. return out;
  307. }
  308. common_preset common_preset_context::load_from_args(int argc, char ** argv) const {
  309. common_preset preset;
  310. preset.name = COMMON_PRESET_DEFAULT_NAME;
  311. bool ok = common_params_to_map(argc, argv, ctx_params.ex, preset.options);
  312. if (!ok) {
  313. throw std::runtime_error("failed to parse CLI arguments into preset");
  314. }
  315. return preset;
  316. }
  317. common_presets common_preset_context::cascade(const common_presets & base, const common_presets & added) const {
  318. common_presets out = base; // copy
  319. for (const auto & [name, preset_added] : added) {
  320. if (out.find(name) != out.end()) {
  321. // if exists, merge
  322. common_preset & target = out[name];
  323. target.merge(preset_added);
  324. } else {
  325. // otherwise, add directly
  326. out[name] = preset_added;
  327. }
  328. }
  329. return out;
  330. }
  331. common_presets common_preset_context::cascade(const common_preset & base, const common_presets & presets) const {
  332. common_presets out;
  333. for (const auto & [name, preset] : presets) {
  334. common_preset tmp = base; // copy
  335. tmp.name = name;
  336. tmp.merge(preset);
  337. out[name] = std::move(tmp);
  338. }
  339. return out;
  340. }