backend.go 11 KB

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