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