convert-lora-to-ggml.py 4.2 KB

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