| 146 | } |
| 147 | |
| 148 | static void llama_adapter_lora_init_impl(llama_model & model, const char * path_lora, llama_adapter_lora & adapter) { |
| 149 | LLAMA_LOG_INFO("%s: loading lora adapter from '%s' ...\n", __func__, path_lora); |
| 150 | |
| 151 | ggml_context * ctx_init; |
| 152 | gguf_init_params meta_gguf_params = { |
| 153 | /* .no_alloc = */ true, |
| 154 | /* .ctx = */ &ctx_init, |
| 155 | }; |
| 156 | |
| 157 | gguf_context_ptr ctx_gguf { gguf_init_from_file(path_lora, meta_gguf_params) }; |
| 158 | if (!ctx_gguf) { |
| 159 | throw std::runtime_error("failed to load lora adapter file from " + std::string(path_lora)); |
| 160 | } |
| 161 | |
| 162 | ggml_context_ptr ctx { ctx_init }; |
| 163 | |
| 164 | // check metadata |
| 165 | { |
| 166 | auto get_kv_str = [&](const std::string & key) -> std::string { |
| 167 | int id = gguf_find_key(ctx_gguf.get(), key.c_str()); |
| 168 | return id < 0 ? "" : std::string(gguf_get_val_str(ctx_gguf.get(), id)); |
| 169 | }; |
| 170 | auto get_kv_f32 = [&](const std::string & key) -> float { |
| 171 | int id = gguf_find_key(ctx_gguf.get(), key.c_str()); |
| 172 | return id < 0 ? 0.0f : gguf_get_val_f32(ctx_gguf.get(), id); |
| 173 | }; |
| 174 | LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN); |
| 175 | |
| 176 | auto general_type = get_kv_str(llm_kv(LLM_KV_GENERAL_TYPE)); |
| 177 | if (general_type != "adapter") { |
| 178 | throw std::runtime_error("expect general.type to be 'adapter', but got: " + general_type); |
| 179 | } |
| 180 | |
| 181 | auto general_arch_str = get_kv_str(llm_kv(LLM_KV_GENERAL_ARCHITECTURE)); |
| 182 | auto general_arch = llm_arch_from_string(general_arch_str); |
| 183 | if (general_arch != model.arch) { |
| 184 | throw std::runtime_error("model arch and LoRA arch mismatch"); |
| 185 | } |
| 186 | |
| 187 | auto adapter_type = get_kv_str(llm_kv(LLM_KV_ADAPTER_TYPE)); |
| 188 | if (adapter_type != "lora") { |
| 189 | throw std::runtime_error("expect adapter.type to be 'lora', but got: " + adapter_type); |
| 190 | } |
| 191 | |
| 192 | adapter.alpha = get_kv_f32(llm_kv(LLM_KV_ADAPTER_LORA_ALPHA)); |
| 193 | } |
| 194 | |
| 195 | int n_tensors = gguf_get_n_tensors(ctx_gguf.get()); |
| 196 | |
| 197 | // contexts for each buffer type |
| 198 | std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map; |
| 199 | auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * { |
| 200 | auto it = ctx_map.find(buft); |
| 201 | if (it == ctx_map.end()) { |
| 202 | // add a new context |
| 203 | ggml_init_params params = { |
| 204 | /*.mem_size =*/ n_tensors*ggml_tensor_overhead(), |
| 205 | /*.mem_buffer =*/ NULL, |
no test coverage detected