preset.cpp 13 KB

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