llama-adapter.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. #include "llama-adapter.h"
  2. #include "llama-model.h"
  3. #include <algorithm>
  4. #include <map>
  5. #include <cassert>
  6. #include <stdexcept>
  7. // vec
  8. struct ggml_tensor * llama_control_vector::tensor_for(int il) const {
  9. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  10. return nullptr;
  11. }
  12. return tensors[il];
  13. }
  14. struct ggml_tensor * llama_control_vector::apply_to(struct ggml_context * ctx, struct ggml_tensor * cur, int il) const {
  15. ggml_tensor * layer_dir = tensor_for(il);
  16. if (layer_dir != nullptr) {
  17. cur = ggml_add(ctx, cur, layer_dir);
  18. }
  19. return cur;
  20. }
  21. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  22. const auto & hparams = model.hparams;
  23. GGML_ASSERT(cvec.tensors.empty());
  24. GGML_ASSERT(cvec.ctxs.empty());
  25. GGML_ASSERT(cvec.bufs.empty());
  26. // create a context for each buffer type
  27. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  28. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  29. auto it = ctx_map.find(buft);
  30. if (it == ctx_map.end()) {
  31. struct ggml_init_params params = {
  32. /*.mem_size =*/ hparams.n_layer*ggml_tensor_overhead(),
  33. /*.mem_buffer =*/ NULL,
  34. /*.no_alloc =*/ true,
  35. };
  36. ggml_context * ctx = ggml_init(params);
  37. if (!ctx) {
  38. return nullptr;
  39. }
  40. ctx_map[buft] = ctx;
  41. cvec.ctxs.emplace_back(ctx);
  42. return ctx;
  43. }
  44. return it->second;
  45. };
  46. // make tensors
  47. cvec.tensors.reserve(hparams.n_layer);
  48. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  49. for (size_t il = 1; il < hparams.n_layer; il++) {
  50. ggml_backend_buffer_type_t buft = llama_model_select_buft(model, il);
  51. ggml_context * ctx = ctx_for_buft(buft);
  52. if (!ctx) {
  53. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  54. return false;
  55. }
  56. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd);
  57. cvec.tensors.push_back(tensor);
  58. }
  59. // allocate tensors / buffers and zero
  60. cvec.bufs.reserve(ctx_map.size());
  61. for (auto it : ctx_map) {
  62. ggml_backend_buffer_type_t buft = it.first;
  63. ggml_context * ctx = it.second;
  64. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  65. if (!buf) {
  66. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  67. return false;
  68. }
  69. ggml_backend_buffer_clear(buf, 0);
  70. cvec.bufs.emplace_back(buf);
  71. }
  72. return true;
  73. }
  74. int32_t llama_control_vector_apply(
  75. struct llama_control_vector & cvec,
  76. const llama_model & model,
  77. const float * data,
  78. size_t len,
  79. int32_t n_embd,
  80. int32_t il_start,
  81. int32_t il_end) {
  82. const auto & hparams = model.hparams;
  83. if (data == nullptr) {
  84. // disable the current control vector (but leave allocated for later)
  85. cvec.layer_start = -1;
  86. cvec.layer_end = -1;
  87. return 0;
  88. }
  89. if (n_embd != (int) hparams.n_embd) {
  90. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  91. return 1;
  92. }
  93. if (cvec.tensors.empty()) {
  94. if (!llama_control_vector_init(cvec, model)) {
  95. return 1;
  96. }
  97. }
  98. cvec.layer_start = il_start;
  99. cvec.layer_end = il_end;
  100. for (size_t il = 1; il < hparams.n_layer; il++) {
  101. assert(cvec.tensors[il] != nullptr);
  102. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  103. if (off + n_embd <= len) {
  104. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  105. }
  106. }
  107. return 0;
  108. }
  109. // lora
  110. llama_lora_weight * llama_lora_adapter::get_weight(struct ggml_tensor * w) {
  111. const std::string name(w->name);
  112. const auto pos = ab_map.find(name);
  113. if (pos != ab_map.end()) {
  114. return &pos->second;
  115. }
  116. return nullptr;
  117. }
  118. void llama_lora_adapter_free(struct llama_lora_adapter * adapter) {
  119. delete adapter;
  120. }
  121. static void llama_lora_adapter_init_impl(struct llama_model & model, const char * path_lora, struct llama_lora_adapter & adapter) {
  122. LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora);
  123. ggml_context * ctx_init;
  124. struct gguf_init_params meta_gguf_params = {
  125. /* .no_alloc = */ true,
  126. /* .ctx = */ &ctx_init,
  127. };
  128. gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) };
  129. if (!ctx_gguf) {
  130. throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora));
  131. }
  132. ggml_context_ptr ctx { ctx_init };
  133. // check metadata
  134. {
  135. auto get_kv_str = [&](const std::string & key) -> std::string {
  136. int id = gguf_find_key(ctx_gguf.get(), key.c_str());
  137. return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf.get(), id));
  138. };
  139. auto get_kv_f32 = [&](const std::string & key) -> float {
  140. int id = gguf_find_key(ctx_gguf.get(), key.c_str());
  141. return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf.get(), id);
  142. };
  143. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  144. auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE));
  145. if (general_type != "adapter") {
  146. throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type);
  147. }
  148. auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE));
  149. auto general_arch = llm_arch_from_string(general_arch_str);
  150. if (general_arch != model.arch) {
  151. throw std::runtime_error("model arch and LoRA arch mismatch");
  152. }
  153. auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE));
  154. if (adapter_type != "lora") {
  155. throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type);
  156. }
  157. adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA));
  158. }
  159. int n_tensors = gguf_get_n_tensors(ctx_gguf.get());
  160. // contexts for each buffer type
  161. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  162. auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
  163. auto it = ctx_map.find(buft);
  164. if (it == ctx_map.end()) {
  165. // add a new context
  166. struct ggml_init_params params = {
  167. /*.mem_size =*/ n_tensors*ggml_tensor_overhead(),
  168. /*.mem_buffer =*/ NULL,
  169. /*.no_alloc =*/ true,
  170. };
  171. ggml_context * buft_ctx = ggml_init(params);
  172. if (!buft_ctx) {
  173. return nullptr;
  174. }
  175. ctx_map[buft] = buft_ctx;
  176. adapter.ctxs.emplace_back(buft_ctx);
  177. return buft_ctx;
  178. };
  179. return it->second;
  180. };
  181. // bundle lora_a and lora_b into pairs
  182. std::map<std::string, llama_lora_weight> ab_map;
  183. auto str_endswith = [](const std::string & str, const std::string & suffix) {
  184. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  185. };
  186. for (ggml_tensor * cur = ggml_get_first_tensor(ctx.get()); cur; cur = ggml_get_next_tensor(ctx.get(), cur)) {
  187. std::string name(cur->name);
  188. if (str_endswith(name, ".lora_a")) {
  189. replace_all(name, ".lora_a", "");
  190. if (ab_map.find(name) == ab_map.end()) {
  191. ab_map[name] = llama_lora_weight(cur, nullptr);
  192. } else {
  193. ab_map[name].a = cur;
  194. }
  195. } else if (str_endswith(name, ".lora_b")) {
  196. replace_all(name, ".lora_b", "");
  197. if (ab_map.find(name) == ab_map.end()) {
  198. ab_map[name] = llama_lora_weight(nullptr, cur);
  199. } else {
  200. ab_map[name].b = cur;
  201. }
  202. } else {
  203. throw std::runtime_error("LoRA tensor '" + name + "' has unexpected suffix");
  204. }
  205. }
  206. // add tensors
  207. for (auto & it : ab_map) {
  208. const std::string & name = it.first;
  209. llama_lora_weight & w = it.second;
  210. if (!w.a || !w.b) {
  211. throw std::runtime_error("LoRA tensor pair for '" + name + "' is missing one component");
  212. }
  213. // device buft and device ctx
  214. auto * model_tensor = llama_model_get_tensor(model, name.c_str());
  215. if (!model_tensor) {
  216. throw std::runtime_error("LoRA tensor '" + name + "' does not exist in base model");
  217. }
  218. struct ggml_context * dev_ctx = ctx_for_buft(ggml_backend_buffer_get_type(model_tensor->buffer));
  219. // validate tensor shape
  220. if (model_tensor->ne[0] != w.a->ne[0] || model_tensor->ne[1] != w.b->ne[1]) {
  221. throw std::runtime_error("tensor '" + name + "' has incorrect shape");
  222. }
  223. if (w.a->ne[1] != w.b->ne[0]) {
  224. throw std::runtime_error("lora_a tensor is not transposed (hint: adapter from \"finetune\" example is no longer supported)");
  225. }
  226. // save tensor to adapter
  227. struct ggml_tensor * tensor_a = ggml_dup_tensor(dev_ctx, w.a);
  228. struct ggml_tensor * tensor_b = ggml_dup_tensor(dev_ctx, w.b);
  229. ggml_set_name(tensor_a, w.a->name);
  230. ggml_set_name(tensor_b, w.b->name);
  231. adapter.ab_map[name] = llama_lora_weight(tensor_a, tensor_b);
  232. }
  233. // allocate tensors / buffers and zero
  234. {
  235. adapter.ctxs.reserve(ctx_map.size());
  236. adapter.bufs.reserve(ctx_map.size());
  237. for (auto & it : ctx_map) {
  238. ggml_backend_buffer_type_t buft = it.first;
  239. ggml_context * ctx_dev = it.second;
  240. ggml_backend_buffer_ptr buf { ggml_backend_alloc_ctx_tensors_from_buft(ctx_dev, buft) };
  241. if (!buf) {
  242. throw std::runtime_error("failed to allocate buffer for lora adapter\n");
  243. }
  244. LLAMA_LOG_INFO("%s: %10s LoRA buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf.get()), ggml_backend_buffer_get_size(buf.get())/1024.0/1024.0);
  245. adapter.bufs.emplace_back(std::move(buf));
  246. }
  247. }
  248. // set tensor data
  249. {
  250. llama_file gguf_file(path_lora, "rb");
  251. std::vector<uint8_t> read_buf;
  252. auto set_tensor = [&](struct ggml_tensor * orig, struct ggml_tensor * dev) {
  253. size_t offs = gguf_get_data_offset(ctx_gguf.get()) + gguf_get_tensor_offset(ctx_gguf.get(), gguf_find_tensor(ctx_gguf.get(), orig->name));
  254. size_t size = ggml_nbytes(orig);
  255. read_buf.resize(size);
  256. gguf_file.seek(offs, SEEK_SET);
  257. gguf_file.read_raw(read_buf.data(), size);
  258. ggml_backend_tensor_set(dev, read_buf.data(), 0, size);
  259. };
  260. for (auto & it : adapter.ab_map) {
  261. auto orig = ab_map[it.first];
  262. auto dev = it.second;
  263. set_tensor(orig.a, dev.a);
  264. set_tensor(orig.b, dev.b);
  265. }
  266. }
  267. LLAMA_LOG_INFO("%s: loaded %zu tensors from lora file\n", __func__, adapter.ab_map.size()*2);
  268. }
  269. struct llama_lora_adapter * llama_lora_adapter_init(struct llama_model * model, const char * path_lora) {
  270. struct llama_lora_adapter * adapter = new llama_lora_adapter();
  271. try {
  272. llama_lora_adapter_init_impl(*model, path_lora, *adapter);
  273. return adapter;
  274. } catch (const std::exception & err) {
  275. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  276. delete adapter;
  277. }
  278. return nullptr;
  279. }