minicpmv-surgery.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import argparse
  2. import os
  3. import torch
  4. from transformers import AutoModel, AutoTokenizer
  5. ap = argparse.ArgumentParser()
  6. ap.add_argument("-m", "--model", help="Path to MiniCPM-V-2.5 model")
  7. args = ap.parse_args()
  8. # find the model part that includes the the multimodal projector weights
  9. model = AutoModel.from_pretrained(args.model, trust_remote_code=True, local_files_only=True)
  10. checkpoint = model.state_dict()
  11. # get a list of mm tensor names
  12. mm_tensors = [k for k, v in checkpoint.items() if k.startswith("resampler")]
  13. # store these tensors in a new dictionary and torch.save them
  14. projector = {name: checkpoint[name].float() for name in mm_tensors}
  15. torch.save(projector, f"{args.model}/minicpmv.projector")
  16. clip_tensors = [k for k, v in checkpoint.items() if k.startswith("vpm")]
  17. if len(clip_tensors) > 0:
  18. clip = {name.replace("vpm.", ""): checkpoint[name].float() for name in clip_tensors}
  19. torch.save(clip, f"{args.model}/minicpmv.clip")
  20. # added tokens should be removed to be able to convert Mistral models
  21. if os.path.exists(f"{args.model}/added_tokens.json"):
  22. with open(f"{args.model}/added_tokens.json", "w") as f:
  23. f.write("{}\n")
  24. config = model.llm.config
  25. config._name_or_path = "openbmb/MiniCPM-Llama3-V-2.5"
  26. config.auto_map = {
  27. "AutoConfig": "configuration_minicpm.MiniCPMConfig",
  28. "AutoModel": "modeling_minicpm.MiniCPMModel",
  29. "AutoModelForCausalLM": "modeling_minicpm.MiniCPMForCausalLM",
  30. "AutoModelForSeq2SeqLM": "modeling_minicpm.MiniCPMForCausalLM",
  31. "AutoModelForSequenceClassification": "modeling_minicpm.MiniCPMForSequenceClassification"
  32. }
  33. model.llm.save_pretrained(f"{args.model}/model")
  34. tok = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
  35. tok.save_pretrained(f"{args.model}/model")
  36. # os.system(f"cp {args.model}/modeling_minicpm.py {args.model}/MiniCPM_l3/modeling_minicpm.py")
  37. print("Done!")
  38. print(f"Now you can convert {args.model} to a regular LLaMA GGUF file.")
  39. print(f"Also, use {args.model}/minicpmv.projector to prepare a minicpmv-encoder.gguf file.")