llama.go 7.01 KB
Newer Older
Jeffrey Morgan's avatar
Jeffrey Morgan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// MIT License

// Copyright (c) 2023 go-skynet authors

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package llama

Jeffrey Morgan's avatar
Jeffrey Morgan committed
25
26
// #cgo LDFLAGS: -Lbuild -lbinding -lllama -lm -lggml_static -lstdc++
// #cgo CXXFLAGS: -std=c++11
Jeffrey Morgan's avatar
Jeffrey Morgan committed
27
28
// #cgo darwin LDFLAGS: -framework Accelerate -framework Foundation -framework Metal -framework MetalKit -framework MetalPerformanceShaders
// #include "binding/binding.h"
Jeffrey Morgan's avatar
Jeffrey Morgan committed
29
// #include <stdlib.h>
Jeffrey Morgan's avatar
Jeffrey Morgan committed
30
import "C"
Bruce MacDonald's avatar
Bruce MacDonald committed
31

Jeffrey Morgan's avatar
Jeffrey Morgan committed
32
33
34
35
36
37
38
39
import (
	"fmt"
	"strings"
	"sync"
	"unsafe"
)

type LLama struct {
Michael Yang's avatar
Michael Yang committed
40
	ctx         unsafe.Pointer
Jeffrey Morgan's avatar
Jeffrey Morgan committed
41
42
43
44
	embeddings  bool
	contextSize int
}

45
func New(model string, mo ModelOptions) (*LLama, error) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
46
	modelPath := C.CString(model)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
47
	defer C.free(unsafe.Pointer(modelPath))
Jeffrey Morgan's avatar
Jeffrey Morgan committed
48
49
50

	ctx := C.load_model(modelPath, C.int(mo.ContextSize), C.int(mo.Seed), C.bool(mo.F16Memory), C.bool(mo.MLock), C.bool(mo.Embeddings), C.bool(mo.MMap), C.bool(mo.LowVRAM), C.bool(mo.VocabOnly), C.int(mo.NGPULayers), C.int(mo.NBatch), C.CString(mo.MainGPU), C.CString(mo.TensorSplit), C.bool(mo.NUMA))
	if ctx == nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
51
52
53
		return nil, fmt.Errorf("failed loading model")
	}

Jeffrey Morgan's avatar
Jeffrey Morgan committed
54
	ll := &LLama{ctx: ctx, contextSize: mo.ContextSize, embeddings: mo.Embeddings}
Jeffrey Morgan's avatar
Jeffrey Morgan committed
55
56
57
58
59

	return ll, nil
}

func (l *LLama) Free() {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
60
	C.llama_binding_free_model(l.ctx)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
61
62
63
64
65
66
67
68
69
}

func (l *LLama) Eval(text string, opts ...PredictOption) error {
	po := NewPredictOptions(opts...)

	input := C.CString(text)
	if po.Tokens == 0 {
		po.Tokens = 99999999
	}
Michael Yang's avatar
Michael Yang committed
70
	defer C.free(unsafe.Pointer(input))
Bruce MacDonald's avatar
Bruce MacDonald committed
71

Jeffrey Morgan's avatar
Jeffrey Morgan committed
72
73
74
75
76
77
78
	reverseCount := len(po.StopPrompts)
	reversePrompt := make([]*C.char, reverseCount)
	var pass **C.char
	for i, s := range po.StopPrompts {
		cs := C.CString(s)
		reversePrompt[i] = cs
		pass = &reversePrompt[0]
Michael Yang's avatar
Michael Yang committed
79
		defer C.free(unsafe.Pointer(cs))
Jeffrey Morgan's avatar
Jeffrey Morgan committed
80
81
	}

Michael Yang's avatar
Michael Yang committed
82
83
84
85
86
87
88
89
90
	cLogitBias := C.CString(po.LogitBias)
	defer C.free(unsafe.Pointer(cLogitBias))

	cMainGPU := C.CString(po.MainGPU)
	defer C.free(unsafe.Pointer(cMainGPU))

	cTensorSplit := C.CString(po.TensorSplit)
	defer C.free(unsafe.Pointer(cTensorSplit))

Jeffrey Morgan's avatar
Jeffrey Morgan committed
91
92
93
94
95
	params := C.llama_allocate_params(input, C.int(po.Seed), C.int(po.Threads), C.int(po.Tokens), C.int(po.TopK),
		C.float(po.TopP), C.float(po.Temperature), C.float(po.Penalty), C.int(po.Repeat),
		C.bool(po.IgnoreEOS), C.bool(po.F16KV),
		C.int(po.Batch), C.int(po.NKeep), pass, C.int(reverseCount),
		C.float(po.TailFreeSamplingZ), C.float(po.TypicalP), C.float(po.FrequencyPenalty), C.float(po.PresencePenalty),
Michael Yang's avatar
Michael Yang committed
96
97
		C.int(po.Mirostat), C.float(po.MirostatETA), C.float(po.MirostatTAU), C.bool(po.PenalizeNL), cLogitBias,
		C.bool(po.MLock), C.bool(po.MMap), cMainGPU, cTensorSplit,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
98
	)
Michael Yang's avatar
Michael Yang committed
99
100
	defer C.llama_free_params(params)

Jeffrey Morgan's avatar
Jeffrey Morgan committed
101
	ret := C.eval(params, l.ctx, input)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
102
103
104
105
106
107
108
	if ret != 0 {
		return fmt.Errorf("inference failed")
	}

	return nil
}

109
func (l *LLama) Predict(text string, po PredictOptions) (string, error) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
110
	if po.TokenCallback != nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
111
		setCallback(l.ctx, po.TokenCallback)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
112
113
114
115
116
117
	}

	input := C.CString(text)
	if po.Tokens == 0 {
		po.Tokens = 99999999
	}
Michael Yang's avatar
Michael Yang committed
118
119
	defer C.free(unsafe.Pointer(input))

Jeffrey Morgan's avatar
Jeffrey Morgan committed
120
121
122
123
124
125
126
127
128
	out := make([]byte, po.Tokens)

	reverseCount := len(po.StopPrompts)
	reversePrompt := make([]*C.char, reverseCount)
	var pass **C.char
	for i, s := range po.StopPrompts {
		cs := C.CString(s)
		reversePrompt[i] = cs
		pass = &reversePrompt[0]
Michael Yang's avatar
Michael Yang committed
129
		defer C.free(unsafe.Pointer(cs))
Jeffrey Morgan's avatar
Jeffrey Morgan committed
130
131
	}

Michael Yang's avatar
Michael Yang committed
132
133
134
135
136
137
138
139
140
	cLogitBias := C.CString(po.LogitBias)
	defer C.free(unsafe.Pointer(cLogitBias))

	cMainGPU := C.CString(po.MainGPU)
	defer C.free(unsafe.Pointer(cMainGPU))

	cTensorSplit := C.CString(po.TensorSplit)
	defer C.free(unsafe.Pointer(cTensorSplit))

Jeffrey Morgan's avatar
Jeffrey Morgan committed
141
142
143
144
145
	params := C.llama_allocate_params(input, C.int(po.Seed), C.int(po.Threads), C.int(po.Tokens), C.int(po.TopK),
		C.float(po.TopP), C.float(po.Temperature), C.float(po.Penalty), C.int(po.Repeat),
		C.bool(po.IgnoreEOS), C.bool(po.F16KV),
		C.int(po.Batch), C.int(po.NKeep), pass, C.int(reverseCount),
		C.float(po.TailFreeSamplingZ), C.float(po.TypicalP), C.float(po.FrequencyPenalty), C.float(po.PresencePenalty),
Michael Yang's avatar
Michael Yang committed
146
		C.int(po.Mirostat), C.float(po.MirostatETA), C.float(po.MirostatTAU), C.bool(po.PenalizeNL), cLogitBias,
Bruce MacDonald's avatar
Bruce MacDonald committed
147
		C.bool(po.MLock), C.bool(po.MMap), cMainGPU, cTensorSplit,
Jeffrey Morgan's avatar
Jeffrey Morgan committed
148
	)
Michael Yang's avatar
Michael Yang committed
149
	defer C.llama_free_params(params)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
150

Jeffrey Morgan's avatar
Jeffrey Morgan committed
151
	ret := C.llama_predict(params, l.ctx, (*C.char)(unsafe.Pointer(&out[0])), C.bool(po.DebugMode))
Jeffrey Morgan's avatar
Jeffrey Morgan committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
	if ret != 0 {
		return "", fmt.Errorf("inference failed")
	}
	res := C.GoString((*C.char)(unsafe.Pointer(&out[0])))

	res = strings.TrimPrefix(res, " ")
	res = strings.TrimPrefix(res, text)
	res = strings.TrimPrefix(res, "\n")

	for _, s := range po.StopPrompts {
		res = strings.TrimRight(res, s)
	}

	if po.TokenCallback != nil {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
166
		setCallback(l.ctx, nil)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
	}

	return res, nil
}

// CGo only allows us to use static calls from C to Go, we can't just dynamically pass in func's.
// This is the next best thing, we register the callbacks in this map and call tokenCallback from
// the C code. We also attach a finalizer to LLama, so it will unregister the callback when the
// garbage collection frees it.

// SetTokenCallback registers a callback for the individual tokens created when running Predict. It
// will be called once for each token. The callback shall return true as long as the model should
// continue predicting the next token. When the callback returns false the predictor will return.
// The tokens are just converted into Go strings, they are not trimmed or otherwise changed. Also
// the tokens may not be valid UTF-8.
// Pass in nil to remove a callback.
//
// It is save to call this method while a prediction is running.
func (l *LLama) SetTokenCallback(callback func(token string) bool) {
Jeffrey Morgan's avatar
Jeffrey Morgan committed
186
	setCallback(l.ctx, callback)
Jeffrey Morgan's avatar
Jeffrey Morgan committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
}

var (
	m         sync.Mutex
	callbacks = map[uintptr]func(string) bool{}
)

//export tokenCallback
func tokenCallback(statePtr unsafe.Pointer, token *C.char) bool {
	m.Lock()
	defer m.Unlock()

	if callback, ok := callbacks[uintptr(statePtr)]; ok {
		return callback(C.GoString(token))
	}

	return true
}

// setCallback can be used to register a token callback for LLama. Pass in a nil callback to
// remove the callback.
func setCallback(statePtr unsafe.Pointer, callback func(string) bool) {
	m.Lock()
	defer m.Unlock()

	if callback == nil {
		delete(callbacks, uintptr(statePtr))
	} else {
		callbacks[uintptr(statePtr)] = callback
	}
}