bigdl-core-cpp 2.5.0b20240317__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. bigdl/cpp/__init__.py +0 -0
  2. bigdl/cpp/convert.py +1468 -0
  3. bigdl/cpp/libs/baby-llama.exe +0 -0
  4. bigdl/cpp/libs/batched-bench.exe +0 -0
  5. bigdl/cpp/libs/batched.exe +0 -0
  6. bigdl/cpp/libs/beam-search.exe +0 -0
  7. bigdl/cpp/libs/benchmark.exe +0 -0
  8. bigdl/cpp/libs/convert-llama2c-to-ggml.exe +0 -0
  9. bigdl/cpp/libs/embedding.exe +0 -0
  10. bigdl/cpp/libs/export-lora.exe +0 -0
  11. bigdl/cpp/libs/finetune.exe +0 -0
  12. bigdl/cpp/libs/gguf.exe +0 -0
  13. bigdl/cpp/libs/gritlm.exe +0 -0
  14. bigdl/cpp/libs/imatrix.exe +0 -0
  15. bigdl/cpp/libs/infill.exe +0 -0
  16. bigdl/cpp/libs/llama-bench.exe +0 -0
  17. bigdl/cpp/libs/llava-cli.exe +0 -0
  18. bigdl/cpp/libs/lookahead.exe +0 -0
  19. bigdl/cpp/libs/lookup.exe +0 -0
  20. bigdl/cpp/libs/ls-sycl-device.exe +0 -0
  21. bigdl/cpp/libs/main.exe +0 -0
  22. bigdl/cpp/libs/parallel.exe +0 -0
  23. bigdl/cpp/libs/passkey.exe +0 -0
  24. bigdl/cpp/libs/perplexity.exe +0 -0
  25. bigdl/cpp/libs/q8dot.exe +0 -0
  26. bigdl/cpp/libs/quantize-stats.exe +0 -0
  27. bigdl/cpp/libs/quantize.exe +0 -0
  28. bigdl/cpp/libs/save-load-state.exe +0 -0
  29. bigdl/cpp/libs/server.exe +0 -0
  30. bigdl/cpp/libs/simple.exe +0 -0
  31. bigdl/cpp/libs/speculative.exe +0 -0
  32. bigdl/cpp/libs/tokenize.exe +0 -0
  33. bigdl/cpp/libs/train-text-from-scratch.exe +0 -0
  34. bigdl/cpp/libs/vdot.exe +0 -0
  35. bigdl_core_cpp-2.5.0b20240317.data/scripts/init-llama-cpp.bat +15 -0
  36. bigdl_core_cpp-2.5.0b20240317.data/scripts/init-llama-cpp.ps1 +13 -0
  37. bigdl_core_cpp-2.5.0b20240317.dist-info/METADATA +18 -0
  38. bigdl_core_cpp-2.5.0b20240317.dist-info/RECORD +40 -0
  39. bigdl_core_cpp-2.5.0b20240317.dist-info/WHEEL +5 -0
  40. bigdl_core_cpp-2.5.0b20240317.dist-info/top_level.txt +1 -0
bigdl/cpp/convert.py ADDED
@@ -0,0 +1,1468 @@
1
+ #!/usr/bin/env python3
2
+ # this file is copied from https://github.com/ggerganov/llama.cpp/blob/1e35d619a6fb0b9c5e3dc955345980ff056ddbaf/convert.py
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import concurrent.futures
8
+ import enum
9
+ import faulthandler
10
+ import functools
11
+ import itertools
12
+ import json
13
+ import math
14
+ import mmap
15
+ import os
16
+ import pickle
17
+ import re
18
+ import signal
19
+ import struct
20
+ import sys
21
+ import time
22
+ import zipfile
23
+ from abc import ABCMeta, abstractmethod
24
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+ from typing import IO, TYPE_CHECKING, Any, Callable, Iterable, Literal, TypeVar
28
+
29
+ import numpy as np
30
+ from sentencepiece import SentencePieceProcessor
31
+
32
+ if 'NO_LOCAL_GGUF' not in os.environ:
33
+ sys.path.insert(1, str(Path(__file__).parent / 'gguf-py'))
34
+ import gguf
35
+
36
+ if TYPE_CHECKING:
37
+ from typing import TypeAlias
38
+
39
+ if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
40
+ faulthandler.register(signal.SIGUSR1)
41
+
42
+ NDArray: TypeAlias = 'np.ndarray[Any, Any]'
43
+
44
+ ARCH = gguf.MODEL_ARCH.LLAMA
45
+
46
+ DEFAULT_CONCURRENCY = 8
47
+
48
+ #
49
+ # data types
50
+ #
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class DataType:
55
+ name: str
56
+ dtype: np.dtype[Any]
57
+ valid_conversions: list[str]
58
+
59
+ def elements_to_bytes(self, n_elements: int) -> int:
60
+ return n_elements * self.dtype.itemsize
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class UnquantizedDataType(DataType):
65
+ pass
66
+
67
+
68
+ DT_F16 = UnquantizedDataType('F16', dtype = np.dtype(np.float16), valid_conversions = ['F32', 'Q8_0'])
69
+ DT_F32 = UnquantizedDataType('F32', dtype = np.dtype(np.float32), valid_conversions = ['F16', 'Q8_0'])
70
+ DT_I32 = UnquantizedDataType('I32', dtype = np.dtype(np.int16), valid_conversions = [])
71
+ DT_BF16 = UnquantizedDataType('BF16', dtype = np.dtype(np.uint16), valid_conversions = ['F32', 'F16', 'Q8_0'])
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class QuantizedDataType(DataType):
76
+ block_size: int
77
+ quantized_dtype: np.dtype[Any]
78
+ ggml_type: gguf.GGMLQuantizationType
79
+
80
+ def quantize(self, arr: NDArray) -> NDArray:
81
+ raise NotImplementedError(f'Quantization for {self.name} not implemented')
82
+
83
+ def elements_to_bytes(self, n_elements: int) -> int:
84
+ assert n_elements % self.block_size == 0, f'Invalid number of elements {n_elements} for {self.name} with block size {self.block_size}'
85
+ return self.quantized_dtype.itemsize * (n_elements // self.block_size)
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Q8_0QuantizedDataType(QuantizedDataType):
90
+ # Mini Q8_0 quantization in Python!
91
+ def quantize(self, arr: NDArray) -> NDArray:
92
+ assert arr.size % self.block_size == 0 and arr.size != 0, f'Bad array size {arr.size}'
93
+ assert arr.dtype == np.float32, f'Bad array type {arr.dtype}'
94
+ n_blocks = arr.size // self.block_size
95
+ blocks = arr.reshape((n_blocks, self.block_size))
96
+ # Much faster implementation of block quantization contributed by @Cebtenzzre
97
+
98
+ def quantize_blocks_q8_0(blocks: NDArray) -> Iterable[tuple[Any, Any]]:
99
+ d = abs(blocks).max(axis = 1) / np.float32(127)
100
+ with np.errstate(divide = 'ignore'):
101
+ qs = (blocks / d[:, None]).round()
102
+ qs[d == 0] = 0
103
+ yield from zip(d, qs)
104
+ return np.fromiter(quantize_blocks_q8_0(blocks), count = n_blocks, dtype = self.quantized_dtype)
105
+
106
+
107
+ DT_Q8_0 = Q8_0QuantizedDataType('Q8_0',
108
+ dtype = np.dtype(np.float32), valid_conversions = [],
109
+ ggml_type = gguf.GGMLQuantizationType.Q8_0, block_size = 32,
110
+ quantized_dtype = np.dtype([('d', '<f2'), ('qs', 'i1', (32,))]))
111
+
112
+ # Quantized types skipped here because they may also map to np.float32
113
+ NUMPY_TYPE_TO_DATA_TYPE: dict[np.dtype[Any], DataType] = {}
114
+ for dt in (DT_BF16, DT_F16, DT_F32, DT_I32):
115
+ if dt.dtype in NUMPY_TYPE_TO_DATA_TYPE:
116
+ raise ValueError(f'Invalid duplicate data type {dt}')
117
+ NUMPY_TYPE_TO_DATA_TYPE[dt.dtype] = dt
118
+
119
+ SAFETENSORS_DATA_TYPES: dict[str, DataType] = {
120
+ 'BF16': DT_BF16,
121
+ 'F16': DT_F16,
122
+ 'F32': DT_F32,
123
+ 'I32': DT_I32,
124
+ }
125
+
126
+ # TODO: match this with `llama_ftype`
127
+ # TODO: rename to LLAMAFileType
128
+ # TODO: move to `gguf.py`
129
+
130
+
131
+ class GGMLFileType(enum.IntEnum):
132
+ AllF32 = 0
133
+ MostlyF16 = 1 # except 1d tensors
134
+ MostlyQ8_0 = 7 # except 1d tensors
135
+
136
+ def type_for_tensor(self, name: str, tensor: LazyTensor) -> DataType:
137
+ dt = GGML_FILE_TYPE_TO_DATA_TYPE.get(self)
138
+ if dt is None:
139
+ raise ValueError(self)
140
+ # 1D tensors are always F32.
141
+ return dt if len(tensor.shape) > 1 else DT_F32
142
+
143
+
144
+ GGML_FILE_TYPE_TO_DATA_TYPE: dict[GGMLFileType, DataType] = {
145
+ GGMLFileType.AllF32 : DT_F32,
146
+ GGMLFileType.MostlyF16 : DT_F16,
147
+ GGMLFileType.MostlyQ8_0: DT_Q8_0,
148
+ }
149
+
150
+ #
151
+ # hparams loading
152
+ #
153
+
154
+
155
+ @dataclass
156
+ class Params:
157
+ n_vocab: int
158
+ n_embd: int
159
+ n_layer: int
160
+ n_ctx: int
161
+ n_ff: int
162
+ n_head: int
163
+ n_head_kv: int
164
+ n_experts: int | None = None
165
+ n_experts_used: int | None = None
166
+ f_norm_eps: float | None = None
167
+
168
+ rope_scaling_type: gguf.RopeScalingType | None = None
169
+ f_rope_freq_base: float | None = None
170
+ f_rope_scale: float | None = None
171
+ n_orig_ctx: int | None = None
172
+ rope_finetuned: bool | None = None
173
+
174
+ ftype: GGMLFileType | None = None
175
+
176
+ # path to the directory containing the model files
177
+ path_model: Path | None = None
178
+
179
+ @staticmethod
180
+ def guessed(model: LazyModel) -> Params:
181
+ # try transformer naming first
182
+ n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
183
+
184
+ # try transformer naming first
185
+ if "model.layers.0.self_attn.q_proj.weight" in model:
186
+ n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
187
+ elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
188
+ n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
189
+ else:
190
+ n_layer = next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
191
+
192
+ if n_layer < 1:
193
+ raise Exception("failed to guess 'n_layer'. This model is unknown or unsupported.\n"
194
+ "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
195
+
196
+ n_head = n_embd // 128 # guessed
197
+ n_mult = 256 # guessed
198
+
199
+ # TODO: verify this
200
+ n_ff = int(2 * (4 * n_embd) / 3)
201
+ n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
202
+
203
+ return Params(
204
+ n_vocab = n_vocab,
205
+ n_embd = n_embd,
206
+ n_layer = n_layer,
207
+ n_ctx = -1,
208
+ n_ff = n_ff,
209
+ n_head = n_head,
210
+ n_head_kv = n_head,
211
+ f_norm_eps = 1e-5,
212
+ )
213
+
214
+ @staticmethod
215
+ def loadHFTransformerJson(model: LazyModel, config_path: Path) -> Params:
216
+ config = json.load(open(config_path))
217
+
218
+ rope_scaling_type = f_rope_scale = n_orig_ctx = rope_finetuned = None
219
+ rope_scaling = config.get("rope_scaling")
220
+
221
+ if rope_scaling is not None and (typ := rope_scaling.get("type")):
222
+ rope_factor = rope_scaling.get("factor")
223
+ f_rope_scale = rope_factor
224
+ if typ == "linear":
225
+ rope_scaling_type = gguf.RopeScalingType.LINEAR
226
+ elif typ == "yarn":
227
+ rope_scaling_type = gguf.RopeScalingType.YARN
228
+ n_orig_ctx = rope_scaling['original_max_position_embeddings']
229
+ rope_finetuned = rope_scaling['finetuned']
230
+ else:
231
+ raise NotImplementedError(f'Unknown rope scaling type: {typ}')
232
+
233
+ if "max_sequence_length" in config:
234
+ n_ctx = config["max_sequence_length"]
235
+ elif "max_position_embeddings" in config:
236
+ n_ctx = config["max_position_embeddings"]
237
+ else:
238
+ raise Exception("failed to guess 'n_ctx'. This model is unknown or unsupported.\n"
239
+ "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
240
+
241
+ n_experts = None
242
+ n_experts_used = None
243
+
244
+ if "num_local_experts" in config:
245
+ n_experts = config["num_local_experts"]
246
+ n_experts_used = config["num_experts_per_tok"]
247
+
248
+ return Params(
249
+ n_vocab = config["vocab_size"],
250
+ n_embd = config["hidden_size"],
251
+ n_layer = config["num_hidden_layers"],
252
+ n_ctx = n_ctx,
253
+ n_ff = config["intermediate_size"],
254
+ n_head = (n_head := config["num_attention_heads"]),
255
+ n_head_kv = config.get("num_key_value_heads", n_head),
256
+ n_experts = n_experts,
257
+ n_experts_used = n_experts_used,
258
+ f_norm_eps = config["rms_norm_eps"],
259
+ f_rope_freq_base = config.get("rope_theta"),
260
+ rope_scaling_type = rope_scaling_type,
261
+ f_rope_scale = f_rope_scale,
262
+ n_orig_ctx = n_orig_ctx,
263
+ rope_finetuned = rope_finetuned,
264
+ )
265
+
266
+ # LLaMA v2 70B params.json
267
+ # {"dim": 8192, "multiple_of": 4096, "ffn_dim_multiplier": 1.3, "n_heads": 64, "n_kv_heads": 8, "n_layers": 80, "norm_eps": 1e-05, "vocab_size": -1}
268
+ @staticmethod
269
+ def loadOriginalParamsJson(model: LazyModel, config_path: Path) -> Params:
270
+ config = json.load(open(config_path))
271
+
272
+ n_experts = None
273
+ n_experts_used = None
274
+ f_rope_freq_base = None
275
+
276
+ # hack to determine LLaMA v1 vs v2 vs CodeLlama
277
+ if config.get("moe"):
278
+ # Mixtral
279
+ n_ctx = 32768
280
+ elif config.get("rope_theta") == 1000000:
281
+ # CodeLlama
282
+ n_ctx = 16384
283
+ elif config["norm_eps"] == 1e-05:
284
+ # LLaMA v2
285
+ n_ctx = 4096
286
+ else:
287
+ # LLaMA v1
288
+ n_ctx = 2048
289
+
290
+ if "layers.0.feed_forward.w1.weight" in model:
291
+ n_ff = model["layers.0.feed_forward.w1.weight"].shape[0]
292
+
293
+ if config.get("moe"):
294
+ n_ff = model["layers.0.feed_forward.experts.0.w1.weight"].shape[0]
295
+ n_experts = config["moe"]["num_experts"]
296
+ n_experts_used = config["moe"]["num_experts_per_tok"]
297
+ f_rope_freq_base = 1e6
298
+
299
+ return Params(
300
+ n_vocab = model["tok_embeddings.weight"].shape[0],
301
+ n_embd = config["dim"],
302
+ n_layer = config["n_layers"],
303
+ n_ctx = n_ctx,
304
+ n_ff = n_ff,
305
+ n_head = (n_head := config["n_heads"]),
306
+ n_head_kv = config.get("n_kv_heads", n_head),
307
+ n_experts = n_experts,
308
+ n_experts_used = n_experts_used,
309
+ f_norm_eps = config["norm_eps"],
310
+ f_rope_freq_base = config.get("rope_theta", f_rope_freq_base),
311
+ )
312
+
313
+ @staticmethod
314
+ def load(model_plus: ModelPlus) -> Params:
315
+ hf_config_path = model_plus.paths[0].parent / "config.json"
316
+ orig_config_path = model_plus.paths[0].parent / "params.json"
317
+
318
+ if hf_config_path.exists():
319
+ params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
320
+ elif orig_config_path.exists():
321
+ params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
322
+ elif model_plus.format != 'none':
323
+ params = Params.guessed(model_plus.model)
324
+ else:
325
+ raise ValueError('Cannot guess params when model format is none')
326
+
327
+ params.path_model = model_plus.paths[0].parent
328
+
329
+ return params
330
+
331
+
332
+ #
333
+ # vocab
334
+ #
335
+
336
+ class BpeVocab:
337
+ def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
338
+ self.bpe_tokenizer = json.loads(open(str(fname_tokenizer), encoding="utf-8").read())
339
+ if isinstance(self.bpe_tokenizer.get('model'), dict):
340
+ self.vocab = self.bpe_tokenizer["model"]["vocab"]
341
+ else:
342
+ self.vocab = self.bpe_tokenizer
343
+ added_tokens: dict[str, int]
344
+ if fname_added_tokens is not None:
345
+ # FIXME: Verify that added tokens here _cannot_ overlap with the main vocab.
346
+ added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
347
+ else:
348
+ # Fall back to trying to find the added tokens in tokenizer.json
349
+ tokenizer_json_file = fname_tokenizer.parent / 'tokenizer.json'
350
+ if not tokenizer_json_file.is_file():
351
+ added_tokens = {}
352
+ else:
353
+ tokenizer_json = json.load(open(tokenizer_json_file, encoding="utf-8"))
354
+ added_tokens = dict(
355
+ (item['content'], item['id'])
356
+ for item in tokenizer_json.get('added_tokens', [])
357
+ # Added tokens here can be duplicates of the main vocabulary.
358
+ if item['content'] not in self.bpe_tokenizer)
359
+
360
+ vocab_size: int = len(self.vocab)
361
+ expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
362
+ actual_ids = sorted(added_tokens.values())
363
+ if expected_ids != actual_ids:
364
+ expected_end_id = vocab_size + len(actual_ids) - 1
365
+ raise Exception(f"Expected the {len(actual_ids)} added token ID(s) to be sequential in the range {vocab_size} - {expected_end_id}; got {actual_ids}")
366
+
367
+ items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
368
+ self.added_tokens_dict = added_tokens
369
+ self.added_tokens_list = [text for (text, idx) in items]
370
+ self.vocab_size_base: int = vocab_size
371
+ self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
372
+ self.fname_tokenizer = fname_tokenizer
373
+ self.fname_added_tokens = fname_added_tokens
374
+
375
+ def bpe_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
376
+ reverse_vocab = {id: encoded_tok for encoded_tok, id in self.vocab.items()}
377
+
378
+ for i, _ in enumerate(self.vocab):
379
+ yield reverse_vocab[i], 0.0, gguf.TokenType.NORMAL
380
+
381
+ def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
382
+ for text in self.added_tokens_list:
383
+ score = -1000.0
384
+ yield text.encode("utf-8"), score, gguf.TokenType.CONTROL
385
+
386
+ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
387
+ yield from self.bpe_tokens()
388
+ yield from self.added_tokens()
389
+
390
+ def __repr__(self) -> str:
391
+ return f"<BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
392
+
393
+
394
+ class SentencePieceVocab:
395
+ def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
396
+ self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
397
+ added_tokens: dict[str, int]
398
+ if fname_added_tokens is not None:
399
+ added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
400
+ else:
401
+ added_tokens = {}
402
+
403
+ vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
404
+
405
+ new_tokens = {id: piece for piece, id in added_tokens.items() if id >= vocab_size}
406
+ expected_new_ids = list(range(vocab_size, vocab_size + len(new_tokens)))
407
+ actual_new_ids = sorted(new_tokens.keys())
408
+
409
+ if expected_new_ids != actual_new_ids:
410
+ raise ValueError(f"Expected new token IDs {expected_new_ids} to be sequential; got {actual_new_ids}")
411
+
412
+ # Token pieces that were added to the base vocabulary.
413
+ self.added_tokens_dict = added_tokens
414
+ self.added_tokens_list = [new_tokens[id] for id in actual_new_ids]
415
+ self.vocab_size_base = vocab_size
416
+ self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
417
+ self.fname_tokenizer = fname_tokenizer
418
+ self.fname_added_tokens = fname_added_tokens
419
+
420
+ def sentencepiece_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
421
+ tokenizer = self.sentencepiece_tokenizer
422
+ for i in range(tokenizer.vocab_size()):
423
+ piece = tokenizer.id_to_piece(i)
424
+ text: bytes = piece.encode("utf-8")
425
+ score: float = tokenizer.get_score(i)
426
+
427
+ toktype = gguf.TokenType.NORMAL
428
+ if tokenizer.is_unknown(i):
429
+ toktype = gguf.TokenType.UNKNOWN
430
+ if tokenizer.is_control(i):
431
+ toktype = gguf.TokenType.CONTROL
432
+
433
+ # NOTE: I think added_tokens are user defined.
434
+ # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
435
+ # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
436
+
437
+ if tokenizer.is_unused(i):
438
+ toktype = gguf.TokenType.UNUSED
439
+ if tokenizer.is_byte(i):
440
+ toktype = gguf.TokenType.BYTE
441
+
442
+ yield text, score, toktype
443
+
444
+ def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
445
+ for text in self.added_tokens_list:
446
+ score = -1000.0
447
+ yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
448
+
449
+ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
450
+ yield from self.sentencepiece_tokens()
451
+ yield from self.added_tokens()
452
+
453
+ def __repr__(self) -> str:
454
+ return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
455
+
456
+
457
+ class HfVocab:
458
+ def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None = None) -> None:
459
+ try:
460
+ from transformers import AutoTokenizer
461
+ except ImportError as e:
462
+ raise ImportError(
463
+ "To use HfVocab, please install the `transformers` package. "
464
+ "You can install it with `pip install transformers`."
465
+ ) from e
466
+
467
+ print("fname_tokenizer:", fname_tokenizer)
468
+ # Allow the tokenizer to default to slow or fast versions.
469
+ # Explicitly set tokenizer to use local paths.
470
+ self.tokenizer = AutoTokenizer.from_pretrained(
471
+ fname_tokenizer,
472
+ cache_dir=fname_tokenizer,
473
+ local_files_only=True,
474
+ )
475
+
476
+ # Initialize lists and dictionaries for added tokens
477
+ self.added_tokens_list = []
478
+ self.added_tokens_dict = dict()
479
+ self.added_tokens_ids = set()
480
+
481
+ # Process added tokens
482
+ for tok, tokidx in sorted(
483
+ self.tokenizer.get_added_vocab().items(), key=lambda x: x[1]
484
+ ):
485
+ # Only consider added tokens that are not in the base vocabulary
486
+ if tokidx >= self.tokenizer.vocab_size:
487
+ self.added_tokens_list.append(tok)
488
+ self.added_tokens_dict[tok] = tokidx
489
+ self.added_tokens_ids.add(tokidx)
490
+
491
+ # Store special tokens and their IDs
492
+ self.specials = {
493
+ tok: self.tokenizer.get_vocab()[tok]
494
+ for tok in self.tokenizer.all_special_tokens
495
+ }
496
+ self.special_ids = set(self.tokenizer.all_special_ids)
497
+
498
+ # Set vocabulary sizes
499
+ self.vocab_size_base = self.tokenizer.vocab_size
500
+ self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
501
+
502
+ self.fname_tokenizer = fname_tokenizer
503
+ self.fname_added_tokens = fname_added_tokens
504
+
505
+ def hf_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
506
+ reverse_vocab = {
507
+ id: encoded_tok for encoded_tok, id in self.tokenizer.get_vocab().items()
508
+ }
509
+
510
+ for token_id in range(self.vocab_size_base):
511
+ # Skip processing added tokens here
512
+ if token_id in self.added_tokens_ids:
513
+ continue
514
+
515
+ # Convert token text to bytes
516
+ token_text = reverse_vocab[token_id].encode("utf-8")
517
+
518
+ # Yield token text, score, and type
519
+ yield token_text, self.get_token_score(token_id), self.get_token_type(
520
+ token_id, token_text, self.special_ids # Reuse already stored special IDs
521
+ )
522
+
523
+ def get_token_type(self, token_id: int, token_text: bytes, special_ids: set[int]) -> gguf.TokenType:
524
+ # Special case for byte tokens
525
+ if re.fullmatch(br"<0x[0-9A-Fa-f]{2}>", token_text):
526
+ return gguf.TokenType.BYTE
527
+
528
+ # Determine token type based on whether it's a special token
529
+ return gguf.TokenType.CONTROL if token_id in special_ids else gguf.TokenType.NORMAL
530
+
531
+ def get_token_score(self, token_id: int) -> float:
532
+ # Placeholder for actual logic to determine the token's score
533
+ # This needs to be implemented based on specific requirements
534
+ return -1000.0 # Default score
535
+
536
+ def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
537
+ for text in self.added_tokens_list:
538
+ if text in self.specials:
539
+ toktype = self.get_token_type(self.specials[text], b'', self.special_ids)
540
+ score = self.get_token_score(self.specials[text])
541
+ else:
542
+ toktype = gguf.TokenType.USER_DEFINED
543
+ score = -1000.0
544
+
545
+ yield text.encode("utf-8"), score, toktype
546
+
547
+ def has_newline_token(self):
548
+ return "<0x0A>" in self.tokenizer.vocab or "\n" in self.tokenizer.vocab
549
+
550
+ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
551
+ yield from self.hf_tokens()
552
+ yield from self.added_tokens()
553
+
554
+ def __repr__(self) -> str:
555
+ return f"<HfVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
556
+
557
+
558
+ Vocab: TypeAlias = "BpeVocab | SentencePieceVocab | HfVocab"
559
+
560
+
561
+ #
562
+ # data loading
563
+ # TODO: reuse (probably move to gguf.py?)
564
+ #
565
+
566
+
567
+ def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
568
+ # print( "permute debug " + str(weights.shape[0]) + " x " + str(weights.shape[1]) + " nhead " + str(n_head) + " nheadkv " + str(n_kv_head) )
569
+ if n_head_kv is not None and n_head != n_head_kv:
570
+ n_head = n_head_kv
571
+ return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
572
+ .swapaxes(1, 2)
573
+ .reshape(weights.shape))
574
+
575
+
576
+ class Tensor(metaclass=ABCMeta):
577
+ data_type: DataType
578
+
579
+ @abstractmethod
580
+ def astype(self, data_type: DataType) -> Tensor: ...
581
+ @abstractmethod
582
+ def permute(self, n_head: int, n_head_kv: int) -> Tensor: ...
583
+ @abstractmethod
584
+ def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor: ...
585
+ @abstractmethod
586
+ def part(self, n_part: int) -> UnquantizedTensor: ...
587
+ @abstractmethod
588
+ def to_ggml(self) -> GGMLCompatibleTensor: ...
589
+
590
+
591
+ def bf16_to_fp32(bf16_arr: np.ndarray[Any, np.dtype[np.uint16]]) -> NDArray:
592
+ assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
593
+ fp32_arr = bf16_arr.astype(np.uint32) << 16
594
+ return fp32_arr.view(np.float32)
595
+
596
+
597
+ class UnquantizedTensor(Tensor):
598
+ def __init__(self, ndarray: NDArray) -> None:
599
+ assert isinstance(ndarray, np.ndarray)
600
+ self.ndarray = ndarray
601
+ self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
602
+
603
+ def astype(self, data_type: DataType) -> Tensor:
604
+ dtype = data_type.dtype
605
+ if self.data_type == DT_BF16:
606
+ self.ndarray = bf16_to_fp32(self.ndarray)
607
+ return UnquantizedTensor(self.ndarray.astype(dtype))
608
+
609
+ def to_ggml(self) -> UnquantizedTensor:
610
+ return self
611
+
612
+ def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor:
613
+ r = self.ndarray.shape[0] // 3
614
+ return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head, n_head_kv))
615
+
616
+ def part(self, n_part: int) -> UnquantizedTensor:
617
+ r = self.ndarray.shape[0] // 3
618
+ return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
619
+
620
+ def permute(self, n_head: int, n_head_kv: int) -> UnquantizedTensor:
621
+ return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
622
+
623
+
624
+ def load_unquantized(lazy_tensor: LazyTensor, expected_dtype: Any = None, convert: bool = False) -> NDArray:
625
+ tensor = lazy_tensor.load()
626
+ assert isinstance(tensor, UnquantizedTensor)
627
+
628
+ # double-check:
629
+ actual_shape = list(tensor.ndarray.shape)
630
+ assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
631
+ if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
632
+ if convert:
633
+ tensor.ndarray = tensor.ndarray.astype(expected_dtype)
634
+ else:
635
+ raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
636
+
637
+ return tensor.ndarray
638
+
639
+
640
+ GGMLCompatibleTensor = UnquantizedTensor
641
+
642
+
643
+ @dataclass
644
+ class LazyTensor:
645
+ _load: Callable[[], Tensor]
646
+ shape: list[int]
647
+ data_type: DataType
648
+ description: str
649
+
650
+ def load(self) -> Tensor:
651
+ ret = self._load()
652
+ # Should be okay if it maps to the same numpy type?
653
+ assert ret.data_type == self.data_type or (self.data_type.dtype == ret.data_type.dtype), \
654
+ (self.data_type, ret.data_type, self.description)
655
+ return ret
656
+
657
+ def astype(self, data_type: DataType) -> LazyTensor:
658
+ self.validate_conversion_to(data_type)
659
+
660
+ def load() -> Tensor:
661
+ return self.load().astype(data_type)
662
+ return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
663
+
664
+ def validate_conversion_to(self, data_type: DataType) -> None:
665
+ if data_type != self.data_type and data_type.name not in self.data_type.valid_conversions:
666
+ raise ValueError(f'Cannot validate conversion from {self.data_type} to {data_type}.')
667
+
668
+
669
+ LazyModel: TypeAlias = 'dict[str, LazyTensor]'
670
+
671
+
672
+ @dataclass
673
+ class ModelPlus:
674
+ model: LazyModel
675
+ paths: list[Path] # Where this was read from.
676
+ format: Literal['ggml', 'torch', 'safetensors', 'none']
677
+ vocab: Vocab | None # For GGML models (which have vocab built in), the vocab.
678
+
679
+
680
+ def merge_sharded(models: list[LazyModel]) -> LazyModel:
681
+ # Original LLaMA models have each file contain one part of each tensor.
682
+ # Use a dict instead of a set to preserve order.
683
+ names = {name: None for model in models for name in model}
684
+
685
+ def convert(name: str) -> LazyTensor:
686
+ lazy_tensors: list[LazyTensor] = [model[name] for model in models]
687
+ if len(lazy_tensors) == 1:
688
+ # only one file; don't go through this procedure since there might
689
+ # be quantized tensors
690
+ return lazy_tensors[0]
691
+ if len(lazy_tensors[0].shape) == 1:
692
+ # the tensor is just duplicated in every file
693
+ return lazy_tensors[0]
694
+ if name.startswith('tok_embeddings.') or \
695
+ name.endswith('.attention.wo.weight') or \
696
+ name.endswith('.feed_forward.w2.weight'):
697
+ # split by columns
698
+ axis = 1
699
+ else:
700
+ # split by rows
701
+ axis = 0
702
+ concatenated_shape = list(lazy_tensors[0].shape)
703
+ concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
704
+
705
+ def load() -> UnquantizedTensor:
706
+ ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
707
+ concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
708
+ return UnquantizedTensor(concatenated)
709
+ description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
710
+ return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
711
+ return {name: convert(name) for name in names}
712
+
713
+
714
+ def merge_multifile_models(models_plus: list[ModelPlus]) -> ModelPlus:
715
+ formats = set(mp.format for mp in models_plus)
716
+ assert len(formats) == 1, "different formats?"
717
+ format = formats.pop()
718
+ paths = [path for mp in models_plus for path in mp.paths]
719
+ # Use the first non-None vocab, if any.
720
+ try:
721
+ vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
722
+ except StopIteration:
723
+ vocab = None
724
+
725
+ if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
726
+ # Transformers models put different tensors in different files, but
727
+ # don't split individual tensors between files.
728
+ model: LazyModel = {}
729
+ for mp in models_plus:
730
+ model.update(mp.model)
731
+ else:
732
+ model = merge_sharded([mp.model for mp in models_plus])
733
+
734
+ return ModelPlus(model, paths, format, vocab) # pytype: disable=wrong-arg-types
735
+
736
+
737
+ def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
738
+ def load() -> Tensor:
739
+ return lazy_tensor.load().permute(n_head, n_head_kv)
740
+ return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
741
+
742
+
743
+ def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int, n_head_kv: int) -> LazyTensor:
744
+ def load() -> Tensor:
745
+ return lazy_tensor.load().permute_part(n_part, n_head, n_head_kv)
746
+ s = lazy_tensor.shape.copy()
747
+ s[0] = s[0] // 3
748
+ return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
749
+
750
+
751
+ def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
752
+ def load() -> Tensor:
753
+ return lazy_tensor.load().part(n_part)
754
+ s = lazy_tensor.shape.copy()
755
+ s[0] = s[0] // 3
756
+ return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
757
+
758
+
759
+ # Functionality that simulates `torch.load` but where individual tensors are
760
+ # only loaded into memory on demand, not all at once.
761
+ # PyTorch can't do this natively as of time of writing:
762
+ # - https://github.com/pytorch/pytorch/issues/64327
763
+ # This allows us to de-shard without multiplying RAM usage, and also
764
+ # conveniently drops the PyTorch dependency (though we still need numpy).
765
+
766
+
767
+ @dataclass
768
+ class LazyStorageKind:
769
+ data_type: DataType
770
+
771
+
772
+ @dataclass
773
+ class LazyStorage:
774
+ load: Callable[[int, int], NDArray]
775
+ kind: LazyStorageKind
776
+ description: str
777
+
778
+
779
+ class LazyUnpickler(pickle.Unpickler):
780
+ def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
781
+ super().__init__(fp)
782
+ self.data_base_path = data_base_path
783
+ self.zip_file = zip_file
784
+
785
+ def persistent_load(self, pid: Any) -> Any:
786
+ assert pid[0] == 'storage'
787
+ assert isinstance(pid[1], LazyStorageKind)
788
+ data_type = pid[1].data_type
789
+ filename_stem = pid[2]
790
+ filename = f'{self.data_base_path}/{filename_stem}'
791
+ info = self.zip_file.getinfo(filename)
792
+
793
+ def load(offset: int, elm_count: int) -> NDArray:
794
+ dtype = data_type.dtype
795
+ fp = self.zip_file.open(info)
796
+ fp.seek(offset * dtype.itemsize)
797
+ size = elm_count * dtype.itemsize
798
+ data = fp.read(size)
799
+ assert len(data) == size
800
+ return np.frombuffer(data, dtype)
801
+ description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
802
+ return LazyStorage(load=load, kind=pid[1], description=description)
803
+
804
+ @staticmethod
805
+ def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
806
+ requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
807
+ assert isinstance(storage, LazyStorage)
808
+
809
+ def load() -> UnquantizedTensor:
810
+ elm_count = stride[0] * size[0]
811
+ return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
812
+ description = f'pickled storage_offset={storage_offset} in {storage.description}'
813
+ return LazyTensor(load, list(size), storage.kind.data_type, description)
814
+
815
+ @staticmethod
816
+ def rebuild_from_type_v2(func, new_type, args, state):
817
+ return func(*args)
818
+
819
+ CLASSES: dict[tuple[str, str], Any] = {
820
+ # getattr used here as a workaround for mypy not being smart enough to determine
821
+ # the staticmethods have a __func__ attribute.
822
+ ('torch._tensor', '_rebuild_from_type_v2'): getattr(rebuild_from_type_v2, '__func__'),
823
+ ('torch._utils', '_rebuild_tensor_v2'): getattr(lazy_rebuild_tensor_v2, '__func__'),
824
+ ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
825
+ ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
826
+ ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
827
+ ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
828
+ ('torch', 'Tensor'): LazyTensor,
829
+ }
830
+
831
+ def find_class(self, module: str, name: str) -> Any:
832
+ if not module.startswith('torch'):
833
+ return super().find_class(module, name)
834
+ return self.CLASSES[(module, name)]
835
+
836
+
837
+ def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
838
+ zf = zipfile.ZipFile(outer_fp)
839
+ pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
840
+ assert len(pickle_paths) == 1, pickle_paths
841
+ pickle_fp = zf.open(pickle_paths[0], 'r')
842
+ unpickler = LazyUnpickler(pickle_fp,
843
+ data_base_path=pickle_paths[0][:-4],
844
+ zip_file=zf)
845
+ model = unpickler.load()
846
+ if 'model' in model: model = model['model']
847
+ as_dict = dict(model.items())
848
+ return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
849
+
850
+
851
+ def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
852
+ header_size, = struct.unpack('<Q', fp.read(8))
853
+ header: dict[str, dict[str, Any]] = json.loads(fp.read(header_size))
854
+ # Use mmap for the actual data to avoid race conditions with the file offset.
855
+ mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
856
+ byte_buf = mapped[8 + header_size:]
857
+
858
+ def convert(info: dict[str, Any]) -> LazyTensor:
859
+ data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
860
+ numpy_dtype = data_type.dtype
861
+ shape: list[int] = info['shape']
862
+ begin, end = info['data_offsets']
863
+ assert 0 <= begin <= end <= len(byte_buf)
864
+ assert end - begin == math.prod(shape) * numpy_dtype.itemsize
865
+ buf = byte_buf[begin:end]
866
+
867
+ def load() -> UnquantizedTensor:
868
+ return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
869
+ description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
870
+ return LazyTensor(load, shape, data_type, description)
871
+ model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
872
+ return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
873
+
874
+
875
+ def must_read(fp: IO[bytes], length: int) -> bytes:
876
+ ret = fp.read(length)
877
+ if len(ret) < length:
878
+ raise Exception("unexpectedly reached end of file")
879
+ return ret
880
+
881
+
882
+ @functools.lru_cache(maxsize=None)
883
+ def lazy_load_file(path: Path) -> ModelPlus:
884
+ fp = open(path, 'rb')
885
+ first8 = fp.read(8)
886
+ fp.seek(0)
887
+ if first8[:2] == b'PK':
888
+ # A zip file, i.e. PyTorch format
889
+ return lazy_load_torch_file(fp, path)
890
+ elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
891
+ # Probably safetensors
892
+ return lazy_load_safetensors_file(fp, path)
893
+ else:
894
+ raise ValueError(f"unknown format: {path}")
895
+
896
+
897
+ In = TypeVar('In')
898
+ Out = TypeVar('Out')
899
+
900
+
901
+ def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False) -> Iterable[Out]:
902
+ '''Parallel map, but with backpressure. If the caller doesn't call `next`
903
+ fast enough, this will stop calling `func` at some point rather than
904
+ letting results pile up in memory. Specifically, there is a max of one
905
+ output value buffered per thread.'''
906
+ if concurrency < 2:
907
+ yield from map(func, iterable)
908
+ # Not reached.
909
+ iterable = iter(iterable)
910
+ executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor]
911
+ if use_processpool_executor:
912
+ executor_class = ProcessPoolExecutor
913
+ else:
914
+ executor_class = ThreadPoolExecutor
915
+ with executor_class(max_workers=max_workers) as executor:
916
+ futures: list[concurrent.futures.Future[Out]] = []
917
+ done = False
918
+ for _ in range(concurrency):
919
+ try:
920
+ futures.append(executor.submit(func, next(iterable)))
921
+ except StopIteration:
922
+ done = True
923
+ break
924
+
925
+ while futures:
926
+ result = futures.pop(0).result()
927
+ while not done and len(futures) < concurrency:
928
+ try:
929
+ futures.append(executor.submit(func, next(iterable)))
930
+ except StopIteration:
931
+ done = True
932
+ break
933
+ yield result
934
+
935
+
936
+ def check_vocab_size(params: Params, vocab: Vocab, pad_vocab: bool = False) -> None:
937
+ # Handle special case where the model's vocab size is not set
938
+ if params.n_vocab == -1:
939
+ raise ValueError(
940
+ f"The model's vocab size is set to -1 in params.json. Please update it manually. Maybe {vocab.vocab_size}?"
941
+ )
942
+
943
+ # Check for a vocab size mismatch
944
+ if params.n_vocab == vocab.vocab_size:
945
+ print("Ignoring added_tokens.json since model matches vocab size without it.")
946
+ return
947
+
948
+ if pad_vocab and params.n_vocab > vocab.vocab_size:
949
+ pad_count = params.n_vocab - vocab.vocab_size
950
+ print(
951
+ f"Padding vocab with {pad_count} token(s) - <dummy00001> through <dummy{pad_count:05}>"
952
+ )
953
+ for i in range(1, pad_count + 1):
954
+ vocab.added_tokens_dict[f"<dummy{i:05}>"] = -1
955
+ vocab.added_tokens_list.append(f"<dummy{i:05}>")
956
+ vocab.vocab_size = params.n_vocab
957
+ return
958
+
959
+ msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer} has {vocab.vocab_size})."
960
+ if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20:
961
+ msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
962
+ if vocab.vocab_size < params.n_vocab:
963
+ msg += " Add the --pad-vocab option and try again."
964
+
965
+ raise Exception(msg)
966
+
967
+
968
+ class OutputFile:
969
+ def __init__(self, fname_out: Path, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE) -> None:
970
+ self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH], endianess=endianess)
971
+
972
+ def add_meta_arch(self, params: Params) -> None:
973
+ name = "LLaMA"
974
+
975
+ # TODO: better logic to determine model name
976
+ if params.n_ctx == 4096:
977
+ name = "LLaMA v2"
978
+ elif params.path_model is not None:
979
+ name = str(params.path_model.parent).split('/')[-1]
980
+
981
+ self.gguf.add_name (name)
982
+ self.gguf.add_context_length (params.n_ctx)
983
+ self.gguf.add_embedding_length (params.n_embd)
984
+ self.gguf.add_block_count (params.n_layer)
985
+ self.gguf.add_feed_forward_length (params.n_ff)
986
+ self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
987
+ self.gguf.add_head_count (params.n_head)
988
+ self.gguf.add_head_count_kv (params.n_head_kv)
989
+
990
+ if params.n_experts:
991
+ self.gguf.add_expert_count(params.n_experts)
992
+
993
+ if params.n_experts_used:
994
+ self.gguf.add_expert_used_count(params.n_experts_used)
995
+
996
+ if params.f_norm_eps:
997
+ self.gguf.add_layer_norm_rms_eps(params.f_norm_eps)
998
+ else:
999
+ raise ValueError('f_norm_eps is None')
1000
+
1001
+ if params.f_rope_freq_base is not None:
1002
+ self.gguf.add_rope_freq_base(params.f_rope_freq_base)
1003
+
1004
+ if params.rope_scaling_type:
1005
+ assert params.f_rope_scale is not None
1006
+ self.gguf.add_rope_scaling_type(params.rope_scaling_type)
1007
+ self.gguf.add_rope_scaling_factor(params.f_rope_scale)
1008
+
1009
+ if params.n_orig_ctx is not None:
1010
+ self.gguf.add_rope_scaling_orig_ctx_len(params.n_orig_ctx)
1011
+
1012
+ if params.rope_finetuned is not None:
1013
+ self.gguf.add_rope_scaling_finetuned(params.rope_finetuned)
1014
+
1015
+ if params.ftype is not None:
1016
+ self.gguf.add_file_type(params.ftype)
1017
+
1018
+ def handle_tokenizer_model(self, vocab: Vocab) -> str:
1019
+ # Map the vocab types to the supported tokenizer models
1020
+ tokenizer_model = {
1021
+ SentencePieceVocab: "llama",
1022
+ HfVocab: "llama",
1023
+ BpeVocab: "gpt2",
1024
+ }.get(type(vocab))
1025
+
1026
+ # Block if vocab type is not predefined
1027
+ if tokenizer_model is None:
1028
+ raise ValueError("Unknown vocab type: Not supported")
1029
+
1030
+ return tokenizer_model
1031
+
1032
+ def extract_vocabulary_from_model(self, vocab: Vocab) -> tuple[list[bytes], list[float], list[gguf.TokenType]]:
1033
+ tokens = []
1034
+ scores = []
1035
+ toktypes = []
1036
+
1037
+ # NOTE: `all_tokens` returns the base vocabulary and added tokens
1038
+ for text, score, toktype in vocab.all_tokens():
1039
+ tokens.append(text)
1040
+ scores.append(score)
1041
+ toktypes.append(toktype)
1042
+
1043
+ assert len(tokens) == vocab.vocab_size
1044
+
1045
+ return tokens, scores, toktypes
1046
+
1047
+ def add_meta_vocab(self, vocab: Vocab) -> None:
1048
+ # Handle the tokenizer model
1049
+ tokenizer_model = self.handle_tokenizer_model(vocab)
1050
+
1051
+ # Ensure that tokenizer_model is added to the GGUF model
1052
+ self.gguf.add_tokenizer_model(tokenizer_model)
1053
+
1054
+ # Extract model vocabulary for model conversion
1055
+ tokens, scores, toktypes = self.extract_vocabulary_from_model(vocab)
1056
+
1057
+ # Add extracted token information for model conversion
1058
+ self.gguf.add_token_list(tokens)
1059
+ self.gguf.add_token_scores(scores)
1060
+ self.gguf.add_token_types(toktypes)
1061
+
1062
+ def add_meta_special_vocab(self, svocab: gguf.SpecialVocab) -> None:
1063
+ svocab.add_to_gguf(self.gguf)
1064
+
1065
+ def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
1066
+ n_elements = int(np.prod(tensor.shape))
1067
+ raw_dtype = getattr(tensor.data_type, 'ggml_type', None)
1068
+ data_type = getattr(tensor.data_type, 'quantized_type', None) or tensor.data_type.dtype
1069
+ data_nbytes = tensor.data_type.elements_to_bytes(n_elements)
1070
+ self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes, raw_dtype=raw_dtype)
1071
+
1072
+ def write_meta(self) -> None:
1073
+ self.gguf.write_header_to_file()
1074
+ self.gguf.write_kv_data_to_file()
1075
+
1076
+ def write_tensor_info(self) -> None:
1077
+ self.gguf.write_ti_data_to_file()
1078
+
1079
+ def close(self) -> None:
1080
+ self.gguf.close()
1081
+
1082
+ @staticmethod
1083
+ def write_vocab_only(
1084
+ fname_out: Path, params: Params, vocab: Vocab, svocab: gguf.SpecialVocab,
1085
+ endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE, pad_vocab: bool = False,
1086
+ ) -> None:
1087
+ check_vocab_size(params, vocab, pad_vocab = pad_vocab)
1088
+
1089
+ of = OutputFile(fname_out, endianess=endianess)
1090
+
1091
+ # meta data
1092
+ of.add_meta_arch(params)
1093
+ of.add_meta_vocab(vocab)
1094
+ of.add_meta_special_vocab(svocab)
1095
+
1096
+ of.write_meta()
1097
+
1098
+ of.close()
1099
+
1100
+ @staticmethod
1101
+ def do_item(item: tuple[str, LazyTensor]) -> tuple[DataType, NDArray]:
1102
+ name, lazy_tensor = item
1103
+ tensor = lazy_tensor.load().to_ggml()
1104
+ return (lazy_tensor.data_type, tensor.ndarray)
1105
+
1106
+ @staticmethod
1107
+ def maybe_do_quantize(item: tuple[DataType, NDArray]) -> NDArray:
1108
+ dt, arr = item
1109
+ if not isinstance(dt, QuantizedDataType):
1110
+ return arr
1111
+ return dt.quantize(arr)
1112
+
1113
+ @staticmethod
1114
+ def write_all(
1115
+ fname_out: Path, ftype: GGMLFileType, params: Params, model: LazyModel, vocab: Vocab, svocab: gguf.SpecialVocab,
1116
+ concurrency: int = DEFAULT_CONCURRENCY, endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE,
1117
+ pad_vocab: bool = False,
1118
+ ) -> None:
1119
+ check_vocab_size(params, vocab, pad_vocab=pad_vocab)
1120
+
1121
+ of = OutputFile(fname_out, endianess=endianess)
1122
+
1123
+ # meta data
1124
+ of.add_meta_arch(params)
1125
+ of.add_meta_vocab(vocab)
1126
+ of.add_meta_special_vocab(svocab)
1127
+
1128
+ # tensor info
1129
+ for name, lazy_tensor in model.items():
1130
+ of.add_tensor_info(name, lazy_tensor)
1131
+
1132
+ of.write_meta()
1133
+ of.write_tensor_info()
1134
+
1135
+ # tensor data
1136
+ ndarrays_inner = bounded_parallel_map(OutputFile.do_item, model.items(), concurrency = concurrency)
1137
+ if ftype == GGMLFileType.MostlyQ8_0:
1138
+ ndarrays = bounded_parallel_map(
1139
+ OutputFile.maybe_do_quantize, ndarrays_inner, concurrency=concurrency, max_workers=concurrency,
1140
+ use_processpool_executor=True,
1141
+ )
1142
+ else:
1143
+ ndarrays = map(OutputFile.maybe_do_quantize, ndarrays_inner)
1144
+
1145
+ start = time.time()
1146
+ for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
1147
+ elapsed = time.time() - start
1148
+ size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
1149
+ padi = len(str(len(model)))
1150
+ print(
1151
+ f"[{i+1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type.name:4} | T+{int(elapsed):4}"
1152
+ )
1153
+ of.gguf.write_tensor_data(ndarray)
1154
+
1155
+ of.close()
1156
+
1157
+
1158
+ def pick_output_type(model: LazyModel, output_type_str: str | None) -> GGMLFileType:
1159
+ wq_type = model[gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0) + ".weight"].data_type
1160
+
1161
+ if output_type_str == "f32" or (output_type_str is None and wq_type == DT_F32):
1162
+ return GGMLFileType.AllF32
1163
+ if output_type_str == "f16" or (output_type_str is None and wq_type in (DT_F16, DT_BF16)):
1164
+ return GGMLFileType.MostlyF16
1165
+ if output_type_str == "q8_0":
1166
+ return GGMLFileType.MostlyQ8_0
1167
+
1168
+ name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
1169
+
1170
+ raise Exception(f"Unexpected combination of types: {name_to_type}")
1171
+
1172
+
1173
+ def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
1174
+ return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
1175
+ for (name, tensor) in model.items()}
1176
+
1177
+
1178
+ def convert_model_names(model: LazyModel, params: Params, skip_unknown: bool) -> LazyModel:
1179
+ tmap = gguf.TensorNameMap(ARCH, params.n_layer)
1180
+ should_skip: set[gguf.MODEL_TENSOR] = set(gguf.MODEL_TENSOR_SKIP.get(ARCH, []))
1181
+
1182
+ tmp = model
1183
+
1184
+ # HF models permut or pack some of the tensors, so we need to undo that
1185
+ for i in itertools.count():
1186
+ if f"model.layers.{i}.self_attn.q_proj.weight" in model:
1187
+ print(f"Permuting layer {i}")
1188
+ tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.q_proj.weight"], params.n_head, params.n_head)
1189
+ tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.k_proj.weight"], params.n_head, params.n_head_kv)
1190
+ # tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
1191
+ elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
1192
+ print(f"Unpacking and permuting layer {i}")
1193
+ tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 0, params.n_head, params.n_head)
1194
+ tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 1, params.n_head, params.n_head_kv)
1195
+ tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
1196
+ del tmp[f"model.layers.{i}.self_attn.W_pack.weight"]
1197
+ else:
1198
+ break
1199
+
1200
+ out: LazyModel = {}
1201
+ for name, lazy_tensor in model.items():
1202
+ tensor_type, name_new = tmap.get_type_and_name(name, try_suffixes = (".weight", ".bias")) or (None, None)
1203
+ if name_new is None:
1204
+ if skip_unknown:
1205
+ print(f"Unexpected tensor name: {name} - skipping")
1206
+ continue
1207
+ else:
1208
+ raise Exception(f"Unexpected tensor name: {name}. Use --skip-unknown to ignore it (e.g. LLaVA)")
1209
+
1210
+ if tensor_type in should_skip:
1211
+ print(f"skipping tensor {name_new}")
1212
+ continue
1213
+
1214
+ print(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type.name:6s} | {lazy_tensor.shape}")
1215
+ out[name_new] = lazy_tensor
1216
+
1217
+ return out
1218
+
1219
+
1220
+ def nth_multifile_path(path: Path, n: int) -> Path | None:
1221
+ '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
1222
+ the nth path in the model.
1223
+ '''
1224
+ # Support the following patterns:
1225
+ patterns: list[tuple[str, str]] = [
1226
+ # - x.00.pth, x.01.pth, etc.
1227
+ (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
1228
+ # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
1229
+ (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
1230
+ # x.bin, x.bin.1, etc.
1231
+ (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
1232
+ ]
1233
+ for regex, replacement in patterns:
1234
+ if re.search(regex, path.name):
1235
+ new_path = path.with_name(re.sub(regex, replacement, path.name))
1236
+ if new_path.exists():
1237
+ return new_path
1238
+ return None
1239
+
1240
+
1241
+ def find_multifile_paths(path: Path) -> list[Path]:
1242
+ '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
1243
+ the whole list of paths in the model.
1244
+ '''
1245
+ ret: list[Path] = []
1246
+ for i in itertools.count():
1247
+ nth_path = nth_multifile_path(path, i)
1248
+ if nth_path is None:
1249
+ break
1250
+ ret.append(nth_path)
1251
+ if not ret:
1252
+ # No matches. This should only happen if the file was named, e.g.,
1253
+ # foo.0, and there was no file named foo. Oh well, try to process it
1254
+ # as a single file.
1255
+ return [path]
1256
+ return ret
1257
+
1258
+
1259
+ def load_some_model(path: Path) -> ModelPlus:
1260
+ '''Load a model of any supported format.'''
1261
+ # Be extra-friendly and accept either a file or a directory:
1262
+ if path.is_dir():
1263
+ # Check if it's a set of safetensors files first
1264
+ globs = ["model-00001-of-*.safetensors", "model.safetensors"]
1265
+ files = [file for glob in globs for file in path.glob(glob)]
1266
+ if not files:
1267
+ # Try the PyTorch patterns too, with lower priority
1268
+ globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
1269
+ files = [file for glob in globs for file in path.glob(glob)]
1270
+ if not files:
1271
+ raise Exception(f"Can't find model in directory {path}")
1272
+ if len(files) > 1:
1273
+ raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
1274
+ path = files[0]
1275
+
1276
+ paths = find_multifile_paths(path)
1277
+ models_plus: list[ModelPlus] = []
1278
+ for path in paths:
1279
+ print(f"Loading model file {path}")
1280
+ models_plus.append(lazy_load_file(path))
1281
+
1282
+ model_plus = merge_multifile_models(models_plus)
1283
+ return model_plus
1284
+
1285
+
1286
+ class VocabFactory:
1287
+ _FILES = {"spm": "tokenizer.model", "bpe": "vocab.json", "hfft": "tokenizer.json"}
1288
+
1289
+ def __init__(self, path: Path):
1290
+ self.path = path
1291
+ self.file_paths = self._detect_files()
1292
+ print(f"Found vocab files: {self.file_paths}")
1293
+
1294
+ def _detect_files(self) -> dict[str, Path | None]:
1295
+ def locate(file: str) -> Path | None:
1296
+ if (path := self.path / file).exists():
1297
+ return path
1298
+ if (path := self.path.parent / file).exists():
1299
+ return path
1300
+ return None
1301
+
1302
+ return {vt: locate(f) for vt, f in self._FILES.items()}
1303
+
1304
+ def _select_file(self, vocab_types: list[str]) -> tuple[str, Path]:
1305
+ for vtype in vocab_types:
1306
+ try:
1307
+ path = self.file_paths[vtype]
1308
+ except KeyError:
1309
+ raise ValueError(f"Unsupported vocabulary type {vtype}") from None
1310
+ if path is not None:
1311
+ return vtype, path
1312
+ raise FileNotFoundError(f"Could not find any of {[self._FILES[vt] for vt in vocab_types]}")
1313
+
1314
+ def _create_special_vocab(self, vocab: Vocab, vocabtype: str, model_parent_path: Path) -> gguf.SpecialVocab:
1315
+ load_merges = vocabtype == "bpe"
1316
+ n_vocab = vocab.vocab_size if hasattr(vocab, "vocab_size") else None
1317
+ return gguf.SpecialVocab(
1318
+ model_parent_path,
1319
+ load_merges=load_merges,
1320
+ special_token_types=None, # Predetermined or passed as a parameter
1321
+ n_vocab=n_vocab,
1322
+ )
1323
+
1324
+ def load_vocab(self, vocab_types: list[str], model_parent_path: Path) -> tuple[Vocab, gguf.SpecialVocab]:
1325
+ vocab_type, path = self._select_file(vocab_types)
1326
+ print(f"Loading vocab file {path!r}, type {vocab_type!r}")
1327
+
1328
+ added_tokens_path = path.parent / "added_tokens.json"
1329
+ vocab: Vocab
1330
+ if vocab_type == "bpe":
1331
+ vocab = BpeVocab(
1332
+ path, added_tokens_path if added_tokens_path.exists() else None
1333
+ )
1334
+ elif vocab_type == "spm":
1335
+ vocab = SentencePieceVocab(
1336
+ path, added_tokens_path if added_tokens_path.exists() else None
1337
+ )
1338
+ elif vocab_type == "hfft":
1339
+ vocab = HfVocab(
1340
+ path.parent, added_tokens_path if added_tokens_path.exists() else None
1341
+ )
1342
+ else:
1343
+ raise ValueError(vocab_type)
1344
+ # FIXME: Respect --vocab-dir?
1345
+ special_vocab = self._create_special_vocab(
1346
+ vocab,
1347
+ vocab_type,
1348
+ model_parent_path,
1349
+ )
1350
+ return vocab, special_vocab
1351
+
1352
+
1353
+ def default_outfile(model_paths: list[Path], file_type: GGMLFileType) -> Path:
1354
+ namestr = {
1355
+ GGMLFileType.AllF32: "f32",
1356
+ GGMLFileType.MostlyF16: "f16",
1357
+ GGMLFileType.MostlyQ8_0:"q8_0",
1358
+ }[file_type]
1359
+ ret = model_paths[0].parent / f"ggml-model-{namestr}.gguf"
1360
+ if ret in model_paths:
1361
+ sys.stderr.write(
1362
+ f"Error: Default output path ({ret}) would overwrite the input. "
1363
+ "Please explicitly specify a path using --outfile.\n")
1364
+ sys.exit(1)
1365
+ return ret
1366
+
1367
+
1368
+ def do_dump_model(model_plus: ModelPlus) -> None:
1369
+ print(f"model_plus.paths = {model_plus.paths!r}")
1370
+ print(f"model_plus.format = {model_plus.format!r}")
1371
+ print(f"model_plus.vocab = {model_plus.vocab!r}")
1372
+ for name, lazy_tensor in model_plus.model.items():
1373
+ print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
1374
+
1375
+
1376
+ def main(args_in: list[str] | None = None) -> None:
1377
+ output_choices = ["f32", "f16"]
1378
+ if np.uint32(1) == np.uint32(1).newbyteorder("<"):
1379
+ # We currently only support Q8_0 output on little endian systems.
1380
+ output_choices.append("q8_0")
1381
+ parser = argparse.ArgumentParser(description="Convert a LLaMA model to a GGML compatible file")
1382
+ parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
1383
+ parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
1384
+ parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
1385
+ parser.add_argument("--outtype", choices=output_choices, help="output format - note: q8_0 may be very slow (default: f16 or f32 based on input)")
1386
+ parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
1387
+ parser.add_argument("--vocab-type", help="vocab types to try in order, choose from 'spm', 'bpe', 'hfft' (default: spm,hfft)", default="spm,hfft")
1388
+ parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
1389
+ parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
1390
+ parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
1391
+ parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default=DEFAULT_CONCURRENCY)
1392
+ parser.add_argument("--big-endian", action="store_true", help="model is executed on big endian machine")
1393
+ parser.add_argument("--pad-vocab", action="store_true", help="add pad tokens when model vocab expects more than tokenizer metadata provides")
1394
+ parser.add_argument("--skip-unknown", action="store_true", help="skip unknown tensor names instead of failing")
1395
+
1396
+ args = parser.parse_args(args_in)
1397
+
1398
+ if args.dump_single:
1399
+ model_plus = lazy_load_file(args.model)
1400
+ do_dump_model(model_plus)
1401
+ return
1402
+
1403
+ if not args.vocab_only:
1404
+ model_plus = load_some_model(args.model)
1405
+ else:
1406
+ model_plus = ModelPlus(model = {}, paths = [args.model / 'dummy'], format = 'none', vocab = None)
1407
+
1408
+ if args.dump:
1409
+ do_dump_model(model_plus)
1410
+ return
1411
+ endianess = gguf.GGUFEndian.LITTLE
1412
+ if args.big_endian:
1413
+ endianess = gguf.GGUFEndian.BIG
1414
+
1415
+ params = Params.load(model_plus)
1416
+ if params.n_ctx == -1:
1417
+ if args.ctx is None:
1418
+ raise Exception("The model doesn't have a context size, and you didn't specify one with --ctx\n"
1419
+ "Please specify one with --ctx:\n"
1420
+ " - LLaMA v1: --ctx 2048\n"
1421
+ " - LLaMA v2: --ctx 4096\n")
1422
+ params.n_ctx = args.ctx
1423
+
1424
+ if args.outtype:
1425
+ params.ftype = {
1426
+ "f32": GGMLFileType.AllF32,
1427
+ "f16": GGMLFileType.MostlyF16,
1428
+ "q8_0": GGMLFileType.MostlyQ8_0,
1429
+ }[args.outtype]
1430
+
1431
+ print(f"params = {params}")
1432
+
1433
+ model_parent_path = model_plus.paths[0].parent
1434
+ vocab_path = Path(args.vocab_dir or args.model or model_parent_path)
1435
+ vocab_factory = VocabFactory(vocab_path)
1436
+ vocab, special_vocab = vocab_factory.load_vocab(args.vocab_type.split(","), model_parent_path)
1437
+
1438
+ if args.vocab_only:
1439
+ if not args.outfile:
1440
+ raise ValueError("need --outfile if using --vocab-only")
1441
+ outfile = args.outfile
1442
+ OutputFile.write_vocab_only(outfile, params, vocab, special_vocab,
1443
+ endianess=endianess, pad_vocab=args.pad_vocab)
1444
+ print(f"Wrote {outfile}")
1445
+ return
1446
+
1447
+ if model_plus.vocab is not None and args.vocab_dir is None:
1448
+ vocab = model_plus.vocab
1449
+
1450
+ print(f"Vocab info: {vocab}")
1451
+ print(f"Special vocab info: {special_vocab}")
1452
+
1453
+ model = model_plus.model
1454
+ model = convert_model_names(model, params, args.skip_unknown)
1455
+ ftype = pick_output_type(model, args.outtype)
1456
+ model = convert_to_output_type(model, ftype)
1457
+ outfile = args.outfile or default_outfile(model_plus.paths, ftype)
1458
+
1459
+ params.ftype = ftype
1460
+ print(f"Writing {outfile}, format {ftype}")
1461
+
1462
+ OutputFile.write_all(outfile, ftype, params, model, vocab, special_vocab,
1463
+ concurrency=args.concurrency, endianess=endianess, pad_vocab=args.pad_vocab)
1464
+ print(f"Wrote {outfile}")
1465
+
1466
+
1467
+ if __name__ == '__main__':
1468
+ main()