ggml.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. package ggml
  2. // #cgo CPPFLAGS: -I${SRCDIR}/ggml/include
  3. // #include <stdlib.h>
  4. // #include <stdint.h>
  5. // #include "ggml.h"
  6. // #include "ggml-cpu.h"
  7. // #include "ggml-backend.h"
  8. import "C"
  9. import (
  10. "errors"
  11. "fmt"
  12. "io"
  13. "log/slog"
  14. "maps"
  15. "os"
  16. "slices"
  17. "strconv"
  18. "strings"
  19. "unicode"
  20. "unsafe"
  21. "github.com/ollama/ollama/format"
  22. fs "github.com/ollama/ollama/fs/ggml"
  23. "github.com/ollama/ollama/ml"
  24. ggml "github.com/ollama/ollama/ml/backend/ggml/ggml/src"
  25. "golang.org/x/sync/errgroup"
  26. )
  27. func devices() []*C.struct_ggml_backend_device {
  28. ggml.OnceLoad()
  29. ds := make([]*C.struct_ggml_backend_device, C.ggml_backend_dev_count())
  30. for i := range ds {
  31. ds[i] = C.ggml_backend_dev_get(C.size_t(i))
  32. }
  33. return ds
  34. }
  35. type Backend struct {
  36. meta *fs.GGML
  37. sched *C.struct_ggml_backend_sched
  38. tensors map[string]*C.struct_ggml_tensor
  39. // input is the backend used for inputs
  40. input *C.struct_ggml_backend_buffer_type
  41. // output is the backend used for outputs
  42. output *C.struct_ggml_backend_buffer_type
  43. // layers is the backend used for repeating layers
  44. layers map[int]*C.struct_ggml_backend_buffer_type
  45. flashAttention bool
  46. // maxGraphNodes is the maximum allowed number of graph nodes in this scheduler
  47. maxGraphNodes int
  48. }
  49. func New(r *os.File, params ml.BackendParams) (ml.Backend, error) {
  50. meta, n, err := fs.Decode(r, -1)
  51. if err != nil {
  52. return nil, err
  53. }
  54. slog.Info(
  55. "",
  56. "architecture", meta.KV().Architecture(),
  57. "file_type", meta.KV().FileType(),
  58. "name", meta.KV().String("general.name"),
  59. "description", meta.KV().String("general.description"),
  60. "num_tensors", len(meta.Tensors().Items()),
  61. "num_key_values", len(meta.KV()),
  62. )
  63. type deviceBufferType struct {
  64. d *C.struct_ggml_backend_device
  65. bts []*C.struct_ggml_backend_buffer_type
  66. }
  67. var cpus, accels, gpus []*C.struct_ggml_backend_device
  68. for _, d := range devices() {
  69. switch C.ggml_backend_dev_type(d) {
  70. case C.GGML_BACKEND_DEVICE_TYPE_CPU:
  71. if len(cpus) == 0 {
  72. // only the first cpu device should be used
  73. cpus = append(cpus, d)
  74. }
  75. case C.GGML_BACKEND_DEVICE_TYPE_ACCEL:
  76. accels = append(accels, d)
  77. case C.GGML_BACKEND_DEVICE_TYPE_GPU:
  78. gpus = append(gpus, d)
  79. }
  80. }
  81. // create list of buffer types for the cpu
  82. cpuDeviceBufferType := deviceBufferType{d: C.ggml_backend_dev_by_type(C.GGML_BACKEND_DEVICE_TYPE_CPU)}
  83. for _, d := range append(accels, append(gpus, cpus...)...) {
  84. switch C.ggml_backend_dev_type(d) {
  85. case C.GGML_BACKEND_DEVICE_TYPE_CPU,
  86. C.GGML_BACKEND_DEVICE_TYPE_ACCEL:
  87. cpuDeviceBufferType.bts = append(cpuDeviceBufferType.bts, C.ggml_backend_dev_buffer_type(d))
  88. }
  89. }
  90. // create list of buffer types for each gpu
  91. var gpuDeviceBufferTypes []deviceBufferType
  92. for _, d := range gpus {
  93. bt := C.ggml_backend_dev_buffer_type(d)
  94. gpuDeviceBufferTypes = append(gpuDeviceBufferTypes, deviceBufferType{
  95. d: d,
  96. bts: append([]*C.struct_ggml_backend_buffer_type{bt}, cpuDeviceBufferType.bts...),
  97. })
  98. }
  99. useDefaultSplit := true
  100. for _, s := range params.TensorSplit {
  101. if s != 0 {
  102. useDefaultSplit = false
  103. break
  104. }
  105. }
  106. // calculate splits
  107. splits := make([]float32, len(gpus))
  108. if useDefaultSplit {
  109. // default: split on free memory
  110. for i := range splits {
  111. var free, total C.size_t
  112. C.ggml_backend_dev_memory(gpus[i], &free, &total)
  113. splits[i] = float32(free)
  114. }
  115. } else {
  116. splits = params.TensorSplit
  117. }
  118. var sum float32
  119. // cumulative sum of all splits
  120. for i := range splits {
  121. sum += splits[i]
  122. splits[i] = sum
  123. }
  124. // normalize splits
  125. for i := range splits {
  126. splits[i] /= sum
  127. }
  128. // inputs always use cpu
  129. input := cpuDeviceBufferType
  130. blocks := int(meta.KV().BlockCount())
  131. // define a range of gpu layers. anything outside of this range is assigned to the cpu
  132. gpuRangeStart := max(0, blocks-params.NumGPULayers)
  133. gpuRangeStop := min(gpuRangeStart+params.NumGPULayers, blocks+1)
  134. assignLayer := func(i int) deviceBufferType {
  135. if i < gpuRangeStart || i >= gpuRangeStop {
  136. return cpuDeviceBufferType
  137. }
  138. index := slices.IndexFunc(splits, func(f float32) bool { return float32(i-gpuRangeStart)/float32(gpuRangeStop-gpuRangeStart) < f })
  139. if index < 0 || index >= len(gpuDeviceBufferTypes) {
  140. return cpuDeviceBufferType
  141. }
  142. return gpuDeviceBufferTypes[index]
  143. }
  144. // repeating layers are assigned based on their index in reverse order, e.g. i / (block_count + 1)
  145. layers := make([]deviceBufferType, blocks)
  146. for i := range layers {
  147. layers[i] = assignLayer(i)
  148. }
  149. // outputs are assigned iff allowed by splits and configured number of gpu layers
  150. output := assignLayer(blocks)
  151. maxTensors := len(meta.Tensors().Items())
  152. maxTensors += 1
  153. // each layer has at most 2 extra tensors for rope operations
  154. maxTensors += blocks * 2
  155. type tensor struct {
  156. source *fs.Tensor
  157. target string
  158. }
  159. // some tensors are mapped to different names so keep a list
  160. targets := make(map[string][]string)
  161. // contexts are shared by tensors of the same buffer type
  162. ctxs := make(map[*C.struct_ggml_backend_buffer_type]*C.struct_ggml_context)
  163. createTensor := func(t tensor, bts []*C.struct_ggml_backend_buffer_type) *C.struct_ggml_tensor {
  164. for _, bt := range bts {
  165. if _, ok := ctxs[bt]; !ok {
  166. ctxs[bt] = C.ggml_init(C.struct_ggml_init_params{
  167. mem_size: C.ggml_tensor_overhead() * C.size_t(maxTensors),
  168. no_alloc: true,
  169. })
  170. }
  171. targets[t.source.Name] = append(targets[t.source.Name], t.target)
  172. name := t.source.Name
  173. if t.target != "" {
  174. name = t.target
  175. }
  176. cname := C.CString(name)
  177. defer C.free(unsafe.Pointer(cname))
  178. if tt := C.ggml_get_tensor(ctxs[bt], cname); tt != nil {
  179. return tt
  180. }
  181. tt := C.ggml_new_tensor(ctxs[bt], t.source.Kind, C.int(len(t.source.Shape)), (*C.int64_t)(unsafe.Pointer(&t.source.Shape[0])))
  182. C.ggml_set_name(tt, cname)
  183. slog.Debug("created tensor", "name", name, "shape", t.source.Shape, "dtype", t.source.Kind, "buffer_type", C.GoString(C.ggml_backend_buft_name(bt)))
  184. //nolint:staticcheck // TODO: check if buffer type supports this tensor
  185. return tt
  186. }
  187. return nil
  188. }
  189. contains := func(s string, parts ...string) bool {
  190. split := strings.Split(s, ".")
  191. for _, part := range parts {
  192. if slices.Contains(split, part) {
  193. return true
  194. }
  195. }
  196. return false
  197. }
  198. for _, t := range meta.Tensors().Items() {
  199. switch {
  200. case contains(t.Name, "position_embd", "token_embd", "token_norm_embd", "token_types"):
  201. createTensor(tensor{source: t}, input.bts)
  202. if _, ok := meta.Tensors().GroupLayers()["output"]; !ok && t.Name == "token_embd.weight" {
  203. createTensor(tensor{source: t, target: "output.weight"}, output.bts)
  204. }
  205. case contains(t.Name, "cls", "output", "output_norm"):
  206. createTensor(tensor{source: t}, output.bts)
  207. case strings.HasPrefix(t.Name, "v.") || strings.HasPrefix(t.Name, "mm."):
  208. // TODO: assign vision tensors to the gpu if possible
  209. createTensor(tensor{source: t}, output.bts)
  210. case contains(t.Name, "rope_freqs", "rope_factors_long", "rope_factors_short"):
  211. // these tensors should be repeated per layer
  212. for i, layer := range layers {
  213. createTensor(tensor{
  214. source: t,
  215. target: "blk." + strconv.Itoa(i) + "." + t.Name,
  216. }, layer.bts)
  217. }
  218. default:
  219. layerIndex := -1
  220. if fields := strings.FieldsFunc(t.Name, func(r rune) bool { return !unicode.IsNumber(r) }); len(fields) > 0 {
  221. if i, err := strconv.Atoi(fields[0]); err == nil {
  222. layerIndex = i
  223. }
  224. }
  225. if layerIndex >= 0 {
  226. createTensor(tensor{source: t}, layers[layerIndex].bts)
  227. } else {
  228. // load all other tensors on the cpu
  229. createTensor(tensor{source: t}, input.bts)
  230. }
  231. }
  232. }
  233. // allocate buffers for each context
  234. bbs := make(map[*C.struct_ggml_context]*C.struct_ggml_backend_buffer, len(ctxs))
  235. for bt, c := range ctxs {
  236. if C.ggml_get_first_tensor(c) == nil {
  237. continue
  238. }
  239. b := C.ggml_backend_alloc_ctx_tensors_from_buft(c, bt)
  240. C.ggml_backend_buffer_set_usage(b, C.GGML_BACKEND_BUFFER_USAGE_WEIGHTS)
  241. bbs[c] = b
  242. }
  243. for bs := range maps.Values(bbs) {
  244. slog.Info("model weights", "buffer", C.GoString(C.ggml_backend_buffer_name(bs)), "size", format.HumanBytes2(uint64(C.ggml_backend_buffer_get_size(bs))))
  245. }
  246. // map tensor names to tensors for easy lookup later
  247. tensors := make(map[string]*C.struct_ggml_tensor)
  248. for _, c := range ctxs {
  249. for t := C.ggml_get_first_tensor(c); t != nil; t = C.ggml_get_next_tensor(c, t) {
  250. tensors[C.GoString(C.ggml_get_name(t))] = t
  251. }
  252. }
  253. // concurrently read in tensor data. uses a section reader which is safe for concurrent reads
  254. sr := io.NewSectionReader(r, int64(meta.Tensors().Offset), n-int64(meta.Tensors().Offset))
  255. var g errgroup.Group
  256. for _, t := range meta.Tensors().Items() {
  257. for _, target := range targets[t.Name] {
  258. g.Go(func() error {
  259. if target == "" {
  260. target = t.Name
  261. }
  262. tt, ok := tensors[target]
  263. if !ok {
  264. return fmt.Errorf("unassigned tensor: %s", t.Name)
  265. }
  266. bts := make([]byte, t.Size())
  267. n, err := io.ReadFull(io.NewSectionReader(sr, int64(t.Offset), int64(t.Size())), bts)
  268. if err != nil {
  269. return err
  270. }
  271. if n != len(bts) {
  272. return errors.New("short read")
  273. }
  274. C.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), 0, C.size_t(t.Size()))
  275. return nil
  276. })
  277. }
  278. }
  279. if g.Wait() != nil {
  280. return nil, err
  281. }
  282. // map devices to backend buffer types so new tensors can be assigned to the correct device
  283. deviceBufferTypes := make(map[*C.struct_ggml_backend_device]*C.struct_ggml_backend_buffer_type)
  284. // create backends and buffer types used for the compute graph scheduler
  285. var schedBackends []*C.struct_ggml_backend
  286. var schedBufts []*C.struct_ggml_backend_buffer_type
  287. for _, d := range append(gpus, append(accels, cpus...)...) {
  288. b := C.ggml_backend_dev_init(d, nil)
  289. bt := C.ggml_backend_get_default_buffer_type(b)
  290. if d := C.ggml_backend_get_device(b); C.ggml_backend_dev_type(d) == C.GGML_BACKEND_DEVICE_TYPE_CPU && len(gpus) > 0 {
  291. // use the first gpu host buffer type for gpu if possible
  292. if hbt := C.ggml_backend_dev_host_buffer_type(gpus[0]); hbt != nil {
  293. bt = hbt
  294. }
  295. }
  296. deviceBufferTypes[d] = bt
  297. schedBackends = append(schedBackends, b)
  298. schedBufts = append(schedBufts, bt)
  299. slog.Info("compute graph", "backend", C.GoString(C.ggml_backend_name(b)), "buffer_type", C.GoString(C.ggml_backend_buft_name(bt)))
  300. if C.ggml_backend_is_cpu(b) {
  301. // set number of threads for cpu backend
  302. C.ggml_backend_cpu_set_n_threads(b, C.int(Threads(params.NumThreads)))
  303. }
  304. }
  305. maxGraphNodes := max(8192, len(meta.Tensors().Items())*5)
  306. return &Backend{
  307. flashAttention: params.FlashAttention,
  308. meta: meta,
  309. tensors: tensors,
  310. sched: C.ggml_backend_sched_new(
  311. (*C.ggml_backend_t)(unsafe.Pointer(&schedBackends[0])),
  312. (*C.ggml_backend_buffer_type_t)(unsafe.Pointer(&schedBufts[0])),
  313. C.int(len(schedBackends)),
  314. C.size_t(maxGraphNodes),
  315. true,
  316. ),
  317. input: deviceBufferTypes[input.d],
  318. output: deviceBufferTypes[output.d],
  319. layers: func() map[int]*C.struct_ggml_backend_buffer_type {
  320. m := make(map[int]*C.struct_ggml_backend_buffer_type)
  321. for i, layer := range layers {
  322. m[i] = deviceBufferTypes[layer.d]
  323. }
  324. return m
  325. }(),
  326. maxGraphNodes: maxGraphNodes,
  327. }, nil
  328. }
  329. func init() {
  330. ml.RegisterBackend("ggml", New)
  331. }
  332. func (b *Backend) Config() ml.Config {
  333. return b.meta.KV()
  334. }
  335. func (b *Backend) Get(name string) ml.Tensor {
  336. if t, ok := b.tensors[name]; ok {
  337. return &Tensor{b: b, t: t}
  338. }
  339. return nil
  340. }
  341. func (b *Backend) NewContext() ml.Context {
  342. return b.NewContextSize(b.maxGraphNodes)
  343. }
  344. func (b *Backend) NewContextSize(n int) ml.Context {
  345. if n > b.maxGraphNodes {
  346. panic(fmt.Errorf("requested number of graph nodes (%v) for new context exceeds maximum (%v)", n, b.maxGraphNodes))
  347. }
  348. return &Context{
  349. b: b,
  350. maxGraphNodes: n,
  351. ctx: C.ggml_init(C.struct_ggml_init_params{
  352. mem_size: C.size_t(n)*C.ggml_tensor_overhead() + C.ggml_graph_overhead_custom(C.size_t(n), false),
  353. no_alloc: true,
  354. }),
  355. }
  356. }
  357. func (b *Backend) CacheConfig() ml.CacheConfig {
  358. if b.flashAttention {
  359. return ml.CacheConfig{CachePadding: 256, MaskDType: ml.DTypeF16, MaskBatchPadding: C.GGML_KQ_MASK_PAD}
  360. } else {
  361. return ml.CacheConfig{CachePadding: 32, PermutedV: true}
  362. }
  363. }
  364. type Context struct {
  365. b *Backend
  366. ctx *C.struct_ggml_context
  367. graph *C.struct_ggml_cgraph
  368. // buft is the buffer type used for new tensors
  369. buft *C.struct_ggml_backend_buffer_type
  370. // maxGraphNodes is the maximum allowed number of graph nodes in this context
  371. maxGraphNodes int
  372. }
  373. func (c Context) Input() ml.Context {
  374. if c.b.input != nil {
  375. return &Context{
  376. b: c.b,
  377. ctx: c.ctx,
  378. buft: c.b.input,
  379. maxGraphNodes: c.maxGraphNodes,
  380. }
  381. }
  382. return &c
  383. }
  384. func (c Context) Output() ml.Context {
  385. if c.b.output != nil {
  386. return &Context{
  387. b: c.b,
  388. ctx: c.ctx,
  389. buft: c.b.output,
  390. maxGraphNodes: c.maxGraphNodes,
  391. }
  392. }
  393. return &c
  394. }
  395. func (c Context) Layer(i int) ml.Context {
  396. if buft, ok := c.b.layers[i]; ok {
  397. return &Context{
  398. b: c.b,
  399. ctx: c.ctx,
  400. buft: buft,
  401. maxGraphNodes: c.maxGraphNodes,
  402. }
  403. }
  404. return &c
  405. }
  406. func (c *Context) Forward(tensors ...ml.Tensor) ml.Context {
  407. if c.graph == nil {
  408. c.graph = C.ggml_new_graph_custom(c.ctx, C.size_t(c.maxGraphNodes), false)
  409. }
  410. for _, tensor := range tensors {
  411. C.ggml_build_forward_expand(c.graph, tensor.(*Tensor).t)
  412. }
  413. return c
  414. }
  415. func (c Context) Compute(tensors ...ml.Tensor) {
  416. C.ggml_backend_sched_graph_compute_async(c.b.sched, c.graph)
  417. C.ggml_backend_sched_reset(c.b.sched)
  418. needSync := true
  419. sync := func() {
  420. if needSync {
  421. C.ggml_backend_sched_synchronize(c.b.sched)
  422. needSync = false
  423. }
  424. }
  425. for _, t := range tensors {
  426. if C.ggml_nbytes(t.(*Tensor).t) > 0 {
  427. t.(*Tensor).sync = sync
  428. }
  429. }
  430. }
  431. func (c Context) MaxGraphNodes() int {
  432. return c.maxGraphNodes
  433. }
  434. func shapeToGGML(shape []int) *C.int64_t {
  435. sh := make([]C.int64_t, len(shape))
  436. for i, s := range shape {
  437. sh[i] = C.int64_t(s)
  438. }
  439. return &sh[0]
  440. }
  441. func pad(length, pad C.size_t) C.size_t {
  442. return ((length + pad - 1) / pad) * pad
  443. }
  444. func (c Context) newTensor(dtype ml.DType, shape []int) ml.Tensor {
  445. if c.buft == nil {
  446. panic("set Input, Output, or Layer before creating tensors")
  447. }
  448. var cdtype uint32
  449. switch dtype {
  450. case ml.DTypeF32:
  451. cdtype = C.GGML_TYPE_F32
  452. case ml.DTypeF16:
  453. cdtype = C.GGML_TYPE_F16
  454. case ml.DTypeQ80:
  455. cdtype = C.GGML_TYPE_Q8_0
  456. case ml.DTypeQ40:
  457. cdtype = C.GGML_TYPE_Q4_0
  458. case ml.DTypeI32:
  459. cdtype = C.GGML_TYPE_I32
  460. default:
  461. panic("unsupported dtype")
  462. }
  463. if len(shape) < 1 || shape[0] == 0 {
  464. var shape C.int64_t = 0
  465. return &Tensor{b: c.b, t: C.ggml_new_tensor(c.ctx, cdtype, 1, &shape)}
  466. } else if len(shape) > 4 {
  467. panic("unsupported number of dimensions")
  468. }
  469. for _, dim := range shape {
  470. if dim < 1 {
  471. panic("invalid shape")
  472. }
  473. }
  474. t := C.ggml_new_tensor(c.ctx, cdtype, C.int(len(shape)), shapeToGGML(shape))
  475. size := pad(C.ggml_backend_buft_get_alloc_size(c.buft, t), C.ggml_backend_buft_get_alignment(c.buft))
  476. b := C.ggml_backend_buft_alloc_buffer(c.buft, size)
  477. C.ggml_backend_tensor_alloc(b, t, C.ggml_backend_buffer_get_base(b))
  478. return &Tensor{b: c.b, t: t}
  479. }
  480. func (c Context) Empty(dtype ml.DType, shape ...int) ml.Tensor {
  481. return c.newTensor(dtype, shape)
  482. }
  483. func (c Context) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
  484. t := c.newTensor(dtype, shape)
  485. C.ggml_set_zero(t.(*Tensor).t)
  486. return t
  487. }
  488. func checkShape[S ~[]E, E any](s S, shape ...int) error {
  489. n := len(s)
  490. if n == 0 {
  491. return nil
  492. }
  493. for _, v := range shape {
  494. n /= v
  495. }
  496. if n != 1 {
  497. return fmt.Errorf("invalid shape: %v", shape)
  498. }
  499. return nil
  500. }
  501. func (c Context) FromFloatSlice(s []float32, shape ...int) (ml.Tensor, error) {
  502. if err := checkShape(s, shape...); err != nil {
  503. return nil, err
  504. }
  505. t := c.newTensor(ml.DTypeF32, shape)
  506. if len(s) > 0 {
  507. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  508. }
  509. return t, nil
  510. }
  511. func (c Context) FromIntSlice(s []int32, shape ...int) (ml.Tensor, error) {
  512. if err := checkShape(s, shape...); err != nil {
  513. return nil, err
  514. }
  515. t := c.newTensor(ml.DTypeI32, shape)
  516. if len(s) > 0 {
  517. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  518. }
  519. return t, nil
  520. }
  521. func (c *Context) Close() {
  522. if c != nil {
  523. C.ggml_free(c.ctx)
  524. }
  525. }
  526. type Tensor struct {
  527. b *Backend
  528. t *C.struct_ggml_tensor
  529. sync func()
  530. }
  531. func (t *Tensor) LogValue() slog.Value {
  532. return slog.GroupValue(
  533. slog.String("name", C.GoString(C.ggml_get_name(t.t))),
  534. slog.String("type", C.GoString(C.ggml_type_name(t.t._type))),
  535. slog.Any("shape", t.Shape()),
  536. )
  537. }
  538. func (t *Tensor) Dim(n int) int {
  539. return int(t.t.ne[n])
  540. }
  541. func (t *Tensor) Stride(n int) int {
  542. return int(t.t.nb[n])
  543. }
  544. func (t *Tensor) Shape() []int {
  545. shape := make([]int, C.ggml_n_dims(t.t))
  546. for i := range shape {
  547. shape[i] = t.Dim(i)
  548. }
  549. return shape
  550. }
  551. func (t *Tensor) Bytes() (data []byte) {
  552. if t.sync != nil {
  553. data = make([]byte, C.ggml_nbytes(t.t))
  554. t.sync()
  555. C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
  556. }
  557. return
  558. }
  559. func (t *Tensor) Floats() (data []float32) {
  560. if t.sync != nil {
  561. data = make([]float32, C.ggml_nelements(t.t))
  562. t.sync()
  563. C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
  564. }
  565. return
  566. }
  567. func (t *Tensor) DType() ml.DType {
  568. switch t.t._type {
  569. case C.GGML_TYPE_F32:
  570. return ml.DTypeF32
  571. case C.GGML_TYPE_F16:
  572. return ml.DTypeF16
  573. case C.GGML_TYPE_Q8_0:
  574. return ml.DTypeQ80
  575. case C.GGML_TYPE_Q4_0:
  576. return ml.DTypeQ40
  577. case C.GGML_TYPE_I32:
  578. return ml.DTypeI32
  579. default:
  580. return ml.DTypeOther
  581. }
  582. }
  583. func (t *Tensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  584. return &Tensor{
  585. b: t.b,
  586. t: C.ggml_add(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  587. }
  588. }
  589. func (t *Tensor) Stack(ctx ml.Context, dim int, s ...ml.Tensor) ml.Tensor {
  590. if len(s) > 0 {
  591. return t.Concat(ctx, s[0].Stack(ctx, dim, s[1:]...), dim)
  592. }
  593. return t
  594. }
  595. func (t *Tensor) Concat(ctx ml.Context, t2 ml.Tensor, dim int) ml.Tensor {
  596. return &Tensor{
  597. b: t.b,
  598. t: C.ggml_concat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.int(dim)),
  599. }
  600. }
  601. func (t *Tensor) Contiguous(ctx ml.Context) ml.Tensor {
  602. return &Tensor{
  603. b: t.b,
  604. t: C.ggml_cont(ctx.(*Context).ctx, t.t),
  605. }
  606. }
  607. func (t *Tensor) Mul(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  608. return &Tensor{
  609. b: t.b,
  610. t: C.ggml_mul(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  611. }
  612. }
  613. func (t *Tensor) Mulmat(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  614. return &Tensor{
  615. b: t.b,
  616. t: C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  617. }
  618. }
  619. func (t *Tensor) MulmatFullPrec(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  620. mul := C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t)
  621. C.ggml_mul_mat_set_prec(mul, C.GGML_PREC_F32)
  622. return &Tensor{
  623. b: t.b,
  624. t: mul,
  625. }
  626. }
  627. func (t *Tensor) LayerNorm(ctx ml.Context, w, b ml.Tensor, eps float32) ml.Tensor {
  628. tt := (&Tensor{b: t.b, t: C.ggml_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  629. if b != nil {
  630. tt = tt.Add(ctx, b)
  631. }
  632. return tt
  633. }
  634. func (t *Tensor) RMSNorm(ctx ml.Context, w ml.Tensor, eps float32) ml.Tensor {
  635. return (&Tensor{b: t.b, t: C.ggml_rms_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  636. }
  637. func (t *Tensor) Pad(ctx ml.Context, shape ...int) ml.Tensor {
  638. if len(shape) != 4 {
  639. panic("expected 4 dimensions")
  640. }
  641. return &Tensor{
  642. b: t.b,
  643. t: C.ggml_pad(ctx.(*Context).ctx, t.t, C.int(shape[0]), C.int(shape[1]), C.int(shape[2]), C.int(shape[3])),
  644. }
  645. }
  646. func (t *Tensor) Permute(ctx ml.Context, shape ...int) ml.Tensor {
  647. if len(shape) != 4 {
  648. panic("expected 4 dimensions")
  649. }
  650. return &Tensor{
  651. b: t.b,
  652. t: C.ggml_permute(ctx.(*Context).ctx, t.t, C.int(shape[0]), C.int(shape[1]), C.int(shape[2]), C.int(shape[3])),
  653. }
  654. }
  655. func (t *Tensor) Rows(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  656. return &Tensor{
  657. b: t.b,
  658. t: C.ggml_get_rows(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  659. }
  660. }
  661. func (t *Tensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  662. return &Tensor{
  663. b: t.b,
  664. t: C.ggml_cpy(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  665. }
  666. }
  667. func (t *Tensor) Reshape(ctx ml.Context, shape ...int) ml.Tensor {
  668. switch len(shape) {
  669. case 1:
  670. return &Tensor{
  671. b: t.b,
  672. t: C.ggml_reshape_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0])),
  673. }
  674. case 2:
  675. return &Tensor{
  676. b: t.b,
  677. t: C.ggml_reshape_2d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1])),
  678. }
  679. case 3:
  680. return &Tensor{
  681. b: t.b,
  682. t: C.ggml_reshape_3d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1]), C.int64_t(shape[2])),
  683. }
  684. case 4:
  685. return &Tensor{
  686. b: t.b,
  687. t: C.ggml_reshape_4d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1]), C.int64_t(shape[2]), C.int64_t(shape[3])),
  688. }
  689. default:
  690. panic("unsupported number of dimensions")
  691. }
  692. }
  693. func (t *Tensor) Scale(ctx ml.Context, s float64) ml.Tensor {
  694. return &Tensor{
  695. b: t.b,
  696. t: C.ggml_scale(ctx.(*Context).ctx, t.t, (C.float)(s)),
  697. }
  698. }
  699. func (t *Tensor) Softmax(ctx ml.Context) ml.Tensor {
  700. return &Tensor{
  701. b: t.b,
  702. t: C.ggml_soft_max(ctx.(*Context).ctx, t.t),
  703. }
  704. }
  705. func (t *Tensor) Tanh(ctx ml.Context) ml.Tensor {
  706. return &Tensor{
  707. b: t.b,
  708. t: C.ggml_tanh_inplace(ctx.(*Context).ctx, t.t),
  709. }
  710. }
  711. func (t *Tensor) Unpad(ctx ml.Context, shape ...int) ml.Tensor {
  712. if len(shape) != 4 {
  713. panic("expected 4 dimensions")
  714. }
  715. return &Tensor{
  716. b: t.b,
  717. t: C.ggml_unpad(ctx.(*Context).ctx, t.t, C.int(shape[0]), C.int(shape[1]), C.int(shape[2]), C.int(shape[3])),
  718. }
  719. }
  720. func (t *Tensor) View(ctx ml.Context, offset int, shape ...int) ml.Tensor {
  721. switch len(shape) {
  722. case 1:
  723. return &Tensor{
  724. b: t.b,
  725. t: C.ggml_view_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.size_t(offset)),
  726. }
  727. case 3:
  728. return &Tensor{
  729. b: t.b,
  730. t: C.ggml_view_2d(ctx.(*Context).ctx, t.t,
  731. C.int64_t(shape[0]), C.int64_t(shape[2]),
  732. C.size_t(shape[1]),
  733. C.size_t(offset)),
  734. }
  735. case 5:
  736. return &Tensor{
  737. b: t.b,
  738. t: C.ggml_view_3d(ctx.(*Context).ctx, t.t,
  739. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]),
  740. C.size_t(shape[1]), C.size_t(shape[3]),
  741. C.size_t(offset)),
  742. }
  743. case 7:
  744. return &Tensor{
  745. b: t.b,
  746. t: C.ggml_view_4d(ctx.(*Context).ctx, t.t,
  747. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]), C.int64_t(shape[6]),
  748. C.size_t(shape[1]), C.size_t(shape[3]), C.size_t(shape[5]),
  749. C.size_t(offset)),
  750. }
  751. default:
  752. panic("unsupported number of dimensions")
  753. }
  754. }
  755. const (
  756. ropeTypeNorm C.int = 0
  757. ropeTypeNeox C.int = 2
  758. ropeTypeMrope C.int = 8
  759. ropeTypeVision C.int = 24
  760. )
  761. func (t *Tensor) RoPE(ctx ml.Context, positionIDs, ropeFactors ml.Tensor, ropeDim, ropeType uint32, ropeBase, ropeScale float32) ml.Tensor {
  762. if ropeFactors == nil {
  763. ropeFactors = &Tensor{b: t.b}
  764. }
  765. dequant := t.t
  766. if C.ggml_is_quantized(t.t._type) {
  767. dequant = C.ggml_cast(ctx.(*Context).ctx, t.t, C.GGML_TYPE_F32)
  768. }
  769. return &Tensor{
  770. b: t.b,
  771. t: C.ggml_rope_ext(
  772. ctx.(*Context).ctx, dequant, positionIDs.(*Tensor).t, ropeFactors.(*Tensor).t,
  773. C.int(ropeDim),
  774. C.int(ropeType),
  775. 131072, // YaRN n_ctx_train
  776. C.float(ropeBase),
  777. C.float(ropeScale),
  778. 0., // YaRN ext_factor
  779. 1., // YaRN attn_factor
  780. 32., // YaRN beta_fast
  781. 1., // YaRN beta_slow
  782. ),
  783. }
  784. }
  785. func (t *Tensor) GELU(ctx ml.Context) ml.Tensor {
  786. return &Tensor{
  787. b: t.b,
  788. t: C.ggml_gelu_inplace(ctx.(*Context).ctx, t.t),
  789. }
  790. }
  791. func (t *Tensor) SILU(ctx ml.Context) ml.Tensor {
  792. return &Tensor{
  793. b: t.b,
  794. t: C.ggml_silu_inplace(ctx.(*Context).ctx, t.t),
  795. }
  796. }
  797. func (t *Tensor) Conv2D(ctx ml.Context, t2 ml.Tensor, s0, s1, p0, p1, d0, d1 int) ml.Tensor {
  798. return &Tensor{
  799. b: t.b,
  800. t: C.ggml_conv_2d(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.int(s0), C.int(s1), C.int(p0), C.int(p1), C.int(d0), C.int(d1)),
  801. }
  802. }
  803. func (t *Tensor) AvgPool2D(ctx ml.Context, k, s int, p float32) ml.Tensor {
  804. return &Tensor{
  805. b: t.b,
  806. t: C.ggml_pool_2d(ctx.(*Context).ctx, t.t, C.GGML_OP_POOL_AVG, C.int(k), C.int(k), C.int(s), C.int(s), C.float(p), C.float(p)),
  807. }
  808. }
  809. func (t *Tensor) Set(ctx ml.Context, t2 ml.Tensor, offset int, strides ...int) ml.Tensor {
  810. var tt *C.struct_ggml_tensor
  811. switch len(strides) {
  812. case 0:
  813. tt = C.ggml_set_1d(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.size_t(offset))
  814. case 1:
  815. tt = C.ggml_set_2d(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.size_t(offset), C.size_t(strides[0]))
  816. default:
  817. panic("unsupported number of dimensions")
  818. }
  819. return &Tensor{b: t.b, t: tt}
  820. }
  821. func (t *Tensor) ScaledDotProductAttention(ctx ml.Context, key, value, mask ml.Tensor, scale float64) ml.Tensor {
  822. var kqMask *C.struct_ggml_tensor
  823. if mask != nil {
  824. kqMask = mask.(*Tensor).t
  825. }
  826. query := t.Permute(ctx, 0, 2, 1, 3)
  827. key = key.Permute(ctx, 0, 2, 1, 3)
  828. if t.b.flashAttention {
  829. value = value.Permute(ctx, 0, 2, 1, 3)
  830. kqv := C.ggml_flash_attn_ext(ctx.(*Context).ctx, query.(*Tensor).t, key.(*Tensor).t, value.(*Tensor).t, kqMask, C.float(scale), 0, 0)
  831. C.ggml_flash_attn_ext_set_prec(kqv, C.GGML_PREC_F32)
  832. return &Tensor{b: t.b, t: kqv}
  833. } else {
  834. kq := key.MulmatFullPrec(ctx, query)
  835. kq = &Tensor{
  836. b: t.b,
  837. t: C.ggml_soft_max_ext(ctx.(*Context).ctx, kq.(*Tensor).t, kqMask, C.float(scale), 0),
  838. }
  839. kqv := value.Mulmat(ctx, kq)
  840. return kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  841. }
  842. }