|
| 1 | +package yzma |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/hybridgroup/yzma/pkg/llama" |
| 9 | + "github.com/tmc/langchaingo/llms" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + defaultTemperature = 0.8 |
| 14 | + defaultTopK = 40 |
| 15 | + defaultTopP = 0.9 |
| 16 | +) |
| 17 | + |
| 18 | +// LLM is a yzma local implementation wrapper to call directly to llama.cpp libs using the FFI interface. |
| 19 | +type LLM struct { |
| 20 | + model string |
| 21 | + options options |
| 22 | +} |
| 23 | + |
| 24 | +// New creates a new yzma LLM implementation. |
| 25 | +func New(opts ...Option) (*LLM, error) { |
| 26 | + o := options{} |
| 27 | + for _, opt := range opts { |
| 28 | + opt(&o) |
| 29 | + } |
| 30 | + |
| 31 | + libPath := os.Getenv("YZMA_LIB") |
| 32 | + if libPath == "" { |
| 33 | + return nil, errors.New("no path to yzma libs") |
| 34 | + } |
| 35 | + |
| 36 | + if err := llama.Load(""); err != nil { |
| 37 | + return nil, err |
| 38 | + } |
| 39 | + |
| 40 | + llama.LogSet(llama.LogSilent()) |
| 41 | + llama.Init() |
| 42 | + |
| 43 | + llm := LLM{ |
| 44 | + model: o.model, |
| 45 | + options: o, |
| 46 | + } |
| 47 | + |
| 48 | + return &llm, nil |
| 49 | +} |
| 50 | + |
| 51 | +// Close frees all resources. |
| 52 | +func (o *LLM) Close() { |
| 53 | + llama.BackendFree() |
| 54 | +} |
| 55 | + |
| 56 | +// Call calls yzma with the given prompt. |
| 57 | +func (o *LLM) Call(ctx context.Context, prompt string, options ...llms.CallOption) (string, error) { |
| 58 | + return llms.GenerateFromSinglePrompt(ctx, o, prompt, options...) |
| 59 | +} |
| 60 | + |
| 61 | +// GenerateContent implements the Model interface. |
| 62 | +func (o *LLM) GenerateContent(ctx context.Context, messages []llms.MessageContent, options ...llms.CallOption) (*llms.ContentResponse, error) { |
| 63 | + opts := llms.CallOptions{} |
| 64 | + for _, opt := range options { |
| 65 | + opt(&opts) |
| 66 | + } |
| 67 | + |
| 68 | + modelName := o.model |
| 69 | + if opts.Model != "" { |
| 70 | + modelName = opts.Model |
| 71 | + } |
| 72 | + |
| 73 | + maxTokens := int32(1024) |
| 74 | + if opts.MaxTokens > 0 { |
| 75 | + maxTokens = int32(opts.MaxTokens) |
| 76 | + } |
| 77 | + |
| 78 | + // TODO: allow for setting any passed model params |
| 79 | + model := llama.ModelLoadFromFile(modelName, llama.ModelDefaultParams()) |
| 80 | + if model == llama.Model(0) { |
| 81 | + return nil, errors.New("unable to load model") |
| 82 | + } |
| 83 | + defer llama.ModelFree(model) |
| 84 | + |
| 85 | + // TODO: allow for setting any passed context options |
| 86 | + ctxParams := llama.ContextDefaultParams() |
| 87 | + ctxParams.NCtx = uint32(4096) |
| 88 | + ctxParams.NBatch = uint32(2048) |
| 89 | + |
| 90 | + lctx := llama.InitFromModel(model, ctxParams) |
| 91 | + if lctx == llama.Context(0) { |
| 92 | + return nil, errors.New("unable to init model") |
| 93 | + } |
| 94 | + |
| 95 | + defer llama.Free(lctx) |
| 96 | + |
| 97 | + vocab := llama.ModelGetVocab(model) |
| 98 | + sampler := initSampler(opts) |
| 99 | + |
| 100 | + msg := chatTemplate(templateForModel(model), convertMessageContent(messages), true) |
| 101 | + |
| 102 | + // call once to get the size of the tokens from the prompt |
| 103 | + count := llama.Tokenize(vocab, msg, nil, true, true) |
| 104 | + |
| 105 | + // now get the actual tokens |
| 106 | + tokens := make([]llama.Token, count) |
| 107 | + llama.Tokenize(vocab, msg, tokens, true, true) |
| 108 | + |
| 109 | + batch := llama.BatchGetOne(tokens) |
| 110 | + |
| 111 | + if llama.ModelHasEncoder(model) { |
| 112 | + llama.Encode(lctx, batch) |
| 113 | + |
| 114 | + start := llama.ModelDecoderStartToken(model) |
| 115 | + if start == llama.TokenNull { |
| 116 | + start = llama.VocabBOS(vocab) |
| 117 | + } |
| 118 | + |
| 119 | + batch = llama.BatchGetOne([]llama.Token{start}) |
| 120 | + } |
| 121 | + |
| 122 | + result := "" |
| 123 | + |
| 124 | + for pos := int32(0); pos < maxTokens; pos += batch.NTokens { |
| 125 | + llama.Decode(lctx, batch) |
| 126 | + token := llama.SamplerSample(sampler, lctx, -1) |
| 127 | + |
| 128 | + if llama.VocabIsEOG(vocab, token) { |
| 129 | + break |
| 130 | + } |
| 131 | + |
| 132 | + buf := make([]byte, 64) |
| 133 | + len := llama.TokenToPiece(vocab, token, buf, 0, true) |
| 134 | + |
| 135 | + result = result + string(buf[:len]) |
| 136 | + batch = llama.BatchGetOne([]llama.Token{token}) |
| 137 | + } |
| 138 | + |
| 139 | + choices := []*llms.ContentChoice{ |
| 140 | + { |
| 141 | + Content: result, |
| 142 | + }, |
| 143 | + } |
| 144 | + |
| 145 | + response := &llms.ContentResponse{Choices: choices} |
| 146 | + return response, nil |
| 147 | +} |
| 148 | + |
| 149 | +func initSampler(opts llms.CallOptions) llama.Sampler { |
| 150 | + temperature := defaultTemperature |
| 151 | + if opts.Temperature > 0 { |
| 152 | + temperature = opts.Temperature |
| 153 | + } |
| 154 | + topK := defaultTopK |
| 155 | + if opts.TopK > 0 { |
| 156 | + topK = opts.TopK |
| 157 | + } |
| 158 | + |
| 159 | + minP := 0.1 |
| 160 | + |
| 161 | + topP := defaultTopP |
| 162 | + if opts.TopP > 0 { |
| 163 | + topP = opts.TopP |
| 164 | + } |
| 165 | + |
| 166 | + sampler := llama.SamplerChainInit(llama.SamplerChainDefaultParams()) |
| 167 | + llama.SamplerChainAdd(sampler, llama.SamplerInitTopK(int32(topK))) |
| 168 | + llama.SamplerChainAdd(sampler, llama.SamplerInitTopP(float32(topP), 1)) |
| 169 | + llama.SamplerChainAdd(sampler, llama.SamplerInitMinP(float32(minP), 1)) |
| 170 | + llama.SamplerChainAdd(sampler, llama.SamplerInitTempExt(float32(temperature), 0, 1.0)) |
| 171 | + llama.SamplerChainAdd(sampler, llama.SamplerInitDist(llama.DefaultSeed)) |
| 172 | + |
| 173 | + return sampler |
| 174 | +} |
| 175 | + |
| 176 | +func templateForModel(model llama.Model) string { |
| 177 | + template := llama.ModelChatTemplate(model, "") |
| 178 | + if template == "" { |
| 179 | + template = "chatml" |
| 180 | + } |
| 181 | + return template |
| 182 | +} |
| 183 | + |
| 184 | +func convertMessageContent(msgs []llms.MessageContent) []llama.ChatMessage { |
| 185 | + chatMsgs := []llama.ChatMessage{} |
| 186 | + for _, m := range msgs { |
| 187 | + p := m.Parts[0] |
| 188 | + switch pt := p.(type) { |
| 189 | + case llms.TextContent: |
| 190 | + chatMsgs = append(chatMsgs, llama.NewChatMessage(string(m.Role), pt.Text)) |
| 191 | + } |
| 192 | + } |
| 193 | + return chatMsgs |
| 194 | +} |
| 195 | + |
| 196 | +func chatTemplate(template string, msgs []llama.ChatMessage, add bool) string { |
| 197 | + buf := make([]byte, 2048) |
| 198 | + len := llama.ChatApplyTemplate(template, msgs, add, buf) |
| 199 | + result := string(buf[:len]) |
| 200 | + return result |
| 201 | +} |
0 commit comments