llama.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. package llama
  2. //go:generate make -j 8
  3. /*
  4. #cgo CFLAGS: -O3 -std=c17 -DGGML_BUILD=1 -DNDEBUG -DLOG_DISABLE_LOGS -DGGML_USE_LLAMAFILE -DGGML_USE_CPU -DGGML_USE_CPU_AARCH64
  5. #cgo CXXFLAGS: -O3 -std=c++17 -DGGML_BUILD=1 -DNDEBUG -DLOG_DISABLE_LOGS -DGGML_USE_LLAMAFILE -DGGML_USE_CPU -DGGML_USE_CPU_AARCH64
  6. #cgo amd64,avx CFLAGS: -mavx
  7. #cgo amd64,avx CXXFLAGS: -mavx
  8. #cgo amd64,avx2 CFLAGS: -mavx2 -mfma -mf16c
  9. #cgo amd64,avx2 CXXFLAGS: -mavx2 -mfma -mf16c
  10. #cgo amd64,avx512 CFLAGS: -mavx512f -mavx512dq -mavx512bw
  11. #cgo amd64,avx512 CXXFLAGS: -mavx512f -mavx512dq -mavx512bw
  12. #cgo amd64,avx512bf16 CFLAGS: -mavx512bf16 -D__AVX512BF16__
  13. #cgo amd64,avx512bf16 CXXFLAGS: -mavx512bf16 -D__AVX512BF16__
  14. #cgo amd64,avx512vbmi CFLAGS: -mavx512vbmi -D__AVX512VBMI__
  15. #cgo amd64,avx512vbmi CXXFLAGS: -mavx512vbmi -D__AVX512VBMI__
  16. #cgo amd64,avx512vnni CFLAGS: -mavx512vnni -D__AVX512VNNI__
  17. #cgo amd64,avx512vnni CXXFLAGS: -mavx512vnni -D__AVX512VNNI__
  18. #cgo amd64,f16c CFLAGS: -mf16c
  19. #cgo amd64,f16c CXXFLAGS: -mf16c
  20. #cgo amd64,fma CFLAGS: -mfma
  21. #cgo amd64,fma CXXFLAGS: -mfma
  22. #cgo cuda CFLAGS: -fPIE -DGGML_USE_CUDA -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  23. #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
  24. #cgo cuda_jetpack5 LDFLAGS: -lggml_cuda_jetpack5
  25. #cgo cuda_jetpack6 LDFLAGS: -lggml_cuda_jetpack6
  26. #cgo cuda_v11 LDFLAGS: -lggml_cuda_v11
  27. #cgo cuda_v12 LDFLAGS: -lggml_cuda_v12
  28. #cgo darwin,amd64 CFLAGS: -Wno-incompatible-pointer-types-discards-qualifiers
  29. #cgo darwin,amd64 CXXFLAGS: -Wno-incompatible-pointer-types-discards-qualifiers
  30. #cgo darwin,amd64 LDFLAGS: -framework Foundation
  31. #cgo darwin,amd64,avx2 CFLAGS: -DGGML_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
  32. #cgo darwin,amd64,avx2 CXXFLAGS: -DGGML_USE_ACCELERATE -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
  33. #cgo darwin,amd64,avx2 LDFLAGS: -framework Accelerate
  34. #cgo darwin,arm64 CFLAGS: -DGGML_USE_METAL -DGGML_USE_ACCELERATE -DGGML_METAL_EMBED_LIBRARY -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64 -DGGML_USE_BLAS -DGGML_BLAS_USE_ACCELERATE
  35. #cgo darwin,arm64 CXXFLAGS: -DGGML_USE_METAL -DGGML_USE_ACCELERATE -DGGML_METAL_EMBED_LIBRARY -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64 -DGGML_USE_BLAS -DGGML_BLAS_USE_ACCELERATE
  36. #cgo darwin,arm64 LDFLAGS: -framework Foundation -framework Metal -framework MetalKit -framework Accelerate
  37. #cgo linux CFLAGS: -D_GNU_SOURCE
  38. #cgo linux CXXFLAGS: -D_GNU_SOURCE
  39. #cgo linux LDFLAGS: -ldl
  40. #cgo linux,amd64 LDFLAGS: -L${SRCDIR}/build/linux-amd64
  41. #cgo linux,arm64 CFLAGS: -D__aarch64__ -D__ARM_NEON -D__ARM_FEATURE_FMA
  42. #cgo linux,arm64 CXXFLAGS: -D__aarch64__ -D__ARM_NEON -D__ARM_FEATURE_FMA
  43. #cgo linux,arm64 LDFLAGS: -L${SRCDIR}/build/linux-arm64
  44. #cgo linux,arm64,sve CFLAGS: -march=armv8.6-a+sve
  45. #cgo linux,arm64,sve CXXFLAGS: -march=armv8.6-a+sve
  46. #cgo linux,cuda LDFLAGS: -lcuda -lcudart -lcublas -lcublasLt -lpthread -lrt -lresolv
  47. #cgo linux,rocm LDFLAGS: -lpthread -lrt -lresolv
  48. #cgo rocm CFLAGS: -DGGML_USE_CUDA -DGGML_USE_HIP -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  49. #cgo rocm CXXFLAGS: -DGGML_USE_CUDA -DGGML_USE_HIP -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_CUDA_MMV_Y=1 -DGGML_BUILD=1
  50. #cgo rocm LDFLAGS: -L${SRCDIR} -lggml_rocm -lhipblas -lamdhip64 -lrocblas
  51. #cgo windows CFLAGS: -Wno-discarded-qualifiers -D_WIN32_WINNT=0x602
  52. #cgo windows CXXFLAGS: -D_WIN32_WINNT=0x602
  53. #cgo windows LDFLAGS: -lmsvcrt -static-libstdc++ -static-libgcc -static
  54. #cgo windows,amd64 LDFLAGS: -L${SRCDIR}/build/windows-amd64
  55. #cgo windows,arm64 CFLAGS: -D__aarch64__ -D__ARM_NEON -D__ARM_FEATURE_FMA
  56. #cgo windows,arm64 CXXFLAGS: -D__aarch64__ -D__ARM_NEON -D__ARM_FEATURE_FMA
  57. #cgo windows,arm64 LDFLAGS: -L${SRCDIR}/build/windows-arm64
  58. #cgo windows,cuda LDFLAGS: -lcuda -lcudart -lcublas -lcublasLt
  59. #cgo windows,rocm LDFLAGS: -lggml_rocm -lhipblas -lamdhip64 -lrocblas
  60. #include <stdlib.h>
  61. #include "llama.h"
  62. #include "clip.h"
  63. #include "ggml.h"
  64. #include "llava.h"
  65. #include "mllama.h"
  66. #include "sampling_ext.h"
  67. extern bool llamaProgressCallback(float progress, void *user_data);
  68. extern void llamaLog(int level, char* text, void* user_data);
  69. typedef enum {COMP_UNKNOWN,COMP_GCC,COMP_CLANG} COMPILER;
  70. COMPILER inline get_compiler() {
  71. #if defined(__clang__)
  72. return COMP_CLANG;
  73. #elif defined(__GNUC__)
  74. return COMP_GCC;
  75. #else
  76. return UNKNOWN_COMPILER;
  77. #endif
  78. }
  79. */
  80. import "C"
  81. import (
  82. _ "embed"
  83. "errors"
  84. "fmt"
  85. "runtime"
  86. "runtime/cgo"
  87. "slices"
  88. "strings"
  89. "sync/atomic"
  90. "unsafe"
  91. )
  92. func BackendInit() {
  93. C.llama_backend_init()
  94. }
  95. func PrintSystemInfo() string {
  96. var compiler string
  97. switch C.get_compiler() {
  98. case C.COMP_UNKNOWN:
  99. compiler = "cgo(unknown_compiler)"
  100. case C.COMP_GCC:
  101. compiler = "cgo(gcc)"
  102. case C.COMP_CLANG:
  103. compiler = "cgo(clang)"
  104. }
  105. return C.GoString(C.llama_print_system_info()) + compiler
  106. }
  107. var logLevel atomic.Int32
  108. func init() {
  109. logLevel.Store(int32(C.GGML_LOG_LEVEL_INFO))
  110. C.llama_log_set((C.ggml_log_callback)(C.llamaLog), nil)
  111. }
  112. func EnableDebug() {
  113. logLevel.Store(int32(C.GGML_LOG_LEVEL_DEBUG))
  114. }
  115. //export llamaLog
  116. func llamaLog(level int32, text *C.char, _ unsafe.Pointer) {
  117. if level < logLevel.Load() {
  118. return
  119. }
  120. fmt.Print(C.GoString(text))
  121. }
  122. func GetModelArch(modelPath string) (string, error) {
  123. mp := C.CString(modelPath)
  124. defer C.free(unsafe.Pointer(mp))
  125. gguf_ctx := C.gguf_init_from_file(mp, C.struct_gguf_init_params{no_alloc: true, ctx: (**C.struct_ggml_context)(C.NULL)})
  126. if gguf_ctx == nil {
  127. return "", errors.New("unable to load model file")
  128. }
  129. defer C.gguf_free(gguf_ctx)
  130. key := C.CString("general.architecture")
  131. defer C.free(unsafe.Pointer(key))
  132. arch_index := C.gguf_find_key(gguf_ctx, key)
  133. if int(arch_index) < 0 {
  134. return "", errors.New("unknown model architecture")
  135. }
  136. arch := C.gguf_get_val_str(gguf_ctx, arch_index)
  137. return C.GoString(arch), nil
  138. }
  139. type ContextParams struct {
  140. c C.struct_llama_context_params
  141. }
  142. func NewContextParams(numCtx int, batchSize int, numSeqMax int, threads int, flashAttention bool, kvCacheType string) ContextParams {
  143. params := C.llama_context_default_params()
  144. params.n_ctx = C.uint(numCtx)
  145. params.n_batch = C.uint(batchSize)
  146. params.n_seq_max = C.uint(numSeqMax)
  147. params.n_threads = C.int(threads)
  148. params.n_threads_batch = params.n_threads
  149. params.embeddings = C.bool(true)
  150. params.flash_attn = C.bool(flashAttention)
  151. params.type_k = kvCacheTypeFromStr(strings.ToLower(kvCacheType))
  152. params.type_v = kvCacheTypeFromStr(strings.ToLower(kvCacheType))
  153. return ContextParams{c: params}
  154. }
  155. // kvCacheTypeFromStr converts a string cache type to the corresponding GGML type value
  156. func kvCacheTypeFromStr(s string) C.enum_ggml_type {
  157. if s == "" {
  158. return C.GGML_TYPE_F16
  159. }
  160. switch s {
  161. case "q8_0":
  162. return C.GGML_TYPE_Q8_0
  163. case "q4_0":
  164. return C.GGML_TYPE_Q4_0
  165. default:
  166. return C.GGML_TYPE_F16
  167. }
  168. }
  169. type Context struct {
  170. c *C.struct_llama_context
  171. numThreads int
  172. }
  173. var ErrKvCacheFull = errors.New("could not find a kv cache slot")
  174. func (c *Context) Decode(batch *Batch) error {
  175. // Positive return values does not mean a fatal error, but rather a warning.
  176. // 0 - success
  177. // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context)
  178. // < 0 - error
  179. code := int(C.llama_decode(c.c, batch.c))
  180. if code < 0 {
  181. return fmt.Errorf("llama_decode failed with code %d", code)
  182. }
  183. if code > 0 {
  184. return ErrKvCacheFull
  185. }
  186. return nil
  187. }
  188. func (c *Context) Model() *Model {
  189. return &Model{c: C.llama_get_model(c.c)}
  190. }
  191. func (c *Context) KvCacheSeqAdd(seqId int, p0 int, p1 int, delta int) {
  192. C.llama_kv_cache_seq_add(c.c, C.int(seqId), C.int(p0), C.int(p1), C.int(delta))
  193. }
  194. func (c *Context) KvCacheSeqRm(seqId int, p0 int, p1 int) bool {
  195. return bool(C.llama_kv_cache_seq_rm(c.c, C.int(seqId), C.int(p0), C.int(p1)))
  196. }
  197. func (c *Context) KvCacheSeqCp(srcSeqId int, dstSeqId int, p0 int, p1 int) {
  198. C.llama_kv_cache_seq_cp(c.c, C.int(srcSeqId), C.int(dstSeqId), C.int(p0), C.int(p1))
  199. }
  200. func (c *Context) KvCacheClear() {
  201. C.llama_kv_cache_clear(c.c)
  202. }
  203. func (c *Context) KvCacheDefrag() {
  204. C.llama_kv_cache_defrag(c.c)
  205. }
  206. // Get the embeddings for a sequence id
  207. func (c *Context) GetEmbeddingsSeq(seqId int) []float32 {
  208. embeddings := unsafe.Pointer(C.llama_get_embeddings_seq(c.c, C.int(seqId)))
  209. if embeddings == nil {
  210. return nil
  211. }
  212. return unsafe.Slice((*float32)(embeddings), c.Model().NEmbd())
  213. }
  214. func (c *Context) GetEmbeddingsIth(i int) []float32 {
  215. embeddings := unsafe.Pointer(C.llama_get_embeddings_ith(c.c, C.int32_t(i)))
  216. if embeddings == nil {
  217. return nil
  218. }
  219. return unsafe.Slice((*float32)(embeddings), c.Model().NEmbd())
  220. }
  221. type ModelParams struct {
  222. NumGpuLayers int
  223. MainGpu int
  224. UseMmap bool
  225. UseMlock bool
  226. TensorSplit []float32
  227. Progress func(float32)
  228. VocabOnly bool
  229. }
  230. //export llamaProgressCallback
  231. func llamaProgressCallback(progress C.float, userData unsafe.Pointer) C.bool {
  232. handle := *(*cgo.Handle)(userData)
  233. callback := handle.Value().(func(float32))
  234. callback(float32(progress))
  235. return true
  236. }
  237. func LoadModelFromFile(modelPath string, params ModelParams) (*Model, error) {
  238. cparams := C.llama_model_default_params()
  239. cparams.n_gpu_layers = C.int(params.NumGpuLayers)
  240. cparams.main_gpu = C.int32_t(params.MainGpu)
  241. cparams.use_mmap = C.bool(params.UseMmap)
  242. cparams.use_mlock = C.bool(params.UseMlock)
  243. cparams.vocab_only = C.bool(params.VocabOnly)
  244. if len(params.TensorSplit) > 0 {
  245. tensorSplitData := &params.TensorSplit[0]
  246. var tensorSplitPin runtime.Pinner
  247. tensorSplitPin.Pin(tensorSplitData)
  248. defer tensorSplitPin.Unpin()
  249. cparams.tensor_split = (*C.float)(unsafe.Pointer(tensorSplitData))
  250. }
  251. if params.Progress != nil {
  252. handle := cgo.NewHandle(params.Progress)
  253. defer handle.Delete()
  254. var handlePin runtime.Pinner
  255. handlePin.Pin(&handle)
  256. defer handlePin.Unpin()
  257. cparams.progress_callback = C.llama_progress_callback(C.llamaProgressCallback)
  258. cparams.progress_callback_user_data = unsafe.Pointer(&handle)
  259. }
  260. m := Model{c: C.llama_load_model_from_file(C.CString(modelPath), cparams)}
  261. if m.c == nil {
  262. return nil, fmt.Errorf("unable to load model: %s", modelPath)
  263. }
  264. return &m, nil
  265. }
  266. func FreeModel(model *Model) {
  267. C.llama_free_model(model.c)
  268. }
  269. func NewContextWithModel(model *Model, params ContextParams) (*Context, error) {
  270. c := Context{
  271. c: C.llama_new_context_with_model(model.c, params.c),
  272. numThreads: int(params.c.n_threads),
  273. }
  274. if c.c == nil {
  275. return nil, errors.New("unable to create llama context")
  276. }
  277. return &c, nil
  278. }
  279. func (m *Model) NumVocab() int {
  280. return int(C.llama_n_vocab(m.c))
  281. }
  282. func (m *Model) TokenIsEog(token int) bool {
  283. return bool(C.llama_token_is_eog(m.c, C.llama_token(token)))
  284. }
  285. func (m *Model) AddBOSToken() bool {
  286. return bool(C.llama_add_bos_token(m.c))
  287. }
  288. func (m *Model) ApplyLoraFromFile(context *Context, loraPath string, scale float32, threads int) error {
  289. cLoraPath := C.CString(loraPath)
  290. defer C.free(unsafe.Pointer(cLoraPath))
  291. loraAdapter := C.llama_lora_adapter_init(m.c, cLoraPath)
  292. if loraAdapter == nil {
  293. return errors.New("unable to load lora")
  294. }
  295. err := -1
  296. if loraAdapter != nil {
  297. err = int(C.llama_lora_adapter_set(context.c, loraAdapter, C.float(scale)))
  298. }
  299. if err != 0 {
  300. return errors.New("error applying lora from file")
  301. }
  302. return nil
  303. }
  304. type Batch struct {
  305. c C.struct_llama_batch
  306. batchSize int
  307. maxSeq int
  308. embedSize int
  309. }
  310. // Creates a new batch for either word tokens or image embeddings (if embedSize is non-zero).
  311. // Batches cannot contain both types at the same time. batchSize is the maximum number of entries
  312. // that can be added per sequence
  313. func NewBatch(batchSize int, maxSeq int, embedSize int) (*Batch, error) {
  314. b := Batch{
  315. c: C.llama_batch_init(C.int(batchSize*maxSeq), C.int(embedSize), C.int(maxSeq)),
  316. batchSize: batchSize,
  317. maxSeq: maxSeq,
  318. embedSize: embedSize,
  319. }
  320. // Check to see if any of the allocations in llama_batch_init() failed
  321. nilPointer := (embedSize == 0 && b.c.token == nil) || (embedSize != 0 && b.c.embd == nil) ||
  322. b.c.pos == nil || b.c.n_seq_id == nil || b.c.seq_id == nil || b.c.logits == nil ||
  323. slices.Contains(unsafe.Slice(b.c.seq_id, b.allocSize()), nil)
  324. if nilPointer {
  325. C.llama_batch_free(b.c)
  326. return nil, fmt.Errorf("unable to allocate batch (batchSize=%v maxSeq=%v embedSize=%v)", batchSize, maxSeq, embedSize)
  327. }
  328. return &b, nil
  329. }
  330. func (b *Batch) Size() int {
  331. return b.batchSize
  332. }
  333. func (b *Batch) allocSize() int {
  334. return b.batchSize * b.maxSeq
  335. }
  336. func (b *Batch) NumTokens() int {
  337. return int(b.c.n_tokens)
  338. }
  339. func (b *Batch) IsEmbedding() bool {
  340. return b.embedSize != 0
  341. }
  342. // Add adds either a token or an image embedding to the batch depending on the type
  343. // when the batch was initialized. The other argument will be ignored. Adds to the
  344. // batch with the given position for the given sequence ids, and optionally instructs
  345. // to include logits.
  346. func (b *Batch) Add(token int, embed []float32, pos int, logits bool, seqIds ...int) {
  347. if !b.IsEmbedding() {
  348. unsafe.Slice(b.c.token, b.allocSize())[b.c.n_tokens] = C.llama_token(token)
  349. } else {
  350. copy(unsafe.Slice((*float32)(b.c.embd), b.allocSize()*b.embedSize)[int(b.c.n_tokens)*b.embedSize:], embed)
  351. }
  352. unsafe.Slice(b.c.pos, b.allocSize())[b.c.n_tokens] = C.llama_pos(pos)
  353. unsafe.Slice(b.c.n_seq_id, b.allocSize())[b.c.n_tokens] = C.int(len(seqIds))
  354. for i, s := range seqIds {
  355. unsafe.Slice((unsafe.Slice(b.c.seq_id, b.allocSize())[b.c.n_tokens]), C.int(len(seqIds)))[i] = C.int32_t(s)
  356. }
  357. if logits {
  358. unsafe.Slice(b.c.logits, b.allocSize())[b.c.n_tokens] = 1
  359. } else {
  360. unsafe.Slice(b.c.logits, b.allocSize())[b.c.n_tokens] = 0
  361. }
  362. b.c.n_tokens += 1
  363. }
  364. func (b *Batch) Clear() {
  365. b.c.n_tokens = 0
  366. }
  367. func (b *Batch) Free() {
  368. b.batchSize = 0
  369. C.llama_batch_free(b.c)
  370. }
  371. type Model struct {
  372. c *C.struct_llama_model
  373. }
  374. func (m *Model) Detokenize(tokens []int) (string, error) {
  375. var text string
  376. for _, token := range tokens {
  377. piece := m.TokenToPiece(token)
  378. if piece == "" {
  379. return "", fmt.Errorf("failed to convert token %d to piece", token)
  380. }
  381. text += piece
  382. }
  383. return text, nil
  384. }
  385. func (m *Model) TokenToPiece(token int) string {
  386. tokenLen := 12
  387. buf := make([]byte, tokenLen)
  388. if token > m.NumVocab() {
  389. return ""
  390. }
  391. tokenLen = int(C.llama_token_to_piece(
  392. m.c,
  393. C.int32_t(token),
  394. (*C.char)(unsafe.Pointer(&buf[0])),
  395. C.int32_t(tokenLen),
  396. C.int32_t(0),
  397. C.bool(true),
  398. ))
  399. if tokenLen < 0 {
  400. tokenLen = -tokenLen
  401. buf = make([]byte, tokenLen)
  402. C.llama_token_to_piece(
  403. m.c,
  404. C.int32_t(token),
  405. (*C.char)(unsafe.Pointer(&buf[0])),
  406. C.int32_t(tokenLen),
  407. C.int32_t(0),
  408. C.bool(true),
  409. )
  410. }
  411. return strings.TrimRight(string(buf), "\x00")
  412. }
  413. func (m *Model) Tokenize(text string, addSpecial bool, parseSpecial bool) ([]int, error) {
  414. maxTokens := len(text) + 2
  415. cTokens := make([]C.llama_token, maxTokens)
  416. cText := C.CString(text)
  417. defer C.free(unsafe.Pointer(cText))
  418. result := C.llama_tokenize(
  419. m.c,
  420. cText,
  421. C.int32_t(len(text)),
  422. &cTokens[0],
  423. C.int32_t(maxTokens),
  424. C.bool(addSpecial),
  425. C.bool(parseSpecial),
  426. )
  427. // if the result is negative, reallocate and retry with the correct buffer size
  428. if result < 0 {
  429. maxTokens = int(-result)
  430. cTokens = make([]C.llama_token, maxTokens)
  431. result = C.llama_tokenize(
  432. m.c,
  433. cText,
  434. C.int32_t(len(text)),
  435. &cTokens[0],
  436. C.int32_t(maxTokens),
  437. C.bool(addSpecial),
  438. C.bool(parseSpecial),
  439. )
  440. if result < 0 {
  441. return nil, fmt.Errorf("tokenization failed, required %d tokens", -result)
  442. }
  443. }
  444. tokens := make([]int, result)
  445. for i := range result {
  446. tokens[i] = int(cTokens[i])
  447. }
  448. return tokens, nil
  449. }
  450. func (m *Model) NEmbd() int {
  451. return int(C.llama_n_embd(m.c))
  452. }
  453. func Quantize(infile, outfile string, ftype uint32) error {
  454. cinfile := C.CString(infile)
  455. defer C.free(unsafe.Pointer(cinfile))
  456. coutfile := C.CString(outfile)
  457. defer C.free(unsafe.Pointer(coutfile))
  458. params := C.llama_model_quantize_default_params()
  459. params.nthread = -1
  460. params.ftype = ftype
  461. if rc := C.llama_model_quantize(cinfile, coutfile, &params); rc != 0 {
  462. return fmt.Errorf("llama_model_quantize: %d", rc)
  463. }
  464. return nil
  465. }
  466. // vision processing
  467. type ClipContext struct {
  468. c *C.struct_clip_ctx
  469. }
  470. func NewClipContext(llamaContext *Context, modelPath string) (*ClipContext, error) {
  471. mp := C.CString(modelPath)
  472. defer C.free(unsafe.Pointer(mp))
  473. c := C.clip_model_load(mp, 1)
  474. if c == nil {
  475. return nil, fmt.Errorf("unable to load clip model: %v", modelPath)
  476. }
  477. projEmbedSize := int(C.clip_n_mmproj_embd(c))
  478. modelEmbedSize := llamaContext.Model().NEmbd()
  479. if projEmbedSize != modelEmbedSize {
  480. return nil, fmt.Errorf("projector embedding size (%d) does not match model (%d)", projEmbedSize, modelEmbedSize)
  481. }
  482. return &ClipContext{c: c}, nil
  483. }
  484. func (c *ClipContext) Free() {
  485. C.clip_free(c.c)
  486. }
  487. func (c *ClipContext) NewEmbed(llamaContext *Context, data []byte) ([][]float32, error) {
  488. l := C.llava_image_embed_make_with_bytes(c.c, C.int(llamaContext.numThreads), (*C.uchar)(unsafe.Pointer(&data[0])), C.int(len(data)))
  489. if l == nil {
  490. return nil, errors.New("unable to make llava embedding from image")
  491. }
  492. numTokens := int(l.n_image_pos)
  493. numEmbed := llamaContext.Model().NEmbd()
  494. s := unsafe.Slice((*float32)(l.embed), numEmbed*numTokens)
  495. embed := make([][]float32, numTokens)
  496. rows := make([]float32, len(s))
  497. copy(rows, s)
  498. for i := range embed {
  499. embed[i] = rows[i*numEmbed : (i+1)*numEmbed]
  500. }
  501. C.llava_image_embed_free(l)
  502. return embed, nil
  503. }
  504. type MllamaContext struct {
  505. c *C.struct_mllama_ctx
  506. }
  507. func NewMllamaContext(llamaContext *Context, modelPath string) (*MllamaContext, error) {
  508. mp := C.CString(modelPath)
  509. defer C.free(unsafe.Pointer(mp))
  510. c := C.mllama_model_load(mp, 1)
  511. if c == nil {
  512. return nil, fmt.Errorf("unable to load mllama model: %v", modelPath)
  513. }
  514. projEmbedSize := int(C.mllama_n_embd(c))
  515. modelEmbedSize := llamaContext.Model().NEmbd()
  516. if projEmbedSize != modelEmbedSize {
  517. return nil, fmt.Errorf("projector embedding size (%d) does not match model (%d)", projEmbedSize, modelEmbedSize)
  518. }
  519. return &MllamaContext{c: c}, nil
  520. }
  521. func (m *MllamaContext) Free() {
  522. C.mllama_free(m.c)
  523. }
  524. func (m *MllamaContext) NewEmbed(llamaContext *Context, data []byte, aspectRatioId int) ([][]float32, error) {
  525. img := C.mllama_image_init()
  526. defer C.mllama_image_free(img)
  527. ok := bool(C.mllama_image_load_from_data(unsafe.Pointer(&data[0]), C.int(len(data)), 560, 560, 3, 4, C.int(aspectRatioId), img))
  528. if !ok {
  529. return nil, errors.New("unable to load mllama image data")
  530. }
  531. rows := make([]float32, m.EmbedSize(llamaContext))
  532. ok = bool(C.mllama_image_encode(m.c, C.int(llamaContext.numThreads), img, (*C.float)(unsafe.Pointer(&rows[0]))))
  533. if !ok {
  534. return nil, errors.New("unable to make mllama embedding from image")
  535. }
  536. embed := make([][]float32, 1)
  537. embed[0] = rows
  538. return embed, nil
  539. }
  540. func (m *MllamaContext) EmbedSize(llamaContext *Context) int {
  541. numTokens := int(C.mllama_n_positions(m.c) * C.mllama_n_tiles(m.c))
  542. numEmbed := llamaContext.Model().NEmbd()
  543. return numTokens * numEmbed
  544. }
  545. func (c *Context) SetCrossAttention(state bool) {
  546. C.llama_set_cross_attention(c.c, C.bool(state))
  547. }
  548. func (c *Context) Synchronize() {
  549. C.llama_synchronize(c.c)
  550. }
  551. // sampling
  552. // TODO: this is a temporary wrapper to allow calling C++ code from CGo
  553. type SamplingContext struct {
  554. c *C.struct_common_sampler
  555. }
  556. type SamplingParams struct {
  557. TopK int
  558. TopP float32
  559. MinP float32
  560. TypicalP float32
  561. Temp float32
  562. RepeatLastN int
  563. PenaltyRepeat float32
  564. PenaltyFreq float32
  565. PenaltyPresent float32
  566. Mirostat int
  567. MirostatTau float32
  568. MirostatEta float32
  569. PenalizeNl bool
  570. Seed uint32
  571. Grammar string
  572. }
  573. func NewSamplingContext(model *Model, params SamplingParams) (*SamplingContext, error) {
  574. var cparams C.struct_common_sampler_cparams
  575. cparams.top_k = C.int32_t(params.TopK)
  576. cparams.top_p = C.float(params.TopP)
  577. cparams.min_p = C.float(params.MinP)
  578. cparams.typical_p = C.float(params.TypicalP)
  579. cparams.temp = C.float(params.Temp)
  580. cparams.penalty_last_n = C.int32_t(params.RepeatLastN)
  581. cparams.penalty_repeat = C.float(params.PenaltyRepeat)
  582. cparams.penalty_freq = C.float(params.PenaltyFreq)
  583. cparams.penalty_present = C.float(params.PenaltyFreq)
  584. cparams.mirostat = C.int32_t(params.Mirostat)
  585. cparams.mirostat_tau = C.float(params.MirostatTau)
  586. cparams.mirostat_eta = C.float(params.MirostatEta)
  587. cparams.penalize_nl = C.bool(params.PenalizeNl)
  588. cparams.seed = C.uint32_t(params.Seed)
  589. grammar := C.CString(params.Grammar)
  590. defer C.free(unsafe.Pointer(grammar))
  591. cparams.grammar = grammar
  592. context := &SamplingContext{c: C.common_sampler_cinit(model.c, &cparams)}
  593. if context.c == nil {
  594. return nil, errors.New("unable to create sampling context")
  595. }
  596. runtime.SetFinalizer(context, func(s *SamplingContext) { C.common_sampler_cfree(s.c) })
  597. return context, nil
  598. }
  599. func (s *SamplingContext) Reset() {
  600. C.common_sampler_creset(s.c)
  601. }
  602. func (s *SamplingContext) Sample(llamaContext *Context, idx int) int {
  603. return int(C.common_sampler_csample(s.c, llamaContext.c, C.int(idx)))
  604. }
  605. func (s *SamplingContext) Accept(id int, applyGrammar bool) {
  606. C.common_sampler_caccept(s.c, C.llama_token(id), C.bool(applyGrammar))
  607. }
  608. // SchemaToGrammar converts the provided JSON schema to a grammar. It returns
  609. // nil if the provided schema is invalid JSON or an invalid JSON schema.
  610. func SchemaToGrammar(schema []byte) []byte {
  611. cStr := C.CString(string(schema))
  612. defer C.free(unsafe.Pointer(cStr))
  613. // Allocate buffer for grammar output with reasonable size
  614. const maxLen = 32768 // 32KB
  615. buf := make([]byte, maxLen)
  616. // Call C function to convert schema to grammar
  617. n := C.schema_to_grammar(cStr, (*C.char)(unsafe.Pointer(&buf[0])), C.size_t(maxLen))
  618. if n == 0 {
  619. // preserve nil
  620. return nil
  621. }
  622. return buf[:n]
  623. }