llama.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // MIT License
  2. // Copyright (c) 2023 go-skynet authors
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. // The above copyright notice and this permission notice shall be included in all
  10. // copies or substantial portions of the Software.
  11. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. // SOFTWARE.
  18. //go:generate cmake -S . -B build
  19. //go:generate cmake --build build
  20. package llama
  21. // #cgo LDFLAGS: -Lbuild -lbinding -lllama -lm -lggml_static -lstdc++
  22. // #cgo CXXFLAGS: -std=c++11
  23. // #cgo darwin LDFLAGS: -framework Accelerate -framework Foundation -framework Metal -framework MetalKit -framework MetalPerformanceShaders
  24. // #include "binding/binding.h"
  25. // #include <stdlib.h>
  26. import "C"
  27. import (
  28. "fmt"
  29. "strings"
  30. "sync"
  31. "unsafe"
  32. )
  33. type LLama struct {
  34. ctx unsafe.Pointer
  35. embeddings bool
  36. contextSize int
  37. }
  38. func New(model string, opts ...ModelOption) (*LLama, error) {
  39. mo := NewModelOptions(opts...)
  40. modelPath := C.CString(model)
  41. defer C.free(unsafe.Pointer(modelPath))
  42. 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))
  43. if ctx == nil {
  44. return nil, fmt.Errorf("failed loading model")
  45. }
  46. ll := &LLama{ctx: ctx, contextSize: mo.ContextSize, embeddings: mo.Embeddings}
  47. return ll, nil
  48. }
  49. func (l *LLama) Free() {
  50. C.llama_binding_free_model(l.ctx)
  51. }
  52. func (l *LLama) Eval(text string, opts ...PredictOption) error {
  53. po := NewPredictOptions(opts...)
  54. input := C.CString(text)
  55. if po.Tokens == 0 {
  56. po.Tokens = 99999999
  57. }
  58. reverseCount := len(po.StopPrompts)
  59. reversePrompt := make([]*C.char, reverseCount)
  60. var pass **C.char
  61. for i, s := range po.StopPrompts {
  62. cs := C.CString(s)
  63. reversePrompt[i] = cs
  64. pass = &reversePrompt[0]
  65. }
  66. params := C.llama_allocate_params(input, C.int(po.Seed), C.int(po.Threads), C.int(po.Tokens), C.int(po.TopK),
  67. C.float(po.TopP), C.float(po.Temperature), C.float(po.Penalty), C.int(po.Repeat),
  68. C.bool(po.IgnoreEOS), C.bool(po.F16KV),
  69. C.int(po.Batch), C.int(po.NKeep), pass, C.int(reverseCount),
  70. C.float(po.TailFreeSamplingZ), C.float(po.TypicalP), C.float(po.FrequencyPenalty), C.float(po.PresencePenalty),
  71. C.int(po.Mirostat), C.float(po.MirostatETA), C.float(po.MirostatTAU), C.bool(po.PenalizeNL), C.CString(po.LogitBias),
  72. C.CString(po.PathPromptCache), C.bool(po.PromptCacheAll), C.bool(po.MLock), C.bool(po.MMap),
  73. C.CString(po.MainGPU), C.CString(po.TensorSplit),
  74. C.bool(po.PromptCacheRO),
  75. )
  76. ret := C.eval(params, l.ctx, input)
  77. if ret != 0 {
  78. return fmt.Errorf("inference failed")
  79. }
  80. fmt.Println("hi 4")
  81. C.llama_free_params(params)
  82. fmt.Println("hi 5")
  83. return nil
  84. }
  85. func (l *LLama) Predict(text string, opts ...PredictOption) (string, error) {
  86. po := NewPredictOptions(opts...)
  87. fmt.Println("predict 1")
  88. if po.TokenCallback != nil {
  89. setCallback(l.ctx, po.TokenCallback)
  90. }
  91. fmt.Println("predict 2")
  92. input := C.CString(text)
  93. if po.Tokens == 0 {
  94. po.Tokens = 99999999
  95. }
  96. out := make([]byte, po.Tokens)
  97. fmt.Println("predict 3")
  98. reverseCount := len(po.StopPrompts)
  99. reversePrompt := make([]*C.char, reverseCount)
  100. var pass **C.char
  101. for i, s := range po.StopPrompts {
  102. cs := C.CString(s)
  103. reversePrompt[i] = cs
  104. pass = &reversePrompt[0]
  105. }
  106. fmt.Println("predict 4")
  107. params := C.llama_allocate_params(input, C.int(po.Seed), C.int(po.Threads), C.int(po.Tokens), C.int(po.TopK),
  108. C.float(po.TopP), C.float(po.Temperature), C.float(po.Penalty), C.int(po.Repeat),
  109. C.bool(po.IgnoreEOS), C.bool(po.F16KV),
  110. C.int(po.Batch), C.int(po.NKeep), pass, C.int(reverseCount),
  111. C.float(po.TailFreeSamplingZ), C.float(po.TypicalP), C.float(po.FrequencyPenalty), C.float(po.PresencePenalty),
  112. C.int(po.Mirostat), C.float(po.MirostatETA), C.float(po.MirostatTAU), C.bool(po.PenalizeNL), C.CString(po.LogitBias),
  113. C.CString(po.PathPromptCache), C.bool(po.PromptCacheAll), C.bool(po.MLock), C.bool(po.MMap),
  114. C.CString(po.MainGPU), C.CString(po.TensorSplit),
  115. C.bool(po.PromptCacheRO),
  116. )
  117. fmt.Println("predict 4.5")
  118. ret := C.llama_predict(params, l.ctx, (*C.char)(unsafe.Pointer(&out[0])), C.bool(po.DebugMode))
  119. if ret != 0 {
  120. return "", fmt.Errorf("inference failed")
  121. }
  122. res := C.GoString((*C.char)(unsafe.Pointer(&out[0])))
  123. fmt.Println("predict 5")
  124. res = strings.TrimPrefix(res, " ")
  125. res = strings.TrimPrefix(res, text)
  126. res = strings.TrimPrefix(res, "\n")
  127. for _, s := range po.StopPrompts {
  128. res = strings.TrimRight(res, s)
  129. }
  130. fmt.Println("predict 6")
  131. C.llama_free_params(params)
  132. if po.TokenCallback != nil {
  133. setCallback(l.ctx, nil)
  134. }
  135. return res, nil
  136. }
  137. // CGo only allows us to use static calls from C to Go, we can't just dynamically pass in func's.
  138. // This is the next best thing, we register the callbacks in this map and call tokenCallback from
  139. // the C code. We also attach a finalizer to LLama, so it will unregister the callback when the
  140. // garbage collection frees it.
  141. // SetTokenCallback registers a callback for the individual tokens created when running Predict. It
  142. // will be called once for each token. The callback shall return true as long as the model should
  143. // continue predicting the next token. When the callback returns false the predictor will return.
  144. // The tokens are just converted into Go strings, they are not trimmed or otherwise changed. Also
  145. // the tokens may not be valid UTF-8.
  146. // Pass in nil to remove a callback.
  147. //
  148. // It is save to call this method while a prediction is running.
  149. func (l *LLama) SetTokenCallback(callback func(token string) bool) {
  150. setCallback(l.ctx, callback)
  151. }
  152. var (
  153. m sync.Mutex
  154. callbacks = map[uintptr]func(string) bool{}
  155. )
  156. //export tokenCallback
  157. func tokenCallback(statePtr unsafe.Pointer, token *C.char) bool {
  158. m.Lock()
  159. defer m.Unlock()
  160. if callback, ok := callbacks[uintptr(statePtr)]; ok {
  161. return callback(C.GoString(token))
  162. }
  163. return true
  164. }
  165. // setCallback can be used to register a token callback for LLama. Pass in a nil callback to
  166. // remove the callback.
  167. func setCallback(statePtr unsafe.Pointer, callback func(string) bool) {
  168. m.Lock()
  169. defer m.Unlock()
  170. if callback == nil {
  171. delete(callbacks, uintptr(statePtr))
  172. } else {
  173. callbacks[uintptr(statePtr)] = callback
  174. }
  175. }