|
| 1 | +""" |
| 2 | +Simple linear model merge by averaging safetensors weights. |
| 3 | +
|
| 4 | +This bypasses mergekit's architecture detection, which is useful for |
| 5 | +new model architectures that mergekit doesn't support yet. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + python -m open_instruct.merge_models \ |
| 9 | + --models /path/model1 /path/model2 /path/model3 \ |
| 10 | + --output_dir /path/to/output \ |
| 11 | + --model_weights 1.0 1.0 1.0 |
| 12 | +""" |
| 13 | + |
| 14 | +import argparse |
| 15 | +import math |
| 16 | +import shutil |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +import torch |
| 20 | +from safetensors import safe_open |
| 21 | +from safetensors.torch import save_file |
| 22 | +from tqdm import tqdm |
| 23 | + |
| 24 | +from open_instruct import logger_utils |
| 25 | + |
| 26 | +logger = logger_utils.setup_logger(__name__) |
| 27 | + |
| 28 | +parser = argparse.ArgumentParser(description="Linear merge of HuggingFace models") |
| 29 | +parser.add_argument("--models", nargs="+", required=True, help="Paths to models to merge") |
| 30 | +parser.add_argument( |
| 31 | + "--model_weights", nargs="+", type=float, default=None, help="Weights for each model (default: equal weights)" |
| 32 | +) |
| 33 | +parser.add_argument("--output_dir", required=True, help="Output directory for merged model") |
| 34 | +parser.add_argument( |
| 35 | + "--dtype", default="bfloat16", choices=["bfloat16", "float16", "float32"], help="Output dtype (default: bfloat16)" |
| 36 | +) |
| 37 | + |
| 38 | + |
| 39 | +def get_safetensor_files(model_path: Path) -> list[str]: |
| 40 | + """Get sorted list of safetensor filenames in a model directory.""" |
| 41 | + return sorted(f.name for f in model_path.glob("*.safetensors")) |
| 42 | + |
| 43 | + |
| 44 | +def _load_tensors(model_paths: list[Path], safetensor_file: str) -> list[dict[str, torch.Tensor]]: |
| 45 | + """Load tensors from all models for a single safetensor file.""" |
| 46 | + model_tensors = [] |
| 47 | + for model_path in model_paths: |
| 48 | + sf_path = model_path / safetensor_file |
| 49 | + with safe_open(str(sf_path), framework="pt", device="cpu") as f: |
| 50 | + tensors = {key: f.get_tensor(key) for key in f.keys()} # noqa: SIM118 (safe_open is not iterable) |
| 51 | + model_tensors.append(tensors) |
| 52 | + return model_tensors |
| 53 | + |
| 54 | + |
| 55 | +def _merge_tensors( |
| 56 | + model_tensors: list[dict[str, torch.Tensor]], model_weights: list[float], torch_dtype: torch.dtype |
| 57 | +) -> dict[str, torch.Tensor]: |
| 58 | + """Merge tensors from multiple models using weighted averaging.""" |
| 59 | + tensor_names = list(model_tensors[0].keys()) |
| 60 | + merged_tensors = {} |
| 61 | + for name in tensor_names: |
| 62 | + merged = torch.zeros_like(model_tensors[0][name], dtype=torch_dtype) |
| 63 | + for i, tensors in enumerate(model_tensors): |
| 64 | + merged += tensors[name].to(torch_dtype) * model_weights[i] |
| 65 | + merged_tensors[name] = merged |
| 66 | + return merged_tensors |
| 67 | + |
| 68 | + |
| 69 | +def merge_models( |
| 70 | + model_paths: list[Path], |
| 71 | + output_dir: Path, |
| 72 | + model_weights: list[float] | None = None, |
| 73 | + dtype: torch.dtype = torch.bfloat16, |
| 74 | +) -> None: |
| 75 | + """Merge models by weighted averaging of their safetensors weights.""" |
| 76 | + model_weights = model_weights or [1.0] * len(model_paths) |
| 77 | + |
| 78 | + if len(model_weights) != len(model_paths): |
| 79 | + raise ValueError(f"Number of weights ({len(model_weights)}) must match number of models ({len(model_paths)})") |
| 80 | + |
| 81 | + total_weight = sum(model_weights) |
| 82 | + if math.isclose(total_weight, 0.0): |
| 83 | + raise ValueError("Weights must not sum to zero") |
| 84 | + model_weights = [w / total_weight for w in model_weights] |
| 85 | + |
| 86 | + logger.info(f"Merging {len(model_paths)} models with weights: {model_weights}") |
| 87 | + |
| 88 | + safetensor_files = get_safetensor_files(model_paths[0]) |
| 89 | + logger.info(f"Found {len(safetensor_files)} safetensor files") |
| 90 | + |
| 91 | + # Verify all models have identical safetensor file sets |
| 92 | + for model_path in model_paths[1:]: |
| 93 | + other_files = get_safetensor_files(model_path) |
| 94 | + if other_files != safetensor_files: |
| 95 | + raise ValueError(f"Model {model_path} has different safetensor files: {other_files} vs {safetensor_files}") |
| 96 | + |
| 97 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 98 | + |
| 99 | + for safetensor_file in tqdm(safetensor_files, desc="Processing files"): |
| 100 | + model_tensors = _load_tensors(model_paths, safetensor_file) |
| 101 | + merged_tensors = _merge_tensors(model_tensors, model_weights, dtype) |
| 102 | + save_file(merged_tensors, str(output_dir / safetensor_file)) |
| 103 | + |
| 104 | + # Copy config files from first model |
| 105 | + config_files = ["config.json", "generation_config.json", "model.safetensors.index.json"] |
| 106 | + for f in config_files: |
| 107 | + src = model_paths[0] / f |
| 108 | + if src.exists(): |
| 109 | + shutil.copy(src, output_dir / f) |
| 110 | + logger.info(f"Copied {f}") |
| 111 | + |
| 112 | + # Copy tokenizer files from first model |
| 113 | + tokenizer_files = [ |
| 114 | + "tokenizer.json", |
| 115 | + "tokenizer.model", |
| 116 | + "tokenizer_config.json", |
| 117 | + "special_tokens_map.json", |
| 118 | + "added_tokens.json", |
| 119 | + "vocab.json", |
| 120 | + "merges.txt", |
| 121 | + "chat_template.jinja", |
| 122 | + ] |
| 123 | + for f in tokenizer_files: |
| 124 | + src = model_paths[0] / f |
| 125 | + if src.exists(): |
| 126 | + shutil.copy(src, output_dir / f) |
| 127 | + logger.info(f"Copied {f}") |
| 128 | + |
| 129 | + logger.info(f"Merge complete! Output at: {output_dir}") |
| 130 | + |
| 131 | + |
| 132 | +def main() -> None: |
| 133 | + args = parser.parse_args() |
| 134 | + merge_models( |
| 135 | + model_paths=[Path(p) for p in args.models], |
| 136 | + output_dir=Path(args.output_dir), |
| 137 | + model_weights=args.model_weights, |
| 138 | + dtype=getattr(torch, args.dtype), |
| 139 | + ) |
| 140 | + |
| 141 | + |
| 142 | +if __name__ == "__main__": |
| 143 | + main() |
0 commit comments