llama.go 21 KB

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