ggml.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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}, input.bts)
  210. default:
  211. layerIndex := -1
  212. if fields := strings.FieldsFunc(t.Name, func(r rune) bool { return !unicode.IsNumber(r) }); len(fields) > 0 {
  213. if i, err := strconv.Atoi(fields[0]); err == nil {
  214. layerIndex = i
  215. }
  216. }
  217. if layerIndex >= 0 {
  218. createTensor(tensor{source: t}, layers[layerIndex].bts)
  219. } else {
  220. // this is a repeating tensor that doesn't explicitly associated with a layer so
  221. // duplicate it for each layer
  222. for i, layer := range layers {
  223. createTensor(tensor{
  224. source: t,
  225. target: "blk." + strconv.Itoa(i) + "." + t.Name,
  226. }, layer.bts)
  227. }
  228. }
  229. }
  230. }
  231. // allocate buffers for each context
  232. bbs := make(map[*C.struct_ggml_context]*C.struct_ggml_backend_buffer, len(ctxs))
  233. for bt, c := range ctxs {
  234. if C.ggml_get_first_tensor(c) == nil {
  235. continue
  236. }
  237. b := C.ggml_backend_alloc_ctx_tensors_from_buft(c, bt)
  238. C.ggml_backend_buffer_set_usage(b, C.GGML_BACKEND_BUFFER_USAGE_WEIGHTS)
  239. bbs[c] = b
  240. }
  241. for bs := range maps.Values(bbs) {
  242. slog.Info("model weights", "buffer", C.GoString(C.ggml_backend_buffer_name(bs)), "size", format.HumanBytes2(uint64(C.ggml_backend_buffer_get_size(bs))))
  243. }
  244. // map tensor names to tensors for easy lookup later
  245. tensors := make(map[string]*C.struct_ggml_tensor)
  246. for _, c := range ctxs {
  247. for t := C.ggml_get_first_tensor(c); t != nil; t = C.ggml_get_next_tensor(c, t) {
  248. tensors[C.GoString(C.ggml_get_name(t))] = t
  249. }
  250. }
  251. // concurrently read in tensor data. uses a section reader which is safe for concurrent reads
  252. sr := io.NewSectionReader(r, int64(meta.Tensors().Offset), n-int64(meta.Tensors().Offset))
  253. var g errgroup.Group
  254. for _, t := range meta.Tensors().Items() {
  255. for _, target := range targets[t.Name] {
  256. g.Go(func() error {
  257. if target == "" {
  258. target = t.Name
  259. }
  260. tt, ok := tensors[target]
  261. if !ok {
  262. return fmt.Errorf("unassigned tensor: %s", t.Name)
  263. }
  264. bts := make([]byte, t.Size())
  265. n, err := io.ReadFull(io.NewSectionReader(sr, int64(t.Offset), int64(t.Size())), bts)
  266. if err != nil {
  267. return err
  268. }
  269. if n != len(bts) {
  270. return errors.New("short read")
  271. }
  272. C.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), 0, C.size_t(t.Size()))
  273. return nil
  274. })
  275. }
  276. }
  277. if g.Wait() != nil {
  278. return nil, err
  279. }
  280. // map devices to backend buffer types so new tensors can be assigned to the correct device
  281. deviceBufferTypes := make(map[*C.struct_ggml_backend_device]*C.struct_ggml_backend_buffer_type)
  282. // create backends and buffer types used for the compute graph scheduler
  283. var schedBackends []*C.struct_ggml_backend
  284. var schedBufts []*C.struct_ggml_backend_buffer_type
  285. for _, d := range append(gpus, append(accels, cpus...)...) {
  286. b := C.ggml_backend_dev_init(d, nil)
  287. bt := C.ggml_backend_get_default_buffer_type(b)
  288. if d := C.ggml_backend_get_device(b); C.ggml_backend_dev_type(d) == C.GGML_BACKEND_DEVICE_TYPE_CPU && len(gpus) > 0 {
  289. // use the first gpu host buffer type for gpu if possible
  290. if hbt := C.ggml_backend_dev_host_buffer_type(gpus[0]); hbt != nil {
  291. bt = hbt
  292. }
  293. }
  294. deviceBufferTypes[d] = bt
  295. schedBackends = append(schedBackends, b)
  296. schedBufts = append(schedBufts, bt)
  297. slog.Info("compute graph", "backend", C.GoString(C.ggml_backend_name(b)), "buffer_type", C.GoString(C.ggml_backend_buft_name(bt)))
  298. if C.ggml_backend_is_cpu(b) {
  299. // set number of threads for cpu backend
  300. C.ggml_backend_cpu_set_n_threads(b, C.int(Threads(params.NumThreads)))
  301. }
  302. }
  303. maxGraphNodes := max(8192, len(meta.Tensors().Items())*5)
  304. return &Backend{
  305. flashAttention: params.FlashAttention,
  306. meta: meta,
  307. tensors: tensors,
  308. sched: C.ggml_backend_sched_new(
  309. (*C.ggml_backend_t)(unsafe.Pointer(&schedBackends[0])),
  310. (*C.ggml_backend_buffer_type_t)(unsafe.Pointer(&schedBufts[0])),
  311. C.int(len(schedBackends)),
  312. C.size_t(maxGraphNodes),
  313. true,
  314. ),
  315. input: deviceBufferTypes[input.d],
  316. output: deviceBufferTypes[output.d],
  317. layers: func() map[int]*C.struct_ggml_backend_buffer_type {
  318. m := make(map[int]*C.struct_ggml_backend_buffer_type)
  319. for i, layer := range layers {
  320. m[i] = deviceBufferTypes[layer.d]
  321. }
  322. return m
  323. }(),
  324. maxGraphNodes: maxGraphNodes,
  325. }, nil
  326. }
  327. func init() {
  328. ml.RegisterBackend("ggml", New)
  329. }
  330. func (b *Backend) Config() ml.Config {
  331. return b.meta.KV()
  332. }
  333. func (b *Backend) Get(name string) ml.Tensor {
  334. if t, ok := b.tensors[name]; ok {
  335. return &Tensor{b: b, t: t}
  336. }
  337. return nil
  338. }
  339. func (b *Backend) NewContext() ml.Context {
  340. return b.NewContextSize(b.maxGraphNodes)
  341. }
  342. func (b *Backend) NewContextSize(n int) ml.Context {
  343. if n > b.maxGraphNodes {
  344. panic(fmt.Errorf("requested number of graph nodes (%v) for new context exceeds maximum (%v)", n, b.maxGraphNodes))
  345. }
  346. return &Context{
  347. b: b,
  348. maxGraphNodes: n,
  349. ctx: C.ggml_init(C.struct_ggml_init_params{
  350. mem_size: C.size_t(n)*C.ggml_tensor_overhead() + C.ggml_graph_overhead_custom(C.size_t(n), false),
  351. no_alloc: true,
  352. }),
  353. }
  354. }
  355. func (b *Backend) CacheConfig() ml.CacheConfig {
  356. if b.flashAttention {
  357. return ml.CacheConfig{CachePadding: 256, MaskDType: ml.DTypeF16, MaskBatchPadding: C.GGML_KQ_MASK_PAD}
  358. } else {
  359. return ml.CacheConfig{CachePadding: 32, PermutedV: true}
  360. }
  361. }
  362. type Context struct {
  363. b *Backend
  364. ctx *C.struct_ggml_context
  365. graph *C.struct_ggml_cgraph
  366. // buft is the buffer type used for new tensors
  367. buft *C.struct_ggml_backend_buffer_type
  368. // maxGraphNodes is the maximum allowed number of graph nodes in this context
  369. maxGraphNodes int
  370. }
  371. func (c Context) Input() ml.Context {
  372. if c.b.input != nil {
  373. return &Context{
  374. b: c.b,
  375. ctx: c.ctx,
  376. buft: c.b.input,
  377. maxGraphNodes: c.maxGraphNodes,
  378. }
  379. }
  380. return &c
  381. }
  382. func (c Context) Output() ml.Context {
  383. if c.b.output != nil {
  384. return &Context{
  385. b: c.b,
  386. ctx: c.ctx,
  387. buft: c.b.output,
  388. maxGraphNodes: c.maxGraphNodes,
  389. }
  390. }
  391. return &c
  392. }
  393. func (c Context) Layer(i int) ml.Context {
  394. if buft, ok := c.b.layers[i]; ok {
  395. return &Context{
  396. b: c.b,
  397. ctx: c.ctx,
  398. buft: buft,
  399. maxGraphNodes: c.maxGraphNodes,
  400. }
  401. }
  402. return &c
  403. }
  404. func (c *Context) Forward(tensors ...ml.Tensor) ml.Context {
  405. if c.graph == nil {
  406. c.graph = C.ggml_new_graph_custom(c.ctx, C.size_t(c.maxGraphNodes), false)
  407. }
  408. for _, tensor := range tensors {
  409. C.ggml_build_forward_expand(c.graph, tensor.(*Tensor).t)
  410. }
  411. return c
  412. }
  413. func (c Context) Compute(tensors ...ml.Tensor) {
  414. C.ggml_backend_sched_graph_compute_async(c.b.sched, c.graph)
  415. C.ggml_backend_sched_reset(c.b.sched)
  416. needSync := true
  417. sync := func() {
  418. if needSync {
  419. C.ggml_backend_sched_synchronize(c.b.sched)
  420. needSync = false
  421. }
  422. }
  423. for _, t := range tensors {
  424. if C.ggml_nbytes(t.(*Tensor).t) > 0 {
  425. t.(*Tensor).sync = sync
  426. }
  427. }
  428. }
  429. func (c Context) MaxGraphNodes() int {
  430. return c.maxGraphNodes
  431. }
  432. func shapeToGGML(shape []int) *C.int64_t {
  433. sh := make([]C.int64_t, len(shape))
  434. for i, s := range shape {
  435. sh[i] = C.int64_t(s)
  436. }
  437. return &sh[0]
  438. }
  439. func pad(length, pad C.size_t) C.size_t {
  440. return ((length + pad - 1) / pad) * pad
  441. }
  442. func (c Context) newTensor(dtype ml.DType, shape []int) ml.Tensor {
  443. if c.buft == nil {
  444. panic("set Input, Output, or Layer before creating tensors")
  445. }
  446. var cdtype uint32
  447. switch dtype {
  448. case ml.DTypeF32:
  449. cdtype = C.GGML_TYPE_F32
  450. case ml.DTypeF16:
  451. cdtype = C.GGML_TYPE_F16
  452. case ml.DTypeQ80:
  453. cdtype = C.GGML_TYPE_Q8_0
  454. case ml.DTypeQ40:
  455. cdtype = C.GGML_TYPE_Q4_0
  456. case ml.DTypeI32:
  457. cdtype = C.GGML_TYPE_I32
  458. default:
  459. panic("unsupported dtype")
  460. }
  461. if len(shape) < 1 || shape[0] == 0 {
  462. var shape C.int64_t = 0
  463. return &Tensor{b: c.b, t: C.ggml_new_tensor(c.ctx, cdtype, 1, &shape)}
  464. } else if len(shape) > 4 {
  465. panic("unsupported number of dimensions")
  466. }
  467. for _, dim := range shape {
  468. if dim < 1 {
  469. panic("invalid shape")
  470. }
  471. }
  472. t := C.ggml_new_tensor(c.ctx, cdtype, C.int(len(shape)), shapeToGGML(shape))
  473. size := pad(C.ggml_backend_buft_get_alloc_size(c.buft, t), C.ggml_backend_buft_get_alignment(c.buft))
  474. b := C.ggml_backend_buft_alloc_buffer(c.buft, size)
  475. C.ggml_backend_tensor_alloc(b, t, C.ggml_backend_buffer_get_base(b))
  476. return &Tensor{b: c.b, t: t}
  477. }
  478. func (c Context) Empty(dtype ml.DType, shape ...int) ml.Tensor {
  479. return c.newTensor(dtype, shape)
  480. }
  481. func (c Context) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
  482. t := c.newTensor(dtype, shape)
  483. C.ggml_set_zero(t.(*Tensor).t)
  484. return t
  485. }
  486. func checkShape[S ~[]E, E any](s S, shape ...int) error {
  487. n := len(s)
  488. if n == 0 {
  489. return nil
  490. }
  491. for _, v := range shape {
  492. n /= v
  493. }
  494. if n != 1 {
  495. return fmt.Errorf("invalid shape: %v", shape)
  496. }
  497. return nil
  498. }
  499. func (c Context) FromFloatSlice(s []float32, shape ...int) (ml.Tensor, error) {
  500. if err := checkShape(s, shape...); err != nil {
  501. return nil, err
  502. }
  503. t := c.newTensor(ml.DTypeF32, shape)
  504. if len(s) > 0 {
  505. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  506. }
  507. return t, nil
  508. }
  509. func (c Context) FromIntSlice(s []int32, shape ...int) (ml.Tensor, error) {
  510. if err := checkShape(s, shape...); err != nil {
  511. return nil, err
  512. }
  513. t := c.newTensor(ml.DTypeI32, shape)
  514. if len(s) > 0 {
  515. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  516. }
  517. return t, nil
  518. }
  519. func (c *Context) Close() {
  520. if c != nil {
  521. C.ggml_free(c.ctx)
  522. }
  523. }
  524. type Tensor struct {
  525. b *Backend
  526. t *C.struct_ggml_tensor
  527. sync func()
  528. }
  529. func (t *Tensor) LogValue() slog.Value {
  530. return slog.GroupValue(
  531. slog.String("name", C.GoString(C.ggml_get_name(t.t))),
  532. slog.String("type", C.GoString(C.ggml_type_name(t.t._type))),
  533. slog.Any("shape", t.Shape()),
  534. )
  535. }
  536. func (t *Tensor) Dim(n int) int {
  537. return int(t.t.ne[n])
  538. }
  539. func (t *Tensor) Stride(n int) int {
  540. return int(t.t.nb[n])
  541. }
  542. func (t *Tensor) Shape() []int {
  543. shape := make([]int, C.ggml_n_dims(t.t))
  544. for i := range shape {
  545. shape[i] = t.Dim(i)
  546. }
  547. return shape
  548. }
  549. func (t *Tensor) Bytes() (data []byte) {
  550. if t.sync != nil {
  551. data = make([]byte, C.ggml_nbytes(t.t))
  552. t.sync()
  553. C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
  554. }
  555. return
  556. }
  557. func (t *Tensor) Floats() (data []float32) {
  558. if t.sync != nil {
  559. data = make([]float32, C.ggml_nelements(t.t))
  560. t.sync()
  561. C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
  562. }
  563. return
  564. }
  565. func (t *Tensor) DType() ml.DType {
  566. switch t.t._type {
  567. case C.GGML_TYPE_F32:
  568. return ml.DTypeF32
  569. case C.GGML_TYPE_F16:
  570. return ml.DTypeF16
  571. case C.GGML_TYPE_Q8_0:
  572. return ml.DTypeQ80
  573. case C.GGML_TYPE_Q4_0:
  574. return ml.DTypeQ40
  575. case C.GGML_TYPE_I32:
  576. return ml.DTypeI32
  577. default:
  578. return ml.DTypeOther
  579. }
  580. }
  581. func (t *Tensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  582. return &Tensor{
  583. b: t.b,
  584. t: C.ggml_add(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  585. }
  586. }
  587. func (t *Tensor) Stack(ctx ml.Context, dim int, s ...ml.Tensor) ml.Tensor {
  588. if len(s) > 0 {
  589. return t.Concat(ctx, s[0].Stack(ctx, dim, s[1:]...), dim)
  590. }
  591. return t
  592. }
  593. func (t *Tensor) Concat(ctx ml.Context, t2 ml.Tensor, dim int) ml.Tensor {
  594. return &Tensor{
  595. b: t.b,
  596. t: C.ggml_concat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.int(dim)),
  597. }
  598. }
  599. func (t *Tensor) Contiguous(ctx ml.Context) ml.Tensor {
  600. return &Tensor{
  601. b: t.b,
  602. t: C.ggml_cont(ctx.(*Context).ctx, t.t),
  603. }
  604. }
  605. func (t *Tensor) Mul(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  606. return &Tensor{
  607. b: t.b,
  608. t: C.ggml_mul(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  609. }
  610. }
  611. func (t *Tensor) Mulmat(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  612. return &Tensor{
  613. b: t.b,
  614. t: C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  615. }
  616. }
  617. func (t *Tensor) MulmatFullPrec(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  618. mul := C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t)
  619. C.ggml_mul_mat_set_prec(mul, C.GGML_PREC_F32)
  620. return &Tensor{
  621. b: t.b,
  622. t: mul,
  623. }
  624. }
  625. func (t *Tensor) LayerNorm(ctx ml.Context, w, b ml.Tensor, eps float32) ml.Tensor {
  626. tt := (&Tensor{b: t.b, t: C.ggml_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  627. if b != nil {
  628. tt = tt.Add(ctx, b)
  629. }
  630. return tt
  631. }
  632. func (t *Tensor) RMSNorm(ctx ml.Context, w ml.Tensor, eps float32) ml.Tensor {
  633. return (&Tensor{b: t.b, t: C.ggml_rms_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  634. }
  635. func (t *Tensor) Pad(ctx ml.Context, shape ...int) ml.Tensor {
  636. if len(shape) != 4 {
  637. panic("expected 4 dimensions")
  638. }
  639. return &Tensor{
  640. b: t.b,
  641. 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])),
  642. }
  643. }
  644. func (t *Tensor) Permute(ctx ml.Context, shape ...int) ml.Tensor {
  645. if len(shape) != 4 {
  646. panic("expected 4 dimensions")
  647. }
  648. return &Tensor{
  649. b: t.b,
  650. 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])),
  651. }
  652. }
  653. func (t *Tensor) Rows(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  654. return &Tensor{
  655. b: t.b,
  656. t: C.ggml_get_rows(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  657. }
  658. }
  659. func (t *Tensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  660. return &Tensor{
  661. b: t.b,
  662. t: C.ggml_cpy(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  663. }
  664. }
  665. func (t *Tensor) Reshape(ctx ml.Context, shape ...int) ml.Tensor {
  666. switch len(shape) {
  667. case 1:
  668. return &Tensor{
  669. b: t.b,
  670. t: C.ggml_reshape_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0])),
  671. }
  672. case 2:
  673. return &Tensor{
  674. b: t.b,
  675. t: C.ggml_reshape_2d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1])),
  676. }
  677. case 3:
  678. return &Tensor{
  679. b: t.b,
  680. 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])),
  681. }
  682. case 4:
  683. return &Tensor{
  684. b: t.b,
  685. 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])),
  686. }
  687. default:
  688. panic("unsupported number of dimensions")
  689. }
  690. }
  691. func (t *Tensor) Scale(ctx ml.Context, s float64) ml.Tensor {
  692. return &Tensor{
  693. b: t.b,
  694. t: C.ggml_scale(ctx.(*Context).ctx, t.t, (C.float)(s)),
  695. }
  696. }
  697. func (t *Tensor) Softmax(ctx ml.Context) ml.Tensor {
  698. return &Tensor{
  699. b: t.b,
  700. t: C.ggml_soft_max(ctx.(*Context).ctx, t.t),
  701. }
  702. }
  703. func (t *Tensor) Tanh(ctx ml.Context) ml.Tensor {
  704. return &Tensor{
  705. b: t.b,
  706. t: C.ggml_tanh_inplace(ctx.(*Context).ctx, t.t),
  707. }
  708. }
  709. func (t *Tensor) Unpad(ctx ml.Context, shape ...int) ml.Tensor {
  710. if len(shape) != 4 {
  711. panic("expected 4 dimensions")
  712. }
  713. return &Tensor{
  714. b: t.b,
  715. 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])),
  716. }
  717. }
  718. func (t *Tensor) View(ctx ml.Context, offset int, shape ...int) ml.Tensor {
  719. switch len(shape) {
  720. case 1:
  721. return &Tensor{
  722. b: t.b,
  723. t: C.ggml_view_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.size_t(offset)),
  724. }
  725. case 3:
  726. return &Tensor{
  727. b: t.b,
  728. t: C.ggml_view_2d(ctx.(*Context).ctx, t.t,
  729. C.int64_t(shape[0]), C.int64_t(shape[2]),
  730. C.size_t(shape[1]),
  731. C.size_t(offset)),
  732. }
  733. case 5:
  734. return &Tensor{
  735. b: t.b,
  736. t: C.ggml_view_3d(ctx.(*Context).ctx, t.t,
  737. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]),
  738. C.size_t(shape[1]), C.size_t(shape[3]),
  739. C.size_t(offset)),
  740. }
  741. case 7:
  742. return &Tensor{
  743. b: t.b,
  744. t: C.ggml_view_4d(ctx.(*Context).ctx, t.t,
  745. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]), C.int64_t(shape[6]),
  746. C.size_t(shape[1]), C.size_t(shape[3]), C.size_t(shape[5]),
  747. C.size_t(offset)),
  748. }
  749. default:
  750. panic("unsupported number of dimensions")
  751. }
  752. }
  753. const (
  754. ropeTypeNorm C.int = 0
  755. ropeTypeNeox C.int = 2
  756. ropeTypeMrope C.int = 8
  757. ropeTypeVision C.int = 24
  758. )
  759. func (t *Tensor) RoPE(ctx ml.Context, positionIDs, ropeFactors ml.Tensor, ropeDim, ropeType uint32, ropeBase, ropeScale float32) ml.Tensor {
  760. if ropeFactors == nil {
  761. ropeFactors = &Tensor{b: t.b}
  762. }
  763. dequant := t.t
  764. if C.ggml_is_quantized(t.t._type) {
  765. dequant = C.ggml_cast(ctx.(*Context).ctx, t.t, C.GGML_TYPE_F32)
  766. }
  767. return &Tensor{
  768. b: t.b,
  769. t: C.ggml_rope_ext(
  770. ctx.(*Context).ctx, dequant, positionIDs.(*Tensor).t, ropeFactors.(*Tensor).t,
  771. C.int(ropeDim),
  772. C.int(ropeType),
  773. 131072, // YaRN n_ctx_train
  774. C.float(ropeBase),
  775. C.float(ropeScale),
  776. 0., // YaRN ext_factor
  777. 1., // YaRN attn_factor
  778. 32., // YaRN beta_fast
  779. 1., // YaRN beta_slow
  780. ),
  781. }
  782. }
  783. func (t *Tensor) GELU(ctx ml.Context) ml.Tensor {
  784. return &Tensor{
  785. b: t.b,
  786. t: C.ggml_gelu_inplace(ctx.(*Context).ctx, t.t),
  787. }
  788. }
  789. func (t *Tensor) SILU(ctx ml.Context) ml.Tensor {
  790. return &Tensor{
  791. b: t.b,
  792. t: C.ggml_silu_inplace(ctx.(*Context).ctx, t.t),
  793. }
  794. }
  795. func (t *Tensor) Conv2D(ctx ml.Context, t2 ml.Tensor, s0, s1, p0, p1, d0, d1 int) ml.Tensor {
  796. return &Tensor{
  797. b: t.b,
  798. 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)),
  799. }
  800. }
  801. func (t *Tensor) AvgPool1D(ctx ml.Context, k, s, p int) ml.Tensor {
  802. return &Tensor{
  803. b: t.b,
  804. t: C.ggml_pool_1d(ctx.(*Context).ctx, t.t, C.GGML_OP_POOL_AVG, C.int(k), C.int(s), C.int(p)),
  805. }
  806. }
  807. func (t *Tensor) Set(ctx ml.Context, t2 ml.Tensor, offset int, strides ...int) ml.Tensor {
  808. var tt *C.struct_ggml_tensor
  809. switch len(strides) {
  810. case 0:
  811. tt = C.ggml_set_1d(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.size_t(offset))
  812. case 1:
  813. tt = C.ggml_set_2d(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.size_t(offset), C.size_t(strides[0]))
  814. default:
  815. panic("unsupported number of dimensions")
  816. }
  817. return &Tensor{b: t.b, t: tt}
  818. }
  819. func (t *Tensor) ScaledDotProductAttention(ctx ml.Context, key, value, mask ml.Tensor, scale float64) ml.Tensor {
  820. var kqMask *C.struct_ggml_tensor
  821. if mask != nil {
  822. kqMask = mask.(*Tensor).t
  823. }
  824. query := t.Permute(ctx, 0, 2, 1, 3)
  825. key = key.Permute(ctx, 0, 2, 1, 3)
  826. if t.b.flashAttention {
  827. value = value.Permute(ctx, 0, 2, 1, 3)
  828. kqv := C.ggml_flash_attn_ext(ctx.(*Context).ctx, query.(*Tensor).t, key.(*Tensor).t, value.(*Tensor).t, kqMask, C.float(scale), 0, 0)
  829. C.ggml_flash_attn_ext_set_prec(kqv, C.GGML_PREC_F32)
  830. return &Tensor{b: t.b, t: kqv}
  831. } else {
  832. kq := key.MulmatFullPrec(ctx, query)
  833. kq = &Tensor{
  834. b: t.b,
  835. t: C.ggml_soft_max_ext(ctx.(*Context).ctx, kq.(*Tensor).t, kqMask, C.float(scale), 0),
  836. }
  837. kqv := value.Mulmat(ctx, kq)
  838. return kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  839. }
  840. }