llama.go 18 KB

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