1
0

gguf_new_metadata.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import logging
  4. import argparse
  5. import os
  6. import sys
  7. import json
  8. from pathlib import Path
  9. import numpy as np
  10. from tqdm import tqdm
  11. from typing import Any, Sequence, NamedTuple
  12. # Necessary to load the local gguf package
  13. if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent / 'gguf-py').exists():
  14. sys.path.insert(0, str(Path(__file__).parent.parent))
  15. import gguf
  16. logger = logging.getLogger("gguf-new-metadata")
  17. class MetadataDetails(NamedTuple):
  18. type: gguf.GGUFValueType
  19. value: Any
  20. description: str = ''
  21. def get_byteorder(reader: gguf.GGUFReader) -> gguf.GGUFEndian:
  22. if np.uint32(1) == np.uint32(1).newbyteorder("<"):
  23. # Host is little endian
  24. host_endian = gguf.GGUFEndian.LITTLE
  25. swapped_endian = gguf.GGUFEndian.BIG
  26. else:
  27. # Sorry PDP or other weird systems that don't use BE or LE.
  28. host_endian = gguf.GGUFEndian.BIG
  29. swapped_endian = gguf.GGUFEndian.LITTLE
  30. if reader.byte_order == "S":
  31. return swapped_endian
  32. else:
  33. return host_endian
  34. def decode_field(field: gguf.ReaderField | None) -> Any:
  35. if field and field.types:
  36. main_type = field.types[0]
  37. if main_type == gguf.GGUFValueType.ARRAY:
  38. sub_type = field.types[-1]
  39. if sub_type == gguf.GGUFValueType.STRING:
  40. return [str(bytes(field.parts[idx]), encoding='utf-8') for idx in field.data]
  41. else:
  42. return [pv for idx in field.data for pv in field.parts[idx].tolist()]
  43. if main_type == gguf.GGUFValueType.STRING:
  44. return str(bytes(field.parts[-1]), encoding='utf-8')
  45. else:
  46. return field.parts[-1][0]
  47. return None
  48. def get_field_data(reader: gguf.GGUFReader, key: str) -> Any:
  49. field = reader.get_field(key)
  50. return decode_field(field)
  51. def find_token(token_list: Sequence[int], token: str) -> Sequence[int]:
  52. token_ids = [index for index, value in enumerate(token_list) if value == token]
  53. if len(token_ids) == 0:
  54. raise LookupError(f'Unable to find "{token}" in token list!')
  55. return token_ids
  56. def copy_with_new_metadata(reader: gguf.GGUFReader, writer: gguf.GGUFWriter, new_metadata: dict[str, MetadataDetails], remove_metadata: Sequence[str]) -> None:
  57. for field in reader.fields.values():
  58. # Suppress virtual fields and fields written by GGUFWriter
  59. if field.name == gguf.Keys.General.ARCHITECTURE or field.name.startswith('GGUF.'):
  60. logger.debug(f'Suppressing {field.name}')
  61. continue
  62. # Skip old chat templates if we have new ones
  63. if field.name.startswith(gguf.Keys.Tokenizer.CHAT_TEMPLATE) and gguf.Keys.Tokenizer.CHAT_TEMPLATE in new_metadata:
  64. logger.debug(f'Skipping {field.name}')
  65. continue
  66. if field.name in remove_metadata:
  67. logger.debug(f'Removing {field.name}')
  68. continue
  69. old_val = MetadataDetails(field.types[0], decode_field(field))
  70. val = new_metadata.get(field.name, old_val)
  71. if field.name in new_metadata:
  72. logger.debug(f'Modifying {field.name}: "{old_val.value}" -> "{val.value}" {val.description}')
  73. del new_metadata[field.name]
  74. elif val.value is not None:
  75. logger.debug(f'Copying {field.name}')
  76. if val.value is not None:
  77. writer.add_key_value(field.name, val.value, val.type)
  78. if gguf.Keys.Tokenizer.CHAT_TEMPLATE in new_metadata:
  79. logger.debug('Adding chat template(s)')
  80. writer.add_chat_template(new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE].value)
  81. del new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE]
  82. for key, val in new_metadata.items():
  83. logger.debug(f'Adding {key}: "{val.value}" {val.description}')
  84. writer.add_key_value(key, val.value, val.type)
  85. total_bytes = 0
  86. for tensor in reader.tensors:
  87. total_bytes += tensor.n_bytes
  88. writer.add_tensor_info(tensor.name, tensor.data.shape, tensor.data.dtype, tensor.data.nbytes, tensor.tensor_type)
  89. bar = tqdm(desc="Writing", total=total_bytes, unit="byte", unit_scale=True)
  90. writer.write_header_to_file()
  91. writer.write_kv_data_to_file()
  92. writer.write_ti_data_to_file()
  93. for tensor in reader.tensors:
  94. writer.write_tensor_data(tensor.data)
  95. bar.update(tensor.n_bytes)
  96. writer.close()
  97. def main() -> None:
  98. tokenizer_metadata = (getattr(gguf.Keys.Tokenizer, n) for n in gguf.Keys.Tokenizer.__dict__.keys() if not n.startswith('_'))
  99. token_names = dict((n.split('.')[-1][:-len('_token_id')], n) for n in tokenizer_metadata if n.endswith('_token_id'))
  100. parser = argparse.ArgumentParser(description="Make a copy of a GGUF file with new metadata")
  101. parser.add_argument("input", type=Path, help="GGUF format model input filename")
  102. parser.add_argument("output", type=Path, help="GGUF format model output filename")
  103. parser.add_argument("--general-name", type=str, help="The models general.name", metavar='"name"')
  104. parser.add_argument("--general-description", type=str, help="The models general.description", metavar='"Description ..."')
  105. parser.add_argument("--chat-template", type=str, help="Chat template string (or JSON string containing templates)", metavar='"{% ... %} ..."')
  106. parser.add_argument("--chat-template-config", type=Path, help="Config file containing chat template(s)", metavar='tokenizer_config.json')
  107. parser.add_argument("--pre-tokenizer", type=str, help="The models tokenizer.ggml.pre", metavar='"pre tokenizer"')
  108. parser.add_argument("--remove-metadata", action="append", type=str, help="Remove metadata (by key name) from output model", metavar='general.url')
  109. parser.add_argument("--special-token", action="append", type=str, help="Special token by value", nargs=2, metavar=(' | '.join(token_names.keys()), '"<token>"'))
  110. parser.add_argument("--special-token-by-id", action="append", type=str, help="Special token by id", nargs=2, metavar=(' | '.join(token_names.keys()), '0'))
  111. parser.add_argument("--force", action="store_true", help="Bypass warnings without confirmation")
  112. parser.add_argument("--verbose", action="store_true", help="Increase output verbosity")
  113. args = parser.parse_args(None if len(sys.argv) > 2 else ["--help"])
  114. logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
  115. new_metadata = {}
  116. remove_metadata = args.remove_metadata or []
  117. if args.general_name:
  118. new_metadata[gguf.Keys.General.NAME] = MetadataDetails(gguf.GGUFValueType.STRING, args.general_name)
  119. if args.general_description:
  120. new_metadata[gguf.Keys.General.DESCRIPTION] = MetadataDetails(gguf.GGUFValueType.STRING, args.general_description)
  121. if args.chat_template:
  122. new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE] = MetadataDetails(gguf.GGUFValueType.STRING, json.loads(args.chat_template) if args.chat_template.startswith('[') else args.chat_template)
  123. if args.chat_template_config:
  124. with open(args.chat_template_config, 'r') as fp:
  125. config = json.load(fp)
  126. template = config.get('chat_template')
  127. if template:
  128. new_metadata[gguf.Keys.Tokenizer.CHAT_TEMPLATE] = MetadataDetails(gguf.GGUFValueType.STRING, template)
  129. if args.pre_tokenizer:
  130. new_metadata[gguf.Keys.Tokenizer.PRE] = MetadataDetails(gguf.GGUFValueType.STRING, args.pre_tokenizer)
  131. if remove_metadata:
  132. logger.warning('*** Warning *** Warning *** Warning **')
  133. logger.warning('* Most metadata is required for a fully functional GGUF file,')
  134. logger.warning('* removing crucial metadata may result in a corrupt output file!')
  135. if not args.force:
  136. logger.warning('* Enter exactly YES if you are positive you want to proceed:')
  137. response = input('YES, I am sure> ')
  138. if response != 'YES':
  139. logger.info("You didn't enter YES. Okay then, see ya!")
  140. sys.exit(0)
  141. logger.info(f'* Loading: {args.input}')
  142. reader = gguf.GGUFReader(args.input, 'r')
  143. arch = get_field_data(reader, gguf.Keys.General.ARCHITECTURE)
  144. endianess = get_byteorder(reader)
  145. token_list = get_field_data(reader, gguf.Keys.Tokenizer.LIST) or []
  146. for name, token in args.special_token or []:
  147. if name not in token_names:
  148. logger.warning(f'Unknown special token "{name}", ignoring...')
  149. else:
  150. ids = find_token(token_list, token)
  151. new_metadata[token_names[name]] = MetadataDetails(gguf.GGUFValueType.UINT32, ids[0], f'= {token}')
  152. if len(ids) > 1:
  153. logger.warning(f'Multiple "{token}" tokens found, choosing ID {ids[0]}, use --special-token-by-id if you want another:')
  154. logger.warning(', '.join(str(i) for i in ids))
  155. for name, id_string in args.special_token_by_id or []:
  156. if name not in token_names:
  157. logger.warning(f'Unknown special token "{name}", ignoring...')
  158. elif not id_string.isdecimal():
  159. raise LookupError(f'Token ID "{id_string}" is not a valid ID!')
  160. else:
  161. id_int = int(id_string)
  162. if id_int >= 0 and id_int < len(token_list):
  163. new_metadata[token_names[name]] = MetadataDetails(gguf.GGUFValueType.UINT32, id_int, f'= {token_list[id_int]}')
  164. else:
  165. raise LookupError(f'Token ID {id_int} is not within token list!')
  166. if os.path.isfile(args.output) and not args.force:
  167. logger.warning('*** Warning *** Warning *** Warning **')
  168. logger.warning(f'* The "{args.output}" GGUF file already exists, it will be overwritten!')
  169. logger.warning('* Enter exactly YES if you are positive you want to proceed:')
  170. response = input('YES, I am sure> ')
  171. if response != 'YES':
  172. logger.info("You didn't enter YES. Okay then, see ya!")
  173. sys.exit(0)
  174. logger.info(f'* Writing: {args.output}')
  175. writer = gguf.GGUFWriter(args.output, arch=arch, endianess=endianess)
  176. alignment = get_field_data(reader, gguf.Keys.General.ALIGNMENT)
  177. if alignment is not None:
  178. logger.debug(f'Setting custom alignment: {alignment}')
  179. writer.data_alignment = alignment
  180. copy_with_new_metadata(reader, writer, new_metadata, remove_metadata)
  181. if __name__ == '__main__':
  182. main()