ggml.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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 (c Context) newTensor(dtype ml.DType, shape []int) ml.Tensor {
  437. if c.buft == nil {
  438. panic("set Input, Output, or Layer before creating tensors")
  439. }
  440. var cdtype uint32
  441. switch dtype {
  442. case ml.DTypeF32:
  443. cdtype = C.GGML_TYPE_F32
  444. case ml.DTypeF16:
  445. cdtype = C.GGML_TYPE_F16
  446. case ml.DTypeI32:
  447. cdtype = C.GGML_TYPE_I32
  448. default:
  449. panic("unsupported dtype")
  450. }
  451. if len(shape) < 1 || shape[0] == 0 {
  452. var shape C.int64_t = 0
  453. return &Tensor{b: c.b, t: C.ggml_new_tensor(c.ctx, cdtype, 1, &shape)}
  454. } else if len(shape) > 4 {
  455. panic("unsupported number of dimensions")
  456. }
  457. for _, dim := range shape {
  458. if dim < 1 {
  459. panic("invalid shape")
  460. }
  461. }
  462. t := C.ggml_new_tensor(c.ctx, cdtype, C.int(len(shape)), shapeToGGML(shape))
  463. b := C.ggml_backend_buft_alloc_buffer(c.buft, C.ggml_nbytes(t))
  464. C.ggml_backend_tensor_alloc(b, t, C.ggml_backend_buffer_get_base(b))
  465. return &Tensor{b: c.b, t: t}
  466. }
  467. func (c Context) Empty(dtype ml.DType, shape ...int) ml.Tensor {
  468. return c.newTensor(dtype, shape)
  469. }
  470. func (c Context) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
  471. t := c.newTensor(dtype, shape)
  472. C.ggml_set_zero(t.(*Tensor).t)
  473. return t
  474. }
  475. func checkShape[S ~[]E, E any](s S, shape ...int) error {
  476. n := len(s)
  477. if n == 0 {
  478. return nil
  479. }
  480. for _, v := range shape {
  481. n /= v
  482. }
  483. if n != 1 {
  484. return fmt.Errorf("invalid shape: %v", shape)
  485. }
  486. return nil
  487. }
  488. func (c Context) FromFloatSlice(s []float32, shape ...int) (ml.Tensor, error) {
  489. if err := checkShape(s, shape...); err != nil {
  490. return nil, err
  491. }
  492. t := c.newTensor(ml.DTypeF32, shape)
  493. if len(s) > 0 {
  494. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  495. }
  496. return t, nil
  497. }
  498. func (c Context) FromIntSlice(s []int32, shape ...int) (ml.Tensor, error) {
  499. if err := checkShape(s, shape...); err != nil {
  500. return nil, err
  501. }
  502. t := c.newTensor(ml.DTypeI32, shape)
  503. if len(s) > 0 {
  504. C.ggml_backend_tensor_set(t.(*Tensor).t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t.(*Tensor).t))
  505. }
  506. return t, nil
  507. }
  508. func (c *Context) Close() {
  509. if c != nil {
  510. C.ggml_free(c.ctx)
  511. }
  512. }
  513. type Tensor struct {
  514. b *Backend
  515. t *C.struct_ggml_tensor
  516. sync func()
  517. }
  518. func (t *Tensor) LogValue() slog.Value {
  519. return slog.GroupValue(
  520. slog.String("name", C.GoString(C.ggml_get_name(t.t))),
  521. slog.String("type", C.GoString(C.ggml_type_name(t.t._type))),
  522. slog.Any("shape", t.Shape()),
  523. )
  524. }
  525. func (t *Tensor) Dim(n int) int {
  526. return int(t.t.ne[n])
  527. }
  528. func (t *Tensor) Stride(n int) int {
  529. return int(t.t.nb[n])
  530. }
  531. func (t *Tensor) Shape() []int {
  532. shape := make([]int, C.ggml_n_dims(t.t))
  533. for i := range shape {
  534. shape[i] = t.Dim(i)
  535. }
  536. return shape
  537. }
  538. func (t *Tensor) Bytes() (data []byte) {
  539. if t.sync != nil {
  540. data = make([]byte, C.ggml_nbytes(t.t))
  541. t.sync()
  542. C.ggml_backend_tensor_get(t.t, unsafe.Pointer(&data[0]), 0, C.ggml_nbytes(t.t))
  543. }
  544. return
  545. }
  546. func (t *Tensor) Floats() (data []float32) {
  547. if t.sync != nil {
  548. data = make([]float32, C.ggml_nelements(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) DType() ml.DType {
  555. switch t.t._type {
  556. case C.GGML_TYPE_F32:
  557. return ml.DTypeF32
  558. case C.GGML_TYPE_F16:
  559. return ml.DTypeF16
  560. case C.GGML_TYPE_I32:
  561. return ml.DTypeI32
  562. default:
  563. return ml.DTypeOther
  564. }
  565. }
  566. func (t *Tensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  567. return &Tensor{
  568. b: t.b,
  569. t: C.ggml_add(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  570. }
  571. }
  572. func (t *Tensor) Stack(ctx ml.Context, dim int, s ...ml.Tensor) ml.Tensor {
  573. if len(s) > 0 {
  574. return t.Concat(ctx, s[0].Stack(ctx, dim, s[1:]...), dim)
  575. }
  576. return t
  577. }
  578. func (t *Tensor) Concat(ctx ml.Context, t2 ml.Tensor, dim int) ml.Tensor {
  579. return &Tensor{
  580. b: t.b,
  581. t: C.ggml_concat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t, C.int(dim)),
  582. }
  583. }
  584. func (t *Tensor) Contiguous(ctx ml.Context) ml.Tensor {
  585. return &Tensor{
  586. b: t.b,
  587. t: C.ggml_cont(ctx.(*Context).ctx, t.t),
  588. }
  589. }
  590. func (t *Tensor) Mul(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  591. return &Tensor{
  592. b: t.b,
  593. t: C.ggml_mul(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  594. }
  595. }
  596. func (t *Tensor) Mulmat(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  597. return &Tensor{
  598. b: t.b,
  599. t: C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  600. }
  601. }
  602. func (t *Tensor) MulmatFullPrec(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  603. mul := C.ggml_mul_mat(ctx.(*Context).ctx, t.t, t2.(*Tensor).t)
  604. C.ggml_mul_mat_set_prec(mul, C.GGML_PREC_F32)
  605. return &Tensor{
  606. b: t.b,
  607. t: mul,
  608. }
  609. }
  610. func (t *Tensor) LayerNorm(ctx ml.Context, w, b ml.Tensor, eps float32) ml.Tensor {
  611. tt := (&Tensor{b: t.b, t: C.ggml_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  612. if b != nil {
  613. tt = tt.Add(ctx, b)
  614. }
  615. return tt
  616. }
  617. func (t *Tensor) RMSNorm(ctx ml.Context, w ml.Tensor, eps float32) ml.Tensor {
  618. return (&Tensor{b: t.b, t: C.ggml_rms_norm(ctx.(*Context).ctx, t.t, C.float(eps))}).Mul(ctx, w)
  619. }
  620. func (t *Tensor) Pad(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_pad(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) Permute(ctx ml.Context, shape ...int) ml.Tensor {
  630. if len(shape) != 4 {
  631. panic("expected 4 dimensions")
  632. }
  633. return &Tensor{
  634. b: t.b,
  635. 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])),
  636. }
  637. }
  638. func (t *Tensor) Rows(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  639. return &Tensor{
  640. b: t.b,
  641. t: C.ggml_get_rows(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  642. }
  643. }
  644. func (t *Tensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  645. return &Tensor{
  646. b: t.b,
  647. t: C.ggml_cpy(ctx.(*Context).ctx, t.t, t2.(*Tensor).t),
  648. }
  649. }
  650. func (t *Tensor) Reshape(ctx ml.Context, shape ...int) ml.Tensor {
  651. switch len(shape) {
  652. case 1:
  653. return &Tensor{
  654. b: t.b,
  655. t: C.ggml_reshape_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0])),
  656. }
  657. case 2:
  658. return &Tensor{
  659. b: t.b,
  660. t: C.ggml_reshape_2d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.int64_t(shape[1])),
  661. }
  662. case 3:
  663. return &Tensor{
  664. b: t.b,
  665. 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])),
  666. }
  667. case 4:
  668. return &Tensor{
  669. b: t.b,
  670. 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])),
  671. }
  672. default:
  673. panic("unsupported number of dimensions")
  674. }
  675. }
  676. func (t *Tensor) Scale(ctx ml.Context, s float64) ml.Tensor {
  677. return &Tensor{
  678. b: t.b,
  679. t: C.ggml_scale(ctx.(*Context).ctx, t.t, (C.float)(s)),
  680. }
  681. }
  682. func (t *Tensor) Softmax(ctx ml.Context) ml.Tensor {
  683. return &Tensor{
  684. b: t.b,
  685. t: C.ggml_soft_max(ctx.(*Context).ctx, t.t),
  686. }
  687. }
  688. func (t *Tensor) Tanh(ctx ml.Context) ml.Tensor {
  689. return &Tensor{
  690. b: t.b,
  691. t: C.ggml_tanh_inplace(ctx.(*Context).ctx, t.t),
  692. }
  693. }
  694. func (t *Tensor) Unpad(ctx ml.Context, shape ...int) ml.Tensor {
  695. if len(shape) != 4 {
  696. panic("expected 4 dimensions")
  697. }
  698. return &Tensor{
  699. b: t.b,
  700. 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])),
  701. }
  702. }
  703. func (t *Tensor) View(ctx ml.Context, offset int, shape ...int) ml.Tensor {
  704. switch len(shape) {
  705. case 1:
  706. return &Tensor{
  707. b: t.b,
  708. t: C.ggml_view_1d(ctx.(*Context).ctx, t.t, C.int64_t(shape[0]), C.size_t(offset)),
  709. }
  710. case 3:
  711. return &Tensor{
  712. b: t.b,
  713. t: C.ggml_view_2d(ctx.(*Context).ctx, t.t,
  714. C.int64_t(shape[0]), C.int64_t(shape[2]),
  715. C.size_t(shape[1]),
  716. C.size_t(offset)),
  717. }
  718. case 5:
  719. return &Tensor{
  720. b: t.b,
  721. t: C.ggml_view_3d(ctx.(*Context).ctx, t.t,
  722. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]),
  723. C.size_t(shape[1]), C.size_t(shape[3]),
  724. C.size_t(offset)),
  725. }
  726. case 7:
  727. return &Tensor{
  728. b: t.b,
  729. t: C.ggml_view_4d(ctx.(*Context).ctx, t.t,
  730. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]), C.int64_t(shape[6]),
  731. C.size_t(shape[1]), C.size_t(shape[3]), C.size_t(shape[5]),
  732. C.size_t(offset)),
  733. }
  734. default:
  735. panic("unsupported number of dimensions")
  736. }
  737. }
  738. const (
  739. ropeTypeNorm C.int = iota
  740. )
  741. func (t *Tensor) RoPE(ctx ml.Context, positionIDs, ropeFactors ml.Tensor, ropeDim uint32, ropeBase, ropeScale float32) ml.Tensor {
  742. if ropeFactors == nil {
  743. ropeFactors = &Tensor{b: t.b}
  744. }
  745. dequant := t.t
  746. if C.ggml_is_quantized(t.t._type) {
  747. dequant = C.ggml_cast(ctx.(*Context).ctx, t.t, C.GGML_TYPE_F32)
  748. }
  749. return &Tensor{
  750. b: t.b,
  751. t: C.ggml_rope_ext(
  752. ctx.(*Context).ctx, dequant, positionIDs.(*Tensor).t, ropeFactors.(*Tensor).t,
  753. C.int(ropeDim),
  754. 131072, // YaRN n_ctx_train
  755. ropeTypeNorm, // ROPE_TYPE_NORM
  756. C.float(ropeBase),
  757. C.float(ropeScale),
  758. 0., // YaRN ext_factor
  759. 1., // YaRN attn_factor
  760. 32., // YaRN beta_fast
  761. 1., // YaRN beta_slow
  762. ),
  763. }
  764. }
  765. func (t *Tensor) GELU(ctx ml.Context) ml.Tensor {
  766. return &Tensor{
  767. b: t.b,
  768. t: C.ggml_gelu_inplace(ctx.(*Context).ctx, t.t),
  769. }
  770. }
  771. func (t *Tensor) SILU(ctx ml.Context) ml.Tensor {
  772. return &Tensor{
  773. b: t.b,
  774. t: C.ggml_silu_inplace(ctx.(*Context).ctx, t.t),
  775. }
  776. }
  777. func (t *Tensor) Conv2D(ctx ml.Context, t2 ml.Tensor, s0, s1, p0, p1, d0, d1 int) ml.Tensor {
  778. return &Tensor{
  779. b: t.b,
  780. 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)),
  781. }
  782. }
  783. func (t *Tensor) ScaledDotProductAttention(ctx ml.Context, key, value, mask ml.Tensor, scale float64) ml.Tensor {
  784. var kqMask *C.struct_ggml_tensor
  785. if mask != nil {
  786. kqMask = mask.(*Tensor).t
  787. }
  788. query := t.Permute(ctx, 0, 2, 1, 3)
  789. key = key.Permute(ctx, 0, 2, 1, 3)
  790. if t.b.flashAttention {
  791. value = value.Permute(ctx, 0, 2, 1, 3)
  792. kqv := C.ggml_flash_attn_ext(ctx.(*Context).ctx, query.(*Tensor).t, key.(*Tensor).t, value.(*Tensor).t, kqMask, C.float(scale), 0, 0)
  793. C.ggml_flash_attn_ext_set_prec(kqv, C.GGML_PREC_F32)
  794. return &Tensor{b: t.b, t: kqv}
  795. } else {
  796. kq := key.MulmatFullPrec(ctx, query)
  797. kq = &Tensor{
  798. b: t.b,
  799. t: C.ggml_soft_max_ext(ctx.(*Context).ctx, kq.(*Tensor).t, kqMask, C.float(scale), 0),
  800. }
  801. kqv := value.Mulmat(ctx, kq)
  802. return kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  803. }
  804. }