ggml.go 25 KB

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