|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import os |
| 4 | +import sys |
| 5 | +from pathlib import Path |
| 6 | +from pprint import pprint |
| 7 | + |
| 8 | +import torch |
| 9 | +from sentencepiece import SentencePieceProcessor |
| 10 | + |
| 11 | +if 'NO_LOCAL_GGUF' not in os.environ: |
| 12 | + sys.path.insert(1, str(Path(__file__).parent / 'gguf-py')) |
| 13 | +import gguf |
| 14 | + |
| 15 | + |
| 16 | +def _flatten_dict(dct, tensors, prefix=None): |
| 17 | + assert isinstance(dct, dict) |
| 18 | + for key in dct.keys(): |
| 19 | + new_prefix = prefix + '.' + key if prefix is not None else key |
| 20 | + if isinstance(dct[key], torch.Tensor): |
| 21 | + tensors[new_prefix] = dct[key] |
| 22 | + elif isinstance(dct[key], dict): |
| 23 | + _flatten_dict(dct[key], tensors, new_prefix) |
| 24 | + else: |
| 25 | + raise ValueError(type(dct[key])) |
| 26 | + return None |
| 27 | + |
| 28 | + |
| 29 | +def _get_sentencepiece_tokenizer_info(dir_model: Path): |
| 30 | + tokenizer_path = dir_model / 'adept_vocab.model' |
| 31 | + print('gguf: getting sentencepiece tokenizer from', tokenizer_path) |
| 32 | + tokenizer = SentencePieceProcessor(str(tokenizer_path)) |
| 33 | + print('gguf: adding tokens') |
| 34 | + tokens: list[bytes] = [] |
| 35 | + scores: list[float] = [] |
| 36 | + toktypes: list[int] = [] |
| 37 | + |
| 38 | + for i in range(tokenizer.vocab_size()): |
| 39 | + text: bytes |
| 40 | + score: float |
| 41 | + |
| 42 | + piece = tokenizer.id_to_piece(i) |
| 43 | + text = piece.encode("utf-8") |
| 44 | + score = tokenizer.get_score(i) |
| 45 | + |
| 46 | + toktype = 1 |
| 47 | + if tokenizer.is_unknown(i): |
| 48 | + toktype = 2 |
| 49 | + if tokenizer.is_control(i): |
| 50 | + toktype = 3 |
| 51 | + if tokenizer.is_unused(i): |
| 52 | + toktype = 5 |
| 53 | + if tokenizer.is_byte(i): |
| 54 | + toktype = 6 |
| 55 | + |
| 56 | + tokens.append(text) |
| 57 | + scores.append(score) |
| 58 | + toktypes.append(toktype) |
| 59 | + pass |
| 60 | + return tokens, scores, toktypes |
| 61 | + |
| 62 | + |
| 63 | +def main(): |
| 64 | + parser = argparse.ArgumentParser(description="Convert a Persimmon model from Adept (e.g. Persimmon 8b chat) to a GGML compatible file") |
| 65 | + parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input") |
| 66 | + parser.add_argument("--ckpt-path", type=Path, help="path to persimmon checkpoint .pt file") |
| 67 | + parser.add_argument("--model-dir", type=Path, help="directory containing model e.g. 8b_chat_model_release") |
| 68 | + parser.add_argument("--adept-inference-dir", type=str, help="path to adept-inference code directory") |
| 69 | + args = parser.parse_args() |
| 70 | + sys.path.append(str(args.adept_inference_dir)) |
| 71 | + persimmon_model = torch.load(args.ckpt_path) |
| 72 | + hparams = persimmon_model['args'] |
| 73 | + pprint(hparams) |
| 74 | + tensors: dict[str, torch.Tensor] = {} |
| 75 | + _flatten_dict(persimmon_model['model'], tensors, None) |
| 76 | + |
| 77 | + arch = gguf.MODEL_ARCH.PERSIMMON |
| 78 | + gguf_writer = gguf.GGUFWriter(args.outfile, gguf.MODEL_ARCH_NAMES[arch]) |
| 79 | + |
| 80 | + block_count = hparams.num_layers |
| 81 | + head_count = hparams.num_attention_heads |
| 82 | + head_count_kv = head_count |
| 83 | + ctx_length = hparams.seq_length |
| 84 | + hidden_size = hparams.hidden_size |
| 85 | + |
| 86 | + gguf_writer.add_name('persimmon-8b-chat') |
| 87 | + gguf_writer.add_context_length(ctx_length) |
| 88 | + gguf_writer.add_embedding_length(hidden_size) |
| 89 | + gguf_writer.add_block_count(block_count) |
| 90 | + gguf_writer.add_feed_forward_length(hparams.ffn_hidden_size) |
| 91 | + # ref: https://github.com/ggerganov/llama.cpp/pull/4889/commits/eea19039fc52ea2dbd1aab45b59ab4e3e29a3443 |
| 92 | + gguf_writer.add_rope_dimension_count(hidden_size // head_count // 2) |
| 93 | + gguf_writer.add_head_count(head_count) |
| 94 | + gguf_writer.add_head_count_kv(head_count_kv) |
| 95 | + gguf_writer.add_rope_freq_base(hparams.rotary_emb_base) |
| 96 | + gguf_writer.add_layer_norm_eps(hparams.layernorm_epsilon) |
| 97 | + |
| 98 | + tokens, scores, toktypes = _get_sentencepiece_tokenizer_info(args.model_dir) |
| 99 | + gguf_writer.add_tokenizer_model('llama') |
| 100 | + gguf_writer.add_token_list(tokens) |
| 101 | + gguf_writer.add_token_scores(scores) |
| 102 | + gguf_writer.add_token_types(toktypes) |
| 103 | + gguf_writer.add_bos_token_id(71013) |
| 104 | + gguf_writer.add_eos_token_id(71013) |
| 105 | + |
| 106 | + tensor_map = gguf.get_tensor_name_map(arch, block_count) |
| 107 | + print(tensor_map) |
| 108 | + for name in tensors.keys(): |
| 109 | + data = tensors[name] |
| 110 | + if name.endswith(".self_attention.rotary_emb.inv_freq"): |
| 111 | + continue |
| 112 | + old_dtype = data.dtype |
| 113 | + # TODO: FP16 conversion produces garbage outputs. (Q8_0 does not, so..?) |
| 114 | + data = data.to(torch.float32).squeeze().numpy() |
| 115 | + new_name = tensor_map.get_name(name, try_suffixes = (".weight", ".bias")) |
| 116 | + if new_name is None: |
| 117 | + print("Can not map tensor '" + name + "'") |
| 118 | + sys.exit() |
| 119 | + n_dims = len(data.shape) |
| 120 | + print(new_name + ", n_dims = " + str(n_dims) + ", " + str(old_dtype) + " --> " + str(data.dtype)) |
| 121 | + gguf_writer.add_tensor(new_name, data) |
| 122 | + print("gguf: write header") |
| 123 | + gguf_writer.write_header_to_file() |
| 124 | + print("gguf: write metadata") |
| 125 | + gguf_writer.write_kv_data_to_file() |
| 126 | + print("gguf: write tensors") |
| 127 | + gguf_writer.write_tensors_to_file() |
| 128 | + |
| 129 | + gguf_writer.close() |
| 130 | + |
| 131 | + print(f"gguf: model successfully exported to '{args.outfile}'") |
| 132 | + print("") |
| 133 | + |
| 134 | + |
| 135 | +if __name__ == '__main__': |
| 136 | + main() |
| 137 | + |
0 commit comments