llama.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package llama
  2. // #cgo darwin,arm64 CFLAGS: -std=c11 -DGGML_USE_METAL -DGGML_METAL_EMBED_LIBRARY -DGGML_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
  3. // #cgo darwin,arm64 CXXFLAGS: -std=c++11 -DGGML_USE_METAL -DGGML_METAL_EMBED_LIBRARY -DGGML_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
  4. // #cgo darwin,amd64 CXXFLAGS: -std=c++11
  5. // #cgo darwin,arm64 LDFLAGS: -ld_classic ${SRCDIR}/ggml-metal.o -framework Foundation -framework Metal -framework MetalKit -framework Accelerate
  6. // #cgo darwin,amd64 LDFLAGS: -ld_classic -framework Foundation -framework Accelerate
  7. // #cgo windows LDFLAGS: -lmsvcrt
  8. // #cgo avx CFLAGS: -mavx
  9. // #cgo avx CXXFLAGS: -mavx
  10. // #cgo avx2 CFLAGS: -mavx -mavx2 -mfma
  11. // #cgo avx2 CXXFLAGS: -mavx -mavx2 -mfma
  12. // #cgo cuda CFLAGS: -DGGML_USE_CUDA -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_MULTIPLATFORM -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  13. // #cgo cuda CXXFLAGS: -std=c++11 -DGGML_USE_CUDA -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_MULTIPLATFORM -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  14. // #cgo rocm CXXFLAGS: -std=c++11 -DGGML_USE_CUDA -DGGML_USE_HIPBLAS -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_MULTIPLATFORM -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  15. // #cgo windows,cuda LDFLAGS: -L. -L"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.3/lib/x64" -lggml-cuda -lcuda -lcudart -lcublas -lcublasLt
  16. // #cgo windows,rocm LDFLAGS: -L. -L"C:/Program Files/AMD/ROCm/5.7/lib" -lggml-hipblas -lhipblas -lamdhip64 -lrocblas
  17. // #include <stdlib.h>
  18. // #include "llama.h"
  19. import "C"
  20. import (
  21. "fmt"
  22. "runtime"
  23. "strings"
  24. "unsafe"
  25. "github.com/ollama/ollama/llm"
  26. )
  27. type Token int32
  28. type Pos int32
  29. type SeqId int32
  30. // SystemInfo is an unused example of calling llama.cpp functions using CGo
  31. func PrintSystemInfo() string {
  32. return C.GoString(C.llama_print_system_info())
  33. }
  34. func BackendInit() {
  35. C.llama_backend_init()
  36. }
  37. type ContextParams struct {
  38. c C.struct_llama_context_params
  39. }
  40. func NewContextParams() ContextParams {
  41. params := C.llama_context_default_params()
  42. params.seed = C.uint(1234)
  43. params.n_ctx = C.uint(2048)
  44. params.n_threads = C.uint(runtime.NumCPU())
  45. params.n_threads_batch = params.n_threads
  46. return ContextParams{c: params}
  47. }
  48. type ModelParams struct {
  49. c C.struct_llama_model_params
  50. }
  51. func NewModelParams() ModelParams {
  52. params := C.llama_model_default_params()
  53. params.n_gpu_layers = 999
  54. return ModelParams{c: params}
  55. }
  56. type Context struct {
  57. c *C.struct_llama_context
  58. }
  59. func (c *Context) Decode(batch Batch) error {
  60. // Positive return values does not mean a fatal error, but rather a warning.
  61. // 0 - success
  62. // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context)
  63. // < 0 - error
  64. code := int(C.llama_decode(c.c, batch.c))
  65. if code < 0 {
  66. return fmt.Errorf("llama_decode failed with code %d", code)
  67. }
  68. if code > 0 {
  69. 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\n", code)
  70. }
  71. return nil
  72. }
  73. func (c *Context) getModel() *Model {
  74. return &Model{c: C.llama_get_model(c.c)}
  75. }
  76. func (c *Context) SampleTokenGreedy(batch Batch) Token {
  77. nv := c.getModel().NumVocab()
  78. // TODO(jmorganca): split this up into different functions
  79. candidates := (*C.struct_llama_token_data)(C.malloc(C.size_t(nv) * C.size_t(unsafe.Sizeof(C.struct_llama_token_data{}))))
  80. defer C.free(unsafe.Pointer(candidates))
  81. // get most recent logits
  82. logits := C.llama_get_logits_ith(c.c, C.int(batch.NumTokens()-1))
  83. for i := 0; i < int(nv); i++ {
  84. ptr := (*C.struct_llama_token_data)(unsafe.Pointer(uintptr(unsafe.Pointer(candidates)) + uintptr(i)*unsafe.Sizeof(C.struct_llama_token_data{})))
  85. ptr.id = C.int(i)
  86. ptr.logit = unsafe.Slice(logits, nv)[i]
  87. ptr.p = 0.0
  88. }
  89. return Token(C.llama_sample_token_greedy(c.c, &C.llama_token_data_array{
  90. data: candidates,
  91. size: C.size_t(nv),
  92. sorted: C.bool(false),
  93. }))
  94. }
  95. func LoadModelFromFile(modelPath string, params ModelParams) *Model {
  96. return &Model{c: C.llama_load_model_from_file(C.CString(modelPath), params.c)}
  97. }
  98. func NewContextWithModel(model *Model, params ContextParams) *Context {
  99. return &Context{c: C.llama_new_context_with_model(model.c, params.c)}
  100. }
  101. func (m *Model) NumVocab() int {
  102. return int(C.llama_n_vocab(m.c))
  103. }
  104. func (m *Model) TokenIsEog(token Token) bool {
  105. return bool(C.llama_token_is_eog(m.c, C.llama_token(token)))
  106. }
  107. type Batch struct {
  108. c C.struct_llama_batch
  109. }
  110. func NewBatch(nTokens int, nSeqs int, nCtx int) Batch {
  111. return Batch{c: C.llama_batch_init(C.int(nTokens), C.int(nSeqs), C.int(nCtx))}
  112. }
  113. func (b *Batch) NumTokens() int {
  114. return int(b.c.n_tokens)
  115. }
  116. func (b *Batch) Add(token Token, pos Pos, seqIds []SeqId, logits bool) {
  117. unsafe.Slice(b.c.token, 512)[b.c.n_tokens] = C.llama_token(token)
  118. unsafe.Slice(b.c.pos, 512)[b.c.n_tokens] = C.llama_pos(pos)
  119. unsafe.Slice(b.c.n_seq_id, 512)[b.c.n_tokens] = C.int(len(seqIds))
  120. for i, s := range seqIds {
  121. unsafe.Slice((unsafe.Slice(b.c.seq_id, 512)[b.c.n_tokens]), C.int(len(seqIds)))[i] = C.int32_t(s)
  122. }
  123. if logits {
  124. unsafe.Slice(b.c.logits, 512)[b.c.n_tokens] = 1
  125. }
  126. b.c.n_tokens += 1
  127. }
  128. func (b *Batch) Clear() {
  129. b.c.n_tokens = 0
  130. }
  131. type Model struct {
  132. c *C.struct_llama_model
  133. }
  134. func (m *Model) TokenToPiece(token Token) string {
  135. buf := make([]byte, 12)
  136. C.llama_token_to_piece(
  137. m.c,
  138. C.int32_t(token),
  139. (*C.char)(unsafe.Pointer(&buf[0])),
  140. C.int32_t(12),
  141. C.bool(true),
  142. )
  143. return strings.TrimRight(string(buf), "\x00")
  144. }
  145. func (m *Model) Tokenize(text string, maxTokens int, addSpecial bool, parseSpecial bool) ([]Token, error) {
  146. cTokens := make([]C.llama_token, maxTokens)
  147. cText := C.CString(text)
  148. defer C.free(unsafe.Pointer(cText))
  149. result := C.llama_tokenize(
  150. m.c,
  151. cText,
  152. C.int32_t(len(text)),
  153. &cTokens[0],
  154. C.int32_t(maxTokens),
  155. C.bool(addSpecial),
  156. C.bool(parseSpecial),
  157. )
  158. if result < 0 {
  159. return nil, fmt.Errorf("tokenization failed, required %d tokens", -result)
  160. }
  161. tokens := make([]Token, result)
  162. for i := 0; i < int(result); i++ {
  163. tokens[i] = Token(cTokens[i])
  164. }
  165. return tokens, nil
  166. }
  167. func Quantize(infile, outfile string, ftype llm.FileType) error {
  168. cinfile := C.CString(infile)
  169. defer C.free(unsafe.Pointer(cinfile))
  170. coutfile := C.CString(outfile)
  171. defer C.free(unsafe.Pointer(coutfile))
  172. params := C.llama_model_quantize_default_params()
  173. params.nthread = -1
  174. params.ftype = ftype.Value()
  175. if rc := C.llama_model_quantize(cinfile, coutfile, &params); rc != 0 {
  176. return fmt.Errorf("llama_model_quantize: %d", rc)
  177. }
  178. return nil
  179. }