qwen2_vl_surgery.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import argparse
  2. from typing import Dict
  3. import torch
  4. import numpy as np
  5. from gguf import *
  6. from transformers import (
  7. Qwen2VLForConditionalGeneration,
  8. Qwen2VLProcessor,
  9. AutoProcessor,
  10. Qwen2VLConfig
  11. )
  12. VISION = "clip.vision"
  13. def k(raw_key: str, arch: str) -> str:
  14. return raw_key.format(arch=arch)
  15. def to_gguf_name(name: str) -> str:
  16. og = name
  17. name = name.replace("text_model", "t").replace("vision_model", "v")
  18. name = name.replace("blocks", "blk").replace("embeddings.", "")
  19. name = name.replace("attn.", "attn_")
  20. name = name.replace("mlp.fc1", "ffn_down").replace("mlp.fc2", "ffn_up").replace("proj.", "out.")
  21. # name = name.replace("layrnorm", "ln").replace("layer_norm", "ln").replace("layernorm", "ln")
  22. name = name.replace("norm1", "ln1").replace("norm2", "ln2")
  23. name = name.replace("merger.mlp", 'mm')
  24. print(f"[to_gguf_name] {og} --> {name}")
  25. return name
  26. def find_vision_tensors(qwen2vl, dtype) -> Dict[str, np.ndarray]:
  27. vision_model = qwen2vl.visual
  28. tensor_map = {}
  29. for name, ten in vision_model.state_dict().items():
  30. ten = ten.numpy()
  31. if 'qkv' in name:
  32. if ten.ndim == 2: # weight
  33. c3, _ = ten.shape
  34. else: # bias
  35. c3 = ten.shape[0]
  36. assert c3 % 3 == 0
  37. c = c3 // 3
  38. wq = ten[:c]
  39. wk = ten[c: c * 2]
  40. wv = ten[c * 2:]
  41. tensor_map[to_gguf_name(f"vision_model.{name}").replace("qkv", "q")] = wq
  42. tensor_map[to_gguf_name(f"vision_model.{name}").replace("qkv", "k")] = wk
  43. tensor_map[to_gguf_name(f"vision_model.{name}").replace("qkv", "v")] = wv
  44. elif 'merger' in name:
  45. if name.endswith("ln_q.weight"):
  46. tensor_map['v.post_ln.weight'] = ten
  47. elif name.endswith("ln_q.bias"):
  48. tensor_map['v.post_ln.bias'] = ten
  49. else:
  50. # "merger.mlp.%d.weight/bias" --> "mm.%d.weight/bias"
  51. tensor_map[to_gguf_name(name)] = ten
  52. elif 'patch_embed.proj.weight' in name:
  53. # NOTE: split Conv3D into Conv2Ds
  54. c1, c2, kt, kh, kw = ten.shape
  55. assert kt == 2, "Current implmentation only support temporal_patch_size of 2"
  56. tensor_map["v.patch_embd.weight"] = ten[:, :, 0, ...]
  57. tensor_map["v.patch_embd.weight.1"] = ten[:, :, 1, ...]
  58. else:
  59. tensor_map[to_gguf_name(f"vision_model.{name}")] = ten
  60. for new_name, ten in tensor_map.items():
  61. if ten.ndim <= 1 or new_name.endswith("_norm.weight"):
  62. tensor_map[new_name] = ten.astype(np.float32)
  63. else:
  64. tensor_map[new_name] = ten.astype(dtype)
  65. tensor_map["v.position_embd.weight"] = np.zeros([10, 10], dtype=np.float32) # dummy tensor, just here as a placeholder
  66. return tensor_map
  67. def main(args):
  68. if args.data_type == 'fp32':
  69. dtype = torch.float32
  70. np_dtype = np.float32
  71. ftype = 0
  72. elif args.data_type == 'fp16':
  73. dtype = torch.float32
  74. np_dtype = np.float16
  75. ftype = 1
  76. else:
  77. raise ValueError()
  78. local_model = False
  79. model_path = ""
  80. model_name = args.model_name
  81. print("model_name: ", model_name)
  82. qwen2vl = Qwen2VLForConditionalGeneration.from_pretrained(
  83. model_name, torch_dtype=dtype, device_map="cpu"
  84. )
  85. cfg: Qwen2VLConfig = qwen2vl.config # type: ignore[reportAssignmentType]
  86. vcfg = cfg.vision_config
  87. if os.path.isdir(model_name):
  88. local_model = True
  89. if model_name.endswith(os.sep):
  90. model_name = model_name[:-1]
  91. model_path = model_name
  92. model_name = os.path.basename(model_name)
  93. fname_out = f"{model_name.replace('/', '-').lower()}-vision.gguf"
  94. fout = GGUFWriter(path=fname_out, arch="clip")
  95. fout.add_description("image encoder for Qwen2VL")
  96. fout.add_file_type(ftype)
  97. fout.add_bool("clip.has_text_encoder", False)
  98. fout.add_bool("clip.has_vision_encoder", True)
  99. fout.add_bool("clip.has_qwen2vl_merger", True)
  100. fout.add_string("clip.projector_type", "qwen2vl_merger")
  101. print(cfg.vision_config)
  102. if 'silu' in cfg.vision_config.hidden_act.lower():
  103. fout.add_bool("clip.use_silu", True)
  104. fout.add_bool("clip.use_gelu", False)
  105. elif 'gelu' in cfg.vision_config.hidden_act.lower():
  106. fout.add_bool("clip.use_silu", False)
  107. fout.add_bool("clip.use_gelu", 'quick' not in cfg.vision_config.hidden_act.lower())
  108. else:
  109. raise ValueError()
  110. tensor_map = find_vision_tensors(qwen2vl, np_dtype)
  111. for name, data in tensor_map.items():
  112. fout.add_tensor(name, data)
  113. fout.add_uint32("clip.vision.patch_size", vcfg.patch_size)
  114. fout.add_uint32("clip.vision.image_size", 14 * 40) # some reasonable size that is divable by (14*2)
  115. fout.add_uint32(k(KEY_EMBEDDING_LENGTH, VISION), vcfg.embed_dim)
  116. fout.add_uint32("clip.vision.projection_dim", vcfg.hidden_size)
  117. fout.add_uint32(k(KEY_ATTENTION_HEAD_COUNT, VISION), vcfg.num_heads)
  118. fout.add_float32(k(KEY_ATTENTION_LAYERNORM_EPS, VISION), 1e-6)
  119. fout.add_uint32(k(KEY_BLOCK_COUNT, VISION), vcfg.depth)
  120. fout.add_uint32(k(KEY_FEED_FORWARD_LENGTH, VISION), 0) # not sure what this does, put 0 here as a placeholder
  121. fout.add_name(model_name)
  122. """
  123. HACK: Since vision rope related parameter aren't stored in the `Qwen2VLConfig,
  124. it will be hardcoded in the `clip_image_build_graph` from `clip.cpp`.
  125. """
  126. if local_model:
  127. processor: Qwen2VLProcessor = AutoProcessor.from_pretrained(model_path)
  128. else:
  129. processor: Qwen2VLProcessor = AutoProcessor.from_pretrained(model_name)
  130. fout.add_array("clip.vision.image_mean", processor.image_processor.image_mean) # type: ignore[reportAttributeAccessIssue]
  131. fout.add_array("clip.vision.image_std", processor.image_processor.image_std) # type: ignore[reportAttributeAccessIssue]
  132. fout.write_header_to_file()
  133. fout.write_kv_data_to_file()
  134. fout.write_tensors_to_file()
  135. fout.close()
  136. print("save model as: ", fname_out)
  137. if __name__ == "__main__":
  138. parser = argparse.ArgumentParser()
  139. parser.add_argument("model_name", nargs='?', default="Qwen/Qwen2-VL-2B-Instruct")
  140. parser.add_argument("--data_type", nargs='?', choices=['fp32', 'fp16'], default="fp32")
  141. args = parser.parse_args()
  142. main(args)