gguf.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import * as base from './base.js';
  2. const gguf = {};
  3. gguf.ModelFactory = class {
  4. match(context) {
  5. const reader = gguf.Reader.open(context.stream);
  6. if (reader) {
  7. context.type = 'gguf';
  8. context.target = reader;
  9. }
  10. }
  11. async open(context) {
  12. const target = context.target;
  13. target.read();
  14. return new gguf.Model(target);
  15. }
  16. };
  17. gguf.Model = class {
  18. constructor(target) {
  19. this.format = target.format;
  20. this.metadata = new Map();
  21. const layers = new Map();
  22. for (const [name, tensor] of target.tensors) {
  23. const [key, param] = name.match(/^(.*)\.(.*?)$/).slice(1);
  24. if (!layers.has(key)) {
  25. layers.set(key, { name: key, type: 'weights', metadata: new Map(), weights: new Map() });
  26. }
  27. const layer = layers.get(key);
  28. layer.weights.set(param, tensor);
  29. }
  30. const metadata = new Map();
  31. let architecture = '?';
  32. for (const [name, value] of target.metadata) {
  33. switch (name) {
  34. case 'general.name': this.name = value; break;
  35. case 'general.architecture': architecture = value; break;
  36. case 'general.description': this.description = value; break;
  37. case 'general.author': this.metadata.set('author', value); break;
  38. case 'general.license': this.metadata.set('license', value); break;
  39. case 'general.file_type':
  40. case 'general.quantization_version':
  41. break;
  42. default:
  43. metadata.set(name, value);
  44. break;
  45. }
  46. }
  47. const tokenizer = { type: 'tokenizer', metadata: new Map(), layers: [] };
  48. const model = { type: architecture, metadata: new Map(), layers: Array.from(layers.values()) };
  49. for (const [name, value] of metadata) {
  50. if (name.startsWith('tokenizer.')) {
  51. const [, param] = name.match(/^(.*)\.(.*?)$/).slice(1);
  52. tokenizer.metadata.set(param, value);
  53. } else if (architecture && name.startsWith(`${architecture}.`)) {
  54. model.metadata.set(name, value);
  55. } else {
  56. this.metadata.set(name, value);
  57. }
  58. }
  59. const graph = { layers: [ model ] };
  60. if (tokenizer.metadata.size > 0) {
  61. graph.layers.push(tokenizer);
  62. }
  63. this.graphs = [ new gguf.Graph(graph) ];
  64. }
  65. };
  66. gguf.Graph = class {
  67. constructor(graph) {
  68. this.name = graph.type;
  69. this.nodes = [];
  70. this.inputs = [];
  71. this.outputs = [];
  72. for (const layer of graph.layers) {
  73. const node = new gguf.Node(layer);
  74. this.nodes.push(node);
  75. }
  76. }
  77. };
  78. gguf.Argument = class {
  79. constructor(name, value) {
  80. this.name = name;
  81. this.value = value;
  82. }
  83. };
  84. gguf.Value = class {
  85. constructor(name, tensor) {
  86. this.name = name;
  87. this.type = tensor.type;
  88. this.quantization = tensor.quantization;
  89. this.initializer = tensor;
  90. }
  91. };
  92. gguf.Node = class {
  93. constructor(layer) {
  94. this.type = Array.isArray(layer.layers) && layer.layers.length > 0 ? new gguf.Graph(layer) : { name: layer.type };
  95. this.name = layer.name || '';
  96. this.inputs = [];
  97. this.outputs = [];
  98. this.attributes = [];
  99. if (layer.weights) {
  100. for (const [name, weight] of layer.weights) {
  101. const tensor = new gguf.Tensor(weight);
  102. const value = new gguf.Value(weight.name, tensor);
  103. const argument = new gguf.Argument(name, [ value ]);
  104. this.inputs.push(argument);
  105. }
  106. }
  107. if (layer.metadata) {
  108. for (const [name, value] of layer.metadata) {
  109. const attribute = new gguf.Attribute(name, value);
  110. this.attributes.push(attribute);
  111. }
  112. }
  113. }
  114. };
  115. gguf.Attribute = class {
  116. constructor(name, value) {
  117. this.name = name;
  118. this.value = value;
  119. }
  120. };
  121. gguf.TensorType = class {
  122. constructor(dataType, shape) {
  123. this.dataType = dataType;
  124. this.shape = shape;
  125. }
  126. toString() {
  127. return (this.dataType || '?') + this.shape.toString();
  128. }
  129. };
  130. gguf.TensorShape = class {
  131. constructor(dimensions) {
  132. this.dimensions = dimensions;
  133. }
  134. toString() {
  135. return `[${this.dimensions.map((dimension) => dimension.toString()).join(',')}]`;
  136. }
  137. };
  138. gguf.Tensor = class {
  139. constructor(tensor) {
  140. const shape = new gguf.TensorShape(tensor.ne);
  141. this.type = new gguf.TensorType(tensor.dtype, shape);
  142. if (tensor.type !== gguf.QuantizationType.F32 && tensor.type !== gguf.QuantizationType.F16) {
  143. this.quantization = {
  144. type: gguf.Utility.enum(gguf.QuantizationType, tensor.type).toLowerCase()
  145. };
  146. }
  147. if (tensor.dtype === 'float32' || tensor.dtype === 'float16' ||
  148. tensor.dtype === 'int8' || tensor.dtype === 'int16' || tensor.dtype === 'int32') {
  149. this.encoding = '<';
  150. this._data = tensor.data;
  151. }
  152. }
  153. get values() {
  154. if (this._data) {
  155. return this._data.peek();
  156. }
  157. return null;
  158. }
  159. };
  160. gguf.Reader = class {
  161. static open(stream) {
  162. if (stream && stream.length > 4) {
  163. const signature = String.fromCharCode.apply(null, stream.peek(4));
  164. if (signature === 'GGUF') {
  165. return new gguf.Reader(stream);
  166. }
  167. }
  168. return null;
  169. }
  170. constructor(stream) {
  171. this.stream = stream;
  172. const QK_K = 256;
  173. gguf.Reader.GGML_QUANT_SIZES = gguf.Reader.GGML_QUANT_SIZES || new Map([
  174. [ gguf.QuantizationType.F32, [ 1, 4, 'float32' ] ],
  175. [ gguf.QuantizationType.F16, [ 1, 2, 'float16' ] ],
  176. [ gguf.QuantizationType.Q4_0, [ 32, 2 + 16, '' ] ],
  177. [ gguf.QuantizationType.Q4_1, [ 32, 2 + 2 + 16, '' ] ],
  178. [ gguf.QuantizationType.Q5_0, [ 32, 2 + 4 + 16, '' ] ],
  179. [ gguf.QuantizationType.Q5_1, [ 32, 2 + 2 + 4 + 16, '' ] ],
  180. [ gguf.QuantizationType.Q8_0, [ 32, 2 + 32, ''] ],
  181. [ gguf.QuantizationType.Q8_1, [ 32, 4 + 4 + 32, ''] ],
  182. [ gguf.QuantizationType.Q2_K, [ 256, 2 + 2 + Math.floor(QK_K / 16) + Math.floor(QK_K / 4), '' ] ],
  183. [ gguf.QuantizationType.Q3_K, [ 256, 2 + Math.floor(QK_K / 4) + Math.floor(QK_K / 8) + 12, '' ] ],
  184. [ gguf.QuantizationType.Q4_K, [ 256, 2 + 2 + Math.floor(QK_K / 2) + 12, '' ] ],
  185. [ gguf.QuantizationType.Q5_K, [ 256, 2 + 2 + Math.floor(QK_K / 2) + Math.floor(QK_K / 8) + 12, '' ] ],
  186. [ gguf.QuantizationType.Q6_K, [ 256, 2 + Math.floor(QK_K / 2) + Math.floor(QK_K / 4) + Math.floor(QK_K / 16), '' ] ],
  187. [ gguf.QuantizationType.Q8_K, [ 256, 4 + QK_K + Math.floor(QK_K / 8), '' ] ],
  188. [ gguf.QuantizationType.I8, [ 1, 4, 'int8' ] ],
  189. [ gguf.QuantizationType.I16, [ 1, 2, 'int16' ] ],
  190. [ gguf.QuantizationType.I32, [ 1, 4, 'int32' ] ]
  191. ]);
  192. }
  193. read() {
  194. const reader = new gguf.StreamReader(this.stream);
  195. this.tensors = new Map();
  196. this.metadata = new Map();
  197. const context = {};
  198. context.header = {};
  199. context.header.magic = String.fromCharCode.apply(null, reader.read(4));
  200. context.header.version = reader.uint32();
  201. this.format = `GGUF v${context.header.version}`;
  202. if (context.header.version >= 2) {
  203. context.header.n_tensors = reader.uint64();
  204. context.header.n_kv = reader.uint64();
  205. for (let i = 0; i < context.header.n_kv; i++) {
  206. const entry = reader.entry();
  207. this.metadata.set(entry.name, entry.value);
  208. }
  209. const tensors = context.header.n_tensors;
  210. if (tensors > 0) {
  211. for (let i = 0; i < tensors; i++) {
  212. const tensor = reader.tensor();
  213. this.tensors.set(tensor.name, tensor);
  214. }
  215. context.alignment = this.metadata.get('general.alignment') || 32;
  216. const offset_pad = reader.position % context.alignment;
  217. if (offset_pad != 0) {
  218. reader.skip(context.alignment - offset_pad);
  219. }
  220. context.offset = reader.position;
  221. if (context.offset < this.stream.length) {
  222. for (const tensor of this.tensors.values()) {
  223. reader.seek(context.offset + tensor.offset);
  224. if (!gguf.Reader.GGML_QUANT_SIZES.has(tensor.type)) {
  225. throw new gguf.Error(`Unsupported tensor quantization type '${tensor.type}'.`);
  226. }
  227. const [block_size, type_size, dtype] = gguf.Reader.GGML_QUANT_SIZES.get(tensor.type);
  228. const n_elems = tensor.ne.reduce((a, b) => a * b, 1);
  229. const n_bytes = Math.floor(n_elems * type_size / block_size);
  230. tensor.dtype = dtype || '?';
  231. tensor.data = reader.stream(n_bytes);
  232. }
  233. }
  234. }
  235. }
  236. this.stream.seek(0);
  237. delete this.stream;
  238. }
  239. };
  240. gguf.StreamReader = class extends base.StreamReader {
  241. constructor(stream) {
  242. super(stream);
  243. }
  244. string() {
  245. const size = this.uint64();
  246. const buffer = this.read(size);
  247. return String.fromCharCode.apply(null, buffer);
  248. }
  249. value(type) {
  250. switch (type) {
  251. case gguf.Type.UINT32: {
  252. return this.uint32();
  253. }
  254. case gguf.Type.INT32: {
  255. return this.int32();
  256. }
  257. case gguf.Type.FLOAT32: {
  258. return this.float32();
  259. }
  260. case gguf.Type.BOOL: {
  261. return this.byte() !== 0;
  262. }
  263. case gguf.Type.STRING: {
  264. return this.string();
  265. }
  266. case gguf.Type.ARRAY: {
  267. const type = this.uint32();
  268. const size = this.uint64();
  269. const value = new Array(size);
  270. for (let i = 0; i < size; i++) {
  271. value[i] = this.value(type);
  272. }
  273. return value;
  274. }
  275. default: {
  276. throw new gguf.Error(`Unsupported GGUF type '${type}'.`);
  277. }
  278. }
  279. }
  280. entry() {
  281. const name = this.string();
  282. const type = this.uint32();
  283. const value = this.value(type);
  284. return { name: name, value: value, type: type };
  285. }
  286. tensor() {
  287. const tensor = {};
  288. tensor.name = this.string();
  289. const n_dims = this.uint32();
  290. tensor.ne = new Array(n_dims);
  291. for (let i = 0; i < n_dims; i++) {
  292. tensor.ne[i] = this.uint64();
  293. }
  294. tensor.type = this.uint32();
  295. tensor.offset = this.uint64();
  296. return tensor;
  297. }
  298. };
  299. gguf.Type = {
  300. UINT8: 0,
  301. INT8: 1,
  302. UINT16: 2,
  303. INT16: 3,
  304. UINT32: 4,
  305. INT32: 5,
  306. FLOAT32: 6,
  307. BOOL: 7,
  308. STRING: 8,
  309. ARRAY: 9,
  310. UINT64: 10,
  311. INT64: 11,
  312. FLOAT64: 12,
  313. };
  314. gguf.QuantizationType = {
  315. F32: 0,
  316. F16: 1,
  317. Q4_0: 2,
  318. Q4_1: 3,
  319. Q5_0: 6,
  320. Q5_1: 7,
  321. Q8_0: 8,
  322. Q8_1: 9,
  323. Q2_K: 10,
  324. Q3_K: 11,
  325. Q4_K: 12,
  326. Q5_K: 13,
  327. Q6_K: 14,
  328. Q8_K: 15,
  329. I8: 16,
  330. I16: 17,
  331. I32: 18,
  332. };
  333. gguf.Utility = class {
  334. static enum(type, value) {
  335. gguf.Utility._enums = gguf.Utility._enums || new Map();
  336. if (!gguf.Utility._enums.has(type)) {
  337. const entries = new Map(Object.entries(type).map(([key, value]) => [ value, key ]));
  338. gguf.Utility._enums.set(type, entries);
  339. }
  340. const entires = gguf.Utility._enums.get(type);
  341. if (entires.has(value)) {
  342. return entires.get(value);
  343. }
  344. return value;
  345. }
  346. };
  347. gguf.Error = class extends Error {
  348. constructor(message) {
  349. super(message);
  350. this.name = 'GGML Error';
  351. }
  352. };
  353. export const ModelFactory = gguf.ModelFactory;