llama.go 21 KB

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