1
0

minicpmv-surgery.py 2.1 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 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, torch_dtype=torch.bfloat16)
  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. if 'resampler.proj' in projector.keys() and hasattr(model.llm.config,'scale_emb') is True:
  16. projector['resampler.proj'] = projector['resampler.proj'] / model.llm.config.scale_emb
  17. torch.save(projector, f"{args.model}/minicpmv.projector")
  18. clip_tensors = [k for k, v in checkpoint.items() if k.startswith("vpm")]
  19. if len(clip_tensors) > 0:
  20. clip = {name.replace("vpm.", ""): checkpoint[name].float() for name in clip_tensors}
  21. torch.save(clip, f"{args.model}/minicpmv.clip")
  22. # added tokens should be removed to be able to convert Mistral models
  23. if os.path.exists(f"{args.model}/added_tokens.json"):
  24. with open(f"{args.model}/added_tokens.json", "w") as f:
  25. f.write("{}\n")
  26. config = model.llm.config
  27. config.auto_map = {
  28. "AutoConfig": "configuration_minicpm.MiniCPMConfig",
  29. "AutoModel": "modeling_minicpm.MiniCPMModel",
  30. "AutoModelForCausalLM": "modeling_minicpm.MiniCPMForCausalLM",
  31. "AutoModelForSeq2SeqLM": "modeling_minicpm.MiniCPMForCausalLM",
  32. "AutoModelForSequenceClassification": "modeling_minicpm.MiniCPMForSequenceClassification"
  33. }
  34. model.llm.save_pretrained(f"{args.model}/model")
  35. tok = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
  36. tok.save_pretrained(f"{args.model}/model")
  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.")