convert-lora-to-ggml.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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("ii", params["r"], params["lora_alpha"]))
  44. def write_tensor_header(
  45. self, name: str, shape: Sequence[int], data_type: DataType
  46. ) -> None:
  47. sname = name.encode("utf-8")
  48. fout.write(
  49. struct.pack(
  50. "iii",
  51. len(shape),
  52. len(sname),
  53. DATA_TYPE_TO_FTYPE[NUMPY_TYPE_TO_DATA_TYPE[data_type]],
  54. )
  55. )
  56. fout.write(struct.pack("i" * len(shape), *shape[::-1]))
  57. fout.write(sname)
  58. fout.seek((fout.tell() + 31) & -32)
  59. if len(sys.argv) != 2:
  60. print(f"Usage: python {sys.argv[0]} <path>")
  61. print(
  62. "Path must contain HuggingFace PEFT LoRA files 'adapter_config.json' and 'adapter_model.bin'"
  63. )
  64. sys.exit(1)
  65. input_json = os.path.join(sys.argv[1], "adapter_config.json")
  66. input_model = os.path.join(sys.argv[1], "adapter_model.bin")
  67. output_path = os.path.join(sys.argv[1], "ggml-adapter-model.bin")
  68. model = torch.load(input_model, map_location="cpu")
  69. with open(input_json, "r") as f:
  70. params = json.load(f)
  71. if params["peft_type"] != "LORA":
  72. print(f"Error: unsupported adapter type {params['peft_type']}, expected LORA")
  73. sys.exit(1)
  74. if params["fan_in_fan_out"] == True:
  75. print("Error: param fan_in_fan_out is not supported")
  76. sys.exit(1)
  77. if params["bias"] is not None and params["bias"] != "none":
  78. print("Error: param bias is not supported")
  79. sys.exit(1)
  80. # TODO: these seem to be layers that have been trained but without lora.
  81. # doesn't seem widely used but eventually should be supported
  82. if params["modules_to_save"] is not None and len(params["modules_to_save"]) > 0:
  83. print("Error: param modules_to_save is not supported")
  84. sys.exit(1)
  85. with open(output_path, "wb") as fout:
  86. fout.truncate()
  87. write_file_header(fout, params)
  88. for k, v in model.items():
  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.numpy()
  96. tname = translate_tensor_name(k)
  97. print(f"{k} => {tname} {t.shape} {t.dtype} {t.nbytes/1024/1024:.2f}MB")
  98. write_tensor_header(fout, tname, t.shape, t.dtype)
  99. t.tofile(fout)
  100. print(f"Converted {input_json} and {input_model} to {output_path}")