convert_lora_to_ggml.py 5.2 KB

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