1
0

convert-lora-to-ggml.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import logging
  4. import json
  5. import os
  6. import struct
  7. import sys
  8. from pathlib import Path
  9. from typing import Any, BinaryIO, Sequence
  10. import numpy as np
  11. import torch
  12. if 'NO_LOCAL_GGUF' not in os.environ:
  13. sys.path.insert(1, str(Path(__file__).parent / 'gguf-py' / 'gguf'))
  14. import gguf
  15. logging.basicConfig(level=logging.DEBUG)
  16. logger = logging.getLogger("lora-to-gguf")
  17. NUMPY_TYPE_TO_FTYPE: dict[str, int] = {"float32": 0, "float16": 1}
  18. def write_file_header(fout: BinaryIO, params: dict[str, Any]) -> None:
  19. fout.write(b"ggla"[::-1]) # magic (ggml lora)
  20. fout.write(struct.pack("i", 1)) # file version
  21. fout.write(struct.pack("i", params["r"]))
  22. # https://opendelta.readthedocs.io/en/latest/modules/deltas.html says that `lora_alpha` is an int
  23. # but some models ship a float value instead
  24. # let's convert to int, but fail if lossless conversion is not possible
  25. assert (
  26. int(params["lora_alpha"]) == params["lora_alpha"]
  27. ), "cannot convert float to int losslessly"
  28. fout.write(struct.pack("i", int(params["lora_alpha"])))
  29. def write_tensor_header(fout: BinaryIO, name: str, shape: Sequence[int], data_type: np.dtype[Any]) -> None:
  30. sname = name.encode("utf-8")
  31. fout.write(
  32. struct.pack(
  33. "iii",
  34. len(shape),
  35. len(sname),
  36. NUMPY_TYPE_TO_FTYPE[data_type.name],
  37. )
  38. )
  39. fout.write(struct.pack("i" * len(shape), *shape[::-1]))
  40. fout.write(sname)
  41. fout.seek((fout.tell() + 31) & -32)
  42. if __name__ == '__main__':
  43. if len(sys.argv) < 2:
  44. logger.info(f"Usage: python {sys.argv[0]} <path> [arch]")
  45. logger.info("Path must contain HuggingFace PEFT LoRA files 'adapter_config.json' and 'adapter_model.bin'")
  46. logger.info(f"Arch must be one of {list(gguf.MODEL_ARCH_NAMES.values())} (default: llama)")
  47. sys.exit(1)
  48. input_json = os.path.join(sys.argv[1], "adapter_config.json")
  49. input_model = os.path.join(sys.argv[1], "adapter_model.bin")
  50. output_path = os.path.join(sys.argv[1], "ggml-adapter-model.bin")
  51. if os.path.exists(input_model):
  52. model = torch.load(input_model, map_location="cpu")
  53. else:
  54. input_model = os.path.join(sys.argv[1], "adapter_model.safetensors")
  55. # lazy import load_file only if lora is in safetensors format.
  56. from safetensors.torch import load_file
  57. model = load_file(input_model, device="cpu")
  58. arch_name = sys.argv[2] if len(sys.argv) == 3 else "llama"
  59. if arch_name not in gguf.MODEL_ARCH_NAMES.values():
  60. logger.error(f"Error: unsupported architecture {arch_name}")
  61. sys.exit(1)
  62. arch = list(gguf.MODEL_ARCH_NAMES.keys())[list(gguf.MODEL_ARCH_NAMES.values()).index(arch_name)]
  63. name_map = gguf.TensorNameMap(arch, 200) # 200 layers ought to be enough for anyone
  64. with open(input_json, "r") as f:
  65. params = json.load(f)
  66. if params["peft_type"] != "LORA":
  67. logger.error(f"Error: unsupported adapter type {params['peft_type']}, expected LORA")
  68. sys.exit(1)
  69. if params["fan_in_fan_out"] is True:
  70. logger.error("Error: param fan_in_fan_out is not supported")
  71. sys.exit(1)
  72. if params["bias"] is not None and params["bias"] != "none":
  73. logger.error("Error: param bias is not supported")
  74. sys.exit(1)
  75. # TODO: these seem to be layers that have been trained but without lora.
  76. # doesn't seem widely used but eventually should be supported
  77. if params["modules_to_save"] is not None and len(params["modules_to_save"]) > 0:
  78. logger.error("Error: param modules_to_save is not supported")
  79. sys.exit(1)
  80. with open(output_path, "wb") as fout:
  81. fout.truncate()
  82. write_file_header(fout, params)
  83. for k, v in model.items():
  84. orig_k = k
  85. if k.endswith(".default.weight"):
  86. k = k.replace(".default.weight", ".weight")
  87. if k in ["llama_proj.weight", "llama_proj.bias"]:
  88. continue
  89. if k.endswith("lora_A.weight"):
  90. if v.dtype != torch.float16 and v.dtype != torch.float32:
  91. v = v.float()
  92. v = v.T
  93. else:
  94. v = v.float()
  95. t = v.detach().numpy()
  96. prefix = "base_model.model."
  97. if k.startswith(prefix):
  98. k = k[len(prefix) :]
  99. lora_suffixes = (".lora_A.weight", ".lora_B.weight")
  100. if k.endswith(lora_suffixes):
  101. suffix = k[-len(lora_suffixes[0]):]
  102. k = k[: -len(lora_suffixes[0])]
  103. else:
  104. logger.error(f"Error: unrecognized tensor name {orig_k}")
  105. sys.exit(1)
  106. tname = name_map.get_name(k)
  107. if tname is None:
  108. logger.error(f"Error: could not map tensor name {orig_k}")
  109. logger.error(" Note: the arch parameter must be specified if the model is not llama")
  110. sys.exit(1)
  111. if suffix == ".lora_A.weight":
  112. tname += ".weight.loraA"
  113. elif suffix == ".lora_B.weight":
  114. tname += ".weight.loraB"
  115. else:
  116. assert False
  117. logger.info(f"{k} => {tname} {t.shape} {t.dtype} {t.nbytes/1024/1024:.2f}MB")
  118. write_tensor_header(fout, tname, t.shape, t.dtype)
  119. t.tofile(fout)
  120. logger.info(f"Converted {input_json} and {input_model} to {output_path}")