ggml.go 22 KB

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