backend.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. package ggml
  2. // #cgo CPPFLAGS: -DNDEBUG
  3. // #include <stdlib.h>
  4. // #include <stdint.h>
  5. // #include "ggml.h"
  6. // #include "ggml-backend.h"
  7. import "C"
  8. import (
  9. "bytes"
  10. "fmt"
  11. "io"
  12. "log/slog"
  13. "os"
  14. "unsafe"
  15. "golang.org/x/sync/errgroup"
  16. "github.com/ollama/ollama/format"
  17. "github.com/ollama/ollama/fs/ggml"
  18. "github.com/ollama/ollama/ml"
  19. )
  20. type Backend struct {
  21. c *C.struct_ggml_context
  22. b *C.struct_ggml_backend
  23. bb *C.struct_ggml_backend_buffer
  24. ggml.KV
  25. ggml.Tensors
  26. }
  27. func New(r *os.File) (ml.Backend, error) {
  28. f, _, err := ggml.Decode(r, -1)
  29. if err != nil {
  30. return nil, err
  31. }
  32. slog.Info(
  33. "",
  34. "architecture", f.KV().Architecture(),
  35. "file_type", f.KV().FileType(),
  36. "name", f.KV().String("general.name"),
  37. "description", f.KV().String("general.description"),
  38. "num_tensors", len(f.Tensors().Items),
  39. "num_key_values", len(f.KV()),
  40. )
  41. c := C.ggml_init(C.struct_ggml_init_params{
  42. mem_size: C.size_t(len(f.Tensors().Items)) * C.ggml_tensor_overhead(),
  43. mem_buffer: nil,
  44. no_alloc: true,
  45. })
  46. for _, t := range f.Tensors().Items {
  47. func() {
  48. cname := C.CString(t.Name)
  49. defer C.free(unsafe.Pointer(cname))
  50. tt := C.ggml_new_tensor(c, t.Kind, C.int(len(t.Shape)), (*C.int64_t)(unsafe.Pointer(&t.Shape[0])))
  51. C.ggml_set_name(tt, cname)
  52. }()
  53. }
  54. b := newBackend()
  55. bb := C.ggml_backend_alloc_ctx_tensors(c, b)
  56. var g errgroup.Group
  57. for _, t := range f.Tensors().Items {
  58. g.Go(func() error {
  59. var b bytes.Buffer
  60. n, err := io.Copy(&b, io.NewSectionReader(r, int64(f.Tensors().Offset+t.Offset), int64(t.Size())))
  61. if err != nil {
  62. return err
  63. }
  64. if n != int64(t.Size()) {
  65. return fmt.Errorf("expected %d bytes, got %d", t.Size(), n)
  66. }
  67. cname := C.CString(t.Name)
  68. defer C.free(unsafe.Pointer(cname))
  69. cbytes := C.CBytes(b.Bytes())
  70. defer C.free(cbytes)
  71. C.ggml_backend_tensor_set(C.ggml_get_tensor(c, cname), cbytes, 0, C.size_t(n))
  72. return nil
  73. })
  74. }
  75. if err := g.Wait(); err != nil {
  76. return nil, err
  77. }
  78. return &Backend{c, b, bb, f.KV(), f.Tensors()}, nil
  79. }
  80. func init() {
  81. ml.RegisterBackend("ggml", New)
  82. }
  83. func (b *Backend) Config() ml.Config {
  84. return b.KV
  85. }
  86. func (b *Backend) Get(name string) ml.Tensor {
  87. cname := C.CString(name)
  88. defer C.free(unsafe.Pointer(cname))
  89. if t := C.ggml_get_tensor(b.c, cname); t != nil {
  90. return &Tensor{t}
  91. }
  92. return nil
  93. }
  94. func (b *Backend) NewContext() ml.Context {
  95. n := max(8192, len(b.Tensors.Items)*5)
  96. bts := make([]byte, C.size_t(n)*C.ggml_tensor_overhead()+C.ggml_graph_overhead_custom(C.size_t(n), false))
  97. c := C.ggml_init(C.struct_ggml_init_params{
  98. mem_buffer: unsafe.Pointer(&bts[0]),
  99. mem_size: C.size_t(len(bts)),
  100. no_alloc: true,
  101. })
  102. return &Context{
  103. b: b.b,
  104. c: c,
  105. g: C.ggml_new_graph_custom(c, C.size_t(n), false),
  106. }
  107. }
  108. type Context struct {
  109. b *C.struct_ggml_backend
  110. c *C.struct_ggml_context
  111. g *C.struct_ggml_cgraph
  112. }
  113. func (c *Context) Forward(t ml.Tensor) {
  114. C.ggml_build_forward_expand(c.g, t.(*Tensor).t)
  115. }
  116. func (c *Context) Compute(t ml.Tensor) ml.Tensor {
  117. c.Forward(t)
  118. a := C.ggml_gallocr_new(C.ggml_backend_get_default_buffer_type(c.b))
  119. C.ggml_gallocr_alloc_graph(a, c.g)
  120. slog.Debug("compute graph memory", "require", format.HumanBytes2(uint64(C.ggml_gallocr_get_buffer_size(a, 0))))
  121. C.ggml_backend_graph_compute(c.b, c.g)
  122. return &Tensor{
  123. C.ggml_graph_node(c.g, C.ggml_graph_n_nodes(c.g)-1),
  124. }
  125. }
  126. func (c Context) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
  127. if len(shape) < 1 || len(shape) > 4 {
  128. panic("unsupported number of dimensions")
  129. }
  130. for _, dim := range shape {
  131. if dim < 1 {
  132. panic("invalid shape")
  133. }
  134. }
  135. var t *C.struct_ggml_tensor
  136. switch dtype {
  137. case ml.DTypeF32:
  138. t = C.ggml_new_tensor(c.c, C.GGML_TYPE_F32, C.int(len(shape)), (*C.int64_t)(unsafe.Pointer(&shape[0])))
  139. case ml.DTypeI32:
  140. t = C.ggml_new_tensor(c.c, C.GGML_TYPE_I32, C.int(len(shape)), (*C.int64_t)(unsafe.Pointer(&shape[0])))
  141. default:
  142. panic("unsupported dtype")
  143. }
  144. b := C.ggml_backend_alloc_buffer(c.b, C.ggml_nbytes(t))
  145. C.ggml_backend_tensor_alloc(b, t, C.ggml_backend_buffer_get_base(b))
  146. C.ggml_set_f32(t, 0.)
  147. return &Tensor{t}
  148. }
  149. func fromSlice[S ~[]E, E float32 | int32](ctx Context, s S, shape []int, dtype uint32) (ml.Tensor, error) {
  150. n := len(s)
  151. for _, v := range shape {
  152. n /= v
  153. }
  154. if n != 1 {
  155. return nil, fmt.Errorf("invalid shape %v for %d elements", shape, len(s))
  156. }
  157. t := C.ggml_new_tensor(ctx.c, dtype, C.int(len(shape)), (*C.int64_t)(unsafe.Pointer(&shape[0])))
  158. b := C.ggml_backend_alloc_buffer(ctx.b, C.ggml_nbytes(t))
  159. C.ggml_backend_tensor_alloc(b, t, C.ggml_backend_buffer_get_base(b))
  160. C.ggml_backend_tensor_set(t, unsafe.Pointer(&s[0]), 0, C.ggml_nbytes(t))
  161. return &Tensor{t}, nil
  162. }
  163. func (c Context) FromFloatSlice(s []float32, shape ...int) (ml.Tensor, error) {
  164. return fromSlice(c, s, shape, C.GGML_TYPE_F32)
  165. }
  166. func (c Context) FromIntSlice(s []int32, shape ...int) (ml.Tensor, error) {
  167. return fromSlice(c, s, shape, C.GGML_TYPE_I32)
  168. }
  169. func (c *Context) Close() error {
  170. C.ggml_free(c.c)
  171. return nil
  172. }
  173. type Tensor struct {
  174. t *C.struct_ggml_tensor
  175. }
  176. func (t *Tensor) LogValue() slog.Value {
  177. return slog.GroupValue(
  178. slog.String("name", C.GoString(C.ggml_get_name(t.t))),
  179. slog.String("type", C.GoString(C.ggml_type_name(t.t._type))),
  180. slog.Any("shape", t.Shape()),
  181. )
  182. }
  183. func (t *Tensor) Dim(n int) int64 {
  184. return int64(t.t.ne[n])
  185. }
  186. func (t *Tensor) Stride(n int) int64 {
  187. return int64(t.t.nb[n])
  188. }
  189. func (t *Tensor) Shape() []int64 {
  190. shape := make([]int64, C.ggml_n_dims(t.t))
  191. for i := range shape {
  192. shape[i] = t.Dim(i)
  193. }
  194. return shape
  195. }
  196. func (t *Tensor) Bytes() []byte {
  197. if bts := C.ggml_get_data(t.t); bts != nil {
  198. return C.GoBytes(bts, C.int(C.ggml_nbytes(t.t)))
  199. }
  200. return nil
  201. }
  202. func (t *Tensor) Floats() []float32 {
  203. if s := C.ggml_get_data_f32(t.t); s != nil {
  204. f32s := make([]float32, C.ggml_nelements(t.t))
  205. for i, v := range unsafe.Slice(s, C.ggml_nelements(t.t)) {
  206. f32s[i] = float32(v)
  207. }
  208. return f32s
  209. }
  210. return nil
  211. }
  212. func (t *Tensor) DType() ml.DType {
  213. switch t.t._type {
  214. case C.GGML_TYPE_F32:
  215. return ml.DTypeF32
  216. case C.GGML_TYPE_I32:
  217. return ml.DTypeI32
  218. default:
  219. return ml.DTypeOther
  220. }
  221. }
  222. func (t *Tensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  223. return &Tensor{
  224. C.ggml_add(ctx.(*Context).c, t.t, t2.(*Tensor).t),
  225. }
  226. }
  227. func (t *Tensor) Stack(ctx ml.Context, dim int, s ...ml.Tensor) ml.Tensor {
  228. if len(s) > 0 {
  229. return t.Concat(ctx, s[0].Stack(ctx, dim, s[1:]...), dim)
  230. }
  231. return t
  232. }
  233. func (t *Tensor) Concat(ctx ml.Context, t2 ml.Tensor, dim int) ml.Tensor {
  234. return &Tensor{
  235. C.ggml_concat(ctx.(*Context).c, t.t, t2.(*Tensor).t, C.int(dim)),
  236. }
  237. }
  238. func (t *Tensor) Contiguous(ctx ml.Context) ml.Tensor {
  239. return &Tensor{
  240. C.ggml_cont(ctx.(*Context).c, t.t),
  241. }
  242. }
  243. func (t *Tensor) Mul(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  244. return &Tensor{
  245. C.ggml_mul(ctx.(*Context).c, t.t, t2.(*Tensor).t),
  246. }
  247. }
  248. func (t *Tensor) Mulmat(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  249. return &Tensor{
  250. C.ggml_mul_mat(ctx.(*Context).c, t.t, t2.(*Tensor).t),
  251. }
  252. }
  253. func (t *Tensor) Norm(ctx ml.Context, eps float32) ml.Tensor {
  254. return &Tensor{
  255. C.ggml_norm(ctx.(*Context).c, t.t, (C.float)(eps)),
  256. }
  257. }
  258. func (t *Tensor) RMSNorm(ctx ml.Context, eps float32) ml.Tensor {
  259. return &Tensor{
  260. C.ggml_rms_norm(ctx.(*Context).c, t.t, C.float(eps)),
  261. }
  262. }
  263. func (t *Tensor) Pad(ctx ml.Context, shape ...int64) ml.Tensor {
  264. if len(shape) != 4 {
  265. panic("expected 4 dimensions")
  266. }
  267. return &Tensor{
  268. C.ggml_pad(ctx.(*Context).c, t.t, C.int(shape[0]), C.int(shape[1]), C.int(shape[2]), C.int(shape[3])),
  269. }
  270. }
  271. func (t *Tensor) Permute(ctx ml.Context, shape ...int) ml.Tensor {
  272. if len(shape) != 4 {
  273. panic("expected 4 dimensions")
  274. }
  275. return &Tensor{
  276. C.ggml_permute(ctx.(*Context).c, t.t, C.int(shape[0]), C.int(shape[1]), C.int(shape[2]), C.int(shape[3])),
  277. }
  278. }
  279. func (t *Tensor) Rows(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  280. return &Tensor{
  281. C.ggml_get_rows(ctx.(*Context).c, t.t, t2.(*Tensor).t),
  282. }
  283. }
  284. func (t *Tensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
  285. return &Tensor{
  286. C.ggml_cpy(ctx.(*Context).c, t.t, t2.(*Tensor).t),
  287. }
  288. }
  289. func (t *Tensor) Reshape(ctx ml.Context, shape ...int64) ml.Tensor {
  290. switch len(shape) {
  291. case 1:
  292. return &Tensor{
  293. C.ggml_reshape_1d(ctx.(*Context).c, t.t, C.int64_t(shape[0])),
  294. }
  295. case 2:
  296. return &Tensor{
  297. C.ggml_reshape_2d(ctx.(*Context).c, t.t, C.int64_t(shape[0]), C.int64_t(shape[1])),
  298. }
  299. case 3:
  300. return &Tensor{
  301. C.ggml_reshape_3d(ctx.(*Context).c, t.t, C.int64_t(shape[0]), C.int64_t(shape[1]), C.int64_t(shape[2])),
  302. }
  303. case 4:
  304. return &Tensor{
  305. C.ggml_reshape_4d(ctx.(*Context).c, t.t, C.int64_t(shape[0]), C.int64_t(shape[1]), C.int64_t(shape[2]), C.int64_t(shape[3])),
  306. }
  307. default:
  308. panic("unsupported number of dimensions")
  309. }
  310. }
  311. func (t *Tensor) Scale(ctx ml.Context, s float64) ml.Tensor {
  312. return &Tensor{
  313. C.ggml_scale(ctx.(*Context).c, t.t, (C.float)(s)),
  314. }
  315. }
  316. func (t *Tensor) Softmax(ctx ml.Context) ml.Tensor {
  317. return &Tensor{
  318. C.ggml_soft_max(ctx.(*Context).c, t.t),
  319. }
  320. }
  321. func (t *Tensor) Tanh(ctx ml.Context) ml.Tensor {
  322. return &Tensor{
  323. C.ggml_tanh_inplace(ctx.(*Context).c, t.t),
  324. }
  325. }
  326. func (t *Tensor) Unpad(ctx ml.Context, shape ...int64) ml.Tensor {
  327. if len(shape) != 4 {
  328. panic("expected 4 dimensions")
  329. }
  330. return &Tensor{
  331. C.ggml_unpad(ctx.(*Context).c, t.t, C.int(shape[0]), C.int(shape[1]), C.int(shape[2]), C.int(shape[3])),
  332. }
  333. }
  334. func (t *Tensor) View(ctx ml.Context, offset int, shape ...int) ml.Tensor {
  335. switch len(shape) {
  336. case 1:
  337. return &Tensor{
  338. C.ggml_view_1d(ctx.(*Context).c, t.t, C.int64_t(shape[0]), C.size_t(offset)),
  339. }
  340. case 3:
  341. return &Tensor{
  342. C.ggml_view_2d(ctx.(*Context).c, t.t,
  343. C.int64_t(shape[0]), C.int64_t(shape[2]),
  344. C.size_t(shape[1]),
  345. C.size_t(offset)),
  346. }
  347. case 5:
  348. return &Tensor{
  349. C.ggml_view_3d(ctx.(*Context).c, t.t,
  350. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]),
  351. C.size_t(shape[1]), C.size_t(shape[3]),
  352. C.size_t(offset)),
  353. }
  354. case 7:
  355. return &Tensor{
  356. C.ggml_view_4d(ctx.(*Context).c, t.t,
  357. C.int64_t(shape[0]), C.int64_t(shape[2]), C.int64_t(shape[4]), C.int64_t(shape[6]),
  358. C.size_t(shape[1]), C.size_t(shape[3]), C.size_t(shape[5]),
  359. C.size_t(offset)),
  360. }
  361. default:
  362. panic("unsupported number of dimensions")
  363. }
  364. }
  365. const (
  366. ropeTypeNorm C.int = iota
  367. )
  368. func (t *Tensor) Rope(ctx ml.Context, positionIDs, ropeFactors ml.Tensor, ropeDim uint32, ropeBase, ropeScale float32) ml.Tensor {
  369. return &Tensor{
  370. C.ggml_rope_ext(
  371. ctx.(*Context).c, t.t, positionIDs.(*Tensor).t, ropeFactors.(*Tensor).t,
  372. C.int(ropeDim),
  373. 131072, // YaRN n_ctx_train
  374. ropeTypeNorm, // ROPE_TYPE_NORM
  375. C.float(ropeBase),
  376. C.float(ropeScale),
  377. 0., // YaRN ext_factor
  378. 1., // YaRN attn_factor
  379. 32., // YaRN beta_fast
  380. 1., // YaRN beta_slow
  381. ),
  382. }
  383. }
  384. func (t *Tensor) GELU(ctx ml.Context) ml.Tensor {
  385. return &Tensor{
  386. C.ggml_gelu_inplace(ctx.(*Context).c, t.t),
  387. }
  388. }
  389. func (t *Tensor) SILU(ctx ml.Context) ml.Tensor {
  390. return &Tensor{
  391. C.ggml_silu_inplace(ctx.(*Context).c, t.t),
  392. }
  393. }
  394. func (t *Tensor) Conv2D(ctx ml.Context, t2 ml.Tensor, s0, s1, p0, p1, d0, d1 int) ml.Tensor {
  395. return &Tensor{
  396. C.ggml_conv_2d(ctx.(*Context).c, t.t, t2.(*Tensor).t, C.int(s0), C.int(s1), C.int(p0), C.int(p1), C.int(d0), C.int(d1)),
  397. }
  398. }