|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import json |
| 8 | +import logging |
| 9 | +import os |
| 10 | +import re |
| 11 | + |
| 12 | +from collections import defaultdict |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +import torch |
| 16 | + |
| 17 | +from torchtitan.protocols.state_dict_adapter import BaseStateDictAdapter |
| 18 | + |
| 19 | +from .args import FluxModelArgs |
| 20 | + |
| 21 | +logger = logging.getLogger() |
| 22 | + |
| 23 | + |
| 24 | +class FluxStateDictAdapter(BaseStateDictAdapter): |
| 25 | + """ |
| 26 | + State dict adapter for Flux model to convert between HuggingFace safetensors format |
| 27 | + and torchtitan DCP format. |
| 28 | +
|
| 29 | + This state dict adapter handles only the state dict of transformer from Flux HF model repo. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__(self, model_args: FluxModelArgs, hf_assets_path: str | None): |
| 33 | + |
| 34 | + # Build fqn to index mapping if hf_assets_path |
| 35 | + if hf_assets_path: |
| 36 | + # If directory is multimodal ensure that hf_assets_path is to the folder containing transformer's safetensors |
| 37 | + if os.path.exists(os.path.join(hf_assets_path, "model_index.json")): |
| 38 | + hf_assets_path = os.path.join(hf_assets_path, "transformers") |
| 39 | + |
| 40 | + # Check if safetensors index file exists |
| 41 | + index_files = [ |
| 42 | + "model.safetensors.index.json", |
| 43 | + "diffusion_pytorch_model.safetensors.index.json", |
| 44 | + ] |
| 45 | + |
| 46 | + hf_safetensors_indx = None |
| 47 | + for index_file in index_files: |
| 48 | + mapping_path = os.path.join(hf_assets_path, index_file) |
| 49 | + if os.path.exists(mapping_path): |
| 50 | + with open(mapping_path, "r") as f: |
| 51 | + hf_safetensors_indx = json.load(f) |
| 52 | + break |
| 53 | + if hf_safetensors_indx is None: |
| 54 | + logger.warning( |
| 55 | + f"no safetensors index file found at hf_assets_path: {hf_assets_path}. \ |
| 56 | + Defaulting to saving a single safetensors file if checkpoint is saved in HF format.", |
| 57 | + ) |
| 58 | + |
| 59 | + if hf_safetensors_indx: |
| 60 | + self.fqn_to_index_mapping = {} |
| 61 | + for hf_key, raw_indx in hf_safetensors_indx["weight_map"].items(): |
| 62 | + indx = re.search(r"\d+", raw_indx).group(0) |
| 63 | + self.fqn_to_index_mapping[hf_key] = indx |
| 64 | + else: |
| 65 | + self.fqn_to_index_mapping = None |
| 66 | + |
| 67 | + self.model_args = model_args |
| 68 | + self.hf_assets_path = hf_assets_path |
| 69 | + |
| 70 | + # mapping containing direct 1 to 1 mappings from HF to torchtitan |
| 71 | + self.from_hf_map_direct = { |
| 72 | + "x_embedder.bias": "img_in.bias", |
| 73 | + "x_embedder.weight": "img_in.weight", |
| 74 | + "context_embedder.bias": "txt_in.bias", |
| 75 | + "context_embedder.weight": "txt_in.weight", |
| 76 | + "norm_out.linear.bias": "final_layer.adaLN_modulation.1.bias", |
| 77 | + "norm_out.linear.weight": "final_layer.adaLN_modulation.1.weight", |
| 78 | + "proj_out.bias": "final_layer.linear.bias", |
| 79 | + "proj_out.weight": "final_layer.linear.weight", |
| 80 | + "time_text_embed.text_embedder.linear_1.bias": "vector_in.in_layer.bias", |
| 81 | + "time_text_embed.text_embedder.linear_1.weight": "vector_in.in_layer.weight", |
| 82 | + "time_text_embed.timestep_embedder.linear_1.bias": "time_in.in_layer.bias", |
| 83 | + "time_text_embed.timestep_embedder.linear_1.weight": "time_in.in_layer.weight", |
| 84 | + "time_text_embed.text_embedder.linear_2.bias": "vector_in.out_layer.bias", |
| 85 | + "time_text_embed.text_embedder.linear_2.weight": "vector_in.out_layer.weight", |
| 86 | + "time_text_embed.timestep_embedder.linear_2.bias": "time_in.out_layer.bias", |
| 87 | + "time_text_embed.timestep_embedder.linear_2.weight": "time_in.out_layer.weight", |
| 88 | + "single_transformer_blocks.{}.attn.norm_k.weight": "single_blocks.{}.norm.key_norm.weight", |
| 89 | + "single_transformer_blocks.{}.attn.norm_q.weight": "single_blocks.{}.norm.query_norm.weight", |
| 90 | + "single_transformer_blocks.{}.norm.linear.bias": "single_blocks.{}.modulation.lin.bias", |
| 91 | + "single_transformer_blocks.{}.norm.linear.weight": "single_blocks.{}.modulation.lin.weight", |
| 92 | + "single_transformer_blocks.{}.proj_out.bias": "single_blocks.{}.linear2.bias", |
| 93 | + "single_transformer_blocks.{}.proj_out.weight": "single_blocks.{}.linear2.weight", |
| 94 | + "transformer_blocks.{}.attn.norm_added_k.weight": "double_blocks.{}.txt_attn.norm.key_norm.weight", |
| 95 | + "transformer_blocks.{}.attn.norm_added_q.weight": "double_blocks.{}.txt_attn.norm.query_norm.weight", |
| 96 | + "transformer_blocks.{}.attn.norm_k.weight": "double_blocks.{}.img_attn.norm.key_norm.weight", |
| 97 | + "transformer_blocks.{}.attn.norm_q.weight": "double_blocks.{}.img_attn.norm.query_norm.weight", |
| 98 | + "transformer_blocks.{}.attn.to_add_out.bias": "double_blocks.{}.txt_attn.proj.bias", |
| 99 | + "transformer_blocks.{}.attn.to_add_out.weight": "double_blocks.{}.txt_attn.proj.weight", |
| 100 | + "transformer_blocks.{}.attn.to_out.0.bias": "double_blocks.{}.img_attn.proj.bias", |
| 101 | + "transformer_blocks.{}.attn.to_out.0.weight": "double_blocks.{}.img_attn.proj.weight", |
| 102 | + "transformer_blocks.{}.ff.net.0.proj.bias": "double_blocks.{}.img_mlp.0.bias", |
| 103 | + "transformer_blocks.{}.ff.net.0.proj.weight": "double_blocks.{}.img_mlp.0.weight", |
| 104 | + "transformer_blocks.{}.ff.net.2.bias": "double_blocks.{}.img_mlp.2.bias", |
| 105 | + "transformer_blocks.{}.ff.net.2.weight": "double_blocks.{}.img_mlp.2.weight", |
| 106 | + "transformer_blocks.{}.ff_context.net.0.proj.bias": "double_blocks.{}.txt_mlp.0.bias", |
| 107 | + "transformer_blocks.{}.ff_context.net.0.proj.weight": "double_blocks.{}.txt_mlp.0.weight", |
| 108 | + "transformer_blocks.{}.ff_context.net.2.bias": "double_blocks.{}.txt_mlp.2.bias", |
| 109 | + "transformer_blocks.{}.ff_context.net.2.weight": "double_blocks.{}.txt_mlp.2.weight", |
| 110 | + "transformer_blocks.{}.norm1.linear.bias": "double_blocks.{}.img_mod.lin.bias", |
| 111 | + "transformer_blocks.{}.norm1.linear.weight": "double_blocks.{}.img_mod.lin.weight", |
| 112 | + "transformer_blocks.{}.norm1_context.linear.bias": "double_blocks.{}.txt_mod.lin.bias", |
| 113 | + "transformer_blocks.{}.norm1_context.linear.weight": "double_blocks.{}.txt_mod.lin.weight", |
| 114 | + } |
| 115 | + |
| 116 | + # combination plan to keep track of the order of layers to be combined |
| 117 | + self.combination_plan = { |
| 118 | + "single_blocks.{}.linear1.bias": [ |
| 119 | + "single_transformer_blocks.{}.attn.to_q.bias", |
| 120 | + "single_transformer_blocks.{}.attn.to_k.bias", |
| 121 | + "single_transformer_blocks.{}.attn.to_v.bias", |
| 122 | + "single_transformer_blocks.{}.proj_mlp.bias", |
| 123 | + ], |
| 124 | + "single_blocks.{}.linear1.weight": [ |
| 125 | + "single_transformer_blocks.{}.attn.to_q.weight", |
| 126 | + "single_transformer_blocks.{}.attn.to_k.weight", |
| 127 | + "single_transformer_blocks.{}.attn.to_v.weight", |
| 128 | + "single_transformer_blocks.{}.proj_mlp.weight", |
| 129 | + ], |
| 130 | + "double_blocks.{}.txt_attn.qkv.bias": [ |
| 131 | + "transformer_blocks.{}.attn.add_q_proj.bias", |
| 132 | + "transformer_blocks.{}.attn.add_k_proj.bias", |
| 133 | + "transformer_blocks.{}.attn.add_v_proj.bias", |
| 134 | + ], |
| 135 | + "double_blocks.{}.txt_attn.qkv.weight": [ |
| 136 | + "transformer_blocks.{}.attn.add_q_proj.weight", |
| 137 | + "transformer_blocks.{}.attn.add_k_proj.weight", |
| 138 | + "transformer_blocks.{}.attn.add_v_proj.weight", |
| 139 | + ], |
| 140 | + "double_blocks.{}.img_attn.qkv.bias": [ |
| 141 | + "transformer_blocks.{}.attn.to_q.bias", |
| 142 | + "transformer_blocks.{}.attn.to_k.bias", |
| 143 | + "transformer_blocks.{}.attn.to_v.bias", |
| 144 | + ], |
| 145 | + "double_blocks.{}.img_attn.qkv.weight": [ |
| 146 | + "transformer_blocks.{}.attn.to_q.weight", |
| 147 | + "transformer_blocks.{}.attn.to_k.weight", |
| 148 | + "transformer_blocks.{}.attn.to_v.weight", |
| 149 | + ], |
| 150 | + } |
| 151 | + |
| 152 | + # reverse of combination plan: maps fqns to the fqn they are combined into |
| 153 | + self.reverse_combination_plan = { |
| 154 | + value: key |
| 155 | + for key, value_list in self.combination_plan.items() |
| 156 | + for value in value_list |
| 157 | + } |
| 158 | + |
| 159 | + # original flux implementation and HF swap shift and scale |
| 160 | + # https://github.com/huggingface/diffusers/blob/main/scripts/convert_flux_to_diffusers.py#L63-L68 |
| 161 | + def _swap_scale_shift(self, weight): |
| 162 | + shift, scale = weight.chunk(2, dim=0) |
| 163 | + new_weight = torch.cat([scale, shift], dim=0) |
| 164 | + return new_weight |
| 165 | + |
| 166 | + def to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]: |
| 167 | + """Convert TorchTitan DCP state dict to HuggingFace safetensors format.""" |
| 168 | + |
| 169 | + to_hf_map_direct = { |
| 170 | + v: k for k, v in self.from_hf_map_direct.items() if v is not None |
| 171 | + } |
| 172 | + hf_state_dict = {} |
| 173 | + |
| 174 | + for key, value in state_dict.items(): |
| 175 | + # Extract layer_num and abstract key if necessary |
| 176 | + if "blocks" in key: |
| 177 | + layer_num = re.search(r"\d+", key).group(0) |
| 178 | + key = re.sub(r"(\d+)", "{}", key, count=1) |
| 179 | + else: |
| 180 | + layer_num = None |
| 181 | + |
| 182 | + if key in to_hf_map_direct: |
| 183 | + # handle direct mapping |
| 184 | + new_key = to_hf_map_direct[key] |
| 185 | + |
| 186 | + # perform swap to be compatible with HF |
| 187 | + if key in [ |
| 188 | + "final_layer.adaLN_modulation.1.weight", |
| 189 | + "final_layer.adaLN_modulation.1.bias", |
| 190 | + ]: |
| 191 | + value = self._swap_scale_shift(value) |
| 192 | + |
| 193 | + if new_key is None: |
| 194 | + continue |
| 195 | + if layer_num: |
| 196 | + new_key = new_key.format(layer_num) |
| 197 | + |
| 198 | + hf_state_dict[new_key] = value |
| 199 | + |
| 200 | + elif key in self.combination_plan: |
| 201 | + # handle splitting layers |
| 202 | + if key in [ |
| 203 | + "single_blocks.{}.linear1.bias", |
| 204 | + "single_blocks.{}.linear1.weight", |
| 205 | + ]: |
| 206 | + mlp_hidden_dim = int( |
| 207 | + self.model_args.hidden_size * self.model_args.mlp_ratio |
| 208 | + ) |
| 209 | + split_plan = [ |
| 210 | + self.model_args.hidden_size, |
| 211 | + self.model_args.hidden_size, |
| 212 | + self.model_args.hidden_size, |
| 213 | + mlp_hidden_dim, |
| 214 | + ] |
| 215 | + # split into q, k, v, mlp |
| 216 | + split_vals = torch.split( |
| 217 | + value, |
| 218 | + split_plan, |
| 219 | + dim=0, |
| 220 | + ) |
| 221 | + else: |
| 222 | + # split into q, k, v |
| 223 | + split_vals = torch.split(value, self.model_args.hidden_size, dim=0) |
| 224 | + |
| 225 | + new_keys = ( |
| 226 | + abstract_key.format(layer_num) |
| 227 | + for abstract_key in self.combination_plan[key] |
| 228 | + ) |
| 229 | + |
| 230 | + for new_key, value in zip(new_keys, split_vals): |
| 231 | + hf_state_dict[new_key] = value |
| 232 | + |
| 233 | + return hf_state_dict |
| 234 | + |
| 235 | + def from_hf(self, hf_state_dict: dict[str, Any]) -> dict[str, Any]: |
| 236 | + """Convert HuggingFace safetensors state dict to TorchTitan DCP format.""" |
| 237 | + state_dict = {} |
| 238 | + |
| 239 | + # Keeps track of HF fqn values to combine into one TT fqn later |
| 240 | + # {tt_fqn : {hf_fqn1 : value}, {hf_fqn2 : value}, ...} |
| 241 | + to_combine = defaultdict(dict) |
| 242 | + |
| 243 | + for key, value in hf_state_dict.items(): |
| 244 | + # extract layer_num and abstract key if necessary |
| 245 | + if "blocks" in key: |
| 246 | + layer_num = re.search(r"\d+", key).group(0) |
| 247 | + key = re.sub(r"(\d+)", "{}", key, count=1) |
| 248 | + else: |
| 249 | + layer_num = None |
| 250 | + |
| 251 | + if key in self.from_hf_map_direct: |
| 252 | + new_key = self.from_hf_map_direct[key] |
| 253 | + |
| 254 | + # perform swap to be compatible with HF |
| 255 | + if key in [ |
| 256 | + "norm_out.linear.weight", |
| 257 | + "norm_out.linear.bias", |
| 258 | + ]: |
| 259 | + value = self._swap_scale_shift(value) |
| 260 | + if new_key is None: |
| 261 | + continue |
| 262 | + if layer_num: |
| 263 | + new_key = new_key.format(layer_num) |
| 264 | + |
| 265 | + state_dict[new_key] = value |
| 266 | + elif key in self.reverse_combination_plan: |
| 267 | + # collect the layers that need to be combined |
| 268 | + tt_abstract_key = self.reverse_combination_plan[key] |
| 269 | + if tt_abstract_key is None: |
| 270 | + continue |
| 271 | + to_combine[tt_abstract_key.format(layer_num)][ |
| 272 | + key.format(layer_num) |
| 273 | + ] = value |
| 274 | + |
| 275 | + # combine collected values |
| 276 | + for tt_fqn, hf_fqn_map in to_combine.items(): |
| 277 | + layer_num = re.search(r"\d+", tt_fqn).group(0) |
| 278 | + tt_abstract_key = re.sub(r"(\d+)", "{}", tt_fqn, count=1) |
| 279 | + combine_values = [] |
| 280 | + # use combination_plan to ensure correct order before concatenation |
| 281 | + for hf_abstract_key in self.combination_plan[tt_abstract_key]: |
| 282 | + hf_key = hf_abstract_key.format(layer_num) |
| 283 | + combine_values.append(hf_fqn_map[hf_key]) |
| 284 | + |
| 285 | + value = torch.cat(combine_values, dim=0) |
| 286 | + state_dict[tt_fqn] = value |
| 287 | + |
| 288 | + return state_dict |
0 commit comments