|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | + |
| 18 | +import argparse |
| 19 | +import os |
| 20 | +import re |
| 21 | +from collections import defaultdict |
| 22 | + |
| 23 | +import torch |
| 24 | + |
| 25 | + |
| 26 | +def convert_amax_hf2vllm( |
| 27 | + hf_state_dict: dict[str, torch.Tensor], |
| 28 | +) -> dict[str, torch.Tensor]: |
| 29 | + """ |
| 30 | + Convert amax values from HuggingFace format to vLLM format. |
| 31 | +
|
| 32 | + This function merges: |
| 33 | + - q_proj, k_proj, v_proj amax values into qkv_proj (taking max) |
| 34 | + - gate_proj, up_proj amax values into gate_up_proj (taking max) |
| 35 | +
|
| 36 | + Args: |
| 37 | + hf_state_dict: HuggingFace state dict containing amax values |
| 38 | +
|
| 39 | + Returns: |
| 40 | + vLLM format state dict with merged amax values |
| 41 | + """ |
| 42 | + vllm_state_dict = {} |
| 43 | + |
| 44 | + # Group keys by their base pattern (without the specific projection name) |
| 45 | + merge_groups = defaultdict(list) |
| 46 | + |
| 47 | + for key, value in hf_state_dict.items(): |
| 48 | + if "_amax" not in key: |
| 49 | + # Copy non-amax keys as-is |
| 50 | + vllm_state_dict[key] = value |
| 51 | + continue |
| 52 | + |
| 53 | + # Check if this is a q/k/v projection that needs merging |
| 54 | + qkv_match = re.search(r"(.*\.)([qkv])_proj(\..+_amax)$", key) |
| 55 | + if qkv_match: |
| 56 | + base_pattern = qkv_match.group(1) + "qkv_proj" + qkv_match.group(3) |
| 57 | + merge_groups[base_pattern].append((key, value)) |
| 58 | + continue |
| 59 | + |
| 60 | + # Check if this is a gate/up projection that needs merging |
| 61 | + gate_up_match = re.search(r"(.*\.)(gate|up)_proj(\..+_amax)$", key) |
| 62 | + if gate_up_match: |
| 63 | + base_pattern = gate_up_match.group(1) + "gate_up_proj" + gate_up_match.group(3) |
| 64 | + merge_groups[base_pattern].append((key, value)) |
| 65 | + continue |
| 66 | + |
| 67 | + # Copy other amax keys as-is (like o_proj, down_proj) |
| 68 | + vllm_state_dict[key] = value |
| 69 | + |
| 70 | + # Merge grouped amax values by taking the maximum |
| 71 | + for merged_key, key_value_pairs in merge_groups.items(): |
| 72 | + if len(key_value_pairs) > 1: |
| 73 | + # Take the maximum across all values for this merged key |
| 74 | + values = [value for _, value in key_value_pairs] |
| 75 | + merged_value = torch.stack(values).max(dim=0)[0] |
| 76 | + vllm_state_dict[merged_key] = merged_value |
| 77 | + print(f"Merged {len(key_value_pairs)} keys into {merged_key}") |
| 78 | + for orig_key, _ in key_value_pairs: |
| 79 | + print(f" - {orig_key}") |
| 80 | + else: |
| 81 | + # Single key, just rename it |
| 82 | + _, value = key_value_pairs[0] |
| 83 | + vllm_state_dict[merged_key] = value |
| 84 | + |
| 85 | + return vllm_state_dict |
| 86 | + |
| 87 | + |
| 88 | +def test_conversion(): |
| 89 | + """Test the conversion logic with sample keys""" |
| 90 | + import torch |
| 91 | + |
| 92 | + # Create sample HF state dict |
| 93 | + sample_hf_keys = [ |
| 94 | + "model.layers.0.self_attn.q_proj.input_quantizer._amax", |
| 95 | + "model.layers.0.self_attn.k_proj.input_quantizer._amax", |
| 96 | + "model.layers.0.self_attn.v_proj.input_quantizer._amax", |
| 97 | + "model.layers.0.self_attn.q_proj.weight_quantizer._amax", |
| 98 | + "model.layers.0.self_attn.k_proj.weight_quantizer._amax", |
| 99 | + "model.layers.0.self_attn.v_proj.weight_quantizer._amax", |
| 100 | + "model.layers.0.self_attn.o_proj.input_quantizer._amax", |
| 101 | + "model.layers.0.self_attn.o_proj.weight_quantizer._amax", |
| 102 | + "model.layers.0.mlp.gate_proj.input_quantizer._amax", |
| 103 | + "model.layers.0.mlp.up_proj.input_quantizer._amax", |
| 104 | + "model.layers.0.mlp.gate_proj.weight_quantizer._amax", |
| 105 | + "model.layers.0.mlp.up_proj.weight_quantizer._amax", |
| 106 | + "model.layers.0.mlp.down_proj.input_quantizer._amax", |
| 107 | + "model.layers.0.mlp.down_proj.weight_quantizer._amax", |
| 108 | + ] |
| 109 | + |
| 110 | + hf_state_dict = {} |
| 111 | + for key in sample_hf_keys: |
| 112 | + hf_state_dict[key] = torch.tensor([1.0, 2.0, 3.0]) # Sample values |
| 113 | + |
| 114 | + print("Testing conversion with sample keys...") |
| 115 | + print(f"Input keys: {len(sample_hf_keys)}") |
| 116 | + |
| 117 | + vllm_state_dict = convert_amax_hf2vllm(hf_state_dict) |
| 118 | + vllm_amax_keys = [k for k in vllm_state_dict if "_amax" in k] |
| 119 | + |
| 120 | + print(f"Output keys: {len(vllm_amax_keys)}") |
| 121 | + print("\nExpected vLLM keys:") |
| 122 | + expected_keys = [ |
| 123 | + "model.layers.0.self_attn.qkv_proj.input_quantizer._amax", |
| 124 | + "model.layers.0.self_attn.qkv_proj.weight_quantizer._amax", |
| 125 | + "model.layers.0.self_attn.o_proj.input_quantizer._amax", |
| 126 | + "model.layers.0.self_attn.o_proj.weight_quantizer._amax", |
| 127 | + "model.layers.0.mlp.gate_up_proj.input_quantizer._amax", |
| 128 | + "model.layers.0.mlp.gate_up_proj.weight_quantizer._amax", |
| 129 | + "model.layers.0.mlp.down_proj.input_quantizer._amax", |
| 130 | + "model.layers.0.mlp.down_proj.weight_quantizer._amax", |
| 131 | + ] |
| 132 | + |
| 133 | + for key in expected_keys: |
| 134 | + print(f" {key}") |
| 135 | + |
| 136 | + print("\nActual vLLM keys:") |
| 137 | + for key in sorted(vllm_amax_keys): |
| 138 | + print(f" {key}") |
| 139 | + |
| 140 | + # Check if all expected keys are present |
| 141 | + missing_keys = set(expected_keys) - set(vllm_amax_keys) |
| 142 | + extra_keys = set(vllm_amax_keys) - set(expected_keys) |
| 143 | + |
| 144 | + if missing_keys: |
| 145 | + print(f"\nMissing keys: {missing_keys}") |
| 146 | + if extra_keys: |
| 147 | + print(f"\nExtra keys: {extra_keys}") |
| 148 | + |
| 149 | + if not missing_keys and not extra_keys: |
| 150 | + print("\n✓ Test passed! All keys converted correctly.") |
| 151 | + else: |
| 152 | + print("\n✗ Test failed! Key mismatch detected.") |
| 153 | + |
| 154 | + |
| 155 | +def main(): |
| 156 | + parser = argparse.ArgumentParser( |
| 157 | + description="Convert amax values from HuggingFace to vLLM format" |
| 158 | + ) |
| 159 | + parser.add_argument("--input", "-i", help="Input HuggingFace checkpoint path") |
| 160 | + parser.add_argument("--output", "-o", help="Output vLLM checkpoint path") |
| 161 | + parser.add_argument("--dry-run", action="store_true", help="Show conversion without saving") |
| 162 | + parser.add_argument("--test", action="store_true", help="Run test with sample data") |
| 163 | + |
| 164 | + args = parser.parse_args() |
| 165 | + |
| 166 | + if args.test: |
| 167 | + test_conversion() |
| 168 | + return |
| 169 | + |
| 170 | + if not args.input or not args.output: |
| 171 | + parser.error("--input and --output are required unless using --test") |
| 172 | + |
| 173 | + # Load HuggingFace checkpoint |
| 174 | + print(f"Loading HuggingFace checkpoint from: {args.input}") |
| 175 | + if os.path.isfile(args.input): |
| 176 | + hf_state_dict = torch.load(args.input, map_location="cpu") |
| 177 | + else: |
| 178 | + raise Exception(f"File not found: {args.input}") |
| 179 | + |
| 180 | + print(f"Loaded {len(hf_state_dict)} keys from HuggingFace checkpoint") |
| 181 | + |
| 182 | + # Filter to only amax keys for analysis |
| 183 | + amax_keys = [k for k in hf_state_dict if "_amax" in k] |
| 184 | + print(f"Found {len(amax_keys)} amax keys") |
| 185 | + |
| 186 | + if args.dry_run: |
| 187 | + print("\nAmax keys in HuggingFace format:") |
| 188 | + for key in sorted(amax_keys): |
| 189 | + print(f" {key}") |
| 190 | + |
| 191 | + # Convert to vLLM format |
| 192 | + print("\nConverting to vLLM format...") |
| 193 | + vllm_state_dict = convert_amax_hf2vllm(hf_state_dict) |
| 194 | + |
| 195 | + vllm_amax_keys = [k for k in vllm_state_dict if "_amax" in k] |
| 196 | + print(f"Result: {len(vllm_amax_keys)} amax keys in vLLM format") |
| 197 | + |
| 198 | + if args.dry_run: |
| 199 | + print("\nAmax keys in vLLM format:") |
| 200 | + for key in sorted(vllm_amax_keys): |
| 201 | + print(f" {key}") |
| 202 | + print("\nDry run complete. No files saved.") |
| 203 | + return |
| 204 | + |
| 205 | + # Save vLLM checkpoint |
| 206 | + print(f"Saving vLLM checkpoint to: {args.output}") |
| 207 | + os.makedirs(os.path.dirname(args.output), exist_ok=True) |
| 208 | + torch.save(vllm_state_dict, args.output) |
| 209 | + print("Conversion complete!") |
| 210 | + |
| 211 | + |
| 212 | +if __name__ == "__main__": |
| 213 | + main() |
0 commit comments