ggml.go 23 KB

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