gguf_set_metadata.py 4.0 KB

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