1
0

convert-lora-to-ggml.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. #!/usr/bin/env python3
  2. import json
  3. import os
  4. import re
  5. import struct
  6. import sys
  7. from typing import Any, Dict, Sequence, BinaryIO
  8. import numpy as np
  9. import torch
  10. NUMPY_TYPE_TO_FTYPE: Dict[str, int] = {"float32": 0, "float16": 1}
  11. HF_SUBLAYER_TO_GGML = {
  12. "self_attn.q_proj": "attn_q",
  13. "self_attn.k_proj": "attn_k",
  14. "self_attn.v_proj": "attn_v",
  15. "self_attn.o_proj": "attn_output",
  16. "mlp.gate_proj": "ffn_gate",
  17. "mlp.down_proj": "ffn_down",
  18. "mlp.up_proj": "ffn_up",
  19. "input_layernorm": "attn_norm",
  20. "post_attention_layernorm": "ffn_norm",
  21. }
  22. def translate_tensor_name(t: str) -> str:
  23. match = re.match(r".*layers\.(\d+)\.(\w+\.\w+)\.lora_(A|B)\.weight", t)
  24. if match:
  25. nn = match.group(1)
  26. sub_layer = match.group(2)
  27. lora_type = match.group(3)
  28. sub_layer_renamed = HF_SUBLAYER_TO_GGML.get(sub_layer)
  29. if sub_layer_renamed is None:
  30. print(f"Error: unrecognized sub-layer {sub_layer} in tensor {t}")
  31. sys.exit(1)
  32. output_string = (
  33. f"blk.{nn}.{HF_SUBLAYER_TO_GGML[sub_layer]}.weight.lora{lora_type}"
  34. )
  35. return output_string
  36. else:
  37. print(f"Error: unrecognized tensor {t}")
  38. sys.exit(1)
  39. def write_file_header(fout: BinaryIO, params: Dict[str, Any]) -> None:
  40. fout.write(b"ggla"[::-1]) # magic (ggml lora)
  41. fout.write(struct.pack("i", 1)) # file version
  42. fout.write(struct.pack("i", params["r"]))
  43. # https://opendelta.readthedocs.io/en/latest/modules/deltas.html says that `lora_alpha` is an int
  44. # but some models ship a float value instead
  45. # let's convert to int, but fail if lossless conversion is not possible
  46. assert (
  47. int(params["lora_alpha"]) == params["lora_alpha"]
  48. ), "cannot convert float to int losslessly"
  49. fout.write(struct.pack("i", int(params["lora_alpha"])))
  50. def write_tensor_header(
  51. self, name: str, shape: Sequence[int], data_type: np.dtype[Any]
  52. ) -> None:
  53. sname = name.encode("utf-8")
  54. fout.write(
  55. struct.pack(
  56. "iii",
  57. len(shape),
  58. len(sname),
  59. NUMPY_TYPE_TO_FTYPE[data_type.name],
  60. )
  61. )
  62. fout.write(struct.pack("i" * len(shape), *shape[::-1]))
  63. fout.write(sname)
  64. fout.seek((fout.tell() + 31) & -32)
  65. if len(sys.argv) != 2:
  66. print(f"Usage: python {sys.argv[0]} <path>")
  67. print(
  68. "Path must contain HuggingFace PEFT LoRA files 'adapter_config.json' and 'adapter_model.bin'"
  69. )
  70. sys.exit(1)
  71. input_json = os.path.join(sys.argv[1], "adapter_config.json")
  72. input_model = os.path.join(sys.argv[1], "adapter_model.bin")
  73. output_path = os.path.join(sys.argv[1], "ggml-adapter-model.bin")
  74. model = torch.load(input_model, map_location="cpu")
  75. with open(input_json, "r") as f:
  76. params = json.load(f)
  77. if params["peft_type"] != "LORA":
  78. print(f"Error: unsupported adapter type {params['peft_type']}, expected LORA")
  79. sys.exit(1)
  80. if params["fan_in_fan_out"] is True:
  81. print("Error: param fan_in_fan_out is not supported")
  82. sys.exit(1)
  83. if params["bias"] is not None and params["bias"] != "none":
  84. print("Error: param bias is not supported")
  85. sys.exit(1)
  86. # TODO: these seem to be layers that have been trained but without lora.
  87. # doesn't seem widely used but eventually should be supported
  88. if params["modules_to_save"] is not None and len(params["modules_to_save"]) > 0:
  89. print("Error: param modules_to_save is not supported")
  90. sys.exit(1)
  91. with open(output_path, "wb") as fout:
  92. fout.truncate()
  93. write_file_header(fout, params)
  94. for k, v in model.items():
  95. if k.endswith(".default.weight"):
  96. k = k.replace(".default.weight", ".weight")
  97. if k in ["llama_proj.weight", "llama_proj.bias"]:
  98. continue
  99. if k.endswith("lora_A.weight"):
  100. if v.dtype != torch.float16 and v.dtype != torch.float32:
  101. v = v.float()
  102. v = v.T
  103. else:
  104. v = v.float()
  105. t = v.detach().numpy()
  106. tname = translate_tensor_name(k)
  107. print(f"{k} => {tname} {t.shape} {t.dtype} {t.nbytes/1024/1024:.2f}MB")
  108. write_tensor_header(fout, tname, t.shape, t.dtype)
  109. t.tofile(fout)
  110. print(f"Converted {input_json} and {input_model} to {output_path}")