ggml.go 24 KB

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