ggml.go 22 KB

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