mirror of
https://github.com/ggerganov/llama.cpp.git
synced 2024-12-26 03:14:35 +00:00
f98eb31c51
* convert-hf : begin refactoring write_tensor * convert : upgrade to sentencepiece v0.2.0 * convert-hf : remove unused n_dims in extra_*_tensors * convert-hf : simplify MoE weights stacking * convert-hf : flake8 linter doesn't like semicolons * convert-hf : allow unusual model part names For example, loading `model-00001-of-00001.safetensors` now works. * convert-hf : fix stacking MoE expert tensors `torch.stack` and `torch.cat` don't do the same thing. * convert-hf : fix Mamba conversion Tested to work even with a SentencePiece-based tokenizer. * convert : use a string for the SentencePiece tokenizer path * convert-hf : display tensor shape * convert-hf : convert norms to f32 by default * convert-hf : sort model part names `os.listdir` is said to list files in arbitrary order. Sorting the file names should let "model-00009-of-00042.safetensors" be loaded before "model-00010-of-00042.safetensors". * convert-hf : use an ABC for Model again It seems Protocol can't be used as a statically type-checked ABC, because its subclasses also can't be instantiated. (why did it seem to work?) At least there's still a way to throw an error when forgetting to define the `model_arch` property of any registered Model subclasses. * convert-hf : use a plain class for Model, and forbid direct instantiation There are no abstract methods used anyway, so using ABC isn't really necessary. * convert-hf : more consistent formatting of cmdline args * convert-hf : align the message logged for converted tensors * convert-hf : fix Refact conversion * convert-hf : save memory with lazy evaluation * convert-hf : flake8 doesn't like lowercase L as a variable name * convert-hf : remove einops requirement for InternLM2 * convert-hf : faster model parts loading Instead of pre-loading them all into a dict, iterate on the tensors in the model parts progressively as needed in Model.write_tensors Conversion for some architectures relies on checking for the presence of specific tensor names, so for multi-part models, the weight map is read from the relevant json file to quickly get these names up-front. * convert-hf : minor changes for consistency * gguf-py : add tqdm as a dependency It's small, and used for a progress bar in GGUFWriter.write_tensors_to_file
129 lines
5.1 KiB
Python
Executable File
129 lines
5.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import argparse
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import numpy as np
|
|
|
|
# Necessary to load the local gguf package
|
|
if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent / 'gguf-py').exists():
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
from gguf import GGUFReader, GGUFValueType # noqa: E402
|
|
|
|
logger = logging.getLogger("gguf-dump")
|
|
|
|
|
|
def get_file_host_endian(reader: GGUFReader) -> tuple[str, str]:
|
|
host_endian = 'LITTLE' if np.uint32(1) == np.uint32(1).newbyteorder("<") else 'BIG'
|
|
if reader.byte_order == 'S':
|
|
file_endian = 'BIG' if host_endian == 'LITTLE' else 'LITTLE'
|
|
else:
|
|
file_endian = host_endian
|
|
return (host_endian, file_endian)
|
|
|
|
|
|
# For more information about what field.parts and field.data represent,
|
|
# please see the comments in the modify_gguf.py example.
|
|
def dump_metadata(reader: GGUFReader, args: argparse.Namespace) -> None:
|
|
host_endian, file_endian = get_file_host_endian(reader)
|
|
print(f'* File is {file_endian} endian, script is running on a {host_endian} endian host.') # noqa: NP100
|
|
print(f'* Dumping {len(reader.fields)} key/value pair(s)') # noqa: NP100
|
|
for n, field in enumerate(reader.fields.values(), 1):
|
|
if not field.types:
|
|
pretty_type = 'N/A'
|
|
elif field.types[0] == GGUFValueType.ARRAY:
|
|
nest_count = len(field.types) - 1
|
|
pretty_type = '[' * nest_count + str(field.types[-1].name) + ']' * nest_count
|
|
else:
|
|
pretty_type = str(field.types[-1].name)
|
|
|
|
log_message = f' {n:5}: {pretty_type:10} | {len(field.data):8} | {field.name}'
|
|
if len(field.types) == 1:
|
|
curr_type = field.types[0]
|
|
if curr_type == GGUFValueType.STRING:
|
|
log_message += ' = {0}'.format(repr(str(bytes(field.parts[-1]), encoding='utf-8')[:60]))
|
|
elif field.types[0] in reader.gguf_scalar_to_np:
|
|
log_message += ' = {0}'.format(field.parts[-1][0])
|
|
print(log_message) # noqa: NP100
|
|
if args.no_tensors:
|
|
return
|
|
print(f'* Dumping {len(reader.tensors)} tensor(s)') # noqa: NP100
|
|
for n, tensor in enumerate(reader.tensors, 1):
|
|
prettydims = ', '.join('{0:5}'.format(d) for d in list(tensor.shape) + [1] * (4 - len(tensor.shape)))
|
|
print(f' {n:5}: {tensor.n_elements:10} | {prettydims} | {tensor.tensor_type.name:7} | {tensor.name}') # noqa: NP100
|
|
|
|
|
|
def dump_metadata_json(reader: GGUFReader, args: argparse.Namespace) -> None:
|
|
import json
|
|
host_endian, file_endian = get_file_host_endian(reader)
|
|
metadata: dict[str, Any] = {}
|
|
tensors: dict[str, Any] = {}
|
|
result = {
|
|
"filename": args.model,
|
|
"endian": file_endian,
|
|
"metadata": metadata,
|
|
"tensors": tensors,
|
|
}
|
|
for idx, field in enumerate(reader.fields.values()):
|
|
curr: dict[str, Any] = {
|
|
"index": idx,
|
|
"type": field.types[0].name if field.types else 'UNKNOWN',
|
|
"offset": field.offset,
|
|
}
|
|
metadata[field.name] = curr
|
|
if field.types[:1] == [GGUFValueType.ARRAY]:
|
|
curr["array_types"] = [t.name for t in field.types][1:]
|
|
if not args.json_array:
|
|
continue
|
|
itype = field.types[-1]
|
|
if itype == GGUFValueType.STRING:
|
|
curr["value"] = [str(bytes(field.parts[idx]), encoding="utf-8") for idx in field.data]
|
|
else:
|
|
curr["value"] = [pv for idx in field.data for pv in field.parts[idx].tolist()]
|
|
elif field.types[0] == GGUFValueType.STRING:
|
|
curr["value"] = str(bytes(field.parts[-1]), encoding="utf-8")
|
|
else:
|
|
curr["value"] = field.parts[-1].tolist()[0]
|
|
if not args.no_tensors:
|
|
for idx, tensor in enumerate(reader.tensors):
|
|
tensors[tensor.name] = {
|
|
"index": idx,
|
|
"shape": tensor.shape.tolist(),
|
|
"type": tensor.tensor_type.name,
|
|
"offset": tensor.field.offset,
|
|
}
|
|
json.dump(result, sys.stdout)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Dump GGUF file metadata")
|
|
parser.add_argument("model", type=str, help="GGUF format model filename")
|
|
parser.add_argument("--no-tensors", action="store_true", help="Don't dump tensor metadata")
|
|
parser.add_argument("--json", action="store_true", help="Produce JSON output")
|
|
parser.add_argument("--json-array", action="store_true", help="Include full array values in JSON output (long)")
|
|
parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
|
|
|
|
args = parser.parse_args(None if len(sys.argv) > 1 else ["--help"])
|
|
|
|
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
|
|
|
|
if not args.json:
|
|
logger.info(f'* Loading: {args.model}')
|
|
|
|
reader = GGUFReader(args.model, 'r')
|
|
|
|
if args.json:
|
|
dump_metadata_json(reader, args)
|
|
else:
|
|
dump_metadata(reader, args)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|