llava-surgery-v2.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import argparse
  2. import glob
  3. import os
  4. import torch
  5. from safetensors.torch import load as safe_load, save as safe_save, safe_open, save_file
  6. # Function to determine if file is a SafeTensor file
  7. def is_safetensor_file(file_path):
  8. return file_path.endswith('.safetensors')
  9. # Unified loading function
  10. def load_model(file_path):
  11. if is_safetensor_file(file_path):
  12. tensors = {}
  13. with safe_open(file_path, framework="pt", device="cpu") as f:
  14. for key in f.keys():
  15. tensors[key] = f.get_tensor(key).clone()
  16. # output shape
  17. print(f"{key} : {tensors[key].shape}")
  18. return tensors, 'safetensor'
  19. else:
  20. return torch.load(file_path, map_location=torch.device('cpu')), 'pytorch'
  21. # Unified saving function
  22. def save_model(model, file_path, file_type):
  23. if file_type == 'safetensor':
  24. # safe_save(model, file_path)
  25. save_file(model, file_path)
  26. else:
  27. torch.save(model, file_path)
  28. # Adapted function to clean vision tower from checkpoint
  29. def clean_vision_tower_from_checkpoint(checkpoint_path):
  30. checkpoint, file_type = load_model(checkpoint_path)
  31. # file_type = 'pytorch'
  32. model_path = os.path.dirname(checkpoint_path)
  33. print(f"Searching for vision tower tensors in {checkpoint_path}")
  34. clip_tensors = [k for k, v in checkpoint.items() if (k.startswith("model.vision_tower") or k.startswith("vit."))]
  35. if len(clip_tensors) > 0:
  36. print(f"Found {len(clip_tensors)} tensors to extract from {checkpoint_path}")
  37. # Adapted for file type
  38. clip_path = os.path.join(model_path, "llava.clip")
  39. if os.path.exists(clip_path):
  40. print(f"Loading existing llava.clip from {clip_path}")
  41. existing_clip, _ = load_model(clip_path)
  42. else:
  43. print(f"Creating new llava.clip at {clip_path}")
  44. existing_clip = {}
  45. # Update existing_clip with new tensors, avoid duplicates
  46. for name in clip_tensors:
  47. simple_name = name[name.index('vision_model.'):] if 'vision_model.' in name else name
  48. print(f"Adding {simple_name} to llava.clip")
  49. if simple_name not in existing_clip:
  50. existing_clip[simple_name] = checkpoint[name]
  51. # Save the updated clip tensors back to llava.clip
  52. save_model(existing_clip, clip_path, 'pytorch')
  53. # Remove the tensors from the original checkpoint
  54. for name in clip_tensors:
  55. del checkpoint[name]
  56. checkpoint_path = checkpoint_path
  57. return True
  58. return False
  59. def find_relevant_checkpoints(checkpoint_paths, newline_criteria, projector):
  60. newline_checkpoint_path = None
  61. projector_checkpoint_path = None
  62. for path in checkpoint_paths:
  63. checkpoint, _ = load_model(path)
  64. if newline_criteria(checkpoint) and newline_checkpoint_path is None:
  65. newline_checkpoint_path = path
  66. if projector(checkpoint):
  67. projector_checkpoint_path = path
  68. return newline_checkpoint_path, projector_checkpoint_path
  69. def newline_criteria(checkpoint):
  70. return any(k.startswith("model.image_newline") for k in checkpoint.keys())
  71. def proj_criteria(checkpoint):
  72. return any(k.startswith("model.mm_projector") or k.startswith("vision_proj.") for k in checkpoint.keys())
  73. # Command-line interface setup
  74. ap = argparse.ArgumentParser()
  75. ap.add_argument("-m", "--model", required=True, help="Path to LLaVA v1.5+ model")
  76. ap.add_argument("-C", "--clean-vision-tower", action="store_true", help="Remove any vision tower from the model files")
  77. args = ap.parse_args()
  78. if args.clean_vision_tower:
  79. # Generalized to handle both PyTorch and SafeTensors models
  80. model_files = sorted(glob.glob(f"{args.model}/*"), key=os.path.getmtime, reverse=True)
  81. # checkpoint_paths = [path for path in model_files if (path.endswith('.bin') and path.startswith('pytorch')) or (path.endswith('.safetensors') and path.startswith('model'))]
  82. checkpoint_paths = [path for path in model_files if (path.endswith('.bin') and 'pytorch' in path.split('/')[-1].split('\\')[-1]) or (path.endswith('.safetensors') and 'model' in path.split('/')[-1].split('\\')[-1])]
  83. for projector_checkpoint_path in checkpoint_paths:
  84. print(f"Cleaning {projector_checkpoint_path}")
  85. if not clean_vision_tower_from_checkpoint(projector_checkpoint_path):
  86. print(f"No vision tower found in {projector_checkpoint_path}")
  87. # we break once none is found, so far all models append them at the end
  88. # break
  89. print("Done! All vision tower tensors are removed from the model files and stored in llava.clip file.")
  90. # Now we look for the projector in the last checkpoint
  91. model_files = sorted(glob.glob(f"{args.model}/*"), key=os.path.getmtime, reverse=True)
  92. checkpoint_paths = [path for path in model_files if (path.endswith('.bin') and 'pytorch' in path.split('/')[-1].split('\\')[-1]) or (path.endswith('.safetensors') and 'model' in path.split('/')[-1].split('\\')[-1])]
  93. # last_checkpoint_path = checkpoint_paths[0]
  94. # first_checkpoint_path = checkpoint_paths[-1]
  95. newline_checkpoint_path, projector_checkpoint_path = find_relevant_checkpoints(checkpoint_paths, newline_criteria, proj_criteria)
  96. print(f"Taking projector from {projector_checkpoint_path}")
  97. first_mm_tensors = []
  98. first_checkpoint = None
  99. if newline_checkpoint_path is not None:
  100. print(f"Taking newline from {newline_checkpoint_path}")
  101. first_checkpoint, file_type = load_model(newline_checkpoint_path)
  102. first_mm_tensors = [k for k, v in first_checkpoint.items() if k.startswith("model.image_newline")]
  103. # Load the checkpoint
  104. mm_tensors = []
  105. last_checkpoint = None
  106. if projector_checkpoint_path is not None:
  107. last_checkpoint, file_type = load_model(projector_checkpoint_path)
  108. mm_tensors = [k for k, v in last_checkpoint.items() if k.startswith("model.mm_projector") or k.startswith("vision_proj.")]
  109. if len(mm_tensors) == 0:
  110. if last_checkpoint is not None:
  111. for k, v in last_checkpoint.items():
  112. print(k)
  113. print(f"Found {len(mm_tensors)} tensors to extract out of {len(last_checkpoint)} tensors.")
  114. print("No tensors found. Is this a LLaVA model?")
  115. exit()
  116. print(f"Found {len(mm_tensors)} tensors to extract.")
  117. print(f"Found additional {len(first_mm_tensors)} tensors to extract.")
  118. # projector = {name: checkpoint.[name].float() for name in mm_tensors}
  119. projector = {}
  120. for name in mm_tensors:
  121. projector[name] = last_checkpoint[name].float()
  122. for name in first_mm_tensors:
  123. projector[name] = first_checkpoint[name].float()
  124. if len(projector) > 0:
  125. save_model(projector, f"{args.model}/llava.projector", 'pytorch')
  126. print("Done!")
  127. print(f"Now you can convert {args.model} to a a regular LLaMA GGUF file.")
  128. print(f"Also, use {args.model}/llava.projector to prepare a llava-encoder.gguf file.")