gguf-set-metadata.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. import sys
  5. from pathlib import Path
  6. # Necessary to load the local gguf package
  7. if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent / 'gguf-py').exists():
  8. sys.path.insert(0, str(Path(__file__).parent.parent))
  9. from gguf import GGUFReader # noqa: E402
  10. def minimal_example(filename: str) -> None:
  11. reader = GGUFReader(filename, 'r+')
  12. field = reader.fields['tokenizer.ggml.bos_token_id']
  13. if field is None:
  14. return
  15. part_index = field.data[0]
  16. field.parts[part_index][0] = 2 # Set tokenizer.ggml.bos_token_id to 2
  17. #
  18. # So what's this field.data thing? It's helpful because field.parts contains
  19. # _every_ part of the GGUF field. For example, tokenizer.ggml.bos_token_id consists
  20. # of:
  21. #
  22. # Part index 0: Key length (27)
  23. # Part index 1: Key data ("tokenizer.ggml.bos_token_id")
  24. # Part index 2: Field type (4, the id for GGUFValueType.UINT32)
  25. # Part index 3: Field value
  26. #
  27. # Note also that each part is an NDArray slice, so even a part that
  28. # is only a single value like the key length will be a NDArray of
  29. # the key length type (numpy.uint32).
  30. #
  31. # The .data attribute in the Field is a list of relevant part indexes
  32. # and doesn't contain internal GGUF details like the key length part.
  33. # In this case, .data will be [3] - just the part index of the
  34. # field value itself.
  35. def set_metadata(reader: GGUFReader, args: argparse.Namespace) -> None:
  36. field = reader.get_field(args.key)
  37. if field is None:
  38. print(f'! Field {repr(args.key)} not found', file = sys.stderr)
  39. sys.exit(1)
  40. # Note that field.types is a list of types. This is because the GGUF
  41. # format supports arrays. For example, an array of UINT32 would
  42. # look like [GGUFValueType.ARRAY, GGUFValueType.UINT32]
  43. handler = reader.gguf_scalar_to_np.get(field.types[0]) if field.types else None
  44. if handler is None:
  45. print(
  46. f'! This tool only supports changing simple values, {repr(args.key)} has unsupported type {field.types}',
  47. file = sys.stderr,
  48. )
  49. sys.exit(1)
  50. current_value = field.parts[field.data[0]][0]
  51. new_value = handler(args.value)
  52. print(f'* Preparing to change field {repr(args.key)} from {current_value} to {new_value}')
  53. if current_value == new_value:
  54. print(f'- Key {repr(args.key)} already set to requested value {current_value}')
  55. sys.exit(0)
  56. if args.dry_run:
  57. sys.exit(0)
  58. if not args.force:
  59. print('*** Warning *** Warning *** Warning **')
  60. print('* Changing fields in a GGUF file can make it unusable. Proceed at your own risk.')
  61. print('* Enter exactly YES if you are positive you want to proceed:')
  62. response = input('YES, I am sure> ')
  63. if response != 'YES':
  64. print("You didn't enter YES. Okay then, see ya!")
  65. sys.exit(0)
  66. field.parts[field.data[0]][0] = new_value
  67. print('* Field changed. Successful completion.')
  68. def main() -> None:
  69. parser = argparse.ArgumentParser(description="Set a simple value in GGUF file metadata")
  70. parser.add_argument("model", type=str, help="GGUF format model filename")
  71. parser.add_argument("key", type=str, help="Metadata key to set")
  72. parser.add_argument("value", type=str, help="Metadata value to set")
  73. parser.add_argument("--dry-run", action="store_true", help="Don't actually change anything")
  74. parser.add_argument("--force", action="store_true", help="Change the field without confirmation")
  75. args = parser.parse_args(None if len(sys.argv) > 1 else ["--help"])
  76. print(f'* Loading: {args.model}')
  77. reader = GGUFReader(args.model, 'r' if args.dry_run else 'r+')
  78. set_metadata(reader, args)
  79. if __name__ == '__main__':
  80. main()