gguf-convert-endian.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import argparse
  4. import os
  5. import sys
  6. from pathlib import Path
  7. import numpy as np
  8. # Necessary to load the local gguf package
  9. if "NO_LOCAL_GGUF" not in os.environ and (Path(__file__).parent.parent.parent / 'gguf-py').exists():
  10. sys.path.insert(0, str(Path(__file__).parent.parent))
  11. import gguf
  12. def convert_byteorder(reader: gguf.GGUFReader, args: argparse.Namespace) -> None:
  13. if np.uint32(1) == np.uint32(1).newbyteorder("<"):
  14. # Host is little endian
  15. host_endian = "little"
  16. swapped_endian = "big"
  17. else:
  18. # Sorry PDP or other weird systems that don't use BE or LE.
  19. host_endian = "big"
  20. swapped_endian = "little"
  21. if reader.byte_order == "S":
  22. file_endian = swapped_endian
  23. else:
  24. file_endian = host_endian
  25. order = host_endian if args.order == "native" else args.order
  26. print(f"* Host is {host_endian.upper()} endian, GGUF file seems to be {file_endian.upper()} endian")
  27. if file_endian == order:
  28. print(f"* File is already {order.upper()} endian. Nothing to do.")
  29. sys.exit(0)
  30. print("* Checking tensors for conversion compatibility")
  31. for tensor in reader.tensors:
  32. if tensor.tensor_type not in (
  33. gguf.GGMLQuantizationType.F32,
  34. gguf.GGMLQuantizationType.F16,
  35. gguf.GGMLQuantizationType.Q8_0,
  36. ):
  37. raise ValueError(f"Cannot handle type {tensor.tensor_type.name} for tensor {repr(tensor.name)}")
  38. print(f"* Preparing to convert from {file_endian.upper()} to {order.upper()}")
  39. if args.dry_run:
  40. return
  41. print("\n*** Warning *** Warning *** Warning **")
  42. print("* This conversion process may damage the file. Ensure you have a backup.")
  43. if order != host_endian:
  44. print("* Requested endian differs from host, you will not be able to load the model on this machine.")
  45. print("* The file will be modified immediately, so if conversion fails or is interrupted")
  46. print("* the file will be corrupted. Enter exactly YES if you are positive you want to proceed:")
  47. response = input("YES, I am sure> ")
  48. if response != "YES":
  49. print("You didn't enter YES. Okay then, see ya!")
  50. sys.exit(0)
  51. print(f"\n* Converting fields ({len(reader.fields)})")
  52. for idx, field in enumerate(reader.fields.values()):
  53. print(f"- {idx:4}: Converting field {repr(field.name)}, part count: {len(field.parts)}")
  54. for part in field.parts:
  55. part.byteswap(inplace=True)
  56. print(f"\n* Converting tensors ({len(reader.tensors)})")
  57. for idx, tensor in enumerate(reader.tensors):
  58. print(
  59. f" - {idx:4}: Converting tensor {repr(tensor.name)}, type={tensor.tensor_type.name}, "
  60. f"elements={tensor.n_elements}... ",
  61. end="",
  62. )
  63. tensor_type = tensor.tensor_type
  64. for part in tensor.field.parts:
  65. part.byteswap(inplace=True)
  66. if tensor_type != gguf.GGMLQuantizationType.Q8_0:
  67. tensor.data.byteswap(inplace=True)
  68. print()
  69. continue
  70. # A Q8_0 block consists of a f16 delta followed by 32 int8 quants, so 34 bytes
  71. block_size = 34
  72. n_blocks = len(tensor.data) // block_size
  73. for block_num in range(n_blocks):
  74. block_offs = block_num * block_size
  75. # I know I said f16, but it doesn't matter here - any simple 16 bit type works.
  76. delta = tensor.data[block_offs:block_offs + 2].view(dtype=np.uint16)
  77. delta.byteswap(inplace=True)
  78. if block_num % 100000 == 0:
  79. print(f"[{(n_blocks - block_num) // 1000}K]", end="")
  80. sys.stdout.flush()
  81. print()
  82. print("* Completion")
  83. def main() -> None:
  84. parser = argparse.ArgumentParser(description="Convert GGUF file byte order")
  85. parser.add_argument(
  86. "model", type=str,
  87. help="GGUF format model filename",
  88. )
  89. parser.add_argument(
  90. "order", type=str, choices=['big', 'little', 'native'],
  91. help="Requested byte order",
  92. )
  93. parser.add_argument(
  94. "--dry-run", action="store_true",
  95. help="Don't actually change anything",
  96. )
  97. args = parser.parse_args(None if len(sys.argv) > 1 else ["--help"])
  98. print(f'* Loading: {args.model}')
  99. reader = gguf.GGUFReader(args.model, 'r' if args.dry_run else 'r+')
  100. convert_byteorder(reader, args)
  101. if __name__ == "__main__":
  102. main()