|
| 1 | +""" |
| 2 | +Utilities for guessing good hyperparameters for fine-tuning. |
| 3 | +""" |
| 4 | + |
| 5 | +import json |
| 6 | +import math |
| 7 | +import struct |
| 8 | +from typing import Dict, Tuple |
| 9 | + |
| 10 | +import huggingface_hub |
| 11 | +import numpy as np |
| 12 | +from transformers import AutoConfig |
| 13 | + |
| 14 | +from .utils.misc_utils import not_none |
| 15 | + |
| 16 | + |
| 17 | +def _list_param_shapes_from_safetensors_remote( |
| 18 | + repo_id: str, |
| 19 | + revision: str = "main", |
| 20 | + token: str | None = None, |
| 21 | +) -> Dict[str, Tuple[int, ...]]: |
| 22 | + """ |
| 23 | + Returns {param_name: shape_tuple} by reading ONLY the safetensors header(s) |
| 24 | + over HTTP (ranged requests). No full file download. |
| 25 | + """ |
| 26 | + fs = huggingface_hub.HfFileSystem(token=token) |
| 27 | + info = huggingface_hub.model_info(repo_id, revision=revision, token=token) |
| 28 | + |
| 29 | + # find all .safetensors files (handles sharded checkpoints) |
| 30 | + st_files = [ |
| 31 | + s.rfilename |
| 32 | + for s in not_none(info.siblings) |
| 33 | + if s.rfilename.endswith(".safetensors") |
| 34 | + ] |
| 35 | + if not st_files: |
| 36 | + raise FileNotFoundError("No .safetensors files found in this repo.") |
| 37 | + |
| 38 | + shapes: Dict[str, Tuple[int, ...]] = {} |
| 39 | + |
| 40 | + for fname in st_files: |
| 41 | + # Open remote file via fsspec; this performs HTTP range reads under the hood |
| 42 | + path = f"{repo_id}@{revision}/{fname}" # HfFileSystem path format |
| 43 | + with fs.open(path, "rb") as f: |
| 44 | + # safetensors spec: |
| 45 | + # [0:8] = little-endian u64 header_len |
| 46 | + # [8:8+header_len] = UTF-8 JSON header |
| 47 | + header_len_bytes = f.read(8) |
| 48 | + assert isinstance(header_len_bytes, bytes) |
| 49 | + if len(header_len_bytes) < 8: |
| 50 | + raise IOError(f"File too small or not safetensors: {fname}") |
| 51 | + (header_len,) = struct.unpack("<Q", header_len_bytes) |
| 52 | + |
| 53 | + header_bytes = f.read(header_len) |
| 54 | + assert isinstance(header_bytes, bytes) |
| 55 | + if len(header_bytes) < header_len: |
| 56 | + raise IOError(f"Incomplete header read for {fname}") |
| 57 | + |
| 58 | + header = json.loads(header_bytes.decode("utf-8")) |
| 59 | + # header maps tensor_name -> { "dtype": "...", "shape": [...], "data_offsets": [start, end] } |
| 60 | + for name, meta in header.items(): |
| 61 | + if name == "__metadata__": # optional global metadata block |
| 62 | + continue |
| 63 | + shapes[name] = tuple(meta["shape"]) |
| 64 | + |
| 65 | + return shapes |
| 66 | + |
| 67 | + |
| 68 | +def get_lora_lr_over_full_finetune_lr(model_name: str, lora_alpha: int = 32) -> float: |
| 69 | + """ |
| 70 | + Return the factor that you should scale the full fine-tuning learning rate by to get the equivalent LoRA learning rate. |
| 71 | + Previously we had a more complicated formula, but the factor of 10 was more accurate empirically. |
| 72 | + See Lora Without Regret (https://thinkingmachines.ai/blog/lora/) for more details. |
| 73 | + """ |
| 74 | + return 10.0 |
| 75 | + |
| 76 | + |
| 77 | +def _get_hidden_size(model_name: str) -> int: |
| 78 | + if "meta-llama/Llama-3" in model_name: |
| 79 | + # Bypass HF_TOKEN requirement for Llama-3 models |
| 80 | + return { |
| 81 | + "meta-llama/Llama-3.2-1B": 2048, |
| 82 | + "meta-llama/Llama-3.2-1B-Instruct": 2048, |
| 83 | + "meta-llama/Llama-3.2-3B": 3072, |
| 84 | + "meta-llama/Llama-3.2-3B-Instruct": 3072, |
| 85 | + "meta-llama/Llama-3.1-8B": 4096, |
| 86 | + "meta-llama/Llama-3.1-8B-Instruct": 4096, |
| 87 | + "meta-llama/Llama-3.1-70B": 8192, |
| 88 | + "meta-llama/Llama-3.3-70B-Instruct": 8192, |
| 89 | + }[model_name] |
| 90 | + |
| 91 | + if model_name in ( |
| 92 | + "deepseek-ai/DeepSeek-V3.1", |
| 93 | + "deepseek-ai/DeepSeek-V3.1-Base", |
| 94 | + "moonshotai/Kimi-K2-Thinking", |
| 95 | + ): |
| 96 | + return 7168 |
| 97 | + |
| 98 | + config = AutoConfig.from_pretrained(model_name) |
| 99 | + return config.hidden_size |
| 100 | + |
| 101 | + |
| 102 | +def get_lora_param_count( |
| 103 | + model_name: str, |
| 104 | + lora_rank: int = 32, |
| 105 | + detailed: bool = False, |
| 106 | + include_experts: bool = True, |
| 107 | + shared_expert_outer_loras: bool = True, |
| 108 | +) -> int | dict[str, int]: |
| 109 | + """ |
| 110 | + Get the number of parameters in the LoRA adapter. |
| 111 | + """ |
| 112 | + |
| 113 | + dim_sum = 0 |
| 114 | + dim_sum_experts = 0 |
| 115 | + ignore = ["gate", "embed_tokens", "q_b_proj", "kv_b_proj"] |
| 116 | + if not include_experts: |
| 117 | + ignore.append("experts") |
| 118 | + |
| 119 | + for name, shape in _list_param_shapes_from_safetensors_remote(model_name).items(): |
| 120 | + if ( |
| 121 | + len(shape) == 2 |
| 122 | + and name.endswith(".weight") |
| 123 | + and not any([v in name.split(".") for v in ignore]) |
| 124 | + ): |
| 125 | + parts = name.split(".") |
| 126 | + if "experts" not in parts or not shared_expert_outer_loras: |
| 127 | + dim_sum += shape[0] + shape[1] |
| 128 | + else: |
| 129 | + # For expert shared outer_loras, we only count the outer dims once, since they are shared across experts |
| 130 | + expert_idx = int(parts[parts.index("experts") + 1]) |
| 131 | + weight_name = parts[parts.index("experts") + 2] |
| 132 | + assert weight_name in ["gate_proj", "down_proj", "up_proj"], ( |
| 133 | + f"Unexpected expert weight name: {weight_name}" |
| 134 | + ) |
| 135 | + intermediate_dim = shape[1] if weight_name == "down_proj" else shape[0] |
| 136 | + outer_dim = shape[0] if weight_name == "down_proj" else shape[1] |
| 137 | + |
| 138 | + dim_sum_experts += intermediate_dim |
| 139 | + if expert_idx == 0: |
| 140 | + dim_sum_experts += outer_dim |
| 141 | + |
| 142 | + non_expert_params = lora_rank * dim_sum |
| 143 | + expert_params = lora_rank * dim_sum_experts |
| 144 | + |
| 145 | + return ( |
| 146 | + (expert_params + non_expert_params) |
| 147 | + if not detailed |
| 148 | + else { |
| 149 | + "expert_params": expert_params, |
| 150 | + "non_expert_params": non_expert_params, |
| 151 | + "total_params": expert_params + non_expert_params, |
| 152 | + } |
| 153 | + ) |
| 154 | + |
| 155 | + |
| 156 | +def get_lr(model_name: str, is_lora: bool = True) -> float: |
| 157 | + base_lr = 5e-05 |
| 158 | + lora_multiplier = 10.0 |
| 159 | + |
| 160 | + lr = base_lr * lora_multiplier if is_lora else base_lr |
| 161 | + if "llama" in model_name.lower(): |
| 162 | + exponent_model = 0.781 |
| 163 | + elif "qwen" in model_name.lower(): |
| 164 | + exponent_model = 0.0775 |
| 165 | + else: |
| 166 | + raise ValueError(f"Unknown model: {model_name}") |
| 167 | + # TODO: sweep to determine LR multipliers for other models |
| 168 | + lr = lr * (2000 / _get_hidden_size(model_name)) ** exponent_model |
| 169 | + return lr |
| 170 | + |
| 171 | + |
| 172 | +def get_full_finetune_param_count(model_name: str) -> float: |
| 173 | + count = 0 |
| 174 | + for name, shape in _list_param_shapes_from_safetensors_remote(model_name).items(): |
| 175 | + count += np.prod(shape) |
| 176 | + return float(count) |
| 177 | + |
| 178 | + |
| 179 | +def get_full_finetune_lr_multiplier(model_name: str): |
| 180 | + return 1.0 / math.sqrt(get_full_finetune_param_count(model_name)) |
| 181 | + |
| 182 | + |
| 183 | +def get_lora_lr_multiplier(model_name: str): |
| 184 | + """ |
| 185 | + Get a model-specific mutliplier for the LR, when training with LoRA. |
| 186 | + Given two models A and B, and learning rate LR_A that's known to be optimal for A, |
| 187 | + we can guess an optimal learning rate for B as |
| 188 | + LR_B = LR_A * get_lora_lr_multiplier(B) / get_lora_lr_multiplier(A) |
| 189 | + """ |
| 190 | + return get_full_finetune_lr_multiplier( |
| 191 | + model_name |
| 192 | + ) * get_lora_lr_over_full_finetune_lr(model_name) |
0 commit comments