Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/docs/gguf.md # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / docs / gguf.md` 834 lines · 43532 bytes Raw Blame History Rendered 1 # GGUF 2 3 GGUF is a file format for storing models for inference with GGML and executors based on GGML. GGUF is a binary format that is designed for fast loading and saving of models, and for ease of reading. Models are traditionally developed using PyTorch or another framework, and then converted to GGUF for use in GGML. 4 5 It is a successor file format to GGML, GGMF and GGJT, and is designed to be unambiguous by containing all the information needed to load a model. It is also designed to be extensible, so that new information can be added to models without breaking compatibility. 6 7 For more information about the motivation behind GGUF, see [Historical State of Affairs](#historical-state-of-affairs). 8 9 ## Specification 10 11 GGUF is a format based on the existing GGJT, but makes a few changes to the format to make it more extensible and easier to use. The following features are desired: 12 13 - Single-file deployment: they can be easily distributed and loaded, and do not require any external files for additional information. 14 - Extensible: new features can be added to GGML-based executors/new information can be added to GGUF models without breaking compatibility with existing models. 15 - `mmap` compatibility: models can be loaded using `mmap` for fast loading and saving. 16 - Easy to use: models can be easily loaded and saved using a small amount of code, with no need for external libraries, regardless of the language used. 17 - Full information: all information needed to load a model is contained in the model file, and no additional information needs to be provided by the user. 18 19 The key difference between GGJT and GGUF is the use of a key-value structure for the hyperparameters (now referred to as metadata), rather than a list of untyped values. This allows for new metadata to be added without breaking compatibility with existing models, and to annotate the model with additional information that may be useful for inference or for identifying the model. 20 21 ### GGUF Naming Convention 22 23 GGUF follow a naming convention of `[].gguf` where each component is delimitated by a `-` if present. Ultimately this is intended to make it easier for humans to at a glance get the most important details of a model. It is not intended to be perfectly parsable in the field due to the diversity of existing gguf filenames. 24 25 The components are: 26 1. **Sidecar**: (Optional) Prefix marking the file as an auxiliary module loaded alongside a base model, rather than a standalone model. When present, sits at the very front of the filename followed by `-`. Lowercase by convention. 27 - `mmproj` : Multimodal projector (vision/audio encoder and projection layer for use with a base LLM) 28 - `mtp` : Multi-Token Prediction heads (speculative-decoding draft module, intended to be loaded alongside a base model of matching architecture and version). Note that oftentimes the MTP weights can be distributed inside the base model, in which case there is no separate `mtp-` sidecar file. 29 1. **BaseName**: A descriptive name for the model base type or architecture. 30 - This can be derived from gguf metadata `general.basename` substituting spaces for dashes. 31 1. **SizeLabel**: Parameter weight class (useful for leader boards) represented as `x` 32 - This can be derived from gguf metadata `general.size_label` if available or calculated if missing. 33 - Rounded decimal point is supported in count with a single letter scale prefix to assist in floating point exponent shown below 34 - `Q`: Quadrillion parameters. 35 - `T`: Trillion parameters. 36 - `B`: Billion parameters. 37 - `M`: Million parameters. 38 - `K`: Thousand parameters. 39 - Additional `-` can be appended as needed to indicate other attributes of interest 40 1. **FineTune**: A descriptive name for the model fine tuning goal (e.g. Chat, Instruct, etc...) 41 - This can be derived from gguf metadata `general.finetune` substituting spaces for dashes. 42 1. **Version**: (Optional) Denotes the model version number, formatted as `v.` 43 - If model is missing a version number then assume `v1.0` (First Public Release) 44 - This can be derived from gguf metadata `general.version` 45 1. **Encoding**: Indicates the weights encoding scheme that was applied to the model. Content, type mixture and arrangement however are determined by user code and can vary depending on project needs. 46 1. **Type**: Indicates the kind of gguf file and the intended purpose for it 47 - If missing, then file is by default a typical gguf tensor model file 48 - `LoRA` : GGUF file is a LoRA adapter 49 - `vocab` : GGUF file with only vocab data and metadata 50 1. **Shard**: (Optional) Indicates and denotes that the model has been split into multiple shards, formatted as `-of-`. 51 - *ShardNum* : Shard position in this model. Must be 5 digits padded by zeros. 52 - Shard number always starts from `00001` onwards (e.g. First shard always starts at `00001-of-XXXXX` rather than `00000-of-XXXXX`). 53 - *ShardTotal* : Total number of shards in this model. Must be 5 digits padded by zeros. 54 55 56 #### Validating Above Naming Convention 57 58 At a minimum all model files should have at least BaseName, SizeLabel, Version, in order to be easily validated as a file that is keeping with the GGUF Naming Convention. An example of this issue is that it is easy for Encoding to be mistaken as a FineTune if Version is omitted. 59 60 To validate you can use this regular expression `^(?:(?mmproj|mtp)-)?(?[A-Za-z0-9\s]*(?:(?:-(?:(?:[A-Za-z\s][A-Za-z0-9\s]*)|(?:[0-9\s]*)))*))-(?:(?(?:\d+x)?(?:\d+\.)?\d+[A-Za-z](?:-[A-Za-z]+(\d+\.)?\d+[A-Za-z]+)?)(?:-(?[A-Za-z0-9\s-]+))?)?-(?:(?v\d+(?:\.\d+)*))(?:-(?(?!LoRA|vocab)[\w_]+))?(?:-(?LoRA|vocab))?(?:-(?\d{5}-of-\d{5}))?\.gguf$` which will check that you got the minimum BaseName, SizeLabel and Version present in the correct order. 61 62 For example: 63 64 * `Mixtral-8x7B-v0.1-KQ2.gguf`: 65 - Model Name: Mixtral 66 - Expert Count: 8 67 - Parameter Count: 7B 68 - Version Number: v0.1 69 - Weight Encoding Scheme: KQ2 70 71 * `Hermes-2-Pro-Llama-3-8B-F16.gguf`: 72 - Model Name: Hermes 2 Pro Llama 3 73 - Expert Count: 0 74 - Parameter Count: 8B 75 - Version Number: v1.0 76 - Weight Encoding Scheme: F16 77 - Shard: N/A 78 79 * `Grok-100B-v1.0-Q4_0-00003-of-00009.gguf` 80 - Model Name: Grok 81 - Expert Count: 0 82 - Parameter Count: 100B 83 - Version Number: v1.0 84 - Weight Encoding Scheme: Q4_0 85 - Shard: 3 out of 9 total shards 86 87 * `mtp-Qwen3-27B-v1.0-Q4_K_M.gguf` 88 - Sidecar: mtp (Multi-Token Prediction draft module) 89 - Model Name: Qwen3 90 - Expert Count: 0 91 - Parameter Count: 27B (of the main model — sidecar tensors are smaller) 92 - Version Number: v1.0 93 - Weight Encoding Scheme: Q4_K_M 94 95 * `mmproj-Qwen2-VL-7B-v1.0-F16.gguf` 96 - Sidecar: mmproj (multimodal projector) 97 - Model Name: Qwen2-VL 98 - Expert Count: 0 99 - Parameter Count: 7B (of the main model — sidecar tensors are smaller) 100 - Version Number: v1.0 101 - Weight Encoding Scheme: F16 102 103 104
Example Node.js Regex Function 105 106 ```js 107 #!/usr/bin/env node 108 const ggufRegex = /^(?:(?mmproj|mtp)-)?(?[A-Za-z0-9\s]*(?:(?:-(?:(?:[A-Za-z\s][A-Za-z0-9\s]*)|(?:[0-9\s]*)))*))-(?:(?(?:\d+x)?(?:\d+\.)?\d+[A-Za-z](?:-[A-Za-z]+(\d+\.)?\d+[A-Za-z]+)?)(?:-(?[A-Za-z0-9\s-]+))?)?-(?:(?v\d+(?:\.\d+)*))(?:-(?(?!LoRA|vocab)[\w_]+))?(?:-(?LoRA|vocab))?(?:-(?\d{5}-of-\d{5}))?\.gguf$/; 109 110 function parseGGUFFilename(filename) { 111 const match = ggufRegex.exec(filename); 112 if (!match) 113 return null; 114 const {Sidecar = null, BaseName = null, SizeLabel = null, FineTune = null, Version = "v1.0", Encoding = null, Type = null, Shard = null} = match.groups; 115 return {Sidecar: Sidecar, BaseName: BaseName, SizeLabel: SizeLabel, FineTune: FineTune, Version: Version, Encoding: Encoding, Type: Type, Shard: Shard}; 116 } 117 118 const testCases = [ 119 {filename: 'Mixtral-8x7B-v0.1-KQ2.gguf', expected: { Sidecar: null, BaseName: 'Mixtral', SizeLabel: '8x7B', FineTune: null, Version: 'v0.1', Encoding: 'KQ2', Type: null, Shard: null}}, 120 {filename: 'Grok-100B-v1.0-Q4_0-00003-of-00009.gguf', expected: { Sidecar: null, BaseName: 'Grok', SizeLabel: '100B', FineTune: null, Version: 'v1.0', Encoding: 'Q4_0', Type: null, Shard: "00003-of-00009"}}, 121 {filename: 'Hermes-2-Pro-Llama-3-8B-v1.0-F16.gguf', expected: { Sidecar: null, BaseName: 'Hermes-2-Pro-Llama-3', SizeLabel: '8B', FineTune: null, Version: 'v1.0', Encoding: 'F16', Type: null, Shard: null}}, 122 {filename: 'Phi-3-mini-3.8B-ContextLength4k-instruct-v1.0.gguf', expected: { Sidecar: null, BaseName: 'Phi-3-mini', SizeLabel: '3.8B-ContextLength4k', FineTune: 'instruct', Version: 'v1.0', Encoding: null, Type: null, Shard: null}}, 123 {filename: 'mtp-Qwen3-27B-v1.0-Q4_K_M.gguf', expected: { Sidecar: 'mtp', BaseName: 'Qwen3', SizeLabel: '27B', FineTune: null, Version: 'v1.0', Encoding: 'Q4_K_M', Type: null, Shard: null}}, 124 {filename: 'mmproj-Qwen2-VL-7B-v1.0-F16.gguf', expected: { Sidecar: 'mmproj', BaseName: 'Qwen2-VL', SizeLabel: '7B', FineTune: null, Version: 'v1.0', Encoding: 'F16', Type: null, Shard: null}}, 125 {filename: 'not-a-known-arrangement.gguf', expected: null}, 126 ]; 127 128 testCases.forEach(({ filename, expected }) => { 129 const result = parseGGUFFilename(filename); 130 const passed = JSON.stringify(result) === JSON.stringify(expected); 131 console.log(`${filename}: ${passed ? "PASS" : "FAIL"}`); 132 if (!passed) { 133 console.log(result); 134 console.log(expected); 135 } 136 }); 137 ``` 138 139
140 141 142 ### File Structure 143 144 ![image](https://github.com/ggerganov/ggml/assets/`1991296`/`c3623641`-3a1d-408e-bfaf-`1b7c4e16aa63`) 145 *diagram by [@mishig25](https://github.com/mishig25) (GGUF v3)* 146 147 GGUF files are structured as follows. They use a global alignment specified in the `general.alignment` metadata field, referred to as `ALIGNMENT` below. Where required, the file is padded with `0x00` bytes to the next multiple of `general.alignment`. 148 149 Fields, including arrays, are written sequentially without alignment unless otherwise specified. 150 151 Models are little-endian by default. They can also come in big-endian for use with big-endian computers; in this case, all values (including metadata values and tensors) will also be big-endian. At the time of writing, there is no way to determine if a model is big-endian; this may be rectified in future versions. If no additional information is provided, assume the model is little-endian. 152 153 The `ggml_type` values below mirror `enum ggml_type` in [`include/ggml.h`](../include/ggml.h), which is authoritative and gains new values over time, so readers should take type codes and block sizes from there. 154 155 ```c 156 enum ggml_type: uint32_t { 157 GGML_TYPE_F32 = 0, 158 GGML_TYPE_F16 = 1, 159 GGML_TYPE_Q4_0 = 2, 160 GGML_TYPE_Q4_1 = 3, 161 // GGML_TYPE_Q4_2 = 4, support has been removed 162 // GGML_TYPE_Q4_3 = 5, support has been removed 163 GGML_TYPE_Q5_0 = 6, 164 GGML_TYPE_Q5_1 = 7, 165 GGML_TYPE_Q8_0 = 8, 166 GGML_TYPE_Q8_1 = 9, 167 GGML_TYPE_Q2_K = 10, 168 GGML_TYPE_Q3_K = 11, 169 GGML_TYPE_Q4_K = 12, 170 GGML_TYPE_Q5_K = 13, 171 GGML_TYPE_Q6_K = 14, 172 GGML_TYPE_Q8_K = 15, 173 GGML_TYPE_IQ2_XXS = 16, 174 GGML_TYPE_IQ2_XS = 17, 175 GGML_TYPE_IQ3_XXS = 18, 176 GGML_TYPE_IQ1_S = 19, 177 GGML_TYPE_IQ4_NL = 20, 178 GGML_TYPE_IQ3_S = 21, 179 GGML_TYPE_IQ2_S = 22, 180 GGML_TYPE_IQ4_XS = 23, 181 GGML_TYPE_I8 = 24, 182 GGML_TYPE_I16 = 25, 183 GGML_TYPE_I32 = 26, 184 GGML_TYPE_I64 = 27, 185 GGML_TYPE_F64 = 28, 186 GGML_TYPE_IQ1_M = 29, 187 GGML_TYPE_BF16 = 30, 188 // GGML_TYPE_Q4_0_4_4 = 31, support has been removed from gguf files 189 // GGML_TYPE_Q4_0_4_8 = 32, 190 // GGML_TYPE_Q4_0_8_8 = 33, 191 GGML_TYPE_TQ1_0 = 34, 192 GGML_TYPE_TQ2_0 = 35, 193 // GGML_TYPE_IQ4_NL_4_4 = 36, 194 // GGML_TYPE_IQ4_NL_4_8 = 37, 195 // GGML_TYPE_IQ4_NL_8_8 = 38, 196 GGML_TYPE_MXFP4 = 39, // MXFP4 (1 block) 197 GGML_TYPE_NVFP4 = 40, // NVFP4 (4 blocks, E4M3 scale) 198 GGML_TYPE_Q1_0 = 41, 199 GGML_TYPE_Q2_0 = 42, 200 GGML_TYPE_F8_E4M3 = 43, 201 GGML_TYPE_COUNT = 44, 202 }; 203 204 enum gguf_metadata_value_type: uint32_t { 205 // The value is a 8-bit unsigned integer. 206 GGUF_METADATA_VALUE_TYPE_UINT8 = 0, 207 // The value is a 8-bit signed integer. 208 GGUF_METADATA_VALUE_TYPE_INT8 = 1, 209 // The value is a 16-bit unsigned little-endian integer. 210 GGUF_METADATA_VALUE_TYPE_UINT16 = 2, 211 // The value is a 16-bit signed little-endian integer. 212 GGUF_METADATA_VALUE_TYPE_INT16 = 3, 213 // The value is a 32-bit unsigned little-endian integer. 214 GGUF_METADATA_VALUE_TYPE_UINT32 = 4, 215 // The value is a 32-bit signed little-endian integer. 216 GGUF_METADATA_VALUE_TYPE_INT32 = 5, 217 // The value is a 32-bit IEEE754 floating point number. 218 GGUF_METADATA_VALUE_TYPE_FLOAT32 = 6, 219 // The value is a boolean. 220 // 1-byte value where 0 is false and 1 is true. 221 // Anything else is invalid, and should be treated as either the model being invalid or the reader being buggy. 222 GGUF_METADATA_VALUE_TYPE_BOOL = 7, 223 // The value is a UTF-8 non-null-terminated string, with length prepended. 224 GGUF_METADATA_VALUE_TYPE_STRING = 8, 225 // The value is an array of other values, with the length and type prepended. 226 /// 227 // Arrays can be nested, and the length of the array is the number of elements in the array, not the number of bytes. 228 GGUF_METADATA_VALUE_TYPE_ARRAY = 9, 229 // The value is a 64-bit unsigned little-endian integer. 230 GGUF_METADATA_VALUE_TYPE_UINT64 = 10, 231 // The value is a 64-bit signed little-endian integer. 232 GGUF_METADATA_VALUE_TYPE_INT64 = 11, 233 // The value is a 64-bit IEEE754 floating point number. 234 GGUF_METADATA_VALUE_TYPE_FLOAT64 = 12, 235 }; 236 237 // A string in GGUF. 238 struct gguf_string_t { 239 // The length of the string, in bytes. 240 uint64_t len; 241 // The string as a UTF-8 non-null-terminated string. 242 char string[len]; 243 }; 244 245 union gguf_metadata_value_t { 246 uint8_t uint8; 247 int8_t int8; 248 uint16_t uint16; 249 int16_t int16; 250 uint32_t uint32; 251 int32_t int32; 252 float float32; 253 uint64_t uint64; 254 int64_t int64; 255 double float64; 256 bool bool_; 257 gguf_string_t string; 258 struct { 259 // Any value type is valid, including arrays. 260 gguf_metadata_value_type type; 261 // Number of elements, not bytes 262 uint64_t len; 263 // The array of values. 264 gguf_metadata_value_t array[len]; 265 } array; 266 }; 267 268 struct gguf_metadata_kv_t { 269 // The key of the metadata. It is a standard GGUF string, with the following caveats: 270 // - It must be a valid ASCII string. 271 // - It must be a hierarchical key, where each segment is `lower_snake_case` and separated by a `.`. 272 // - It must be at most 2^16-1/65535 bytes long. 273 // Any keys that do not follow these rules are invalid. 274 gguf_string_t key; 275 276 // The type of the value. 277 // Must be one of the `gguf_metadata_value_type` values. 278 gguf_metadata_value_type value_type; 279 // The value. 280 gguf_metadata_value_t value; 281 }; 282 283 struct gguf_header_t { 284 // Magic number to announce that this is a GGUF file. 285 // Must be `GGUF` at the byte level: `0x47` `0x47` `0x55` `0x46`. 286 // Your executor might do little-endian byte order, so it might be 287 // check for 0x46554747 and letting the endianness cancel out. 288 // Consider being *very* explicit about the byte order here. 289 uint32_t magic; 290 // The version of the format implemented. 291 // Must be `3` for version described in this spec, which introduces big-endian support. 292 // 293 // This version should only be increased for structural changes to the format. 294 // Changes that do not affect the structure of the file should instead update the metadata 295 // to signify the change. 296 uint32_t version; 297 // The number of tensors in the file. 298 // This is explicit, instead of being included in the metadata, to ensure it is always present 299 // for loading the tensors. 300 uint64_t tensor_count; 301 // The number of metadata key-value pairs. 302 uint64_t metadata_kv_count; 303 // The metadata key-value pairs. 304 gguf_metadata_kv_t metadata_kv[metadata_kv_count]; 305 }; 306 307 uint64_t align_offset(uint64_t offset) { 308 return offset + (ALIGNMENT - (offset % ALIGNMENT)) % ALIGNMENT; 309 } 310 311 struct gguf_tensor_info_t { 312 // The name of the tensor. It is a standard GGUF string, with the caveat that 313 // it must be at most 64 bytes long. 314 gguf_string_t name; 315 // The number of dimensions in the tensor. 316 // Currently at most 4, but this may change in the future. 317 uint32_t n_dimensions; 318 // The dimensions of the tensor. 319 uint64_t dimensions[n_dimensions]; 320 // The type of the tensor. 321 ggml_type type; 322 // The offset of the tensor's data in this file in bytes. 323 // 324 // This offset is relative to `tensor_data`, not to the start 325 // of the file, to make it easier for writers to write the file. 326 // Readers should consider exposing this offset relative to the 327 // file to make it easier to read the data. 328 // 329 // Must be a multiple of `ALIGNMENT`. That is, `align_offset(offset) == offset`. 330 uint64_t offset; 331 }; 332 333 struct gguf_file_t { 334 // The header of the file. 335 gguf_header_t header; 336 337 // Tensor infos, which can be used to locate the tensor data. 338 gguf_tensor_info_t tensor_infos[header.tensor_count]; 339 340 // Padding to the nearest multiple of `ALIGNMENT`. 341 // 342 // That is, if `sizeof(header) + sizeof(tensor_infos)` is not a multiple of `ALIGNMENT`, 343 // this padding is added to make it so. 344 // 345 // This can be calculated as `align_offset(position) - position`, where `position` is 346 // the position of the end of `tensor_infos` (i.e. `sizeof(header) + sizeof(tensor_infos)`). 347 uint8_t _padding[]; 348 349 // Tensor data. 350 // 351 // This is arbitrary binary data corresponding to the weights of the model. This data should be close 352 // or identical to the data in the original model file, but may be different due to quantization or 353 // other optimizations for inference. Any such deviations should be recorded in the metadata or as 354 // part of the architecture definition. 355 // 356 // Each tensor's data must be stored within this array, and located through its `tensor_infos` entry. 357 // The offset of each tensor's data must be a multiple of `ALIGNMENT`, and the space between tensors 358 // should be padded to `ALIGNMENT` bytes. 359 uint8_t tensor_data[]; 360 }; 361 ``` 362 363 ## Standardized key-value pairs 364 365 The following key-value pairs are standardized. This list may grow in the future as more use cases are discovered. Where possible, names are shared with the original model definitions to make it easier to map between the two. 366 367 Not all of these are required, but they are all recommended. Keys that are required are bolded. For omitted pairs, the reader should assume that the value is unknown and either default or error as appropriate. 368 369 The community can develop their own key-value pairs to carry additional data. However, these should be namespaced with the relevant community name to avoid collisions. For example, the `rustformers` community might use `rustformers.` as a prefix for all of their keys. 370 371 If a particular community key is widely used, it may be promoted to a standardized key. 372 373 By convention, most counts/lengths/etc are `uint64` unless otherwise specified. This is to allow for larger models to be supported in the future. Some models may use `uint32` for their values; it is recommended that readers support both. 374 375 ### General 376 377 #### Required 378 379 - **`general.architecture: string`**: describes what architecture this model implements. All lowercase ASCII, with only `[a-z0-9]+` characters allowed. Known values include: 380 - `llama` 381 - `mpt` 382 - `gptneox` 383 - `gptj` 384 - `gpt2` 385 - `bloom` 386 - `falcon` 387 - `mamba` 388 - `rwkv` 389 - **`general.quantization_version: uint32`**: The version of the quantization format. Not required if the model is not quantized (i.e. no tensors are quantized). If any tensors are quantized, this _must_ be present. This is separate to the quantization scheme of the tensors itself; the quantization version may change without changing the scheme's name (e.g. the quantization scheme is Q5_K, and the quantization version is 4). 390 - **`general.alignment: uint32`**: the global alignment to use, as described above. This can vary to allow for different alignment schemes, but it must be a multiple of 8. Some writers may not write the alignment. If the alignment is **not** specified, assume it is `32`. 391 392 #### General metadata 393 394 - `general.name: string`: The name of the model. This should be a human-readable name that can be used to identify the model. It should be unique within the community that the model is defined in. 395 - `general.author: string`: The author of the model. 396 - `general.version: string`: The version of the model. 397 - `general.organization: string`: The organization of the model. 398 - `general.basename: string`: The base model name / architecture of the model 399 - `general.finetune: string`: What has the base model been optimized toward. 400 - `general.description: string`: free-form description of the model including anything that isn't covered by the other fields 401 - `general.quantized_by: string`: The name of the individual who quantized the model 402 - `general.size_label: string`: Size class of the model, such as number of weights and experts. (Useful for leader boards) 403 - `general.license: string`: License of the model, expressed as a [SPDX license expression](https://spdx.github.io/spdx-spec/v2-draft/SPDX-license-expressions/) (e.g. `"MIT OR Apache-2.0`). Do not include any other information, such as the license text or the URL to the license. 404 - `general.license.name: string`: Human friendly license name 405 - `general.license.link: string`: URL to the license. 406 - `general.url: string`: URL to the model's homepage. This can be a GitHub repo, a paper, etc. 407 - `general.doi: string`: Digital Object Identifier (DOI) https://www.doi.org/ 408 - `general.uuid: string`: [Universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier) 409 - `general.repo_url: string`: URL to the model's repository such as a GitHub repo or HuggingFace repo 410 - `general.tags: string[]`: List of tags that can be used as search terms for a search engine or social media 411 - `general.languages: string[]`: What languages can the model speak. Encoded as [ISO 639](https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes) two letter codes 412 - `general.datasets: string[]`: Links or references to datasets that the model was trained upon 413 - `general.file_type: uint32`: An enumerated value describing the type of the majority of the tensors in the file. Optional; can be inferred from the tensor types. 414 - `ALL_F32 = 0` 415 - `MOSTLY_F16 = 1` 416 - `MOSTLY_Q4_0 = 2` 417 - `MOSTLY_Q4_1 = 3` 418 - `MOSTLY_Q4_1_SOME_F16 = 4` 419 - `MOSTLY_Q4_2 = 5` (support removed) 420 - `MOSTLY_Q4_3 = 6` (support removed) 421 - `MOSTLY_Q8_0 = 7` 422 - `MOSTLY_Q5_0 = 8` 423 - `MOSTLY_Q5_1 = 9` 424 - `MOSTLY_Q2_K = 10` 425 - `MOSTLY_Q3_K_S = 11` 426 - `MOSTLY_Q3_K_M = 12` 427 - `MOSTLY_Q3_K_L = 13` 428 - `MOSTLY_Q4_K_S = 14` 429 - `MOSTLY_Q4_K_M = 15` 430 - `MOSTLY_Q5_K_S = 16` 431 - `MOSTLY_Q5_K_M = 17` 432 - `MOSTLY_Q6_K = 18` 433 434 #### Source metadata 435 436 Information about where this model came from. This is useful for tracking the provenance of the model, and for finding the original source if the model is modified. For a model that was converted from GGML, for example, these keys would point to the model that was converted from. 437 438 - `general.source.url: string`: URL to the source of the model's homepage. This can be a GitHub repo, a paper, etc. 439 - `general.source.doi: string`: Source Digital Object Identifier (DOI) https://www.doi.org/ 440 - `general.source.uuid: string`: Source [Universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier) 441 - `general.source.repo_url: string`: URL to the source of the model's repository such as a GitHub repo or HuggingFace repo 442 443 - `general.base_model.count: uint32`: Number of parent models 444 - `general.base_model.{id}.name: string`: The name of the parent model. 445 - `general.base_model.{id}.author: string`: The author of the parent model. 446 - `general.base_model.{id}.version: string`: The version of the parent model. 447 - `general.base_model.{id}.organization: string`: The organization of the parent model. 448 - `general.base_model.{id}.url: string`: URL to the source of the parent model's homepage. This can be a GitHub repo, a paper, etc. 449 - `general.base_model.{id}.doi: string`: Parent Digital Object Identifier (DOI) https://www.doi.org/ 450 - `general.base_model.{id}.uuid: string`: Parent [Universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier) 451 - `general.base_model.{id}.repo_url: string`: URL to the source of the parent model's repository such as a GitHub repo or HuggingFace repo 452 453 ### LLM 454 455 In the following, `[llm]` is used to fill in for the name of a specific LLM architecture. For example, `llama` for LLaMA, `mpt` for MPT, etc. If mentioned in an architecture's section, it is required for that architecture, but not all keys are required for all architectures. Consult the relevant section for more information. 456 457 - `[llm].context_length: uint64`: Also known as `n_ctx`. length of the context (in tokens) that the model was trained on. For most architectures, this is the hard limit on the length of the input. Architectures, like RWKV, that are not reliant on transformer-style attention may be able to handle larger inputs, but this is not guaranteed. 458 - `[llm].embedding_length: uint64`: Also known as `n_embd`. Embedding layer size. 459 - `[llm].block_count: uint64`: The number of blocks of attention+feed-forward layers (i.e. the bulk of the LLM). Does not include the input or embedding layers. 460 - `[llm].feed_forward_length: uint64`: Also known as `n_ff`. The length of the feed-forward layer. 461 - `[llm].use_parallel_residual: bool`: Whether or not the parallel residual logic should be used. 462 - `[llm].tensor_data_layout: string`: When a model is converted to GGUF, tensors may be rearranged to improve performance. This key describes the layout of the tensor data. This is not required; if not present, it is assumed to be `reference`. 463 - `reference`: tensors are laid out in the same order as the original model 464 - further options can be found for each architecture in their respective sections 465 - `[llm].expert_count: uint32`: Number of experts in MoE models (optional for non-MoE arches). 466 - `[llm].expert_used_count: uint32`: Number of experts used during each token token evaluation (optional for non-MoE arches). 467 468 #### Attention 469 470 - `[llm].attention.head_count: uint64`: Also known as `n_head`. Number of attention heads. 471 - `[llm].attention.head_count_kv: uint64`: The number of heads per group used in Grouped-Query-Attention. If not present or if present and equal to `[llm].attention.head_count`, the model does not use GQA. 472 - `[llm].attention.max_alibi_bias: float32`: The maximum bias to use for ALiBI. 473 - `[llm].attention.clamp_kqv: float32`: Value (`C`) to clamp the values of the `Q`, `K`, and `V` tensors between (`[-C, C]`). 474 - `[llm].attention.layer_norm_epsilon: float32`: Layer normalization epsilon. 475 - `[llm].attention.layer_norm_rms_epsilon: float32`: Layer RMS normalization epsilon. 476 - `[llm].attention.key_length: uint32`: The optional size of a key head, $d_k$. If not specified, it will be `n_embd / n_head`. 477 - `[llm].attention.value_length: uint32`: The optional size of a value head, $d_v$. If not specified, it will be `n_embd / n_head`. 478 479 #### RoPE 480 481 - `[llm].rope.dimension_count: uint64`: The number of rotary dimensions for RoPE. 482 - `[llm].rope.freq_base: float32`: The base frequency for RoPE. 483 484 ##### Scaling 485 486 The following keys describe RoPE scaling parameters: 487 488 - `[llm].rope.scaling.type: string`: Can be `none`, `linear`, or `yarn`. 489 - `[llm].rope.scaling.factor: float32`: A scale factor for RoPE to adjust the context length. 490 - `[llm].rope.scaling.original_context_length: uint32_t`: The original context length of the base model. 491 - `[llm].rope.scaling.finetuned: bool`: True if model has been finetuned with RoPE scaling. 492 493 Note that older models may not have these keys, and may instead use the following key: 494 495 - `[llm].rope.scale_linear: float32`: A linear scale factor for RoPE to adjust the context length. 496 497 It is recommended that models use the newer keys if possible, as they are more flexible and allow for more complex scaling schemes. Executors will need to support both indefinitely. 498 499 #### SSM 500 501 - `[llm].ssm.conv_kernel: uint32`: The size of the rolling/shift state. 502 - `[llm].ssm.inner_size: uint32`: The embedding size of the states. 503 - `[llm].ssm.state_size: uint32`: The size of the recurrent state. 504 - `[llm].ssm.time_step_rank: uint32`: The rank of time steps. 505 506 #### Models 507 508 The following sections describe the metadata for each model architecture. Each key specified _must_ be present. 509 510 ##### LLaMA 511 512 - `llama.context_length` 513 - `llama.embedding_length` 514 - `llama.block_count` 515 - `llama.feed_forward_length` 516 - `llama.rope.dimension_count` 517 - `llama.attention.head_count` 518 - `llama.attention.layer_norm_rms_epsilon` 519 520 ###### Optional 521 522 - `llama.rope.scale` 523 - `llama.attention.head_count_kv` 524 - `llama.tensor_data_layout`: 525 - `Meta AI original pth`: 526 ```python 527 def permute(weights: NDArray, n_head: int) -> NDArray: 528 return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:]) 529 .swapaxes(1, 2) 530 .reshape(weights.shape)) 531 ``` 532 - `llama.expert_count` 533 - `llama.expert_used_count` 534 535 ##### MPT 536 537 - `mpt.context_length` 538 - `mpt.embedding_length` 539 - `mpt.block_count` 540 - `mpt.attention.head_count` 541 - `mpt.attention.alibi_bias_max` 542 - `mpt.attention.clip_kqv` 543 - `mpt.attention.layer_norm_epsilon` 544 545 ##### GPT-NeoX 546 547 - `gptneox.context_length` 548 - `gptneox.embedding_length` 549 - `gptneox.block_count` 550 - `gptneox.use_parallel_residual` 551 - `gptneox.rope.dimension_count` 552 - `gptneox.attention.head_count` 553 - `gptneox.attention.layer_norm_epsilon` 554 555 ###### Optional 556 557 - `gptneox.rope.scale` 558 559 ##### GPT-J 560 561 - `gptj.context_length` 562 - `gptj.embedding_length` 563 - `gptj.block_count` 564 - `gptj.rope.dimension_count` 565 - `gptj.attention.head_count` 566 - `gptj.attention.layer_norm_epsilon` 567 568 ###### Optional 569 570 - `gptj.rope.scale` 571 572 ##### GPT-2 573 574 - `gpt2.context_length` 575 - `gpt2.embedding_length` 576 - `gpt2.block_count` 577 - `gpt2.attention.head_count` 578 - `gpt2.attention.layer_norm_epsilon` 579 580 ##### BLOOM 581 582 - `bloom.context_length` 583 - `bloom.embedding_length` 584 - `bloom.block_count` 585 - `bloom.feed_forward_length` 586 - `bloom.attention.head_count` 587 - `bloom.attention.layer_norm_epsilon` 588 589 ##### Falcon 590 591 - `falcon.context_length` 592 - `falcon.embedding_length` 593 - `falcon.block_count` 594 - `falcon.attention.head_count` 595 - `falcon.attention.head_count_kv` 596 - `falcon.attention.use_norm` 597 - `falcon.attention.layer_norm_epsilon` 598 599 ###### Optional 600 601 - `falcon.tensor_data_layout`: 602 603 - `jploski` (author of the original GGML implementation of Falcon): 604 605 ```python 606 # The original query_key_value tensor contains n_head_kv "kv groups", 607 # each consisting of n_head/n_head_kv query weights followed by one key 608 # and one value weight (shared by all query heads in the kv group). 609 # This layout makes it a big pain to work with in GGML. 610 # So we rearrange them here,, so that we have n_head query weights 611 # followed by n_head_kv key weights followed by n_head_kv value weights, 612 # in contiguous fashion. 613 614 if "query_key_value" in src: 615 qkv = model[src].view( 616 n_head_kv, n_head // n_head_kv + 2, head_dim, head_dim * n_head) 617 618 q = qkv[:, :-2 ].reshape(n_head * head_dim, head_dim * n_head) 619 k = qkv[:, [-2]].reshape(n_head_kv * head_dim, head_dim * n_head) 620 v = qkv[:, [-1]].reshape(n_head_kv * head_dim, head_dim * n_head) 621 622 model[src] = torch.cat((q,k,v)).reshape_as(model[src]) 623 ``` 624 625 ##### Mamba 626 627 - `mamba.context_length` 628 - `mamba.embedding_length` 629 - `mamba.block_count` 630 - `mamba.ssm.conv_kernel` 631 - `mamba.ssm.inner_size` 632 - `mamba.ssm.state_size` 633 - `mamba.ssm.time_step_rank` 634 - `mamba.attention.layer_norm_rms_epsilon` 635 636 ##### RWKV 637 638 The vocabulary size is the same as the number of rows in the `head` matrix. 639 640 - `rwkv.architecture_version: uint32`: The only allowed value currently is 4. Version 5 is expected to appear some time in the future. 641 - `rwkv.context_length: uint64`: Length of the context used during training or fine-tuning. RWKV is able to handle larger context than this limit, but the output quality may suffer. 642 - `rwkv.block_count: uint64` 643 - `rwkv.embedding_length: uint64` 644 - `rwkv.feed_forward_length: uint64` 645 646 ##### Whisper 647 648 Keys that do not have types defined should be assumed to share definitions with `llm.` keys. 649 (For example, `whisper.context_length` is equivalent to `llm.context_length`.) 650 This is because they are both transformer models. 651 652 - `whisper.encoder.context_length` 653 - `whisper.encoder.embedding_length` 654 - `whisper.encoder.block_count` 655 - `whisper.encoder.mels_count: uint64` 656 - `whisper.encoder.attention.head_count` 657 658 - `whisper.decoder.context_length` 659 - `whisper.decoder.embedding_length` 660 - `whisper.decoder.block_count` 661 - `whisper.decoder.attention.head_count` 662 663 #### Prompting 664 665 **TODO**: Include prompt format, and/or metadata about how it should be used (instruction, conversation, autocomplete, etc). 666 667 ### LoRA 668 669 **TODO**: Figure out what metadata is needed for LoRA. Probably desired features: 670 671 - match an existing model exactly, so that it can't be misapplied 672 - be marked as a LoRA so executors won't try to run it by itself 673 674 Should this be an architecture, or should it share the details of the original model with additional fields to mark it as a LoRA? 675 676 ### Tokenizer 677 678 The following keys are used to describe the tokenizer of the model. It is recommended that model authors support as many of these as possible, as it will allow for better tokenization quality with supported executors. 679 680 #### GGML 681 682 GGML supports an embedded vocabulary that enables inference of the model, but implementations of tokenization using this vocabulary (i.e. `llama.cpp`'s tokenizer) may have lower accuracy than the original tokenizer used for the model. When a more accurate tokenizer is available and supported, it should be used instead. 683 684 It is not guaranteed to be standardized across models, and may change in the future. It is recommended that model authors use a more standardized tokenizer if possible. 685 686 - `tokenizer.ggml.model: string`: The name of the tokenizer model. 687 - `llama`: Llama style SentencePiece (tokens and scores extracted from HF `tokenizer.model`) 688 - `replit`: Replit style SentencePiece (tokens and scores extracted from HF `spiece.model`) 689 - `gpt2`: GPT-2 / GPT-NeoX style BPE (tokens extracted from HF `tokenizer.json`) 690 - `rwkv`: RWKV tokenizer 691 - `tokenizer.ggml.tokens: array[string]`: A list of tokens indexed by the token ID used by the model. 692 - `tokenizer.ggml.scores: array[float32]`: If present, the score/probability of each token. If not present, all tokens are assumed to have equal probability. If present, it must have the same length and index as `tokens`. 693 - `tokenizer.ggml.token_type: array[int32]`: The token type (1=normal, 2=unknown, 3=control, 4=user defined, 5=unused, 6=byte). If present, it must have the same length and index as `tokens`. 694 - `tokenizer.ggml.merges: array[string]`: If present, the merges of the tokenizer. If not present, the tokens are assumed to be atomic. 695 - `tokenizer.ggml.added_tokens: array[string]`: If present, tokens that were added after training. 696 697 ##### Special tokens 698 699 - `tokenizer.ggml.bos_token_id: uint32`: Beginning of sequence marker 700 - `tokenizer.ggml.eos_token_id: uint32`: End of sequence marker 701 - `tokenizer.ggml.unknown_token_id: uint32`: Unknown token 702 - `tokenizer.ggml.separator_token_id: uint32`: Separator token 703 - `tokenizer.ggml.padding_token_id: uint32`: Padding token 704 705 #### Hugging Face 706 707 Hugging Face maintains their own `tokenizers` library that supports a wide variety of tokenizers. If your executor uses this library, it may be able to use the model's tokenizer directly. 708 709 - `tokenizer.huggingface.json: string`: the entirety of the HF `tokenizer.json` for a given model (e.g. ). Included for compatibility with executors that support HF tokenizers directly. 710 711 #### Other 712 713 Other tokenizers may be used, but are not necessarily standardized. They may be executor-specific. They will be documented here as they are discovered/further developed. 714 715 - `tokenizer.rwkv.world: string`: a RWKV World tokenizer, like [this](https://github.com/BlinkDL/ChatRWKV/blob/main/tokenizer/rwkv_vocab_v20230424.txt). This text file should be included verbatim. 716 - `tokenizer.chat_template : string`: a Jinja template that specifies the input format expected by the model. For more details see: 717 718 ### Computation graph 719 720 This is a future extension and still needs to be discussed, and may necessitate a new GGUF version. At the time of writing, the primary blocker is the stabilization of the computation graph format. 721 722 A sample computation graph of GGML nodes could be included in the model itself, allowing an executor to run the model without providing its own implementation of the architecture. This would allow for a more consistent experience across executors, and would allow for more complex architectures to be supported without requiring the executor to implement them. 723 724 ## Standardized tensor names 725 726 To minimize complexity and maximize compatibility, it is recommended that models using the transformer architecture use the following naming convention for their tensors: 727 728 ### Base layers 729 730 `AA.weight` `AA.bias` 731 732 where `AA` can be: 733 734 - `token_embd`: Token embedding layer 735 - `pos_embd`: Position embedding layer 736 - `output_norm`: Output normalization layer 737 - `output`: Output layer 738 739 ### Attention and feed-forward layer blocks 740 741 `blk.N.BB.weight` `blk.N.BB.bias` 742 743 where N signifies the block number a layer belongs to, and where `BB` could be: 744 745 - `attn_norm`: Attention normalization layer 746 - `attn_norm_2`: Attention normalization layer 747 - `attn_qkv`: Attention query-key-value layer 748 - `attn_q`: Attention query layer 749 - `attn_k`: Attention key layer 750 - `attn_v`: Attention value layer 751 - `attn_output`: Attention output layer 752 753 - `ffn_norm`: Feed-forward network normalization layer 754 - `ffn_up`: Feed-forward network "up" layer 755 - `ffn_gate`: Feed-forward network "gate" layer 756 - `ffn_down`: Feed-forward network "down" layer 757 - `ffn_gate_inp`: Expert-routing layer for the Feed-forward network in MoE models 758 - `ffn_gate_exp`: Feed-forward network "gate" layer per expert in MoE models 759 - `ffn_down_exp`: Feed-forward network "down" layer per expert in MoE models 760 - `ffn_up_exp`: Feed-forward network "up" layer per expert in MoE models 761 762 - `ssm_in`: State space model input projections layer 763 - `ssm_conv1d`: State space model rolling/shift layer 764 - `ssm_x`: State space model selective parametrization layer 765 - `ssm_a`: State space model state compression layer 766 - `ssm_d`: State space model skip connection layer 767 - `ssm_dt`: State space model time step layer 768 - `ssm_out`: State space model output projection layer 769 770 ## Version History 771 772 This document is actively updated to describe the current state of the metadata, and these changes are not tracked outside of the commits. 773 774 However, the format _itself_ has changed. The following sections describe the changes to the format itself. 775 776 ### v3 777 778 Adds big-endian support. 779 780 ### v2 781 782 Most countable values (lengths, etc) were changed from `uint32` to `uint64` to allow for larger models to be supported in the future. 783 784 ### v1 785 786 Initial version. 787 788 ## Historical State of Affairs 789 790 The following information is provided for context, but is not necessary to understand the rest of this document. 791 792 ### Overview 793 794 At present, there are three GGML file formats floating around for LLMs: 795 796 - **GGML** (unversioned): baseline format, with no versioning or alignment. 797 - **GGMF** (versioned): the same as GGML, but with versioning. Only one version exists. 798 - **GGJT**: Aligns the tensors to allow for use with `mmap`, which requires alignment. v1, v2 and v3 are identical, but the latter versions use a different quantization scheme that is incompatible with previous versions. 799 800 GGML is primarily used by the examples in `ggml`, while GGJT is used by `llama.cpp` models. Other executors may use any of the three formats, but this is not 'officially' supported. 801 802 These formats share the same fundamental structure: 803 804 - a magic number with an optional version number 805 - model-specific hyperparameters, including 806 - metadata about the model, such as the number of layers, the number of heads, etc. 807 - a `ftype` that describes the type of the majority of the tensors, 808 - for GGML files, the quantization version is encoded in the `ftype` divided by 1000 809 - an embedded vocabulary, which is a list of strings with length prepended. The GGMF/GGJT formats embed a float32 score next to the strings. 810 - finally, a list of tensors with their length-prepended name, type, and (aligned, in the case of GGJT) tensor data 811 812 Notably, this structure does not identify what model architecture the model belongs to, nor does it offer any flexibility for changing the structure of the hyperparameters. This means that the only way to add new hyperparameters is to add them to the end of the list, which is a breaking change for existing models. 813 814 ### Drawbacks 815 816 Unfortunately, over the last few months, there are a few issues that have become apparent with the existing models: 817 818 - There's no way to identify which model architecture a given model is for, because that information isn't present 819 - Similarly, existing programs cannot intelligently fail upon encountering new architectures 820 - Adding or removing any new hyperparameters is a breaking change, which is impossible for a reader to detect without using heuristics 821 - Each model architecture requires its own conversion script to their architecture's variant of GGML 822 - Maintaining backwards compatibility without breaking the structure of the format requires clever tricks, like packing the quantization version into the ftype, which are not guaranteed to be picked up by readers/writers, and are not consistent between the two formats 823 824 ### Why not other formats? 825 826 There are a few other formats that could be used, but issues include: 827 828 - requiring additional dependencies to load or save the model, which is complicated in a C environment 829 - limited or no support for 4-bit quantization 830 - existing cultural expectations (e.g. whether or not the model is a directory or a file) 831 - lack of support for embedded vocabularies 832 - lack of control over direction of future development 833 834 Ultimately, it is likely that GGUF will remain necessary for the foreseeable future, and it is better to have a single format that is well-documented and supported by all executors than to contort an existing format to fit the needs of GGML.