Advertisement
tastypear

llama converter hack

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