ggml.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. package llm
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "strings"
  8. "github.com/ollama/ollama/util/bufioutil"
  9. )
  10. type GGML struct {
  11. container
  12. model
  13. }
  14. type model interface {
  15. KV() KV
  16. Tensors() Tensors
  17. }
  18. type KV map[string]any
  19. func (kv KV) u64(key string) uint64 {
  20. switch v := kv[key].(type) {
  21. case uint64:
  22. return v
  23. case uint32:
  24. return uint64(v)
  25. case float64:
  26. return uint64(v)
  27. default:
  28. return 0
  29. }
  30. }
  31. func (kv KV) Architecture() string {
  32. if s, ok := kv["general.architecture"].(string); ok {
  33. return s
  34. }
  35. return "unknown"
  36. }
  37. func (kv KV) ParameterCount() uint64 {
  38. return kv.u64("general.parameter_count")
  39. }
  40. func (kv KV) FileType() fileType {
  41. if u64 := kv.u64("general.file_type"); u64 > 0 {
  42. return fileType(uint32(u64))
  43. }
  44. return fileTypeUnknown
  45. }
  46. func (kv KV) BlockCount() uint64 {
  47. return kv.u64(fmt.Sprintf("%s.block_count", kv.Architecture()))
  48. }
  49. func (kv KV) HeadCount() uint64 {
  50. return kv.u64(fmt.Sprintf("%s.attention.head_count", kv.Architecture()))
  51. }
  52. func (kv KV) HeadCountKV() uint64 {
  53. if headCountKV := kv.u64(fmt.Sprintf("%s.attention.head_count_kv", kv.Architecture())); headCountKV > 0 {
  54. return headCountKV
  55. }
  56. return 1
  57. }
  58. func (kv KV) EmbeddingHeadCount() uint64 {
  59. if heads := kv.HeadCount(); heads > 0 {
  60. return kv.EmbeddingLength() / kv.HeadCount()
  61. }
  62. return 0
  63. }
  64. func (kv KV) EmbeddingHeadCountK() uint64 {
  65. if k := kv.u64(fmt.Sprintf("%s.attention.key_length", kv.Architecture())); k > 0 {
  66. return k
  67. }
  68. return kv.EmbeddingHeadCount()
  69. }
  70. func (kv KV) EmbeddingHeadCountV() uint64 {
  71. if v := kv.u64(fmt.Sprintf("%s.attention.value_length", kv.Architecture())); v > 0 {
  72. return v
  73. }
  74. return kv.EmbeddingHeadCount()
  75. }
  76. func (kv KV) GQA() uint64 {
  77. return kv.HeadCount() / kv.HeadCountKV()
  78. }
  79. func (kv KV) EmbeddingLength() uint64 {
  80. return kv.u64(fmt.Sprintf("%s.embedding_length", kv.Architecture()))
  81. }
  82. func (kv KV) ContextLength() uint64 {
  83. return kv.u64(fmt.Sprintf("%s.context_length", kv.Architecture()))
  84. }
  85. func (kv KV) ChatTemplate() string {
  86. s, _ := kv["tokenizer.chat_template"].(string)
  87. return s
  88. }
  89. type Tensors []*Tensor
  90. func (ts Tensors) Layers() map[string]Layer {
  91. layers := make(map[string]Layer)
  92. for _, t := range ts {
  93. parts := strings.Split(t.Name, ".")
  94. if parts[0] == "blk" {
  95. // join first and second part, e.g. blk.%d
  96. parts = append([]string{fmt.Sprintf("%s.%s", parts[0], parts[1])}, parts[2:]...)
  97. }
  98. if _, ok := layers[parts[0]]; !ok {
  99. layers[parts[0]] = make(Layer)
  100. }
  101. layers[parts[0]][strings.Join(parts[1:], ".")] = t
  102. }
  103. return layers
  104. }
  105. type Layer map[string]*Tensor
  106. func (l Layer) size() (size uint64) {
  107. for _, t := range l {
  108. size += t.Size()
  109. }
  110. return size
  111. }
  112. type Tensor struct {
  113. Name string `json:"name"`
  114. Kind uint32 `json:"kind"`
  115. Offset uint64 `json:"-"`
  116. // Shape is the number of elements in each dimension
  117. Shape []uint64 `json:"shape"`
  118. io.WriterTo `json:"-"`
  119. }
  120. func (t Tensor) blockSize() uint64 {
  121. switch t.Kind {
  122. case 0, 1, 24, 25, 26, 27, 28, 30: // F32, F16, I8, I16, I32, I64, F64, BF16
  123. return 1
  124. case 2, 3, 4, 5, 6, 7, 8, 9, 20: // Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, IQ4_NL
  125. return 32
  126. default: // All others
  127. return 256
  128. }
  129. }
  130. func (t Tensor) typeSize() uint64 {
  131. blockSize := t.blockSize()
  132. switch t.Kind {
  133. case 0: // FP32
  134. return 4
  135. case 1: // FP16
  136. return 2
  137. case 2: // Q4_0
  138. return 2 + blockSize/2
  139. case 3: // Q4_1
  140. return 2 + 2 + blockSize/2
  141. case 6: // Q5_0
  142. return 2 + 4 + blockSize/2
  143. case 7: // Q5_1
  144. return 2 + 2 + 4 + blockSize/2
  145. case 8: // Q8_0
  146. return 2 + blockSize
  147. case 9: // Q8_1
  148. return 4 + 4 + blockSize
  149. case 10: // Q2_K
  150. return blockSize/16 + blockSize/4 + 2 + 2
  151. case 11: // Q3_K
  152. return blockSize/8 + blockSize/4 + 12 + 2
  153. case 12: // Q4_K
  154. return 2 + 2 + 12 + blockSize/2
  155. case 13: // Q5_K
  156. return 2 + 2 + 12 + blockSize/8 + blockSize/2
  157. case 14: // Q6_K
  158. return blockSize/2 + blockSize/4 + blockSize/16 + 2
  159. case 15: // Q8_K
  160. return 2 + blockSize + 2*blockSize/16
  161. case 16: // IQ2_XXS
  162. return 2 + 2*blockSize/8
  163. case 17: // IQ2_XS
  164. return 2 + 2*blockSize/8 + blockSize/32
  165. case 18: // IQ3_XXS
  166. return 2 + blockSize/4 + blockSize/8
  167. case 19: // IQ1_S
  168. return 2 + blockSize/8 + blockSize/16
  169. case 20: // IQ4_NL
  170. return 2 + blockSize/2
  171. case 21: // IQ3_S
  172. return 2 + blockSize/4 + blockSize/8 + blockSize/32 + 4
  173. case 22: // IQ2_S
  174. return 2 + blockSize/4 + blockSize/16
  175. case 23: // IQ4_XS
  176. return 2 + 2 + blockSize/2 + blockSize/64
  177. case 24: // I8
  178. return 1
  179. case 25: // I16
  180. return 2
  181. case 26: // I32
  182. return 4
  183. case 27: // I64
  184. return 8
  185. case 28: // F64
  186. return 8
  187. case 29: // IQ1_M
  188. return blockSize/8 + blockSize/16 + blockSize/32
  189. default:
  190. return 0
  191. }
  192. }
  193. func (t Tensor) parameters() uint64 {
  194. var count uint64 = 1
  195. for _, n := range t.Shape {
  196. count *= n
  197. }
  198. return count
  199. }
  200. func (t Tensor) Size() uint64 {
  201. return t.parameters() * t.typeSize() / t.blockSize()
  202. }
  203. type container interface {
  204. Name() string
  205. Decode(io.ReadSeeker) (model, error)
  206. }
  207. const (
  208. // Magic constant for `ggml` files (unversioned).
  209. FILE_MAGIC_GGML = 0x67676d6c
  210. // Magic constant for `ggml` files (versioned, ggmf).
  211. FILE_MAGIC_GGMF = 0x67676d66
  212. // Magic constant for `ggml` files (versioned, ggjt).
  213. FILE_MAGIC_GGJT = 0x67676a74
  214. // Magic constant for `ggla` files (LoRA adapter).
  215. FILE_MAGIC_GGLA = 0x67676C61
  216. // Magic constant for `gguf` files (versioned, gguf)
  217. FILE_MAGIC_GGUF_LE = 0x46554747
  218. FILE_MAGIC_GGUF_BE = 0x47475546
  219. )
  220. var ErrUnsupportedFormat = errors.New("unsupported model format")
  221. func DetectGGMLType(b []byte) string {
  222. switch binary.LittleEndian.Uint32(b[:4]) {
  223. case FILE_MAGIC_GGML:
  224. return "ggml"
  225. case FILE_MAGIC_GGMF:
  226. return "ggmf"
  227. case FILE_MAGIC_GGJT:
  228. return "ggjt"
  229. case FILE_MAGIC_GGLA:
  230. return "ggla"
  231. case FILE_MAGIC_GGUF_LE, FILE_MAGIC_GGUF_BE:
  232. return "gguf"
  233. default:
  234. return ""
  235. }
  236. }
  237. // DecodeGGML decodes a GGML model from the given reader.
  238. //
  239. // It collects array values for arrays with a size less than or equal to
  240. // maxArraySize. If maxArraySize is 0, the default value of 1024 is used. If
  241. // the maxArraySize is negative, all arrays are collected.
  242. func DecodeGGML(rs io.ReadSeeker, maxArraySize int) (*GGML, int64, error) {
  243. if maxArraySize == 0 {
  244. maxArraySize = 1024
  245. }
  246. rs = bufioutil.NewBufferedSeeker(rs, 32<<10)
  247. var magic uint32
  248. if err := binary.Read(rs, binary.LittleEndian, &magic); err != nil {
  249. return nil, 0, err
  250. }
  251. var c container
  252. switch magic {
  253. case FILE_MAGIC_GGML, FILE_MAGIC_GGMF, FILE_MAGIC_GGJT:
  254. return nil, 0, ErrUnsupportedFormat
  255. case FILE_MAGIC_GGLA:
  256. c = &containerGGLA{}
  257. case FILE_MAGIC_GGUF_LE:
  258. c = &containerGGUF{ByteOrder: binary.LittleEndian, maxArraySize: maxArraySize}
  259. case FILE_MAGIC_GGUF_BE:
  260. c = &containerGGUF{ByteOrder: binary.BigEndian, maxArraySize: maxArraySize}
  261. default:
  262. return nil, 0, errors.New("invalid file magic")
  263. }
  264. model, err := c.Decode(rs)
  265. if err != nil {
  266. return nil, 0, err
  267. }
  268. offset, err := rs.Seek(0, io.SeekCurrent)
  269. if err != nil {
  270. return nil, 0, err
  271. }
  272. // final model type
  273. return &GGML{
  274. container: c,
  275. model: model,
  276. }, offset, nil
  277. }
  278. func (llm GGML) GraphSize(context, batch uint64) (partialOffload, fullOffload uint64) {
  279. embedding := llm.KV().EmbeddingLength()
  280. heads := llm.KV().HeadCount()
  281. headsKV := llm.KV().HeadCountKV()
  282. vocab := uint64(llm.KV()["tokenizer.ggml.tokens"].(*array).size)
  283. embeddingHeads := llm.KV().EmbeddingHeadCount()
  284. embeddingHeadsK := llm.KV().EmbeddingHeadCountK()
  285. layers := llm.Tensors().Layers()
  286. switch llm.KV().Architecture() {
  287. case "llama":
  288. fullOffload = 4 * batch * (1 + 4*embedding + context*(1+heads))
  289. partialOffload = 4 * batch * embedding
  290. partialOffload += max(
  291. // 4*batch*(4+6*embedding+context*(2*heads)+llm.KV().GQA()),
  292. 4*batch*(1+embedding+max(context, embedding))+embedding*embedding*9/16+4*context*(batch*heads+embeddingHeads*headsKV),
  293. 4*batch*(embedding+vocab)+embedding*vocab*105/128,
  294. )
  295. if ffnGateExpsWeight, ok := layers["blk.0"]["ffn_gate_exps.weight"]; ok {
  296. // mixtral 8x22b
  297. ff := uint64(llm.KV()["llama.feed_forward_length"].(uint32))
  298. partialOffload = max(
  299. 3*ffnGateExpsWeight.Size()+4*batch*(2*ff+headsKV+embedding+context+embeddingHeads*headsKV),
  300. 4*(context*batch*heads+context*embeddingHeads*headsKV+batch*1024+embeddingHeads*headsKV*batch),
  301. )
  302. } else if ffnGateWeight, ok := layers["blk.0"]["ffn_gate.0.weight"]; ok {
  303. // mixtral 8x7b
  304. ffnGateWeight1 := ffnGateWeight.Shape[1]
  305. fullOffload = 4 * batch * (2 + 3*embedding + context*(1+heads) + 2*headsKV + ffnGateWeight1)
  306. partialOffload = max(
  307. 4*batch*(3+embeddingHeads*headsKV+embedding+context*(1+heads)+ffnGateWeight1)+(embedding*embedding+3*embedding*headsKV*ffnGateWeight1)*9/16,
  308. 4*batch*(1+2*embedding+context*(1+heads))+embedding*(6*context*headsKV/heads+embedding*9/16),
  309. )
  310. }
  311. case "gemma", "gemma2":
  312. fullOffload = max(
  313. 4*batch*(embedding+vocab),
  314. 4*batch*(2+context+context*heads+2*embedding+2*embeddingHeadsK*heads),
  315. )
  316. partialOffload = max(
  317. 4*embedding*batch+embedding*vocab*105/128+4*vocab*batch,
  318. 4*batch*(2*embedding+1+2*embeddingHeadsK*heads+context+context*heads)+
  319. 4*embeddingHeadsK*context*8+
  320. embedding*embeddingHeadsK*heads*9/16,
  321. )
  322. case "command-r":
  323. fullOffload = max(
  324. 4*batch*(embedding+vocab),
  325. 4*batch*(2+4*embedding+context*(1+heads)),
  326. )
  327. partialOffload = max(
  328. 4*batch*(embedding+vocab)+embedding*vocab*105/128,
  329. 4*batch*(1+2*embedding+context*(1+heads))+4*embedding*context+embedding*embedding*9/16,
  330. )
  331. case "qwen2":
  332. fullOffload = max(
  333. 4*batch*(embedding+vocab),
  334. 4*batch*(1+2*embedding+context+context*heads),
  335. )
  336. partialOffload = max(
  337. 4*batch*(embedding+vocab)+embedding*vocab*105/128,
  338. 4*(batch*(1+2*embedding+context*(1+heads))+embedding*(1+context)),
  339. )
  340. case "phi2":
  341. fullOffload = max(
  342. 4*batch*(embedding+vocab),
  343. 4*batch*(1+4*embedding+context+context*heads),
  344. )
  345. partialOffload = max(
  346. 4*batch*(2*embedding+vocab)+embedding*vocab*105/128,
  347. 4*batch*(2+3*embedding+context+context*heads),
  348. )
  349. case "stablelm":
  350. fullOffload = 4 * batch * (context*(1+heads) + 3*embedding + 2)
  351. partialOffload = max(
  352. 4*batch*(vocab+2*embedding),
  353. fullOffload,
  354. )
  355. case "deepseek2":
  356. fullOffload = max(
  357. 4*batch*(3*embedding+vocab),
  358. 4*batch*(3*embedding+2+context*(1+headsKV)+2*embeddingHeadsK*headsKV),
  359. )
  360. partialOffload = max(
  361. 4*batch*(3*embedding+vocab)+embedding*vocab*105/128,
  362. 4*batch*(2*embedding+1+2*embeddingHeadsK*headsKV+context+context*headsKV)+4*embeddingHeadsK*context*headsKV+embedding*embeddingHeadsK*headsKV*9/16,
  363. )
  364. case "chatglm":
  365. fullOffload = 4 * batch * (embedding + vocab)
  366. partialOffload = 4*batch*(embedding+vocab) + embedding*vocab*105/128
  367. if qkvBias, ok := layers["blk.0"]["attn_qkv.bias"]; ok {
  368. fullOffload = max(
  369. fullOffload,
  370. 4*batch*(2+
  371. 2*embedding+
  372. context+
  373. context*heads+
  374. embeddingHeadsK*heads+
  375. qkvBias.Shape[0]),
  376. )
  377. partialOffload = max(
  378. partialOffload,
  379. 4*batch*(1+
  380. 2*embedding+
  381. embeddingHeadsK*heads+
  382. context+
  383. context*heads)+
  384. 4*embeddingHeadsK*context+
  385. 4*context*embeddingHeadsK+
  386. 4*qkvBias.Shape[0],
  387. )
  388. }
  389. }
  390. return
  391. }