| 28 | } |
| 29 | |
| 30 | bool llama_adapter_cvec::init(const llama_model & model) { |
| 31 | const auto & hparams = model.hparams; |
| 32 | |
| 33 | GGML_ASSERT(tensors.empty()); |
| 34 | GGML_ASSERT(ctxs.empty()); |
| 35 | GGML_ASSERT(bufs.empty()); |
| 36 | |
| 37 | // create a context for each buffer type |
| 38 | std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map; |
| 39 | auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * { |
| 40 | auto it = ctx_map.find(buft); |
| 41 | if (it == ctx_map.end()) { |
| 42 | ggml_init_params params = { |
| 43 | /*.mem_size =*/ hparams.n_layer*ggml_tensor_overhead(), |
| 44 | /*.mem_buffer =*/ NULL, |
| 45 | /*.no_alloc =*/ true, |
| 46 | }; |
| 47 | |
| 48 | ggml_context * ctx = ggml_init(params); |
| 49 | if (!ctx) { |
| 50 | return nullptr; |
| 51 | } |
| 52 | |
| 53 | ctx_map[buft] = ctx; |
| 54 | ctxs.emplace_back(ctx); |
| 55 | |
| 56 | return ctx; |
| 57 | } |
| 58 | |
| 59 | return it->second; |
| 60 | }; |
| 61 | |
| 62 | // make tensors |
| 63 | tensors.reserve(hparams.n_layer); |
| 64 | tensors.push_back(nullptr); // there's never a tensor for layer 0 |
| 65 | for (size_t il = 1; il < hparams.n_layer; il++) { |
| 66 | ggml_backend_buffer_type_t buft = model.select_buft(il); |
| 67 | ggml_context * ctx = ctx_for_buft(buft); |
| 68 | if (!ctx) { |
| 69 | LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__); |
| 70 | return false; |
| 71 | } |
| 72 | ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hparams.n_embd); |
| 73 | tensors.push_back(tensor); |
| 74 | } |
| 75 | |
| 76 | // allocate tensors / buffers and zero |
| 77 | bufs.reserve(ctx_map.size()); |
| 78 | for (auto it : ctx_map) { |
| 79 | ggml_backend_buffer_type_t buft = it.first; |
| 80 | ggml_context * ctx = it.second; |
| 81 | ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft); |
| 82 | if (!buf) { |
| 83 | LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__); |
| 84 | return false; |
| 85 | } |
| 86 | ggml_backend_buffer_clear(buf, 0); |
| 87 | bufs.emplace_back(buf); |
nothing calls this directly
no test coverage detected