|
| 1 | +import math |
| 2 | +import re |
| 3 | +from typing import Annotated, Callable |
| 4 | + |
| 5 | +import torch |
| 6 | +import torch.nn as nn |
| 7 | +from pydantic import BaseModel, Field |
| 8 | + |
| 9 | +from modalities.nn.model_initialization.initialization_if import ModelInitializationIF |
| 10 | +from modalities.utils.logger_utils import get_logger |
| 11 | + |
| 12 | +logger = get_logger(name="llama3 initialization") |
| 13 | + |
| 14 | + |
| 15 | +class Llama3InitializerConfig(BaseModel): |
| 16 | + num_layers: Annotated[int, Field(strict=True, gt=0)] |
| 17 | + n_embd: Annotated[int, Field(strict=True, gt=0)] |
| 18 | + depth_init: bool = True |
| 19 | + |
| 20 | + |
| 21 | +class Llama3Initializer(ModelInitializationIF): |
| 22 | + """ |
| 23 | + Follows weight initialization distributions and parameterization for Llama3 as described in TorchTitan. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__(self, num_layers: int, n_embd: int, depth_init: bool) -> None: |
| 27 | + """ |
| 28 | + Initializes the Llama3Initializer. |
| 29 | + Args: |
| 30 | + num_layers: The number of transformer layers in the model. Used to calculate std for certain parameters. |
| 31 | + n_embd: The embedding dimension of the model. Used to calculate std and truncation for certain parameters. |
| 32 | + depth_init: Whether to use depth-aware initialization for certain parameters, where the std |
| 33 | + is scaled based on the layer's depth in the model. If False, a constant std is |
| 34 | + used for all layers baed on num_layers. |
| 35 | + """ |
| 36 | + super().__init__() |
| 37 | + self.depth_init = depth_init |
| 38 | + |
| 39 | + self.regex_to_init = { |
| 40 | + # embedding weights |
| 41 | + r"transformer\.wte\.weight": (nn.init.normal_, {"mean": 0.0, "std": 1}), |
| 42 | + # lm head weights |
| 43 | + r"transformer\.lm_head\.weight": ( |
| 44 | + trunc_normal_, |
| 45 | + { |
| 46 | + "mean": 0.0, |
| 47 | + "std": 1 / math.sqrt(n_embd), |
| 48 | + "a": -3 / math.sqrt(n_embd), |
| 49 | + "b": 3 / math.sqrt(n_embd), |
| 50 | + }, |
| 51 | + ), |
| 52 | + # qkv projections |
| 53 | + r"transformer\.h\.\d+\.attn\.(q_attn|k_attn|v_attn)\.weight": ( |
| 54 | + trunc_normal_, |
| 55 | + { |
| 56 | + "mean": 0.0, |
| 57 | + "std": 0.02, |
| 58 | + "a": -2, |
| 59 | + "b": 2, |
| 60 | + }, |
| 61 | + ), |
| 62 | + # final attention projection in attention block |
| 63 | + r"transformer\.h\.\d+\.attn\.c_proj\.weight": ( |
| 64 | + trunc_normal_, |
| 65 | + { |
| 66 | + "mean": 0.0, |
| 67 | + "std": ( |
| 68 | + (lambda layer_id: 0.02 / math.sqrt(2 * (layer_id + 1))) |
| 69 | + if depth_init |
| 70 | + else 0.02 / math.sqrt(2 * num_layers) |
| 71 | + ), |
| 72 | + "a": -2, |
| 73 | + "b": 2, |
| 74 | + }, |
| 75 | + ), |
| 76 | + # SwiGLU |
| 77 | + r"transformer\.h\.\d+\.mlp\.(W)\.weight": ( |
| 78 | + trunc_normal_, |
| 79 | + { |
| 80 | + "mean": 0.0, |
| 81 | + "std": 0.02, |
| 82 | + "a": -2, |
| 83 | + "b": 2, |
| 84 | + }, |
| 85 | + ), |
| 86 | + r"transformer\.h\.\d+\.mlp\.(V|W_2)\.weight": ( |
| 87 | + trunc_normal_, |
| 88 | + { |
| 89 | + "mean": 0.0, |
| 90 | + "std": ( |
| 91 | + (lambda layer_id: 0.02 / math.sqrt(2 * (layer_id + 1))) |
| 92 | + if depth_init |
| 93 | + else 0.02 / math.sqrt(2 * num_layers) |
| 94 | + ), |
| 95 | + "a": -2, |
| 96 | + "b": 2, |
| 97 | + }, |
| 98 | + ), |
| 99 | + } |
| 100 | + |
| 101 | + def initialize_in_place(self, model: nn.Module): |
| 102 | + self._init_by_fqn_regex(model, self.regex_to_init, depth_init=self.depth_init) |
| 103 | + |
| 104 | + @staticmethod |
| 105 | + def _init_by_fqn_regex(model: nn.Module, regex_to_init: dict[str, tuple[Callable, dict]], depth_init: bool): |
| 106 | + hits = {k: 0 for k in regex_to_init.keys()} |
| 107 | + |
| 108 | + for parameter_name, p in model.named_parameters(): |
| 109 | + if parameter_name.endswith("bias"): |
| 110 | + raise ValueError( |
| 111 | + f"Bias initialization is not allowed for Llama3Initializer. Found bias parameter: {parameter_name}" |
| 112 | + ) |
| 113 | + match_count = 0 |
| 114 | + for weight_regex in regex_to_init.keys(): |
| 115 | + if re.fullmatch(weight_regex, parameter_name): |
| 116 | + init_fn, arg_dict = regex_to_init[weight_regex] |
| 117 | + if arg_dict["std"] is not None and callable(arg_dict["std"]): |
| 118 | + # If std is a function, call it with the layer_id |
| 119 | + layer_id_match = re.search(r"transformer\.h\.(\d+)\.", parameter_name) |
| 120 | + if layer_id_match is not None: |
| 121 | + layer_id = int(layer_id_match.group(1)) |
| 122 | + arg_dict = arg_dict.copy() # create a copy of the arg_dict to avoid mutating the original |
| 123 | + arg_dict["std"] = arg_dict["std"](layer_id) |
| 124 | + else: |
| 125 | + raise ValueError( |
| 126 | + f"Could not extract layer_id from parameter name {parameter_name} " |
| 127 | + "for dynamic std calculation" |
| 128 | + ) |
| 129 | + init_fn(p, **arg_dict) |
| 130 | + match_count += 1 |
| 131 | + hits[weight_regex] += 1 |
| 132 | + |
| 133 | + if match_count == 0: |
| 134 | + logger.warning(f"Parameter {parameter_name} did not match any regex for initialization") |
| 135 | + elif match_count > 1: |
| 136 | + raise ValueError( |
| 137 | + f"Parameter {parameter_name} matched multiple regexes for initialization, which is not allowed" |
| 138 | + ) |
| 139 | + |
| 140 | + for k, count in hits.items(): |
| 141 | + if count == 0: |
| 142 | + raise ValueError( |
| 143 | + f"Regex {k} did not match any FQNs. The model specification probably does not match LLama3." |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +def trunc_normal_( |
| 148 | + tensor: torch.Tensor, |
| 149 | + mean: float = 0.0, |
| 150 | + std: float = 1.0, |
| 151 | + a: float = -2.0, |
| 152 | + b: float = 2.0, |
| 153 | +): |
| 154 | + """ |
| 155 | + Fills the input tensor with values sampled from a truncated normal distribution. |
| 156 | + Values are drawn from a normal distribution with the given mean and standard |
| 157 | + deviation. Any sampled values outside the range defined by a and b are resampled |
| 158 | + until they fall within the bounds. |
| 159 | +
|
| 160 | + To avoid numerical instability in torch.nn.init.trunc_normal_, the initialization |
| 161 | + is always performed using float32 precision. The result is then cast back to the |
| 162 | + original data type of the input tensor. |
| 163 | +
|
| 164 | + Args: |
| 165 | + tensor: an n dimensional torch Tensor |
| 166 | + mean: the mean of the normal distribution |
| 167 | + std: the standard deviation of the normal distribution |
| 168 | + a: the lower bound for truncation |
| 169 | + b: the upper bound for truncation |
| 170 | +
|
| 171 | + Returns: |
| 172 | + The input tensor filled with values from the truncated normal distribution. |
| 173 | + """ |
| 174 | + # This function is copied from from Meta's open-source project TorchTitan, |
| 175 | + # licensed under the BSD 3-Clause License. |
| 176 | + tmp = tensor.float() |
| 177 | + nn.init.trunc_normal_(tmp, mean=mean, std=std, a=a, b=b) |
| 178 | + tensor.copy_(tmp) |
0 commit comments