ggml.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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. n = min(n, b.maxGraphNodes)
  341. return &Context{
  342. b: b,
  343. maxGraphNodes: n,
  344. ctx: C.ggml_init(C.struct_ggml_init_params{
  345. mem_size: C.size_t(n)*C.ggml_tensor_overhead() + C.ggml_graph_overhead_custom(C.size_t(n), false),
  346. no_alloc: true,
  347. }),
  348. }
  349. }
  350. func (b *Backend) CacheConfig() ml.CacheConfig {
  351. if b.flashAttention {
  352. return ml.CacheConfig{CachePadding: 256, MaskDType: ml.DTypeF16, MaskBatchPadding: C.GGML_KQ_MASK_PAD}
  353. } else {
  354. return ml.CacheConfig{CachePadding: 32, PermutedV: true}
  355. }
  356. }
  357. type Context struct {
  358. b *Backend
  359. ctx *C.struct_ggml_context
  360. graph *C.struct_ggml_cgraph
  361. // buft is the buffer type used for new tensors
  362. buft *C.struct_ggml_backend_buffer_type
  363. // maxGraphNodes is the maximum allowed number of graph nodes in this context
  364. maxGraphNodes int
  365. }
  366. func (c Context) Input() ml.Context {
  367. if c.b.input != nil {
  368. return &Context{
  369. b: c.b,
  370. ctx: c.ctx,
  371. buft: c.b.input,
  372. maxGraphNodes: c.maxGraphNodes,
  373. }
  374. }
  375. return &c
  376. }
  377. func (c Context) Output() ml.Context {
  378. if c.b.output != nil {
  379. return &Context{
  380. b: c.b,
  381. ctx: c.ctx,
  382. buft: c.b.output,
  383. maxGraphNodes: c.maxGraphNodes,
  384. }
  385. }
  386. return &c
  387. }
  388. func (c Context) Layer(i int) ml.Context {
  389. if buft, ok := c.b.layers[i]; ok {
  390. return &Context{
  391. b: c.b,
  392. ctx: c.ctx,
  393. buft: buft,
  394. maxGraphNodes: c.maxGraphNodes,
  395. }
  396. }
  397. return &c
  398. }
  399. func (c *Context) Forward(tensors ...ml.Tensor) ml.Context {
  400. if c.graph == nil {
  401. c.graph = C.ggml_new_graph_custom(c.ctx, C.size_t(c.maxGraphNodes), false)
  402. }
  403. for _, tensor := range tensors {
  404. C.ggml_build_forward_expand(c.graph, tensor.(*Tensor).t)
  405. }
  406. return c
  407. }
  408. func (c Context) Compute(tensors ...ml.Tensor) {
  409. C.ggml_backend_sched_graph_compute_async(c.b.sched, c.graph)
  410. C.ggml_backend_sched_reset(c.b.sched)
  411. needSync := true
  412. sync := func() {
  413. if needSync {
  414. C.ggml_backend_sched_synchronize(c.b.sched)
  415. needSync = false
  416. }
  417. }
  418. for _, t := range tensors {
  419. if C.ggml_nbytes(t.(*Tensor).t) > 0 {
  420. t.(*Tensor).sync = sync
  421. }
  422. }
  423. }
  424. func (c Context) MaxGraphNodes() int {
  425. return c.maxGraphNodes
  426. }
  427. func shapeToGGML(shape []int) *C.int64_t {
  428. sh := make([]C.int64_t, len(shape))
  429. for i, s := range shape {
  430. sh[i] = C.int64_t(s)
  431. }
  432. return &sh[0]
  433. }
  434. func (c Context) newTensor(dtype ml.DType, shape []int) ml.Tensor {
  435. if c.buft == nil {
  436. panic("set Input, Output, or Layer before creating tensors")
  437. }
  438. var cdtype uint32
  439. switch dtype {
  440. case ml.DTypeF32:
  441. cdtype = C.GGML_TYPE_F32
  442. case ml.DTypeF16:
  443. cdtype = C.GGML_TYPE_F16
  444. case ml.DTypeI32:
  445. cdtype = C.GGML_TYPE_I32
  446. default:
  447. panic("unsupported dtype")
  448. }
  449. if len(shape) < 1 {
  450. var shape C.int64_t = 0
  451. return &Tensor{b: c.b, t: C.ggml_new_tensor(c.ctx, cdtype, 1, &shape)}
  452. } else if len(shape) > 4 {
  453. panic("unsupported number of dimensions")
  454. }
  455. for _, dim := range shape {
  456. if dim < 1 {
  457. panic("invalid shape")
  458. }
  459. }
  460. t := C.ggml_new_tensor(c.ctx, cdtype, C.int(len(shape)), shapeToGGML(shape))
  461. b := C.ggml_backend_buft_alloc_buffer(c.buft, C.ggml_nbytes(t))
  462. C.ggml_backend_tensor_alloc(b, t, C.ggml_backend_buffer_get_base(b))
  463. return &Tensor{b: c.b, t: t}
  464. }
  465. func (c Context) Empty(dtype ml.DType, shape ...int) ml.Tensor {
  466. return c.newTensor(dtype, shape)
  467. }
  468. func (c Context) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
  469. t := c.newTensor(dtype, shape)
  470. C.ggml_set_zero(t.(*Tensor).t)
  471. return t
  472. }
  473. func checkShape[S ~[]E, E any](s S, shape ...int) error {
  474. n := len(s)
  475. for _, v := range shape {
  476. n /= v
  477. }
  478. if n != 1 {
  479. return fmt.Errorf("invalid shape: %v", shape)
  480. }
  481. return nil
  482. }
  483. func (c Context) FromFloatSlice(s []float32, shape ...int) (ml.Tensor, error) {
  484. if err := checkShape(s, shape...); err != nil && len(shape) > 0 {
  485. return nil, err
  486. }
  487. t := c.newTensor(ml.DTypeF32, shape)
  488. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  489. return t, nil
  490. }
  491. func (c Context) FromIntSlice(s []int32, shape ...int) (ml.Tensor, error) {
  492. if err := checkShape(s, shape...); err != nil && len(shape) > 0 {
  493. return nil, err
  494. }
  495. t := c.newTensor(ml.DTypeI32, shape)
  496. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  497. return t, nil
  498. }
  499. func (c *Context) Close() {
  500. if c != nil {
  501. C.ggml_free(c.ctx)
  502. }
  503. }
  504. type Tensor struct {
  505. b *Backend
  506. t *C.struct_ggml_tensor
  507. sync func()
  508. }
  509. func (t *Tensor) LogValue() slog.Value {
  510. return slog.GroupValue(
  511. slog.String("name", C.GoString(C.ggml_get_name(t.t))),
  512. slog.String("type", C.GoString(C.ggml_type_name(t.t._type))),
  513. slog.Any("shape", t.Shape()),
  514. )
  515. }
  516. func (t *Tensor) Dim(n int) int {
  517. return int(t.t.ne[n])
  518. }
  519. func (t *Tensor) Stride(n int) int {
  520. return int(t.t.nb[n])
  521. }
  522. func (t *Tensor) Shape() []int {
  523. shape := make([]int, C.ggml_n_dims(t.t))
  524. for i := range shape {
  525. shape[i] = t.Dim(i)
  526. }
  527. return shape
  528. }
  529. func (t *Tensor) Bytes() (data []byte) {
  530. if t.sync != nil {
  531. data = make([]byte, C.ggml_nbytes(t.t))
  532. t.sync()
  533. C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
  534. }
  535. return
  536. }
  537. func (t *Tensor) Floats() (data []float32) {
  538. if t.sync != nil {
  539. data = make([]float32, C.ggml_nelements(t.t))
  540. t.sync()
  541. C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
  542. }
  543. return
  544. }
  545. func (t *Tensor) DType() ml.DType {
  546. switch t.t._type {
  547. case C.GGML_TYPE_F32:
  548. return ml.DTypeF32
  549. case C.GGML_TYPE_F16:
  550. return ml.DTypeF16
  551. case C.GGML_TYPE_I32:
  552. return ml.DTypeI32
  553. default:
  554. return ml.DTypeOther
  555. }
  556. }
  557. func (t *Tensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  558. return &Tensor{
  559. b: t.b,
  560. t: C.ggml_add(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  561. }
  562. }
  563. func (t *Tensor) Stack(ctx ml.Context, dim int, s ...ml.Tensor) ml.Tensor {
  564. if len(s) > 0 {
  565. return t.Concat(ctx, s[0].Stack(ctx, dim, s[1:]...), dim)
  566. }
  567. return t
  568. }
  569. func (t *Tensor) Concat(ctx ml.Context, t2 ml.Tensor, dim int) ml.Tensor {
  570. return &Tensor{
  571. b: t.b,
  572. t: C.ggml_concat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.int(dim)),
  573. }
  574. }
  575. func (t *Tensor) Contiguous(ctx ml.Context) ml.Tensor {
  576. return &Tensor{
  577. b: t.b,
  578. t: C.ggml_cont(ctx.(*Context).ctx, t.t),
  579. }
  580. }
  581. func (t *Tensor) Mul(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  582. return &Tensor{
  583. b: t.b,
  584. t: C.ggml_mul(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  585. }
  586. }
  587. func (t *Tensor) Mulmat(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  588. return &Tensor{
  589. b: t.b,
  590. t: C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  591. }
  592. }
  593. func (t *Tensor) MulmatFullPrec(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  594. mul := C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t)
  595. C.ggml_mul_mat_set_prec(mul, C.GGML_PREC_F32)
  596. return &Tensor{
  597. b: t.b,
  598. t: mul,
  599. }
  600. }
  601. func (t *Tensor) LayerNorm(ctx ml.Context, w, b ml.Tensor, eps float32) ml.Tensor {
  602. tt := (&Tensor{b: t.b, t: C.ggml_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  603. if b != nil {
  604. tt = tt.Add(ctx, b)
  605. }
  606. return tt
  607. }
  608. func (t *Tensor) RMSNorm(ctx ml.Context, w ml.Tensor, eps float32) ml.Tensor {
  609. return (&Tensor{b: t.b, t: C.ggml_rms_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  610. }
  611. func (t *Tensor) Pad(ctx ml.Context, shape ...int) ml.Tensor {
  612. if len(shape) != 4 {
  613. panic("expected 4 dimensions")
  614. }
  615. return &Tensor{
  616. b: t.b,
  617. 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])),
  618. }
  619. }
  620. func (t *Tensor) Permute(ctx ml.Context, shape ...int) ml.Tensor {
  621. if len(shape) != 4 {
  622. panic("expected 4 dimensions")
  623. }
  624. return &Tensor{
  625. b: t.b,
  626. 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])),
  627. }
  628. }
  629. func (t *Tensor) Rows(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  630. return &Tensor{
  631. b: t.b,
  632. t: C.ggml_get_rows(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  633. }
  634. }
  635. func (t *Tensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  636. return &Tensor{
  637. b: t.b,
  638. t: C.ggml_cpy(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  639. }
  640. }
  641. func (t *Tensor) Reshape(ctx ml.Context, shape ...int) ml.Tensor {
  642. switch len(shape) {
  643. case 1:
  644. return &Tensor{
  645. b: t.b,
  646. t: C.ggml_reshape_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0])),
  647. }
  648. case 2:
  649. return &Tensor{
  650. b: t.b,
  651. t: C.ggml_reshape_2d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1])),
  652. }
  653. case 3:
  654. return &Tensor{
  655. b: t.b,
  656. 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])),
  657. }
  658. case 4:
  659. return &Tensor{
  660. b: t.b,
  661. 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])),
  662. }
  663. default:
  664. panic("unsupported number of dimensions")
  665. }
  666. }
  667. func (t *Tensor) Scale(ctx ml.Context, s float64) ml.Tensor {
  668. return &Tensor{
  669. b: t.b,
  670. t: C.ggml_scale(ctx.(*Context).ctx, t.t, (C.float)(s)),
  671. }
  672. }
  673. func (t *Tensor) Softmax(ctx ml.Context) ml.Tensor {
  674. return &Tensor{
  675. b: t.b,
  676. t: C.ggml_soft_max(ctx.(*Context).ctx, t.t),
  677. }
  678. }
  679. func (t *Tensor) Tanh(ctx ml.Context) ml.Tensor {
  680. return &Tensor{
  681. b: t.b,
  682. t: C.ggml_tanh_inplace(ctx.(*Context).ctx, t.t),
  683. }
  684. }
  685. func (t *Tensor) Unpad(ctx ml.Context, shape ...int) ml.Tensor {
  686. if len(shape) != 4 {
  687. panic("expected 4 dimensions")
  688. }
  689. return &Tensor{
  690. b: t.b,
  691. 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])),
  692. }
  693. }
  694. func (t *Tensor) View(ctx ml.Context, offset int, shape ...int) ml.Tensor {
  695. switch len(shape) {
  696. case 1:
  697. return &Tensor{
  698. b: t.b,
  699. t: C.ggml_view_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.size_t(offset)),
  700. }
  701. case 3:
  702. return &Tensor{
  703. b: t.b,
  704. t: C.ggml_view_2d(ctx.(*Context).ctx, t.t,
  705. C.int64_t(shape[0]), C.int64_t(shape[2]),
  706. C.size_t(shape[1]),
  707. C.size_t(offset)),
  708. }
  709. case 5:
  710. return &Tensor{
  711. b: t.b,
  712. t: C.ggml_view_3d(ctx.(*Context).ctx, t.t,
  713. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]),
  714. C.size_t(shape[1]), C.size_t(shape[3]),
  715. C.size_t(offset)),
  716. }
  717. case 7:
  718. return &Tensor{
  719. b: t.b,
  720. t: C.ggml_view_4d(ctx.(*Context).ctx, t.t,
  721. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]), C.int64_t(shape[6]),
  722. C.size_t(shape[1]), C.size_t(shape[3]), C.size_t(shape[5]),
  723. C.size_t(offset)),
  724. }
  725. default:
  726. panic("unsupported number of dimensions")
  727. }
  728. }
  729. const (
  730. ropeTypeNorm C.int = iota
  731. )
  732. func (t *Tensor) RoPE(ctx ml.Context, positionIDs, ropeFactors ml.Tensor, ropeDim uint32, ropeBase, ropeScale float32) ml.Tensor {
  733. if ropeFactors == nil {
  734. ropeFactors = &Tensor{b: t.b}
  735. }
  736. dequant := t.t
  737. if C.ggml_is_quantized(t.t._type) {
  738. dequant = C.ggml_cast(ctx.(*Context).ctx, t.t, C.GGML_TYPE_F32)
  739. }
  740. return &Tensor{
  741. b: t.b,
  742. t: C.ggml_rope_ext(
  743. ctx.(*Context).ctx, dequant, positionIDs.(*Tensor).t, ropeFactors.(*Tensor).t,
  744. C.int(ropeDim),
  745. 131072, // YaRN n_ctx_train
  746. ropeTypeNorm, // ROPE_TYPE_NORM
  747. C.float(ropeBase),
  748. C.float(ropeScale),
  749. 0., // YaRN ext_factor
  750. 1., // YaRN attn_factor
  751. 32., // YaRN beta_fast
  752. 1., // YaRN beta_slow
  753. ),
  754. }
  755. }
  756. func (t *Tensor) GELU(ctx ml.Context) ml.Tensor {
  757. return &Tensor{
  758. b: t.b,
  759. t: C.ggml_gelu_inplace(ctx.(*Context).ctx, t.t),
  760. }
  761. }
  762. func (t *Tensor) SILU(ctx ml.Context) ml.Tensor {
  763. return &Tensor{
  764. b: t.b,
  765. t: C.ggml_silu_inplace(ctx.(*Context).ctx, t.t),
  766. }
  767. }
  768. func (t *Tensor) Conv2D(ctx ml.Context, t2 ml.Tensor, s0, s1, p0, p1, d0, d1 int) ml.Tensor {
  769. return &Tensor{
  770. b: t.b,
  771. 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)),
  772. }
  773. }
  774. func (t *Tensor) ScaledDotProductAttention(ctx ml.Context, key, value, mask ml.Tensor, scale float64) ml.Tensor {
  775. var kqMask *C.struct_ggml_tensor
  776. if mask != nil {
  777. kqMask = mask.(*Tensor).t
  778. }
  779. query := t.Permute(ctx, 0, 2, 1, 3)
  780. key = key.Permute(ctx, 0, 2, 1, 3)
  781. if t.b.flashAttention {
  782. value = value.Permute(ctx, 0, 2, 1, 3)
  783. kqv := C.ggml_flash_attn_ext(ctx.(*Context).ctx, query.(*Tensor).t, key.(*Tensor).t, value.(*Tensor).t, kqMask, C.float(scale), 0, 0)
  784. C.ggml_flash_attn_ext_set_prec(kqv, C.GGML_PREC_F32)
  785. return &Tensor{b: t.b, t: kqv}
  786. } else {
  787. kq := key.MulmatFullPrec(ctx, query)
  788. kq = &Tensor{
  789. b: t.b,
  790. t: C.ggml_soft_max_ext(ctx.(*Context).ctx, kq.(*Tensor).t, kqMask, C.float(scale), 0),
  791. }
  792. kqv := value.Mulmat(ctx, kq)
  793. return kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  794. }
  795. }