char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Pop Flamingollama : re-enable manual LoRA adapter free (#19983)312cf0332

char/aliceai-t5-moe
2.2 KiB91 linesraw
1#pragma once
2
3#include "llama.h"
4
5#include "ggml-cpp.h"
6
7#include <string>
8#include <unordered_map>
9#include <vector>
10
11// TODO: pimpl
12
13//
14// llama_adapter_cvec
15//
16
17struct llama_adapter_cvec {
18    ggml_tensor * tensor_for(int il) const;
19
20    ggml_tensor * apply_to(ggml_context * ctx, ggml_tensor * cur, int  il) const;
21
22    bool apply(
23            const llama_model & model,
24            const float * data,
25            size_t len,
26            int32_t n_embd,
27            int32_t il_start,
28            int32_t il_end);
29
30private:
31    bool init(const llama_model & model);
32
33    int32_t layer_start = -1;
34    int32_t layer_end   = -1;
35
36    std::vector<ggml_context_ptr> ctxs;
37    std::vector<ggml_backend_buffer_ptr> bufs;
38
39    std::vector<ggml_tensor *> tensors; // per layer
40};
41
42using llama_adapter_cvec_ptr = std::shared_ptr<llama_adapter_cvec>;
43
44//
45// llama_adapter_lora
46//
47
48struct llama_adapter_lora_weight {
49    ggml_tensor * a = nullptr;
50    ggml_tensor * b = nullptr;
51
52    // get actual scale based on rank and alpha
53    float get_scale(float alpha, float adapter_scale) const {
54        const float rank  = (float) b->ne[0];
55        const float scale = alpha ? adapter_scale * alpha / rank : adapter_scale;
56        return scale;
57    }
58
59    llama_adapter_lora_weight() = default;
60    llama_adapter_lora_weight(ggml_tensor * a, ggml_tensor * b) : a(a), b(b) {}
61};
62
63struct llama_adapter_lora {
64    llama_model * model = nullptr;
65
66    // map tensor name to lora_a_b
67    std::unordered_map<std::string, llama_adapter_lora_weight> ab_map;
68
69    std::vector<ggml_context_ptr> ctxs;
70    std::vector<ggml_backend_buffer_ptr> bufs;
71
72    float alpha;
73
74    // gguf metadata
75    std::unordered_map<std::string, std::string> gguf_kv;
76
77    // activated lora (aLoRA)
78    std::vector<llama_token> alora_invocation_tokens;
79
80    explicit llama_adapter_lora(llama_model * model) : model(model) {}
81    ~llama_adapter_lora() = default;
82
83    llama_adapter_lora_weight * get_weight(ggml_tensor * w);
84
85    uint32_t get_n_nodes() const {
86        return ab_map.size() * 6u; // a, b, scale, add, 2 x mul_mat
87    }
88};
89
90using llama_adapter_loras = std::unordered_map<llama_adapter_lora *, float>;
91using llama_adapter_loras_ptr = std::unique_ptr<llama_adapter_loras>;