llama.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package llama
  2. // #cgo CFLAGS: -std=c11 -DNDEBUG -DLOG_DISABLE_LOGS
  3. // #cgo CXXFLAGS: -std=c++11 -DNDEBUG -DLOG_DISABLE_LOGS
  4. // #cgo darwin,arm64 CFLAGS: -DGGML_USE_METAL -DGGML_METAL_EMBED_LIBRARY -DGGML_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
  5. // #cgo darwin,arm64 CXXFLAGS: -DGGML_USE_METAL -DGGML_METAL_EMBED_LIBRARY -DGGML_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
  6. // #cgo darwin,arm64 LDFLAGS: -ld_classic ${SRCDIR}/ggml-metal.o -framework Foundation -framework Metal -framework MetalKit -framework Accelerate
  7. // #cgo darwin,amd64 CFLAGS: -Wno-incompatible-pointer-types-discards-qualifiers
  8. // #cgo darwin,amd64 CXXFLAGS: -Wno-incompatible-pointer-types-discards-qualifiers
  9. // #cgo darwin,amd64 LDFLAGS: -ld_classic -framework Foundation -framework Accelerate
  10. // #cgo linux CFLAGS: -D_GNU_SOURCE
  11. // #cgo linux CXXFLAGS: -D_GNU_SOURCE
  12. // #cgo windows LDFLAGS: -lmsvcrt
  13. // #cgo avx CFLAGS: -mavx
  14. // #cgo avx CXXFLAGS: -mavx
  15. // #cgo avx2 CFLAGS: -mavx2 -mfma
  16. // #cgo avx2 CXXFLAGS: -mavx2 -mfma
  17. // #cgo cuda CFLAGS: -DGGML_USE_CUDA -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  18. // #cgo cuda CXXFLAGS: -DGGML_USE_CUDA -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  19. // #cgo rocm CFLAGS: -DGGML_USE_CUDA -DGGML_USE_HIPBLAS -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  20. // #cgo rocm CXXFLAGS: -DGGML_USE_CUDA -DGGML_USE_HIPBLAS -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  21. // #cgo rocm LDFLAGS: -L${SRCDIR} -lggml-hipblas -lhipblas -lamdhip64 -lrocblas
  22. // #cgo windows,cuda LDFLAGS: -L. -L"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.3/lib/x64" -lggml-cuda -lcuda -lcudart -lcublas -lcublasLt
  23. // #cgo windows,rocm LDFLAGS: -L. -L"C:/Program Files/AMD/ROCm/5.7/lib"
  24. // #cgo linux,cuda LDFLAGS: -L${SRCDIR} -L/usr/local/cuda/lib64 -lggml-cuda -lcuda -lcudart -lcublas -lcublasLt -lpthread -ldl -lrt
  25. // #cgo linux,rocm LDFLAGS: -L/opt/rocm/lib
  26. // #include <stdlib.h>
  27. // #include "llama.h"
  28. // #include "clip.h"
  29. // #include "llava.h"
  30. // #include "sampling_ext.h"
  31. import "C"
  32. import (
  33. "fmt"
  34. "runtime"
  35. "strings"
  36. "unsafe"
  37. "github.com/ollama/ollama/llm"
  38. )
  39. func BackendInit() {
  40. C.llama_backend_init()
  41. }
  42. func PrintSystemInfo() string {
  43. return C.GoString(C.llama_print_system_info())
  44. }
  45. type ContextParams struct {
  46. c C.struct_llama_context_params
  47. }
  48. func NewContextParams() ContextParams {
  49. params := C.llama_context_default_params()
  50. params.seed = C.uint(1234)
  51. params.n_ctx = C.uint(2048)
  52. params.n_threads = C.uint(runtime.NumCPU())
  53. params.n_threads_batch = params.n_threads
  54. return ContextParams{c: params}
  55. }
  56. type ModelParams struct {
  57. c C.struct_llama_model_params
  58. }
  59. func NewModelParams() ModelParams {
  60. params := C.llama_model_default_params()
  61. params.n_gpu_layers = 999
  62. return ModelParams{c: params}
  63. }
  64. type Context struct {
  65. c *C.struct_llama_context
  66. }
  67. func (c *Context) KvCacheClear() {
  68. C.llama_kv_cache_clear(c.c)
  69. }
  70. func (c *Context) Decode(batch Batch) error {
  71. // Positive return values does not mean a fatal error, but rather a warning.
  72. // 0 - success
  73. // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context)
  74. // < 0 - error
  75. code := int(C.llama_decode(c.c, batch.c))
  76. if code < 0 {
  77. return fmt.Errorf("llama_decode failed with code %d", code)
  78. }
  79. if code > 0 {
  80. return fmt.Errorf("could not find a KV slot for the batch - try reducing the size of the batch or increase the context. code: %d", code)
  81. }
  82. return nil
  83. }
  84. func (c *Context) Model() *Model {
  85. return &Model{c: C.llama_get_model(c.c)}
  86. }
  87. func (c *Context) GetLogitsIth(i int) []float32 {
  88. return unsafe.Slice((*float32)(unsafe.Pointer(C.llama_get_logits_ith(c.c, C.int(i)))), c.Model().NumVocab())
  89. }
  90. func (c *Context) SampleTokenGreedy(logits []float32) int {
  91. candidates := (*C.struct_llama_token_data)(C.malloc(C.size_t(len(logits)) * C.size_t(unsafe.Sizeof(C.struct_llama_token_data{}))))
  92. defer C.free(unsafe.Pointer(candidates))
  93. for i, logit := range logits {
  94. ptr := (*C.struct_llama_token_data)(unsafe.Pointer(uintptr(unsafe.Pointer(candidates)) + uintptr(i)*unsafe.Sizeof(C.struct_llama_token_data{})))
  95. ptr.id = C.int(i)
  96. ptr.logit = C.float(logit)
  97. ptr.p = 0.0
  98. }
  99. return int(C.llama_sample_token_greedy(c.c, &C.llama_token_data_array{
  100. data: candidates,
  101. size: C.size_t(len(logits)),
  102. sorted: C.bool(false),
  103. }))
  104. }
  105. func (c *Context) KvCacheSeqRm(seqId int, p0 int, p1 int) bool {
  106. return bool(C.llama_kv_cache_seq_rm(c.c, C.int(seqId), C.int(p0), C.int(p1)))
  107. }
  108. func LoadModelFromFile(modelPath string, params ModelParams) *Model {
  109. return &Model{c: C.llama_load_model_from_file(C.CString(modelPath), params.c)}
  110. }
  111. func NewContextWithModel(model *Model, params ContextParams) *Context {
  112. return &Context{c: C.llama_new_context_with_model(model.c, params.c)}
  113. }
  114. func (m *Model) NumVocab() int {
  115. return int(C.llama_n_vocab(m.c))
  116. }
  117. func (m *Model) TokenIsEog(token int) bool {
  118. return bool(C.llama_token_is_eog(m.c, C.llama_token(token)))
  119. }
  120. type Batch struct {
  121. c C.struct_llama_batch
  122. }
  123. func NewBatch(nTokens int, embd int, maxSeq int) Batch {
  124. return Batch{c: C.llama_batch_init(C.int(nTokens), C.int(embd), C.int(maxSeq))}
  125. }
  126. func (b *Batch) NumTokens() int {
  127. return int(b.c.n_tokens)
  128. }
  129. // Add adds a token to the batch with the given position for the given
  130. // sequence ids, and optionally instructs to include logits.
  131. func (b *Batch) Add(token int, pos int, seqIds []int, logits bool) {
  132. unsafe.Slice(b.c.token, 512)[b.c.n_tokens] = C.llama_token(token)
  133. unsafe.Slice(b.c.pos, 512)[b.c.n_tokens] = C.llama_pos(pos)
  134. unsafe.Slice(b.c.n_seq_id, 512)[b.c.n_tokens] = C.int(len(seqIds))
  135. for i, s := range seqIds {
  136. unsafe.Slice((unsafe.Slice(b.c.seq_id, 512)[b.c.n_tokens]), C.int(len(seqIds)))[i] = C.int32_t(s)
  137. }
  138. if logits {
  139. unsafe.Slice(b.c.logits, 512)[b.c.n_tokens] = 1
  140. }
  141. b.c.n_tokens += 1
  142. }
  143. func (b *Batch) Clear() {
  144. b.c.n_tokens = 0
  145. }
  146. func (b *Batch) Free() {
  147. C.llama_batch_free(b.c)
  148. }
  149. func BatchGetOne(tokens []int, pos0 int, seqId int) Batch {
  150. return Batch{c: C.llama_batch_get_one((*C.int)(unsafe.Pointer(&tokens[0])), C.int32_t(len(tokens)), C.int(pos0), C.int(seqId))}
  151. }
  152. type Model struct {
  153. c *C.struct_llama_model
  154. }
  155. func (m *Model) TokenToPiece(token int) string {
  156. buf := make([]byte, 12)
  157. C.llama_token_to_piece(
  158. m.c,
  159. C.int32_t(token),
  160. (*C.char)(unsafe.Pointer(&buf[0])),
  161. C.int32_t(12),
  162. C.bool(true),
  163. )
  164. return strings.TrimRight(string(buf), "\x00")
  165. }
  166. func (m *Model) Tokenize(text string, maxTokens int, addSpecial bool, parseSpecial bool) ([]int, error) {
  167. cTokens := make([]C.llama_token, maxTokens)
  168. cText := C.CString(text)
  169. defer C.free(unsafe.Pointer(cText))
  170. result := C.llama_tokenize(
  171. m.c,
  172. cText,
  173. C.int32_t(len(text)),
  174. &cTokens[0],
  175. C.int32_t(maxTokens),
  176. C.bool(addSpecial),
  177. C.bool(parseSpecial),
  178. )
  179. if result < 0 {
  180. return nil, fmt.Errorf("tokenization failed, required %d tokens", -result)
  181. }
  182. tokens := make([]int, result)
  183. for i := 0; i < int(result); i++ {
  184. tokens[i] = int(cTokens[i])
  185. }
  186. return tokens, nil
  187. }
  188. func Quantize(infile, outfile string, ftype llm.FileType) error {
  189. cinfile := C.CString(infile)
  190. defer C.free(unsafe.Pointer(cinfile))
  191. coutfile := C.CString(outfile)
  192. defer C.free(unsafe.Pointer(coutfile))
  193. params := C.llama_model_quantize_default_params()
  194. params.nthread = -1
  195. params.ftype = ftype.Value()
  196. if rc := C.llama_model_quantize(cinfile, coutfile, &params); rc != 0 {
  197. return fmt.Errorf("llama_model_quantize: %d", rc)
  198. }
  199. return nil
  200. }
  201. // llava
  202. type ClipContext struct {
  203. c *C.struct_clip_ctx
  204. }
  205. func NewClipContext(modelPath string) *ClipContext {
  206. mp := C.CString(modelPath)
  207. defer C.free(unsafe.Pointer(mp))
  208. cc := C.clip_model_load(mp, 1)
  209. return &ClipContext{c: cc}
  210. }
  211. type LlavaContext struct {
  212. c *C.struct_llava_context
  213. }
  214. type LlavaImageEmbed struct {
  215. c *C.struct_llava_image_embed
  216. }
  217. func NewLlavaImageEmbed(clipContext *ClipContext, data []byte) *LlavaImageEmbed {
  218. return &LlavaImageEmbed{c: C.llava_image_embed_make_with_bytes(clipContext.c, C.int(runtime.NumCPU()), (*C.uchar)(unsafe.Pointer(&data[0])), C.int(len(data)))}
  219. }
  220. func LlavaEvalImageEmbed(llamaContext *Context, embed *LlavaImageEmbed, nBatch int, nPast *int) {
  221. C.llava_eval_image_embed(llamaContext.c, embed.c, C.int(nBatch), (*C.int)(unsafe.Pointer(nPast)))
  222. }
  223. // sampling
  224. // TODO: this is a temporary wrapper to allow calling C++ code from CGo
  225. type SamplingContext struct {
  226. c *C.struct_llama_sampling_context
  227. }
  228. type SamplingParams struct {
  229. TopK int
  230. TopP float32
  231. TfsZ float32
  232. TypicalP float32
  233. Temp float32
  234. PenaltyRepeat float32
  235. PenaltyFreq float32
  236. PenaltyPresent float32
  237. Mirostat int
  238. MirostatTau float32
  239. MirostatEta float32
  240. PenalizeNl bool
  241. Seed uint32
  242. }
  243. func NewSamplingContext(params SamplingParams) *SamplingContext {
  244. var cparams C.struct_llama_sampling_cparams
  245. cparams.top_k = C.int32_t(params.TopK)
  246. cparams.top_p = C.float(params.TopP)
  247. cparams.tfs_z = C.float(params.TfsZ)
  248. cparams.typical_p = C.float(params.TypicalP)
  249. cparams.temp = C.float(params.Temp)
  250. cparams.penalty_repeat = C.float(params.PenaltyRepeat)
  251. cparams.penalty_freq = C.float(params.PenaltyFreq)
  252. cparams.penalty_present = C.float(params.PenaltyFreq)
  253. cparams.mirostat = C.int32_t(params.Mirostat)
  254. cparams.mirostat_tau = C.float(params.MirostatTau)
  255. cparams.mirostat_eta = C.float(params.MirostatEta)
  256. cparams.penalize_nl = C.bool(params.PenalizeNl)
  257. cparams.seed = C.uint32_t(params.Seed)
  258. return &SamplingContext{c: C.llama_sampling_cinit(&cparams)}
  259. }
  260. func (s *SamplingContext) Free() {
  261. C.llama_sampling_cfree(s.c)
  262. }
  263. func (s *SamplingContext) Reset() {
  264. C.llama_sampling_creset(s.c)
  265. }
  266. func (s *SamplingContext) Sample(ctxMain *Context, ctxConfig *Context, idx int) int {
  267. // TODO (jmorganca): handle nil for all args
  268. if ctxConfig == nil {
  269. return int(C.llama_sampling_csample(s.c, ctxMain.c, nil, C.int(idx)))
  270. }
  271. return int(C.llama_sampling_csample(s.c, ctxMain.c, ctxConfig.c, C.int(idx)))
  272. }
  273. func (s *SamplingContext) Accept(ctxMain *Context, id int, applyGrammar bool) {
  274. C.llama_sampling_caccept(s.c, ctxMain.c, C.llama_token(id), C.bool(applyGrammar))
  275. }