ggml.go 22 KB

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