convert-lora-to-ggml.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import json
  2. import os
  3. import re
  4. import struct
  5. import sys
  6. from typing import Any, Dict, Sequence, TextIO
  7. import torch
  8. from convert import DATA_TYPE_TO_FTYPE, NUMPY_TYPE_TO_DATA_TYPE, DataType
  9. HF_SUBLAYER_TO_GGML = {
  10. "self_attn.q_proj": "attention.wq",
  11. "self_attn.k_proj": "attention.wk",
  12. "self_attn.v_proj": "attention.wv",
  13. "self_attn.o_proj": "attention.wo",
  14. "mlp.gate_proj": "feed_forward.w1",
  15. "mlp.down_proj": "feed_forward.w2",
  16. "mlp.up_proj": "feed_forward.w3",
  17. "input_layernorm": "attention_norm",
  18. "post_attention_layernorm": "ffn_norm",
  19. # "norm": "norm",
  20. # "embed_tokens": "tok_embeddings",
  21. # "lm_head": "output",
  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"layers.{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: TextIO, 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 int(params["lora_alpha"]) == params["lora_alpha"], "cannot convert float to int losslessly"
  48. fout.write(struct.pack("i", int(params["lora_alpha"])))
  49. def write_tensor_header(
  50. self, name: str, shape: Sequence[int], data_type: DataType
  51. ) -> None:
  52. sname = name.encode("utf-8")
  53. fout.write(
  54. struct.pack(
  55. "iii",
  56. len(shape),
  57. len(sname),
  58. DATA_TYPE_TO_FTYPE[NUMPY_TYPE_TO_DATA_TYPE[data_type]],
  59. )
  60. )
  61. fout.write(struct.pack("i" * len(shape), *shape[::-1]))
  62. fout.write(sname)
  63. fout.seek((fout.tell() + 31) & -32)
  64. if len(sys.argv) != 2:
  65. print(f"Usage: python {sys.argv[0]} <path>")
  66. print(
  67. "Path must contain HuggingFace PEFT LoRA files 'adapter_config.json' and 'adapter_model.bin'"
  68. )
  69. sys.exit(1)
  70. input_json = os.path.join(sys.argv[1], "adapter_config.json")
  71. input_model = os.path.join(sys.argv[1], "adapter_model.bin")
  72. output_path = os.path.join(sys.argv[1], "ggml-adapter-model.bin")
  73. model = torch.load(input_model, map_location="cpu")
  74. with open(input_json, "r") as f:
  75. params = json.load(f)
  76. if params["peft_type"] != "LORA":
  77. print(f"Error: unsupported adapter type {params['peft_type']}, expected LORA")
  78. sys.exit(1)
  79. if params["fan_in_fan_out"] is True:
  80. print("Error: param fan_in_fan_out is not supported")
  81. sys.exit(1)
  82. if params["bias"] is not None and params["bias"] != "none":
  83. print("Error: param bias is not supported")
  84. sys.exit(1)
  85. # TODO: these seem to be layers that have been trained but without lora.
  86. # doesn't seem widely used but eventually should be supported
  87. if params["modules_to_save"] is not None and len(params["modules_to_save"]) > 0:
  88. print("Error: param modules_to_save is not supported")
  89. sys.exit(1)
  90. with open(output_path, "wb") as fout:
  91. fout.truncate()
  92. write_file_header(fout, params)
  93. for k, v in model.items():
  94. if k.endswith("lora_A.weight"):
  95. if v.dtype != torch.float16 and v.dtype != torch.float32:
  96. v = v.float()
  97. v = v.T
  98. else:
  99. v = v.float()
  100. t = v.numpy()
  101. tname = translate_tensor_name(k)
  102. print(f"{k} => {tname} {t.shape} {t.dtype} {t.nbytes/1024/1024:.2f}MB")
  103. write_tensor_header(fout, tname, t.shape, t.dtype)
  104. t.tofile(fout)
  105. print(f"Converted {input_json} and {input_model} to {output_path}")