Coverage for transformer_lens/weight_processing.py: 82%

978 statements  

« prev     ^ index     » next       coverage.py v7.10.1, created at 2026-11-25 00:28 +0000

1""" 

2Weight Processing Functions for Transformer Models. 

3 

4This module contains all the weight processing functions extracted from HookedTransformer, 

5organized into a single ProcessWeights class with static methods. These functions are used 

6to modify transformer model weights for better interpretability and analysis. 

7""" 

8import re 

9from typing import Any, Dict, Optional, Union, overload 

10 

11import einops 

12import torch 

13 

14import transformer_lens.utilities as utils 

15from transformer_lens.config.transformer_lens_config import TransformerLensConfig 

16from transformer_lens.conversion_utils.conversion_steps.chain_tensor_conversion import ( 

17 ChainTensorConversion, 

18) 

19from transformer_lens.conversion_utils.conversion_steps.transpose_tensor_conversion import ( 

20 TransposeTensorConversion, 

21) 

22from transformer_lens.conversion_utils.param_processing_conversion import ( 

23 ParamProcessingConversion, 

24) 

25from transformer_lens.FactoredMatrix import FactoredMatrix 

26from transformer_lens.model_bridge.architecture_adapter import ( 

27 ArchitectureAdapter, 

28 ResidualLayout, 

29) 

30from transformer_lens.utilities import filter_dict_by_prefix 

31from transformer_lens.utilities.architectures import POST_NORM_ARCHITECTURES 

32 

33 

34class ProcessWeights: 

35 """ 

36 A collection of static methods for processing transformer model weights. 

37 

38 These methods are extracted from HookedTransformer and provide various weight 

39 transformations for improved model interpretability: 

40 - LayerNorm folding: Merges LayerNorm parameters into subsequent linear layers 

41 - Weight centering: Centers weights that write to the residual stream 

42 - Unembed centering: Centers unembedding weights (translation invariant) 

43 - Value bias folding: Consolidates value biases into output biases 

44 - Attention matrix refactoring: Experimental QK/OV matrix factorization 

45 

46 When an architecture adapter is provided, the methods will translate TransformerLens 

47 parameter names to the target format (e.g., HuggingFace) for processing. 

48 """ 

49 

50 @staticmethod 

51 def _get_param_key(tl_key: str, adapter=None) -> str: 

52 """Convert legacy TL key format (W_Q, b_Q) to component-based format (q.weight, q.bias). 

53 

54 Args: 

55 tl_key: TransformerLens format parameter key (e.g., "blocks.0.attn.W_Q") 

56 adapter: Architecture adapter for translating paths 

57 

58 Returns: 

59 The component-based key (e.g., "blocks.0.attn.q.weight") 

60 """ 

61 if adapter is None: 

62 return tl_key 

63 

64 return ProcessWeights._prepare_component_path(tl_key) 

65 

66 @staticmethod 

67 def _prepare_component_path(tl_key: str) -> str: 

68 """Map a TransformerLens key to bridge-style component path. 

69 

70 Converts TransformerLens weight names (like "W_Q", "b_in") to bridge-style 

71 paths (like "q.weight", "in.bias"). The full path is assembled before being 

72 passed to the architecture adapter for translation. 

73 

74 Args: 

75 tl_key: TransformerLens key like "blocks.0.attn.W_Q" 

76 

77 Returns: 

78 Full path like "blocks.0.attn.q.weight" 

79 """ 

80 suffix_map: Dict[str, str] = { 

81 "W_Q": "q.weight", 

82 "_W_Q": "q.weight", 

83 "b_Q": "q.bias", 

84 "_b_Q": "q.bias", 

85 "W_K": "k.weight", 

86 "_W_K": "k.weight", 

87 "b_K": "k.bias", 

88 "_b_K": "k.bias", 

89 "W_V": "v.weight", 

90 "_W_V": "v.weight", 

91 "b_V": "v.bias", 

92 "_b_V": "v.bias", 

93 "W_O": "o.weight", 

94 "b_O": "o.bias", 

95 "W_in": "in.weight", 

96 "b_in": "in.bias", 

97 "W_gate": "gate.weight", 

98 "b_gate": "gate.bias", 

99 "W_out": "out.weight", 

100 "b_out": "out.bias", 

101 "W_E": "weight", 

102 "b_E": "bias", 

103 "W_pos": "weight", 

104 "b_pos": "bias", 

105 "W_U": "weight", 

106 "b_U": "bias", 

107 "w": "weight", 

108 "b": "bias", 

109 "weight": "weight", 

110 "bias": "bias", 

111 } 

112 if "." not in tl_key: 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true

113 return tl_key 

114 base_path, suffix = tl_key.rsplit(".", 1) 

115 if suffix in suffix_map: 115 ↛ 118line 115 didn't jump to line 118 because the condition on line 115 was always true

116 replacement = suffix_map[suffix] 

117 return f"{base_path}.{replacement}" 

118 return tl_key 

119 

120 @staticmethod 

121 def _resolve_state_dict_key( 

122 state_dict: Dict[str, torch.Tensor], 

123 key: str, 

124 layer: Optional[int] = None, 

125 ) -> str: 

126 """Resolve a bridge-style key to the actual key in the state_dict. 

127 

128 Some architectures (e.g., BD3LM's symbolic attention) store parameters 

129 with HF-style prefixes instead of bridge-style prefixes. This method 

130 handles the key resolution by falling back to a suffix search. 

131 

132 Args: 

133 state_dict: Model state dictionary 

134 key: The expected key (e.g., "blocks.0.mlp.in.weight") 

135 layer: Optional layer index for layer-specific searches 

136 

137 Returns: 

138 The actual key found in state_dict, or the original key if no match 

139 """ 

140 if key in state_dict: 

141 return key 

142 

143 # Extract the component path after "blocks.{i}." 

144 import re 

145 

146 match = re.match(r"blocks\.(\d+)\.(.*)", key) 

147 if match: 147 ↛ 163line 147 didn't jump to line 163 because the condition on line 147 was always true

148 layer_idx = match.group(1) 

149 component_suffix = match.group(2) 

150 # Search for keys ending with the component suffix that include the layer index 

151 for sd_key in state_dict: 

152 if sd_key.endswith(f".{component_suffix}") and f".{layer_idx}." in sd_key: 152 ↛ 153line 152 didn't jump to line 153 because the condition on line 152 was never true

153 return sd_key 

154 

155 # Mixed MoE/dense adapters (Llama4, Laguna, LLaDA2-MoE) put a non-MoE 

156 # layer's gated MLP in the MoE slot under dense_gate/dense_in/dense_out 

157 # so it coexists with the router/experts. When the standard block-level 

158 # mlp.{gate,in,out} key is absent, fall back to that dense_ variant. 

159 # Fails closed: the standard resolution above already ran (so a real 

160 # mlp.gate router is never shadowed), the match is anchored to a block's 

161 # top-level MLP (not any nested `.mlp.`), and the dense key is returned 

162 # only if it exists — models without the convention are untouched. 

163 proj_match = re.match(r"(blocks\.\d+\.mlp\.)(in|gate|out)(\..+)$", key) 

164 if proj_match: 

165 dense_key = f"{proj_match.group(1)}dense_{proj_match.group(2)}{proj_match.group(3)}" 

166 if dense_key in state_dict: 

167 return dense_key 

168 dm = re.match(r"blocks\.(\d+)\.(.*)", dense_key) 

169 if dm: 169 ↛ 174line 169 didn't jump to line 174 because the condition on line 169 was always true

170 for sd_key in state_dict: 

171 if sd_key.endswith(f".{dm.group(2)}") and f".{dm.group(1)}." in sd_key: 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true

172 return sd_key 

173 

174 return key 

175 

176 @staticmethod 

177 def _safe_get_tensor( 

178 state_dict: Dict[str, torch.Tensor], 

179 tl_key: str, 

180 adapter=None, 

181 default: Optional[torch.Tensor] = None, 

182 ) -> Optional[torch.Tensor]: 

183 """Safely get a tensor from state_dict, handling optional parameters. 

184 

185 This is the recommended way to access parameters that may not exist in all architectures 

186 (e.g., biases in Qwen2/LLaMA/Gemma). Returns None if the parameter doesn't exist, 

187 rather than raising a KeyError. 

188 

189 Args: 

190 state_dict: Model state dictionary 

191 tl_key: TransformerLens format parameter key (e.g., "blocks.0.attn.b_Q") 

192 adapter: Optional architecture adapter for key translation 

193 default: Optional default value to return if key not found (defaults to None) 

194 

195 Returns: 

196 The tensor if found, otherwise the default value (None if not specified) 

197 

198 Examples: 

199 # Get optional bias (may be None for Qwen2/LLaMA) 

200 b_Q = ProcessWeights._safe_get_tensor(state_dict, "blocks.0.attn.b_Q", adapter) 

201 

202 # Get required weight (will be None if missing, can check explicitly) 

203 W_Q = ProcessWeights._safe_get_tensor(state_dict, "blocks.0.attn.W_Q", adapter) 

204 if W_Q is None: 

205 raise ValueError("Required weight W_Q not found") 

206 """ 

207 actual_key = ProcessWeights._get_param_key(tl_key, adapter) 

208 return state_dict.get(actual_key, default) 

209 

210 @staticmethod 

211 def fold_layer_norm_bias_single( 

212 w_tensor: torch.Tensor, b_tensor: torch.Tensor, ln_bias: torch.Tensor 

213 ) -> torch.Tensor: 

214 """Fold LayerNorm bias into a single attention bias. 

215 

216 Args: 

217 w_tensor: Weight tensor [n_heads, d_model, d_head] 

218 b_tensor: Bias tensor [n_heads, d_head] 

219 ln_bias: LayerNorm bias [d_model] 

220 

221 Returns: 

222 New bias tensor with folded LayerNorm bias 

223 """ 

224 return b_tensor + (w_tensor * ln_bias[None, :, None]).sum(-2) 

225 

226 @staticmethod 

227 def fold_layer_norm_weight_single( 

228 w_tensor: torch.Tensor, ln_weight: torch.Tensor 

229 ) -> torch.Tensor: 

230 """Fold LayerNorm weight into a single attention weight. 

231 

232 Args: 

233 w_tensor: Weight tensor [n_heads, d_model, d_head] 

234 ln_weight: LayerNorm weight [d_model] 

235 

236 Returns: 

237 New weight tensor with folded LayerNorm weight 

238 """ 

239 return w_tensor * ln_weight[None, :, None] 

240 

241 @staticmethod 

242 def center_weight_single(w_tensor: torch.Tensor) -> torch.Tensor: 

243 """Center a single attention weight by subtracting the mean. 

244 

245 Args: 

246 w_tensor: Weight tensor [n_heads, d_model, d_head] 

247 

248 Returns: 

249 Centered weight tensor 

250 """ 

251 return w_tensor - einops.reduce( 

252 w_tensor, "head_index d_model d_head -> head_index 1 d_head", "mean" 

253 ) 

254 

255 @staticmethod 

256 def fold_layer_norm_biases( 

257 wq_tensor: torch.Tensor, 

258 wk_tensor: torch.Tensor, 

259 wv_tensor: torch.Tensor, 

260 bq_tensor: Optional[torch.Tensor], 

261 bk_tensor: Optional[torch.Tensor], 

262 bv_tensor: Optional[torch.Tensor], 

263 ln_bias: torch.Tensor, 

264 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

265 """Fold LayerNorm bias into attention biases. 

266 

267 When QKV biases don't exist (e.g., GPT-Neo), creates zero-initialized biases 

268 to absorb the LN bias contribution, similar to how MLP folding handles missing biases. 

269 

270 Args: 

271 wq_tensor, wk_tensor, wv_tensor: Weight tensors [n_heads, d_model, d_head] 

272 bq_tensor, bk_tensor, bv_tensor: Bias tensors [n_heads, d_head] or None if no bias 

273 ln_bias: LayerNorm bias [d_model] 

274 

275 Returns: 

276 Tuple of (new_bq, new_bk, new_bv) with folded biases (always non-None) 

277 """ 

278 

279 def _zero_bias(w: torch.Tensor) -> torch.Tensor: 

280 return torch.zeros(w.shape[0], w.shape[2], dtype=w.dtype, device=w.device) 

281 

282 new_bq = ProcessWeights.fold_layer_norm_bias_single( 

283 wq_tensor, bq_tensor if bq_tensor is not None else _zero_bias(wq_tensor), ln_bias 

284 ) 

285 new_bk = ProcessWeights.fold_layer_norm_bias_single( 

286 wk_tensor, bk_tensor if bk_tensor is not None else _zero_bias(wk_tensor), ln_bias 

287 ) 

288 new_bv = ProcessWeights.fold_layer_norm_bias_single( 

289 wv_tensor, bv_tensor if bv_tensor is not None else _zero_bias(wv_tensor), ln_bias 

290 ) 

291 return (new_bq, new_bk, new_bv) 

292 

293 @staticmethod 

294 def fold_layer_norm_weights( 

295 wq_tensor: torch.Tensor, 

296 wk_tensor: torch.Tensor, 

297 wv_tensor: torch.Tensor, 

298 ln_weight: torch.Tensor, 

299 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

300 """Fold LayerNorm weight into attention weights. 

301 

302 Args: 

303 wq_tensor, wk_tensor, wv_tensor: Weight tensors [n_heads, d_model, d_head] 

304 ln_weight: LayerNorm weight [d_model] 

305 

306 Returns: 

307 Tuple of (new_wq, new_wk, new_wv) with folded weights 

308 """ 

309 new_wq = ProcessWeights.fold_layer_norm_weight_single(wq_tensor, ln_weight) 

310 new_wk = ProcessWeights.fold_layer_norm_weight_single(wk_tensor, ln_weight) 

311 new_wv = ProcessWeights.fold_layer_norm_weight_single(wv_tensor, ln_weight) 

312 return (new_wq, new_wk, new_wv) 

313 

314 @staticmethod 

315 def center_attention_weights( 

316 wq_tensor: torch.Tensor, wk_tensor: torch.Tensor, wv_tensor: torch.Tensor 

317 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

318 """Center attention weights by subtracting the mean. 

319 

320 Args: 

321 wq_tensor, wk_tensor, wv_tensor: Weight tensors [n_heads, d_model, d_head] 

322 

323 Returns: 

324 Tuple of (centered_wq, centered_wk, centered_wv) 

325 """ 

326 centered_wq = ProcessWeights.center_weight_single(wq_tensor) 

327 centered_wk = ProcessWeights.center_weight_single(wk_tensor) 

328 centered_wv = ProcessWeights.center_weight_single(wv_tensor) 

329 return (centered_wq, centered_wk, centered_wv) 

330 

331 @staticmethod 

332 def extract_attention_tensors_for_folding( 

333 state_dict: Dict[str, torch.Tensor], cfg, layer: int, adapter 

334 ) -> Dict[str, Union[torch.Tensor, None, Dict[str, str]]]: 

335 """Extract attention tensors in TransformerLens format for layer norm folding. 

336 

337 Args: 

338 state_dict: The state dictionary containing tensors 

339 cfg: Model configuration object 

340 layer: Layer index 

341 adapter: Optional architecture adapter for parameter key translation 

342 

343 Returns: 

344 Dictionary with keys: 'wq', 'wk', 'wv', 'bq', 'bk', 'bv', 'ln1_b', 'ln1_w' 

345 All tensors are in TransformerLens format for consistent processing 

346 """ 

347 b_Q_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.b_Q", adapter) 

348 W_Q_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.W_Q", adapter) 

349 b_K_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.b_K", adapter) 

350 W_K_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.W_K", adapter) 

351 b_V_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.b_V", adapter) 

352 W_V_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.W_V", adapter) 

353 ln1_b_key = ProcessWeights._get_param_key(f"blocks.{layer}.ln1.b", adapter) 

354 ln1_w_key = ProcessWeights._get_param_key(f"blocks.{layer}.ln1.w", adapter) 

355 

356 # For GQA models, Q, K and V weights may use underscore prefix (_W_Q, _W_K, _W_V) 

357 # Check if standard keys exist, otherwise update to use underscore-prefixed versions 

358 if W_Q_key not in state_dict: 

359 W_Q_key = W_Q_key.replace(".W_Q", "._W_Q") 

360 if W_K_key not in state_dict: 

361 W_K_key = W_K_key.replace(".W_K", "._W_K") 

362 if W_V_key not in state_dict: 

363 W_V_key = W_V_key.replace(".W_V", "._W_V") 

364 if b_Q_key not in state_dict: 

365 b_Q_key = b_Q_key.replace(".b_Q", "._b_Q") 

366 if b_K_key not in state_dict: 

367 b_K_key = b_K_key.replace(".b_K", "._b_K") 

368 if b_V_key not in state_dict: 

369 b_V_key = b_V_key.replace(".b_V", "._b_V") 

370 

371 wq_tensor: Optional[torch.Tensor] = state_dict.get(W_Q_key) 

372 wk_tensor: Optional[torch.Tensor] = state_dict.get(W_K_key) 

373 wv_tensor: Optional[torch.Tensor] = state_dict.get(W_V_key) 

374 bq_tensor: Optional[torch.Tensor] = state_dict.get(b_Q_key) 

375 bk_tensor: Optional[torch.Tensor] = state_dict.get(b_K_key) 

376 bv_tensor: Optional[torch.Tensor] = state_dict.get(b_V_key) 

377 ln1_b = state_dict.get(ln1_b_key, None) 

378 ln1_w = state_dict.get(ln1_w_key, None) 

379 if adapter: 

380 wq_tensor = ProcessWeights.convert_tensor_to_tl_format( 

381 W_Q_key, state_dict, wq_tensor, cfg, adapter, layer 

382 ) 

383 wk_tensor = ProcessWeights.convert_tensor_to_tl_format( 

384 W_K_key, state_dict, wk_tensor, cfg, adapter, layer 

385 ) 

386 wv_tensor = ProcessWeights.convert_tensor_to_tl_format( 

387 W_V_key, state_dict, wv_tensor, cfg, adapter, layer 

388 ) 

389 bq_tensor = ProcessWeights.convert_tensor_to_tl_format( 

390 b_Q_key, state_dict, bq_tensor, cfg, adapter, layer 

391 ) 

392 bk_tensor = ProcessWeights.convert_tensor_to_tl_format( 

393 b_K_key, state_dict, bk_tensor, cfg, adapter, layer 

394 ) 

395 bv_tensor = ProcessWeights.convert_tensor_to_tl_format( 

396 b_V_key, state_dict, bv_tensor, cfg, adapter, layer 

397 ) 

398 

399 # Auto-reshape 1D biases for 3D weights (e.g., OPT) 

400 def _reshape_bias_if_needed(bias, weight): 

401 if bias is not None and weight is not None: 

402 if len(weight.shape) == 3 and len(bias.shape) == 1: 

403 n_heads = weight.shape[0] 

404 d_head = weight.shape[2] 

405 if bias.shape[0] == n_heads * d_head: 405 ↛ 407line 405 didn't jump to line 407 because the condition on line 405 was always true

406 return bias.reshape(n_heads, d_head) 

407 return bias 

408 

409 bq_tensor = _reshape_bias_if_needed(bq_tensor, wq_tensor) 

410 bk_tensor = _reshape_bias_if_needed(bk_tensor, wk_tensor) 

411 bv_tensor = _reshape_bias_if_needed(bv_tensor, wv_tensor) 

412 

413 return { 

414 "wq": wq_tensor, 

415 "wk": wk_tensor, 

416 "wv": wv_tensor, 

417 "bq": bq_tensor, 

418 "bk": bk_tensor, 

419 "bv": bv_tensor, 

420 "ln1_b": ln1_b, 

421 "ln1_w": ln1_w, 

422 "keys": { 

423 "W_Q": W_Q_key, 

424 "W_K": W_K_key, 

425 "W_V": W_V_key, 

426 "b_Q": b_Q_key, 

427 "b_K": b_K_key, 

428 "b_V": b_V_key, 

429 "ln1_b": ln1_b_key, 

430 "ln1_w": ln1_w_key, 

431 }, 

432 } 

433 

434 @staticmethod 

435 def _fold_short_conv_layer_norm( 

436 state_dict: Dict[str, torch.Tensor], 

437 cfg, 

438 layer: int, 

439 fold_biases: bool, 

440 adapter, 

441 ln1_w: torch.Tensor, 

442 ln1_b: Optional[torch.Tensor], 

443 keys: Dict[str, str], 

444 ) -> bool: 

445 """Fold ln1 into a short-conv mixer's in-projection. Returns whether it folded. 

446 

447 Hybrid stacks (LFM2) interleave attention layers with short-conv layers that 

448 have no q_proj, so the attention path skips them and their gain would survive 

449 into an otherwise-folded model — one basis per layer type. The in-projection 

450 is the mixer's only reader of the norm output (the conv and the gates consume 

451 its outputs), so scaling its input columns is exact despite the mixer being 

452 quadratic in that projection. 

453 """ 

454 w_key = ProcessWeights._get_param_key(f"blocks.{layer}.conv.W_in", adapter) 

455 conv_W_in = state_dict.get(w_key) 

456 if conv_W_in is None: 456 ↛ 457line 456 didn't jump to line 457 because the condition on line 456 was never true

457 return False 

458 

459 rmsnorm_uses_offset = getattr(cfg, "rmsnorm_uses_offset", False) 

460 effective_ln1_w = (1.0 + ln1_w) if rmsnorm_uses_offset else ln1_w 

461 if conv_W_in.shape[-1] == effective_ln1_w.shape[0]: 461 ↛ 464line 461 didn't jump to line 464 because the condition on line 461 was always true

462 ln1_w_broadcast = effective_ln1_w[None, :] 

463 sum_dim = -1 

464 elif conv_W_in.shape[0] == effective_ln1_w.shape[0]: 

465 ln1_w_broadcast = effective_ln1_w[:, None] 

466 sum_dim = -2 

467 else: 

468 return False 

469 

470 b_key = ProcessWeights._get_param_key(f"blocks.{layer}.conv.b_in", adapter) 

471 if fold_biases and ln1_b is not None: 471 ↛ 474line 471 didn't jump to line 474 because the condition on line 471 was never true

472 # Absorbing the shift needs somewhere to put it; fabricating a bias the 

473 # mixer does not have would not survive distribution to the component. 

474 if b_key not in state_dict: 

475 return False 

476 ln1_b_broadcast = ln1_b[None, :] if sum_dim == -1 else ln1_b[:, None] 

477 state_dict[b_key] = state_dict[b_key] + (conv_W_in * ln1_b_broadcast).sum(sum_dim) 

478 state_dict[keys["ln1_b"]] = torch.zeros_like(ln1_b) 

479 

480 state_dict[w_key] = conv_W_in * ln1_w_broadcast 

481 state_dict[keys["ln1_w"]] = ( 

482 torch.zeros_like(ln1_w) if rmsnorm_uses_offset else torch.ones_like(ln1_w) 

483 ) 

484 return True 

485 

486 @staticmethod 

487 def _fold_layer( 

488 state_dict: Dict[str, torch.Tensor], 

489 cfg, 

490 layer_idx: int, 

491 fold_biases: bool, 

492 center_weights: bool, 

493 adapter, 

494 gqa: str, 

495 ) -> Dict[str, torch.Tensor]: 

496 """Fold LayerNorm for a single layer. 

497 

498 Args: 

499 state_dict: The state dictionary to process (modified in place) 

500 cfg: Model configuration object 

501 layer_idx: The layer index to process 

502 fold_biases: Whether to fold LayerNorm biases 

503 center_weights: Whether to center weights after folding 

504 adapter: Optional architecture adapter for parameter key translation 

505 gqa: GQA prefix string (empty or "_") 

506 """ 

507 layer = layer_idx 

508 tensors = ProcessWeights.extract_attention_tensors_for_folding( 

509 state_dict, cfg, layer, adapter 

510 ) 

511 wq_tensor = tensors["wq"] 

512 wk_tensor = tensors["wk"] 

513 wv_tensor = tensors["wv"] 

514 bq_tensor = tensors["bq"] 

515 bk_tensor = tensors["bk"] 

516 bv_tensor = tensors["bv"] 

517 ln1_b = tensors["ln1_b"] 

518 ln1_w = tensors["ln1_w"] 

519 keys = tensors["keys"] 

520 

521 # Fold LN into QKV (skip if combined QKV, e.g., OpenELM) 

522 if wq_tensor is not None: 

523 assert isinstance(wq_tensor, torch.Tensor) 

524 assert isinstance(keys, dict) 

525 if wk_tensor is not None: 525 ↛ 527line 525 didn't jump to line 527 because the condition on line 525 was always true

526 assert isinstance(wk_tensor, torch.Tensor) 

527 if wv_tensor is not None: 527 ↛ 529line 527 didn't jump to line 529 because the condition on line 527 was always true

528 assert isinstance(wv_tensor, torch.Tensor) 

529 if bq_tensor is not None: 

530 assert isinstance(bq_tensor, torch.Tensor) 

531 if bk_tensor is not None: 

532 assert isinstance(bk_tensor, torch.Tensor) 

533 if bv_tensor is not None: 

534 assert isinstance(bv_tensor, torch.Tensor) 

535 # RMS norm (Gemma): ln1_b may be None, only ln1_w required 

536 if ln1_w is not None: 

537 assert isinstance(ln1_w, torch.Tensor) 

538 # Fold biases if present (RMS norm has none; missing QKV biases get zeros) 

539 if fold_biases and ln1_b is not None: 

540 assert isinstance(ln1_b, torch.Tensor) 

541 assert wq_tensor is not None 

542 assert wk_tensor is not None 

543 assert wv_tensor is not None 

544 bq_tensor, bk_tensor, bv_tensor = ProcessWeights.fold_layer_norm_biases( 

545 wq_tensor, wk_tensor, wv_tensor, bq_tensor, bk_tensor, bv_tensor, ln1_b 

546 ) 

547 if keys["ln1_b"] in state_dict: 547 ↛ 549line 547 didn't jump to line 549 because the condition on line 547 was always true

548 state_dict[keys["ln1_b"]] = torch.zeros_like(ln1_b) 

549 alternate_b_key = ( 

550 keys["ln1_b"].replace("ln_1", "ln1") 

551 if "ln_1" in keys["ln1_b"] 

552 else keys["ln1_b"].replace("ln1", "ln_1") 

553 ) 

554 if alternate_b_key != keys["ln1_b"] and alternate_b_key in state_dict: 554 ↛ 555line 554 didn't jump to line 555 because the condition on line 554 was never true

555 state_dict[alternate_b_key] = torch.zeros_like(ln1_b) 

556 # Fold ln1_w; use (1+w) for rmsnorm_uses_offset (Gemma), then set to identity 

557 rmsnorm_uses_offset = getattr(cfg, "rmsnorm_uses_offset", False) 

558 effective_ln1_w = (1.0 + ln1_w) if rmsnorm_uses_offset else ln1_w 

559 if wk_tensor is not None and wv_tensor is not None: 559 ↛ 564line 559 didn't jump to line 564 because the condition on line 559 was always true

560 wq_tensor, wk_tensor, wv_tensor = ProcessWeights.fold_layer_norm_weights( 

561 wq_tensor, wk_tensor, wv_tensor, effective_ln1_w 

562 ) 

563 # Set ln1.w to identity: ones (standard) or zeros (rmsnorm_uses_offset) 

564 identity_val = ( 

565 torch.zeros_like(ln1_w) if rmsnorm_uses_offset else torch.ones_like(ln1_w) 

566 ) 

567 if keys["ln1_w"] in state_dict: 567 ↛ 569line 567 didn't jump to line 569 because the condition on line 567 was always true

568 state_dict[keys["ln1_w"]] = identity_val 

569 alternate_w_key = ( 

570 keys["ln1_w"].replace("ln_1", "ln1") 

571 if "ln_1" in keys["ln1_w"] 

572 else keys["ln1_w"].replace("ln1", "ln_1") 

573 ) 

574 if alternate_w_key != keys["ln1_w"] and alternate_w_key in state_dict: 574 ↛ 575line 574 didn't jump to line 575 because the condition on line 574 was never true

575 state_dict[alternate_w_key] = identity_val 

576 if center_weights and wk_tensor is not None and (wv_tensor is not None): 

577 wq_tensor, wk_tensor, wv_tensor = ProcessWeights.center_attention_weights( 

578 wq_tensor, wk_tensor, wv_tensor 

579 ) 

580 state_dict = ProcessWeights._store_processed_attention_tensors( 

581 state_dict, 

582 keys, 

583 wq_tensor, 

584 wk_tensor, 

585 wv_tensor, 

586 bq_tensor, 

587 bk_tensor, 

588 bv_tensor, 

589 adapter, 

590 cfg, 

591 layer, 

592 ) 

593 elif ln1_w is not None: 593 ↛ 604line 593 didn't jump to line 604 because the condition on line 593 was always true

594 assert isinstance(ln1_w, torch.Tensor) 

595 assert ln1_b is None or isinstance(ln1_b, torch.Tensor) 

596 assert isinstance(keys, dict) 

597 ProcessWeights._fold_short_conv_layer_norm( 

598 state_dict, cfg, layer, fold_biases, adapter, ln1_w, ln1_b, keys 

599 ) 

600 

601 # ln1_post.w (Gemma 2/3): keep original; independent post-attention normalization 

602 

603 # Fold MLP LN: shared ln1 (Phi-2, GPT-J) or separate ln2 (Pythia) 

604 if getattr(cfg, "parallel_attn_mlp", False) and ln1_w is not None: 

605 # Check if a separate ln2 exists for this layer 

606 ln2_check_key = ProcessWeights._resolve_state_dict_key( 

607 state_dict, 

608 ProcessWeights._get_param_key(f"blocks.{layer_idx}.ln2.w", adapter), 

609 layer_idx, 

610 ) 

611 if ln2_check_key in state_dict: 

612 # Separate ln2 (e.g., GPT-NeoX/Pythia) — fold ln2 → MLP normally 

613 state_dict = ProcessWeights._fold_mlp_layer_norm( 

614 state_dict, cfg, layer, fold_biases, center_weights, adapter 

615 ) 

616 else: 

617 # Shared ln1 (e.g., Phi-2, GPT-J) — fold ln1 → MLP via override 

618 assert isinstance(ln1_w, torch.Tensor) 

619 assert ln1_b is None or isinstance(ln1_b, torch.Tensor) 

620 state_dict = ProcessWeights._fold_mlp_layer_norm( 

621 state_dict, 

622 cfg, 

623 layer, 

624 fold_biases, 

625 center_weights, 

626 adapter, 

627 override_ln_w=ln1_w, 

628 override_ln_b=ln1_b, 

629 ) 

630 else: 

631 state_dict = ProcessWeights._fold_mlp_layer_norm( 

632 state_dict, cfg, layer, fold_biases, center_weights, adapter 

633 ) 

634 

635 return state_dict 

636 

637 @staticmethod 

638 def _fold_mlp_layer_norm( 

639 state_dict: Dict[str, torch.Tensor], 

640 cfg, 

641 layer: int, 

642 fold_biases: bool, 

643 center_weights: bool, 

644 adapter, 

645 override_ln_w: Optional[torch.Tensor] = None, 

646 override_ln_b: Optional[torch.Tensor] = None, 

647 ) -> Dict[str, torch.Tensor]: 

648 """Fold LayerNorm into MLP layer. 

649 

650 Args: 

651 state_dict: The state dictionary to process (modified in place) 

652 cfg: Model configuration object 

653 layer: The layer index to process 

654 fold_biases: Whether to fold LayerNorm biases 

655 center_weights: Whether to center weights after folding 

656 adapter: Optional architecture adapter for parameter key translation 

657 override_ln_w: Override LN weight tensor. Used for parallel architectures 

658 where MLP reads from ln1 (same as attention) instead of a separate ln2. 

659 override_ln_b: Override LN bias tensor. Used with override_ln_w. 

660 """ 

661 if getattr(cfg, "attn_only", False): 

662 return state_dict 

663 

664 mlp_b_in_key = ProcessWeights._resolve_state_dict_key( 

665 state_dict, ProcessWeights._get_param_key(f"blocks.{layer}.mlp.b_in", adapter), layer 

666 ) 

667 mlp_W_in_key = ProcessWeights._resolve_state_dict_key( 

668 state_dict, ProcessWeights._get_param_key(f"blocks.{layer}.mlp.W_in", adapter), layer 

669 ) 

670 mlp_W_gate_key = ( 

671 ProcessWeights._resolve_state_dict_key( 

672 state_dict, 

673 ProcessWeights._get_param_key(f"blocks.{layer}.mlp.W_gate", adapter), 

674 layer, 

675 ) 

676 if getattr(cfg, "gated_mlp", False) 

677 else None 

678 ) 

679 mlp_b_gate_key = ( 

680 ProcessWeights._resolve_state_dict_key( 

681 state_dict, 

682 ProcessWeights._get_param_key(f"blocks.{layer}.mlp.b_gate", adapter), 

683 layer, 

684 ) 

685 if getattr(cfg, "gated_mlp", False) 

686 else None 

687 ) 

688 

689 # For parallel architectures, ln1 values are passed via override params. 

690 # Otherwise, look up ln2 from the state dict. 

691 ln2_w: Optional[torch.Tensor] 

692 ln2_b: Optional[torch.Tensor] 

693 if override_ln_w is not None: 

694 ln2_w = override_ln_w 

695 ln2_b = override_ln_b 

696 ln2_w_key = None # No state dict key to zero out (already done by attention folding) 

697 ln2_b_key = None 

698 has_ln = True 

699 else: 

700 ln2_b_key = ProcessWeights._resolve_state_dict_key( 

701 state_dict, ProcessWeights._get_param_key(f"blocks.{layer}.ln2.b", adapter), layer 

702 ) 

703 ln2_w_key = ProcessWeights._resolve_state_dict_key( 

704 state_dict, ProcessWeights._get_param_key(f"blocks.{layer}.ln2.w", adapter), layer 

705 ) 

706 has_ln = ln2_w_key in state_dict 

707 ln2_w = state_dict.get(ln2_w_key) if has_ln else None 

708 ln2_b = state_dict.get(ln2_b_key) if has_ln else None 

709 

710 # CRITICAL FIX: For RMS norm (Gemma), ln2_b doesn't exist. Only require ln2_w! 

711 if has_ln and ln2_w is not None: 

712 # MoE layers: fold ln2 into router gate and each expert's W_in/W_gate 

713 if getattr(cfg, "num_experts", None) is not None and cfg.num_experts > 0: 

714 # Every expert reads ln2's output, so folding into only some of them 

715 # would change the model — collect them all before touching anything. 

716 expert_keys = [ 

717 key 

718 for e in range(cfg.num_experts) 

719 for suffix in ("W_in.weight", "W_gate.weight") 

720 for key in ( 

721 ProcessWeights._resolve_state_dict_key( 

722 state_dict, f"blocks.{layer}.mlp.experts.{e}.{suffix}", layer 

723 ), 

724 ) 

725 if key in state_dict 

726 ] 

727 if expert_keys: 

728 router_key = ProcessWeights._resolve_state_dict_key( 

729 state_dict, f"blocks.{layer}.mlp.W_gate.weight", layer 

730 ) 

731 if router_key in state_dict: 731 ↛ 733line 731 didn't jump to line 733 because the condition on line 731 was always true

732 state_dict[router_key] = state_dict[router_key] * ln2_w[None, :] 

733 for key in expert_keys: 

734 state_dict[key] = state_dict[key] * ln2_w[None, :] 

735 if ln2_w_key is not None: 735 ↛ 744line 735 didn't jump to line 744 because the condition on line 735 was always true

736 state_dict[ln2_w_key] = torch.ones_like(ln2_w) 

737 alternate_ln2_w_key = ( 

738 ln2_w_key.replace("ln_2", "ln2") 

739 if "ln_2" in ln2_w_key 

740 else ln2_w_key.replace("ln2", "ln_2") 

741 ) 

742 if alternate_ln2_w_key != ln2_w_key and alternate_ln2_w_key in state_dict: 742 ↛ 743line 742 didn't jump to line 743 because the condition on line 742 was never true

743 state_dict[alternate_ln2_w_key] = torch.ones_like(ln2_w) 

744 return state_dict 

745 

746 # A dense layer of an interleaved stack (Llama4, Laguna, LLaDA2-MoE, 

747 # LFM2-MoE) parks its gated MLP under dense_in/dense_gate and has no 

748 # experts of its own, so it folds exactly like a non-MoE layer. Anything 

749 # else here is a sparse layer whose expert weights this state dict does 

750 # not carry — leave its ln2 alone rather than fold half the readers. 

751 if not mlp_W_in_key.endswith(".mlp.dense_in.weight"): 

752 return state_dict 

753 

754 mlp_W_in = ProcessWeights.convert_tensor_to_tl_format( 

755 mlp_W_in_key, state_dict, state_dict.get(mlp_W_in_key), cfg, adapter, layer 

756 ) 

757 assert mlp_W_in is not None, f"MLP W_in not found at key {mlp_W_in_key}" 

758 # rmsnorm_uses_offset: effective scale is (1+w), identity is 0.0 

759 rmsnorm_uses_offset = getattr(cfg, "rmsnorm_uses_offset", False) 

760 effective_ln2_w = (1.0 + ln2_w) if rmsnorm_uses_offset else ln2_w 

761 model_axis = ProcessWeights._mlp_model_axis( 

762 mlp_W_in_key, mlp_W_in, effective_ln2_w.shape[0], adapter, reads_residual=True 

763 ) 

764 if model_axis == 1: 

765 ln2_w_broadcast = effective_ln2_w[None, :] 

766 sum_dim = -1 

767 if ln2_b is not None: 

768 ln2_b_broadcast = ln2_b[None, :] 

769 elif model_axis == 0: 769 ↛ 775line 769 didn't jump to line 775 because the condition on line 769 was always true

770 ln2_w_broadcast = effective_ln2_w[:, None] 

771 sum_dim = -2 

772 if ln2_b is not None: 

773 ln2_b_broadcast = ln2_b[:, None] 

774 else: 

775 raise ValueError( 

776 f"Cannot broadcast MLP weight {mlp_W_in.shape} with layer norm weight {effective_ln2_w.shape}" 

777 ) 

778 # Only fold biases if they exist (LayerNorm). RMS norm has no biases. 

779 if fold_biases and ln2_b is not None: 

780 mlp_b_in = ProcessWeights.convert_tensor_to_tl_format( 

781 mlp_b_in_key, state_dict, state_dict.get(mlp_b_in_key), cfg, adapter, layer 

782 ) 

783 ln2_b_folded = (mlp_W_in * ln2_b_broadcast).sum(sum_dim) 

784 if mlp_b_in is not None: 

785 new_mlp_b_in = mlp_b_in + ln2_b_folded 

786 else: 

787 # MLP has no bias — create one from the folded LN bias 

788 new_mlp_b_in = ln2_b_folded 

789 state_dict[mlp_b_in_key] = ProcessWeights.convert_tensor_to_hf_format( 

790 mlp_b_in_key, new_mlp_b_in, cfg, adapter, layer 

791 ) 

792 # Set ln2.b to zero (skip for parallel override — ln1 already zeroed) 

793 if ln2_b_key is not None: 

794 state_dict[ln2_b_key] = torch.zeros_like(ln2_b) 

795 alternate_ln2_b_key = ( 

796 ln2_b_key.replace("ln_2", "ln2") 

797 if "ln_2" in ln2_b_key 

798 else ln2_b_key.replace("ln2", "ln_2") 

799 ) 

800 if alternate_ln2_b_key != ln2_b_key and alternate_ln2_b_key in state_dict: 800 ↛ 801line 800 didn't jump to line 801 because the condition on line 800 was never true

801 state_dict[alternate_ln2_b_key] = torch.zeros_like(ln2_b) 

802 new_mlp_W_in = mlp_W_in * ln2_w_broadcast 

803 state_dict[mlp_W_in_key] = ProcessWeights.convert_tensor_to_hf_format( 

804 mlp_W_in_key, new_mlp_W_in, cfg, adapter, layer 

805 ) 

806 if getattr(cfg, "gated_mlp", False) and mlp_W_gate_key is not None: 

807 mlp_W_gate = ProcessWeights.convert_tensor_to_tl_format( 

808 mlp_W_gate_key, state_dict, state_dict.get(mlp_W_gate_key), cfg, adapter, layer 

809 ) 

810 # Combined gate+up (OpenELM): no separate gate, already folded above 

811 if mlp_W_gate is not None: 811 ↛ 836line 811 didn't jump to line 836 because the condition on line 811 was always true

812 new_mlp_W_gate = mlp_W_gate * ln2_w_broadcast 

813 state_dict[mlp_W_gate_key] = ProcessWeights.convert_tensor_to_hf_format( 

814 mlp_W_gate_key, new_mlp_W_gate, cfg, adapter, layer 

815 ) 

816 # Also fold ln2 bias into gate bias (mirrors the in-proj bias folding above) 

817 if fold_biases and ln2_b is not None and mlp_b_gate_key is not None: 

818 mlp_b_gate = ProcessWeights.convert_tensor_to_tl_format( 

819 mlp_b_gate_key, 

820 state_dict, 

821 state_dict.get(mlp_b_gate_key), 

822 cfg, 

823 adapter, 

824 layer, 

825 ) 

826 ln2_b_gate_folded = (mlp_W_gate * ln2_b_broadcast).sum(sum_dim) 

827 if mlp_b_gate is not None: 827 ↛ 828line 827 didn't jump to line 828 because the condition on line 827 was never true

828 new_mlp_b_gate = mlp_b_gate + ln2_b_gate_folded 

829 else: 

830 new_mlp_b_gate = ln2_b_gate_folded 

831 state_dict[mlp_b_gate_key] = ProcessWeights.convert_tensor_to_hf_format( 

832 mlp_b_gate_key, new_mlp_b_gate, cfg, adapter, layer 

833 ) 

834 # After folding, set ln2.w to identity (skip for parallel override — 

835 # ln1 was already set to identity by the attention folding code). 

836 if ln2_w_key is not None: 

837 identity_ln2 = ( 

838 torch.zeros_like(ln2_w) if rmsnorm_uses_offset else torch.ones_like(ln2_w) 

839 ) 

840 state_dict[ln2_w_key] = identity_ln2 

841 alternate_ln2_w_key = ( 

842 ln2_w_key.replace("ln_2", "ln2") 

843 if "ln_2" in ln2_w_key 

844 else ln2_w_key.replace("ln2", "ln_2") 

845 ) 

846 if alternate_ln2_w_key != ln2_w_key and alternate_ln2_w_key in state_dict: 846 ↛ 847line 846 didn't jump to line 847 because the condition on line 846 was never true

847 state_dict[alternate_ln2_w_key] = identity_ln2 

848 if center_weights and mlp_W_in_key in state_dict: 

849 mlp_W_in_centered = ProcessWeights.convert_tensor_to_tl_format( 

850 mlp_W_in_key, state_dict, state_dict.get(mlp_W_in_key), cfg, adapter, layer 

851 ) 

852 assert mlp_W_in_centered is not None, f"MLP W_in not found at key {mlp_W_in_key}" 

853 # Center along d_model: TL [d_model, d_mlp] or HF [d_mlp, d_model] 

854 d_model = cfg.d_model if cfg is not None else None 

855 model_axis = ProcessWeights._mlp_model_axis( 

856 mlp_W_in_key, mlp_W_in_centered, d_model, adapter, reads_residual=True 

857 ) 

858 if model_axis == 0: 

859 # TL format [d_model, d_mlp] 

860 mlp_W_in_centered = mlp_W_in_centered - mlp_W_in_centered.mean(0, keepdim=True) 

861 elif model_axis == 1: 861 ↛ 866line 861 didn't jump to line 866 because the condition on line 861 was always true

862 # HF format [d_mlp, d_model] 

863 mlp_W_in_centered = mlp_W_in_centered - mlp_W_in_centered.mean(-1, keepdim=True) 

864 else: 

865 # Fallback: assume TL format 

866 mlp_W_in_centered = mlp_W_in_centered - mlp_W_in_centered.mean(0, keepdim=True) 

867 state_dict[mlp_W_in_key] = ProcessWeights.convert_tensor_to_hf_format( 

868 mlp_W_in_key, mlp_W_in_centered, cfg, adapter, layer 

869 ) 

870 if getattr(cfg, "act_fn", None) is not None and cfg.act_fn.startswith("solu"): 

871 mlp_b_out_key = ProcessWeights._get_param_key(f"blocks.{layer}.mlp.b_out", adapter) 

872 mlp_W_out_key = ProcessWeights._get_param_key(f"blocks.{layer}.mlp.W_out", adapter) 

873 mlp_ln_b_key = ProcessWeights._get_param_key(f"blocks.{layer}.mlp.ln.b", adapter) 

874 mlp_ln_w_key = ProcessWeights._get_param_key(f"blocks.{layer}.mlp.ln.w", adapter) 

875 

876 mlp_b_out = ProcessWeights.convert_tensor_to_tl_format( 

877 mlp_b_out_key, state_dict, state_dict.get(mlp_b_out_key), cfg, adapter, layer 

878 ) 

879 mlp_W_out = ProcessWeights.convert_tensor_to_tl_format( 

880 mlp_W_out_key, state_dict, state_dict.get(mlp_W_out_key), cfg, adapter, layer 

881 ) 

882 mlp_ln_b = state_dict.get(mlp_ln_b_key) 

883 mlp_ln_w = state_dict.get(mlp_ln_w_key) 

884 assert mlp_b_out is not None, f"MLP b_out not found at key {mlp_b_out_key}" 

885 assert mlp_W_out is not None, f"MLP W_out not found at key {mlp_W_out_key}" 

886 assert mlp_ln_b is not None, f"MLP ln.b not found at key {mlp_ln_b_key}" 

887 assert mlp_ln_w is not None, f"MLP ln.w not found at key {mlp_ln_w_key}" 

888 

889 # TL keys hold W_out as [d_mlp, d_model]; nn.Linear bridges hold [d_model, d_mlp]. 

890 # The fold and the centering must use the same neuron axis, so resolve it once. 

891 d_mlp = mlp_ln_w.shape[0] 

892 if mlp_W_out.shape[0] == d_mlp and mlp_W_out.shape[-1] != d_mlp: 

893 neuron_dim = 0 

894 elif mlp_W_out.shape[-1] == d_mlp and mlp_W_out.shape[0] != d_mlp: 894 ↛ 897line 894 didn't jump to line 897 because the condition on line 894 was always true

895 neuron_dim = -1 

896 else: 

897 raise ValueError( 

898 f"Cannot resolve the neuron axis of MLP W_out {tuple(mlp_W_out.shape)} " 

899 f"against the mid-MLP LayerNorm (d_mlp={d_mlp}) at layer {layer}." 

900 ) 

901 ln_shape = (-1, 1) if neuron_dim == 0 else (1, -1) 

902 

903 if fold_biases: 903 ↛ 911line 903 didn't jump to line 911 because the condition on line 903 was always true

904 new_mlp_b_out = mlp_b_out + (mlp_W_out * mlp_ln_b.reshape(ln_shape)).sum(neuron_dim) 

905 state_dict[mlp_b_out_key] = ProcessWeights.convert_tensor_to_hf_format( 

906 mlp_b_out_key, new_mlp_b_out, cfg, adapter, layer 

907 ) 

908 if mlp_ln_b_key in state_dict: 908 ↛ 911line 908 didn't jump to line 911 because the condition on line 908 was always true

909 state_dict[mlp_ln_b_key] = torch.zeros_like(mlp_ln_b) 

910 

911 new_mlp_W_out = mlp_W_out * mlp_ln_w.reshape(ln_shape) 

912 

913 if center_weights: 913 ↛ 918line 913 didn't jump to line 918 because the condition on line 913 was always true

914 # The folded mid-MLP LayerNorm emits activations that are mean-zero across 

915 # neurons, so a per-row constant along that axis never reaches the output. 

916 new_mlp_W_out = new_mlp_W_out - new_mlp_W_out.mean(neuron_dim, keepdim=True) 

917 

918 state_dict[mlp_W_out_key] = ProcessWeights.convert_tensor_to_hf_format( 

919 mlp_W_out_key, new_mlp_W_out, cfg, adapter, layer 

920 ) 

921 

922 if mlp_ln_w_key in state_dict: 922 ↛ 927line 922 didn't jump to line 927 because the condition on line 922 was always true

923 state_dict[mlp_ln_w_key] = torch.ones_like(mlp_ln_w) 

924 

925 # ln2_post.w (Gemma 2/3): keep original; independent post-MLP normalization 

926 

927 return state_dict 

928 

929 @staticmethod 

930 def _store_processed_attention_tensors( 

931 state_dict: Dict[str, torch.Tensor], 

932 keys: Dict[str, str], 

933 wq_tensor: Optional[torch.Tensor], 

934 wk_tensor: Optional[torch.Tensor], 

935 wv_tensor: Optional[torch.Tensor], 

936 bq_tensor: Optional[torch.Tensor], 

937 bk_tensor: Optional[torch.Tensor], 

938 bv_tensor: Optional[torch.Tensor], 

939 adapter, 

940 cfg, 

941 layer: int, 

942 ) -> Dict[str, torch.Tensor]: 

943 """Store processed attention tensors back to state dict in appropriate format. 

944 

945 Args: 

946 state_dict: The state dictionary to update (modified in place) 

947 keys: Dictionary mapping tensor names to state dict keys 

948 wq_tensor, wk_tensor, wv_tensor: Processed attention weight tensors 

949 bq_tensor, bk_tensor, bv_tensor: Processed attention bias tensors 

950 adapter: Optional architecture adapter for parameter key translation 

951 cfg: Model configuration object 

952 layer: The layer index 

953 """ 

954 if wq_tensor is None: 954 ↛ 955line 954 didn't jump to line 955 because the condition on line 954 was never true

955 return state_dict 

956 wq_key = keys["W_Q"] 

957 wk_key = keys["W_K"] 

958 wv_key = keys["W_V"] 

959 bq_key = keys["b_Q"] 

960 bk_key = keys["b_K"] 

961 bv_key = keys["b_V"] 

962 

963 # Store processed tensors directly in 3D format (set_processed_weights will flatten to 2D) 

964 if wq_tensor is None or wk_tensor is None or wv_tensor is None: 964 ↛ 965line 964 didn't jump to line 965 because the condition on line 964 was never true

965 raise ValueError(f"Required attention weights missing for layer {layer}") 

966 state_dict[wq_key] = ProcessWeights.convert_tensor_to_hf_format( 

967 wq_key, wq_tensor, cfg, adapter, layer_idx=layer 

968 ) 

969 state_dict[wk_key] = ProcessWeights.convert_tensor_to_hf_format( 

970 wk_key, wk_tensor, cfg, adapter, layer_idx=layer 

971 ) 

972 state_dict[wv_key] = ProcessWeights.convert_tensor_to_hf_format( 

973 wv_key, wv_tensor, cfg, adapter, layer_idx=layer 

974 ) 

975 if bq_tensor is not None: 

976 state_dict[bq_key] = ProcessWeights.convert_tensor_to_hf_format( 

977 bq_key, bq_tensor, cfg, adapter, layer_idx=layer 

978 ) 

979 if bk_tensor is not None: 

980 state_dict[bk_key] = ProcessWeights.convert_tensor_to_hf_format( 

981 bk_key, bk_tensor, cfg, adapter, layer_idx=layer 

982 ) 

983 if bv_tensor is not None: 

984 state_dict[bv_key] = ProcessWeights.convert_tensor_to_hf_format( 

985 bv_key, bv_tensor, cfg, adapter, layer_idx=layer 

986 ) 

987 

988 return state_dict 

989 

990 @staticmethod 

991 def _unembed_model_axis(weight: torch.Tensor, d_model: Optional[int], adapter=None) -> int: 

992 """Resolve the hidden axis after conversion, including square readouts.""" 

993 if adapter is not None: 

994 conversions = getattr(adapter, "weight_processing_conversions", None) or {} 

995 conversion = conversions.get("unembed.weight", conversions.get("unembed")) 

996 if ProcessWeights._conversion_transposes(conversion): 

997 # Transposing HF [d_vocab, d_model] yields TL [d_model, d_vocab]. 

998 return 0 

999 if d_model is not None and weight.shape[0] != weight.shape[1]: 

1000 if weight.shape[0] == d_model: 

1001 return 0 

1002 if weight.shape[1] == d_model: 1002 ↛ 1004line 1002 didn't jump to line 1004 because the condition on line 1002 was always true

1003 return 1 

1004 raise ValueError(f"Unembedding shape {weight.shape} has no d_model={d_model} axis") 

1005 # Without conversion metadata, Bridge weights are HF; adapter-free inputs are TL. 

1006 return 0 if adapter is None else 1 

1007 

1008 @staticmethod 

1009 def _conversion_transposes(conversion: Any) -> bool: 

1010 """Whether a weight conversion swaps the two axes of a 2-D weight.""" 

1011 if isinstance(conversion, ParamProcessingConversion): 

1012 conversion = conversion.tensor_conversion 

1013 if isinstance(conversion, TransposeTensorConversion): 

1014 return True 

1015 if isinstance(conversion, ChainTensorConversion): 

1016 # Two transposes cancel. 

1017 return ( 

1018 sum(ProcessWeights._conversion_transposes(c) for c in conversion.conversions) % 2 

1019 == 1 

1020 ) 

1021 return False 

1022 

1023 @staticmethod 

1024 def _mlp_model_axis( 

1025 key: str, weight: torch.Tensor, d_model: Optional[int], adapter, reads_residual: bool 

1026 ) -> Optional[int]: 

1027 """d_model axis of a dense MLP weight after conversion, or None; square ones use layout.""" 

1028 if d_model is None: 1028 ↛ 1029line 1028 didn't jump to line 1029 because the condition on line 1028 was never true

1029 return None 

1030 if weight.shape[0] != weight.shape[1]: 

1031 if weight.shape[0] == d_model: 

1032 return 0 

1033 if weight.shape[1] == d_model: 1033 ↛ 1035line 1033 didn't jump to line 1035 because the condition on line 1033 was always true

1034 return 1 

1035 return None 

1036 if weight.shape[0] != d_model: 1036 ↛ 1037line 1036 didn't jump to line 1037 because the condition on line 1036 was never true

1037 return None 

1038 tl_axis = 0 if reads_residual else 1 

1039 if adapter is None: 1039 ↛ 1040line 1039 didn't jump to line 1040 because the condition on line 1039 was never true

1040 return tl_axis 

1041 conversions = getattr(adapter, "weight_processing_conversions", None) or {} 

1042 placeholder = re.sub(r"blocks\.(\d+)\.", "blocks.{i}.", key) 

1043 conversion = conversions.get( 

1044 placeholder, conversions.get(placeholder.removesuffix(".weight")) 

1045 ) 

1046 if ProcessWeights._conversion_transposes(conversion): 

1047 return tl_axis 

1048 if key in getattr(adapter, "_in_out_weight_keys", ()): 

1049 return tl_axis 

1050 return 1 - tl_axis 

1051 

1052 @staticmethod 

1053 def _fold_unembed_layer_norm( 

1054 state_dict: Dict[str, torch.Tensor], cfg, fold_biases: bool, center_weights: bool, adapter 

1055 ) -> Dict[str, torch.Tensor]: 

1056 """Fold LayerNorm into unembedding layer. 

1057 

1058 Args: 

1059 state_dict: The state dictionary to process (modified in place) 

1060 cfg: Model configuration object 

1061 fold_biases: Whether to fold LayerNorm biases 

1062 center_weights: Whether to center weights after folding 

1063 adapter: Optional architecture adapter for parameter key translation 

1064 """ 

1065 unembed_b_U_key = ProcessWeights._get_param_key("unembed.b_U", adapter) 

1066 unembed_W_U_key = ProcessWeights._get_param_key("unembed.W_U", adapter) 

1067 ln_final_b_key = ProcessWeights._get_param_key("ln_final.b", adapter) 

1068 ln_final_w_key = ProcessWeights._get_param_key("ln_final.w", adapter) 

1069 

1070 # Skip layer norm folding if ln_final doesn't exist 

1071 # (e.g., encoder-decoder models like T5 have encoder_ln_final/decoder_ln_final instead) 

1072 if ln_final_w_key not in state_dict: 

1073 return state_dict 

1074 

1075 has_unembed_bias = unembed_b_U_key in state_dict 

1076 unembed_weight = ProcessWeights.convert_tensor_to_tl_format( 

1077 unembed_W_U_key, state_dict, state_dict.get(unembed_W_U_key), cfg, adapter, None 

1078 ) 

1079 ln_weight = state_dict[ln_final_w_key] 

1080 assert unembed_weight is not None, f"Unembed weight not found at key {unembed_W_U_key}" 

1081 # rmsnorm_uses_offset: effective scale is (1+w), identity is 0.0 

1082 rmsnorm_uses_offset = getattr(cfg, "rmsnorm_uses_offset", False) 

1083 effective_ln_weight = (1.0 + ln_weight) if rmsnorm_uses_offset else ln_weight 

1084 if len(unembed_weight.shape) == 2 and len(ln_weight.shape) == 1: 1084 ↛ 1091line 1084 didn't jump to line 1091 because the condition on line 1084 was always true

1085 model_axis = ProcessWeights._unembed_model_axis(unembed_weight, len(ln_weight), adapter) 

1086 if model_axis == 0: 

1087 new_unembed_weight = unembed_weight * effective_ln_weight[:, None] 

1088 else: 

1089 new_unembed_weight = unembed_weight * effective_ln_weight[None, :] 

1090 else: 

1091 raise ValueError( 

1092 f"Unexpected tensor shapes: unembedding {unembed_weight.shape}, layer norm {ln_weight.shape}" 

1093 ) 

1094 state_dict[unembed_W_U_key] = ProcessWeights.convert_tensor_to_hf_format( 

1095 unembed_W_U_key, new_unembed_weight, cfg, adapter, None 

1096 ) 

1097 # Set ln_final.w to identity: zeros (rmsnorm_uses_offset) or ones (standard) 

1098 identity_val = ( 

1099 torch.zeros_like(ln_weight) if rmsnorm_uses_offset else torch.ones_like(ln_weight) 

1100 ) 

1101 if ln_final_w_key in state_dict: 1101 ↛ 1103line 1101 didn't jump to line 1103 because the condition on line 1101 was always true

1102 state_dict[ln_final_w_key] = identity_val 

1103 alternate_final_w_key = ( 

1104 ln_final_w_key.replace("ln_f", "ln_final") 

1105 if "ln_f" in ln_final_w_key 

1106 else ln_final_w_key.replace("ln_final", "ln_f") 

1107 ) 

1108 if alternate_final_w_key != ln_final_w_key and alternate_final_w_key in state_dict: 1108 ↛ 1109line 1108 didn't jump to line 1109 because the condition on line 1108 was never true

1109 state_dict[alternate_final_w_key] = identity_val 

1110 # RMSNorm outputs are not zero-mean, so centering would change predictions. 

1111 if center_weights and not getattr(cfg, "final_rms", False): 

1112 unembed_weight_centered = ProcessWeights.convert_tensor_to_tl_format( 

1113 unembed_W_U_key, state_dict, state_dict.get(unembed_W_U_key), cfg, adapter, None 

1114 ) 

1115 assert ( 

1116 unembed_weight_centered is not None 

1117 ), f"Unembed weight not found at key {unembed_W_U_key}" 

1118 if len(unembed_weight_centered.shape) == 2: 1118 ↛ 1129line 1118 didn't jump to line 1129 because the condition on line 1118 was always true

1119 model_axis = ProcessWeights._unembed_model_axis( 

1120 unembed_weight_centered, len(ln_weight), adapter 

1121 ) 

1122 unembed_weight_centered = unembed_weight_centered - unembed_weight_centered.mean( 

1123 model_axis, keepdim=True 

1124 ) 

1125 state_dict[unembed_W_U_key] = ProcessWeights.convert_tensor_to_hf_format( 

1126 unembed_W_U_key, unembed_weight_centered, cfg, adapter, None 

1127 ) 

1128 else: 

1129 raise ValueError( 

1130 f"Unexpected unembedding weight shape: {unembed_weight_centered.shape}" 

1131 ) 

1132 

1133 return state_dict 

1134 

1135 @staticmethod 

1136 def _fold_final_rms_bias( 

1137 state_dict: Dict[str, torch.Tensor], cfg, fold_biases: bool, adapter 

1138 ) -> Dict[str, torch.Tensor]: 

1139 """Fold final RMS bias into unembedding (separate from regular unembed folding). 

1140 

1141 Args: 

1142 state_dict: The state dictionary to process (modified in place) 

1143 cfg: Model configuration object 

1144 fold_biases: Whether to fold LayerNorm biases 

1145 adapter: Optional architecture adapter for parameter key translation 

1146 """ 

1147 unembed_b_U_key = ProcessWeights._get_param_key("unembed.b_U", adapter) 

1148 unembed_W_U_key = ProcessWeights._get_param_key("unembed.W_U", adapter) 

1149 ln_final_b_key = ProcessWeights._get_param_key("ln_final.b", adapter) 

1150 has_unembed_bias = unembed_b_U_key in state_dict 

1151 has_ln_final_bias = ln_final_b_key in state_dict 

1152 if ( 

1153 not getattr(cfg, "final_rms", False) 

1154 and fold_biases 

1155 and has_unembed_bias 

1156 and has_ln_final_bias 

1157 ): 

1158 unembed_weight = ProcessWeights.convert_tensor_to_tl_format( 

1159 unembed_W_U_key, state_dict, state_dict.get(unembed_W_U_key), cfg, adapter, None 

1160 ) 

1161 ln_bias = state_dict[ln_final_b_key] 

1162 assert unembed_weight is not None, f"Unembed weight not found at key {unembed_W_U_key}" 

1163 if len(unembed_weight.shape) == 2 and len(ln_bias.shape) == 1: 1163 ↛ 1172line 1163 didn't jump to line 1172 because the condition on line 1163 was always true

1164 model_axis = ProcessWeights._unembed_model_axis( 

1165 unembed_weight, len(ln_bias), adapter 

1166 ) 

1167 if model_axis == 0: 

1168 bias_contribution = (unembed_weight * ln_bias[:, None]).sum(dim=-2) 

1169 else: 

1170 bias_contribution = (unembed_weight * ln_bias[None, :]).sum(dim=-1) 

1171 else: 

1172 raise ValueError( 

1173 f"Unexpected tensor shapes: unembedding {unembed_weight.shape}, layer norm bias {ln_bias.shape}" 

1174 ) 

1175 unembed_b_U = ProcessWeights.convert_tensor_to_tl_format( 

1176 unembed_b_U_key, state_dict, state_dict.get(unembed_b_U_key), cfg, adapter, None 

1177 ) 

1178 assert unembed_b_U is not None, f"Unembed bias not found at key {unembed_b_U_key}" 

1179 new_unembed_b_U = unembed_b_U + bias_contribution 

1180 state_dict[unembed_b_U_key] = ProcessWeights.convert_tensor_to_hf_format( 

1181 unembed_b_U_key, new_unembed_b_U, cfg, adapter, None 

1182 ) 

1183 if ln_final_b_key in state_dict: 1183 ↛ 1185line 1183 didn't jump to line 1185 because the condition on line 1183 was always true

1184 state_dict[ln_final_b_key] = torch.zeros_like(ln_bias) 

1185 alternate_final_b_key = ( 

1186 ln_final_b_key.replace("ln_f", "ln_final") 

1187 if "ln_f" in ln_final_b_key 

1188 else ln_final_b_key.replace("ln_final", "ln_f") 

1189 ) 

1190 if alternate_final_b_key != ln_final_b_key and alternate_final_b_key in state_dict: 1190 ↛ 1191line 1190 didn't jump to line 1191 because the condition on line 1190 was never true

1191 state_dict[alternate_final_b_key] = torch.zeros_like(ln_bias) 

1192 

1193 return state_dict 

1194 

1195 @staticmethod 

1196 def fold_layer_norm( 

1197 state_dict: Dict[str, torch.Tensor], 

1198 cfg, 

1199 fold_biases: bool = True, 

1200 center_weights: bool = True, 

1201 adapter=None, 

1202 ) -> Dict[str, torch.Tensor]: 

1203 """Fold Layer Norm. Can also be used to fold RMS Norm, when fold_biases and center_weights are set to False. 

1204 

1205 Takes in a state dict from a pretrained model, formatted to be consistent with 

1206 HookedTransformer but with LayerNorm weights and biases. Folds these into the neighbouring 

1207 weights. See further_comments.md for more details. 

1208 

1209 Args: 

1210 state_dict (Dict[str, torch.Tensor]): State dict of pretrained model. 

1211 cfg: Model configuration object with n_layers, n_key_value_heads, etc. 

1212 fold_biases (bool): Enables folding of LN biases. Should be disabled when RMS Norm is used. 

1213 center_weights (bool): Enables the centering of weights after folding in LN. Should be disabled when RMS Norm is used. 

1214 adapter: Optional architecture adapter for parameter key translation. 

1215 

1216 Returns: 

1217 Dict[str, torch.Tensor]: Modified state dict with LayerNorm folded into linear layers. 

1218 """ 

1219 # Make a deep copy to avoid modifying the original 

1220 state_dict = { 

1221 k: v.clone() if isinstance(v, torch.Tensor) else v for k, v in state_dict.items() 

1222 } 

1223 gqa = "" if getattr(cfg, "n_key_value_heads", None) is None else "_" 

1224 for l in range(cfg.n_layers): 

1225 state_dict = ProcessWeights._fold_layer( 

1226 state_dict, cfg, l, fold_biases, center_weights, adapter, gqa 

1227 ) 

1228 state_dict = ProcessWeights._fold_final_rms_bias(state_dict, cfg, fold_biases, adapter) 

1229 state_dict = ProcessWeights._fold_unembed_layer_norm( 

1230 state_dict, cfg, fold_biases, center_weights, adapter 

1231 ) 

1232 return state_dict 

1233 

1234 @staticmethod 

1235 def fold_layer_norm_with_layout( 

1236 state_dict: Dict[str, torch.Tensor], layout: ResidualLayout, center_weights: bool = True 

1237 ) -> Dict[str, torch.Tensor]: 

1238 """Fold each norm into the linears ``layout.norm_readers`` lists for it. 

1239 

1240 A reader computes ``W(γ ⊙ x̂ + β) + b = (W diag γ) x̂ + (b + Wβ)``, so γ and β move 

1241 into the reader and the norm keeps only the normalization (γ = 1, β = 0); a 

1242 bias-free reader gets a created bias. For LayerNorm, x̂ has zero mean, so the 

1243 reader's weights are also centered over their input axis (``center_weights``). 

1244 """ 

1245 state_dict = dict(state_dict) 

1246 for norm, readers in layout.norm_readers.items(): 

1247 gamma = state_dict[f"{norm}.weight"] 

1248 beta = state_dict.get(f"{norm}.bias") 

1249 for reader in readers: 

1250 weight = state_dict[f"{reader}.weight"] 

1251 if beta is not None: 1251 ↛ 1255line 1251 didn't jump to line 1255 because the condition on line 1251 was always true

1252 # Dropping Wβ on a bias-free key would keep logits but offset hook_k. 

1253 bias_key = f"{reader}.bias" 

1254 state_dict[bias_key] = state_dict.get(bias_key, 0) + weight @ beta 

1255 weight = weight * gamma 

1256 if center_weights: 1256 ↛ 1258line 1256 didn't jump to line 1258 because the condition on line 1256 was always true

1257 weight = weight - weight.mean(dim=1, keepdim=True) 

1258 state_dict[f"{reader}.weight"] = weight 

1259 state_dict[f"{norm}.weight"] = torch.ones_like(gamma) 

1260 if beta is not None: 1260 ↛ 1246line 1260 didn't jump to line 1246 because the condition on line 1260 was always true

1261 state_dict[f"{norm}.bias"] = torch.zeros_like(beta) 

1262 return state_dict 

1263 

1264 @staticmethod 

1265 def center_writing_weights_with_layout( 

1266 state_dict: Dict[str, torch.Tensor], layout: ResidualLayout 

1267 ) -> Dict[str, torch.Tensor]: 

1268 """Center every write ``layout`` lists over d_model. The streams are read only 

1269 through LayerNorms, which remove the mean, so the output is unchanged.""" 

1270 state_dict = dict(state_dict) 

1271 for writer in layout.residual_writers: 

1272 weight = state_dict[f"{writer}.weight"] 

1273 state_dict[f"{writer}.weight"] = weight - weight.mean(dim=0, keepdim=True) 

1274 bias_key = f"{writer}.bias" 

1275 if bias_key in state_dict: 1275 ↛ 1271line 1275 didn't jump to line 1271 because the condition on line 1275 was always true

1276 state_dict[bias_key] = state_dict[bias_key] - state_dict[bias_key].mean() 

1277 for table in layout.embedding_writers: 

1278 weight = state_dict[f"{table}.weight"] 

1279 state_dict[f"{table}.weight"] = weight - weight.mean(dim=1, keepdim=True) 

1280 return state_dict 

1281 

1282 @staticmethod 

1283 def fold_value_biases_with_layout( 

1284 state_dict: Dict[str, torch.Tensor], layout: ResidualLayout, center_outputs: bool = False 

1285 ) -> Dict[str, torch.Tensor]: 

1286 """Move each attention's value bias into its output bias. Attention weights sum 

1287 to 1, so the value bias reaches the output unchanged, as ``W_O b_V``.""" 

1288 state_dict = dict(state_dict) 

1289 for value, output in layout.value_output_pairs: 

1290 value_bias = state_dict.get(f"{value}.bias") 

1291 if value_bias is None: 1291 ↛ 1292line 1291 didn't jump to line 1292 because the condition on line 1291 was never true

1292 continue 

1293 output_bias_key = f"{output}.bias" 

1294 if output_bias_key not in state_dict: 

1295 raise ValueError(f"{output} has no bias to receive the value bias of {value}.") 

1296 output_bias = state_dict[output_bias_key] + state_dict[f"{output}.weight"] @ value_bias 

1297 if center_outputs: 

1298 output_bias = output_bias - output_bias.mean() 

1299 state_dict[output_bias_key] = output_bias 

1300 state_dict[f"{value}.bias"] = torch.zeros_like(value_bias) 

1301 return state_dict 

1302 

1303 @staticmethod 

1304 def center_writing_weights( 

1305 state_dict: Dict[str, torch.Tensor], cfg, adapter=None 

1306 ) -> Dict[str, torch.Tensor]: 

1307 """Center Writing Weights. 

1308 

1309 Centers the weights of the model that write to the residual stream - W_out, W_E, W_pos and 

1310 W_out. This is done by subtracting the mean of the weights from the weights themselves. This 

1311 is done in-place. See fold_layer_norm for more details. 

1312 

1313 Args: 

1314 state_dict (Dict[str, torch.Tensor]): State dict of the model. 

1315 cfg: Model configuration object. 

1316 adapter: Optional architecture adapter for parameter key translation. 

1317 

1318 Returns: 

1319 Dict[str, torch.Tensor]: Modified state dict with centered writing weights. 

1320 """ 

1321 # Post-norm models leave the first attention's input un-normed, so centering 

1322 # the embedding would shift a residual stream nothing re-normalizes. 

1323 architecture = getattr(cfg, "original_architecture", None) 

1324 if architecture in POST_NORM_ARCHITECTURES: 

1325 print(f"Not centering embedding weights for {architecture}") 

1326 else: 

1327 # Make a deep copy to avoid modifying the original 

1328 embed_W_E_key = ProcessWeights._get_param_key("embed.W_E", adapter) 

1329 try: 

1330 pos_embed_W_pos_key = ( 

1331 ProcessWeights._get_param_key("pos_embed.W_pos", adapter) 

1332 if getattr(cfg, "positional_embedding_type", "standard") 

1333 not in ("rotary", "alibi", "none") 

1334 else None 

1335 ) 

1336 except ValueError: 

1337 pos_embed_W_pos_key = None 

1338 if embed_W_E_key not in state_dict: 1338 ↛ 1339line 1338 didn't jump to line 1339 because the condition on line 1338 was never true

1339 raise KeyError( 

1340 f"Expected embedding key '{embed_W_E_key}' not found in state_dict. Available keys: {list(state_dict.keys())[:10]}..." 

1341 ) 

1342 embed_W_E = ProcessWeights.convert_tensor_to_tl_format( 

1343 embed_W_E_key, state_dict, state_dict.get(embed_W_E_key), cfg, adapter, None 

1344 ) 

1345 assert embed_W_E is not None, f"Embedding not found at key {embed_W_E_key}" 

1346 embed_W_E = embed_W_E - embed_W_E.mean(-1, keepdim=True) 

1347 state_dict[embed_W_E_key] = ProcessWeights.convert_tensor_to_hf_format( 

1348 embed_W_E_key, embed_W_E, cfg, adapter, None 

1349 ) 

1350 

1351 if ( 

1352 getattr(cfg, "positional_embedding_type", "standard") 

1353 not in ("rotary", "alibi", "none") 

1354 and pos_embed_W_pos_key is not None 

1355 ): 

1356 if pos_embed_W_pos_key not in state_dict: 1356 ↛ 1357line 1356 didn't jump to line 1357 because the condition on line 1356 was never true

1357 raise KeyError( 

1358 f"Expected positional embedding key '{pos_embed_W_pos_key}' not found in state_dict. Available keys: {list(state_dict.keys())[:10]}..." 

1359 ) 

1360 pos_embed_W_pos = ProcessWeights.convert_tensor_to_tl_format( 

1361 pos_embed_W_pos_key, 

1362 state_dict, 

1363 state_dict.get(pos_embed_W_pos_key), 

1364 cfg, 

1365 adapter, 

1366 None, 

1367 ) 

1368 assert ( 

1369 pos_embed_W_pos is not None 

1370 ), f"Positional embedding not found at key {pos_embed_W_pos_key}" 

1371 pos_embed_W_pos = pos_embed_W_pos - pos_embed_W_pos.mean(-1, keepdim=True) 

1372 state_dict[pos_embed_W_pos_key] = ProcessWeights.convert_tensor_to_hf_format( 

1373 pos_embed_W_pos_key, pos_embed_W_pos, cfg, adapter, None 

1374 ) 

1375 for l in range(cfg.n_layers): 

1376 attn_W_O_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.W_O", adapter) 

1377 attn_b_O_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.b_O", adapter) 

1378 try: 

1379 mlp_W_out_key = ProcessWeights._resolve_state_dict_key( 

1380 state_dict, ProcessWeights._get_param_key(f"blocks.{l}.mlp.W_out", adapter), l 

1381 ) 

1382 mlp_b_out_key = ProcessWeights._resolve_state_dict_key( 

1383 state_dict, ProcessWeights._get_param_key(f"blocks.{l}.mlp.b_out", adapter), l 

1384 ) 

1385 except ValueError: 

1386 mlp_W_out_key = None 

1387 mlp_b_out_key = None 

1388 if attn_W_O_key in state_dict: 

1389 attn_W_O = ProcessWeights.convert_tensor_to_tl_format( 

1390 attn_W_O_key, state_dict, state_dict.get(attn_W_O_key), cfg, adapter, l 

1391 ) 

1392 assert attn_W_O is not None, f"Attention W_O not found at key {attn_W_O_key}" 

1393 attn_W_O = attn_W_O - attn_W_O.mean(-1, keepdim=True) 

1394 state_dict[attn_W_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

1395 attn_W_O_key, attn_W_O, cfg, adapter, l 

1396 ) 

1397 if attn_b_O_key in state_dict: 

1398 attn_b_O = ProcessWeights.convert_tensor_to_tl_format( 

1399 attn_b_O_key, state_dict, state_dict.get(attn_b_O_key), cfg, adapter, l 

1400 ) 

1401 assert attn_b_O is not None, f"Attention b_O not found at key {attn_b_O_key}" 

1402 attn_b_O = attn_b_O - attn_b_O.mean() 

1403 state_dict[attn_b_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

1404 attn_b_O_key, attn_b_O, cfg, adapter, l 

1405 ) 

1406 if not getattr(cfg, "attn_only", False): 

1407 is_moe = getattr(cfg, "num_experts", None) is not None and cfg.num_experts > 0 

1408 if is_moe: 

1409 num_experts = cfg.num_experts 

1410 for e in range(num_experts): 

1411 expert_W_out_key = None 

1412 expert_b_out_key = None 

1413 expert_W_out_patterns = [ 

1414 f"blocks.{l}.mlp.experts.{e}.W_out", 

1415 f"blocks.{l}.mlp.experts.{e}.W_out.weight", 

1416 ] 

1417 for pattern in expert_W_out_patterns: 

1418 if pattern in state_dict: 1418 ↛ 1419line 1418 didn't jump to line 1419 because the condition on line 1418 was never true

1419 expert_W_out_key = pattern 

1420 break 

1421 if expert_W_out_key is None and adapter: 1421 ↛ 1422line 1421 didn't jump to line 1422 because the condition on line 1421 was never true

1422 try: 

1423 candidate = ProcessWeights._get_param_key( 

1424 f"blocks.{l}.mlp.experts.{e}.W_out", adapter 

1425 ) 

1426 expert_W_out_key = ProcessWeights._resolve_state_dict_key( 

1427 state_dict, candidate, l 

1428 ) 

1429 except ValueError: 

1430 pass 

1431 if expert_W_out_key and expert_W_out_key in state_dict: 1431 ↛ 1432line 1431 didn't jump to line 1432 because the condition on line 1431 was never true

1432 expert_W_out = ProcessWeights.convert_tensor_to_tl_format( 

1433 expert_W_out_key, 

1434 state_dict, 

1435 state_dict.get(expert_W_out_key), 

1436 cfg, 

1437 adapter, 

1438 l, 

1439 ) 

1440 assert ( 

1441 expert_W_out is not None 

1442 ), f"Expert W_out not found at key {expert_W_out_key}" 

1443 expert_W_out = expert_W_out - expert_W_out.mean(-1, keepdim=True) 

1444 state_dict[ 

1445 expert_W_out_key 

1446 ] = ProcessWeights.convert_tensor_to_hf_format( 

1447 expert_W_out_key, expert_W_out, cfg, adapter, l 

1448 ) 

1449 expert_b_out_patterns = [ 

1450 f"blocks.{l}.mlp.experts.{e}.b_out", 

1451 f"blocks.{l}.mlp.experts.{e}.b_out.bias", 

1452 ] 

1453 for pattern in expert_b_out_patterns: 

1454 if pattern in state_dict: 1454 ↛ 1455line 1454 didn't jump to line 1455 because the condition on line 1454 was never true

1455 expert_b_out_key = pattern 

1456 break 

1457 if expert_b_out_key is None and adapter: 1457 ↛ 1458line 1457 didn't jump to line 1458 because the condition on line 1457 was never true

1458 try: 

1459 candidate = ProcessWeights._get_param_key( 

1460 f"blocks.{l}.mlp.experts.{e}.b_out", adapter 

1461 ) 

1462 expert_b_out_key = ProcessWeights._resolve_state_dict_key( 

1463 state_dict, candidate, l 

1464 ) 

1465 except ValueError: 

1466 pass 

1467 if expert_b_out_key and expert_b_out_key in state_dict: 1467 ↛ 1468line 1467 didn't jump to line 1468 because the condition on line 1467 was never true

1468 expert_b_out = ProcessWeights.convert_tensor_to_tl_format( 

1469 expert_b_out_key, 

1470 state_dict, 

1471 state_dict.get(expert_b_out_key), 

1472 cfg, 

1473 adapter, 

1474 l, 

1475 ) 

1476 assert ( 

1477 expert_b_out is not None 

1478 ), f"Expert b_out not found at key {expert_b_out_key}" 

1479 expert_b_out = expert_b_out - expert_b_out.mean() 

1480 state_dict[ 

1481 expert_b_out_key 

1482 ] = ProcessWeights.convert_tensor_to_hf_format( 

1483 expert_b_out_key, expert_b_out, cfg, adapter, l 

1484 ) 

1485 elif mlp_W_out_key is not None and mlp_W_out_key in state_dict: 

1486 mlp_W_out = ProcessWeights.convert_tensor_to_tl_format( 

1487 mlp_W_out_key, state_dict, state_dict.get(mlp_W_out_key), cfg, adapter, l 

1488 ) 

1489 assert mlp_W_out is not None, f"MLP W_out not found at key {mlp_W_out_key}" 

1490 # Center along d_model dimension. In TL format W_out is [d_mlp, d_model] 

1491 # so d_model is dim=-1. But bridge adapters may keep HF format 

1492 # [d_model, d_mlp] where d_model is dim=0. Detect via cfg.d_model. 

1493 model_axis = ProcessWeights._mlp_model_axis( 

1494 mlp_W_out_key, mlp_W_out, cfg.d_model, adapter, reads_residual=False 

1495 ) 

1496 if model_axis == 1: 

1497 mlp_W_out = mlp_W_out - mlp_W_out.mean(-1, keepdim=True) 

1498 elif model_axis == 0: 1498 ↛ 1501line 1498 didn't jump to line 1501 because the condition on line 1498 was always true

1499 mlp_W_out = mlp_W_out - mlp_W_out.mean(0, keepdim=True) 

1500 else: 

1501 mlp_W_out = mlp_W_out - mlp_W_out.mean(-1, keepdim=True) 

1502 state_dict[mlp_W_out_key] = ProcessWeights.convert_tensor_to_hf_format( 

1503 mlp_W_out_key, mlp_W_out, cfg, adapter, l 

1504 ) 

1505 if mlp_b_out_key is not None and mlp_b_out_key in state_dict: 

1506 mlp_b_out = ProcessWeights.convert_tensor_to_tl_format( 

1507 mlp_b_out_key, 

1508 state_dict, 

1509 state_dict.get(mlp_b_out_key), 

1510 cfg, 

1511 adapter, 

1512 l, 

1513 ) 

1514 assert mlp_b_out is not None, f"MLP b_out not found at key {mlp_b_out_key}" 

1515 mlp_b_out = mlp_b_out - mlp_b_out.mean() 

1516 state_dict[mlp_b_out_key] = ProcessWeights.convert_tensor_to_hf_format( 

1517 mlp_b_out_key, mlp_b_out, cfg, adapter, l 

1518 ) 

1519 return state_dict 

1520 

1521 @staticmethod 

1522 def center_unembed( 

1523 state_dict: Dict[str, torch.Tensor], cfg=None, adapter=None 

1524 ) -> Dict[str, torch.Tensor]: 

1525 """Center the unembedding weights W_U. 

1526 

1527 This is done by subtracting the mean of the weights from the weights themselves. This is 

1528 done in-place. As softmax is translation invariant, this changes the logits but not the log 

1529 probs, and makes the model logits (slightly) more interpretable - when trying to understand 

1530 how components contribute to the logits, we'll be less misled by components that just add 

1531 something to every logit. 

1532 

1533 Args: 

1534 state_dict (Dict[str, torch.Tensor]): State dict of the model. 

1535 cfg: Model configuration (used to identify the hidden axis for legacy layouts). 

1536 adapter: Optional architecture adapter for parameter key translation. 

1537 

1538 Returns: 

1539 Dict[str, torch.Tensor]: Modified state dict with centered unembedding weights. 

1540 """ 

1541 # Make a deep copy to avoid modifying the original 

1542 state_dict = { 

1543 k: v.clone() if isinstance(v, torch.Tensor) else v for k, v in state_dict.items() 

1544 } 

1545 unembed_W_U_key = ProcessWeights._get_param_key("unembed.W_U", adapter) 

1546 unembed_b_U_key = ProcessWeights._get_param_key("unembed.b_U", adapter) 

1547 if unembed_W_U_key not in state_dict: 

1548 raise KeyError( 

1549 f"Expected unembedding weight key '{unembed_W_U_key}' not found in state_dict. Available keys: {list(state_dict.keys())[:10]}..." 

1550 ) 

1551 W_U = ProcessWeights.convert_tensor_to_tl_format( 

1552 unembed_W_U_key, state_dict, state_dict.get(unembed_W_U_key), None, adapter, None 

1553 ) 

1554 assert W_U is not None, f"Unembed weight not found at key {unembed_W_U_key}" 

1555 

1556 model_axis = ProcessWeights._unembed_model_axis(W_U, getattr(cfg, "d_model", None), adapter) 

1557 vocab_dim = 1 - model_axis 

1558 W_U = W_U - W_U.mean(vocab_dim, keepdim=True) 

1559 state_dict[unembed_W_U_key] = ProcessWeights.convert_tensor_to_hf_format( 

1560 unembed_W_U_key, W_U, None, adapter, None 

1561 ) 

1562 if unembed_b_U_key in state_dict: 

1563 unembed_b_U = ProcessWeights.convert_tensor_to_tl_format( 

1564 unembed_b_U_key, state_dict, state_dict.get(unembed_b_U_key), None, adapter, None 

1565 ) 

1566 assert unembed_b_U is not None, f"Unembed bias not found at key {unembed_b_U_key}" 

1567 unembed_b_U = unembed_b_U - unembed_b_U.mean() 

1568 state_dict[unembed_b_U_key] = ProcessWeights.convert_tensor_to_hf_format( 

1569 unembed_b_U_key, unembed_b_U, None, adapter, None 

1570 ) 

1571 return state_dict 

1572 

1573 @staticmethod 

1574 def fold_value_biases( 

1575 state_dict: Dict[str, torch.Tensor], cfg, adapter=None 

1576 ) -> Dict[str, torch.Tensor]: 

1577 """Fold the value biases into the output bias. 

1578 

1579 Because attention patterns add up to 1, the value biases always have a constant effect on a 

1580 head's output. Further, as the outputs of each head in a layer add together, each head's 

1581 value bias has a constant effect on the *layer's* output, which can make it harder to 

1582 interpret the effect of any given head, and it doesn't matter which head a bias is 

1583 associated with. We can factor this all into a single output bias to the layer, and make it 

1584 easier to interpret the head's output. Formally, we take b_O_new = b_O_original + 

1585 sum_head(b_V_head @ W_O_head). 

1586 

1587 Args: 

1588 state_dict (Dict[str, torch.Tensor]): State dict of the model. 

1589 cfg: Model configuration object. 

1590 adapter: Optional architecture adapter for parameter key translation. 

1591 

1592 Returns: 

1593 Dict[str, torch.Tensor]: Modified state dict with value biases folded into output bias. 

1594 """ 

1595 # Make a deep copy to avoid modifying the original 

1596 state_dict = { 

1597 k: v.clone() if isinstance(v, torch.Tensor) else v for k, v in state_dict.items() 

1598 } 

1599 layer = 0 

1600 for layer in range(cfg.n_layers): 

1601 split_v_bias_key = f"blocks.{layer}.attn.v.bias" 

1602 if split_v_bias_key in state_dict: 

1603 b_V_key = split_v_bias_key 

1604 W_O_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.W_O", adapter) 

1605 b_O_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.b_O", adapter) 

1606 else: 

1607 if getattr(cfg, "n_key_value_heads", None) is None: 

1608 b_V_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.b_V", adapter) 

1609 else: 

1610 b_V_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn._b_V", adapter) 

1611 W_O_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.W_O", adapter) 

1612 b_O_key = ProcessWeights._get_param_key(f"blocks.{layer}.attn.b_O", adapter) 

1613 if b_V_key in state_dict: 

1614 b_V = ProcessWeights.convert_tensor_to_tl_format( 

1615 b_V_key, state_dict, state_dict.get(b_V_key), cfg, adapter, layer 

1616 ) 

1617 assert b_V is not None, f"Value bias not found at key {b_V_key}" 

1618 if b_V.numel() == 0: 1618 ↛ 1619line 1618 didn't jump to line 1619 because the condition on line 1618 was never true

1619 continue 

1620 W_O = ProcessWeights.convert_tensor_to_tl_format( 

1621 W_O_key, state_dict, state_dict.get(W_O_key), cfg, adapter, layer 

1622 ) 

1623 assert W_O is not None, f"Attention W_O not found at key {W_O_key}" 

1624 if b_O_key not in state_dict: 

1625 # Create zero b_O to absorb the folded value bias 

1626 b_O_original = torch.zeros(cfg.d_model, dtype=b_V.dtype, device=b_V.device) 

1627 state_dict[b_O_key] = b_O_original 

1628 else: 

1629 b_O_original_maybe = ProcessWeights.convert_tensor_to_tl_format( 

1630 b_O_key, state_dict, state_dict.get(b_O_key), cfg, adapter, layer 

1631 ) 

1632 assert ( 

1633 b_O_original_maybe is not None 

1634 ), f"Attention b_O not found at key {b_O_key}" 

1635 b_O_original = b_O_original_maybe 

1636 # Align W_O / b_O to b_V's device. 

1637 if W_O.device != b_V.device: 1637 ↛ 1638line 1637 didn't jump to line 1638 because the condition on line 1637 was never true

1638 W_O = W_O.to(b_V.device) 

1639 if b_O_original.device != b_V.device: 1639 ↛ 1640line 1639 didn't jump to line 1640 because the condition on line 1639 was never true

1640 b_O_original = b_O_original.to(b_V.device) 

1641 is_split_format = ".attn.v.bias" in b_V_key or ".attn.k.bias" in b_V_key 

1642 if is_split_format and len(b_V.shape) == 1 and (len(W_O.shape) == 2): 1642 ↛ 1643line 1642 didn't jump to line 1643 because the condition on line 1642 was never true

1643 n_heads = cfg.n_heads 

1644 d_head = cfg.d_head 

1645 d_model = cfg.d_model 

1646 b_V_only = b_V 

1647 b_V_reshaped = b_V_only.reshape(n_heads, d_head) 

1648 W_O_reshaped = einops.rearrange(W_O, "(i h) m -> i h m", i=n_heads) 

1649 folded_b_O = b_O_original + (b_V_reshaped[:, :, None] * W_O_reshaped).sum( 

1650 [0, 1] 

1651 ) 

1652 state_dict[b_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

1653 b_O_key, folded_b_O, cfg, adapter, layer 

1654 ) 

1655 tl_b_O_key = f"blocks.{layer}.attn.b_O" 

1656 if tl_b_O_key in state_dict: 

1657 state_dict[tl_b_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

1658 tl_b_O_key, folded_b_O, cfg, adapter, layer 

1659 ) 

1660 state_dict[b_V_key] = ProcessWeights.convert_tensor_to_hf_format( 

1661 b_V_key, torch.zeros_like(b_V), cfg, adapter, layer 

1662 ) 

1663 elif len(b_V.shape) == 1 and len(W_O.shape) == 2: 1663 ↛ 1664line 1663 didn't jump to line 1664 because the condition on line 1663 was never true

1664 n_heads = cfg.n_heads 

1665 d_head = cfg.d_head 

1666 d_model = cfg.d_model 

1667 v_bias_start = 2 * n_heads * d_head 

1668 v_bias_end = 3 * n_heads * d_head 

1669 b_V_only = b_V[v_bias_start:v_bias_end] 

1670 if b_V_only.numel() == 0: 

1671 continue 

1672 b_V_reshaped = b_V_only.reshape(n_heads, d_head) 

1673 W_O_reshaped = einops.rearrange(W_O, "(i h) m -> i h m", i=n_heads) 

1674 folded_b_O = b_O_original + (b_V_reshaped[:, :, None] * W_O_reshaped).sum( 

1675 [0, 1] 

1676 ) 

1677 new_b_V = b_V.clone() 

1678 new_b_V[v_bias_start:v_bias_end] = 0 

1679 state_dict[b_V_key] = ProcessWeights.convert_tensor_to_hf_format( 

1680 b_V_key, new_b_V, cfg, adapter, layer 

1681 ) 

1682 elif is_split_format and len(b_V.shape) == 1 and len(W_O.shape) == 3: 1682 ↛ 1684line 1682 didn't jump to line 1684 because the condition on line 1682 was never true

1683 # Split bias [n_heads * d_head] with W_O already in TL format [n_heads, d_head, d_model] 

1684 n_heads = cfg.n_heads 

1685 d_head = cfg.d_head 

1686 b_V_reshaped = b_V.reshape(n_heads, d_head) 

1687 if getattr(cfg, "n_key_value_heads", None) is not None: 

1688 b_V_reshaped = torch.repeat_interleave( 

1689 b_V_reshaped, dim=0, repeats=cfg.n_heads // cfg.n_key_value_heads 

1690 ) 

1691 folded_b_O = b_O_original + (b_V_reshaped[:, :, None] * W_O).sum([0, 1]) 

1692 state_dict[b_V_key] = ProcessWeights.convert_tensor_to_hf_format( 

1693 b_V_key, torch.zeros_like(b_V), cfg, adapter, layer 

1694 ) 

1695 elif len(b_V.shape) == 2 and len(W_O.shape) == 3: 1695 ↛ 1709line 1695 didn't jump to line 1709 because the condition on line 1695 was always true

1696 b_V_original_shape = b_V.shape 

1697 if getattr(cfg, "n_key_value_heads", None) is not None: 

1698 b_V = torch.repeat_interleave( 

1699 b_V, dim=0, repeats=cfg.n_heads // cfg.n_key_value_heads 

1700 ) 

1701 folded_b_O = b_O_original + (b_V[:, :, None] * W_O).sum([0, 1]) 

1702 state_dict[b_V_key] = ProcessWeights.convert_tensor_to_hf_format( 

1703 b_V_key, 

1704 torch.zeros(b_V_original_shape, dtype=b_V.dtype, device=b_V.device), 

1705 cfg, 

1706 adapter, 

1707 layer, 

1708 ) 

1709 elif len(b_V.shape) == 2 and len(W_O.shape) == 2: 

1710 n_heads = cfg.n_heads 

1711 d_head = cfg.d_head 

1712 d_model = cfg.d_model 

1713 b_V_original_shape = b_V.shape 

1714 

1715 # Handle split QKV format where bias might be [1, d_model] or [n_heads, d_head] 

1716 is_split_format = ".attn.v.bias" in b_V_key or ".attn.k.bias" in b_V_key 

1717 if is_split_format and b_V.shape[0] == 1 and b_V.shape[1] == n_heads * d_head: 

1718 # Reshape [1, n_heads * d_head] to [n_heads, d_head] 

1719 b_V = b_V.reshape(n_heads, d_head) 

1720 elif b_V.shape != (n_heads, d_head): 

1721 # If not already [n_heads, d_head], try to reshape 

1722 if b_V.numel() == n_heads * d_head: 

1723 b_V = b_V.reshape(n_heads, d_head) 

1724 

1725 if getattr(cfg, "n_key_value_heads", None) is not None: 

1726 b_V = torch.repeat_interleave( 

1727 b_V, dim=0, repeats=cfg.n_heads // cfg.n_key_value_heads 

1728 ) 

1729 

1730 W_O_reshaped = einops.rearrange(W_O, "(i h) m -> i h m", i=n_heads) 

1731 folded_b_O = b_O_original + (b_V[:, :, None] * W_O_reshaped).sum([0, 1]) 

1732 state_dict[b_V_key] = ProcessWeights.convert_tensor_to_hf_format( 

1733 b_V_key, 

1734 torch.zeros(b_V_original_shape, dtype=b_V.dtype, device=b_V.device), 

1735 cfg, 

1736 adapter, 

1737 layer, 

1738 ) 

1739 else: 

1740 raise ValueError(f"Unexpected tensor shapes: b_V {b_V.shape}, W_O {W_O.shape}") 

1741 state_dict[b_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

1742 b_O_key, folded_b_O, cfg, adapter, layer 

1743 ) 

1744 return state_dict 

1745 

1746 @staticmethod 

1747 def process_weights( 

1748 state_dict: Dict[str, torch.Tensor], 

1749 cfg, 

1750 fold_ln: bool = True, 

1751 center_writing_weights: bool = True, 

1752 center_unembed: bool = True, 

1753 fold_value_biases: bool = True, 

1754 refactor_factored_attn_matrices: bool = False, 

1755 adapter=None, 

1756 ) -> Dict[str, torch.Tensor]: 

1757 """Apply all weight processing transformations in the correct order. 

1758 

1759 This is a convenience function that applies all the weight processing steps 

1760 in the same order as the legacy HookedTransformer load path. 

1761 

1762 Args: 

1763 state_dict (Dict[str, torch.Tensor]): State dict of the model. 

1764 cfg: Model configuration object. 

1765 fold_ln (bool): Whether to fold LayerNorm weights into subsequent layers. 

1766 center_writing_weights (bool): Whether to center weights writing to residual stream. 

1767 center_unembed (bool): Whether to center unembedding weights. 

1768 fold_value_biases (bool): Whether to fold value biases into output bias. 

1769 refactor_factored_attn_matrices (bool): Whether to refactor attention matrices. 

1770 adapter: Optional architecture adapter for parameter key translation. 

1771 

1772 Returns: 

1773 Dict[str, torch.Tensor]: Fully processed state dict. 

1774 """ 

1775 # Upcast to float32 for weight processing to avoid precision loss in 

1776 # reduced-precision dtypes (bfloat16, float16). Operations like LayerNorm 

1777 # folding involve multiplications that accumulate rounding errors when 

1778 # performed in low precision. 

1779 original_dtypes: Dict[str, torch.dtype] = {} 

1780 original_keys = set(state_dict) 

1781 for k, v in state_dict.items(): 

1782 if isinstance(v, torch.Tensor) and v.is_floating_point(): 

1783 original_dtypes[k] = v.dtype 

1784 # float64 is kept: casting it would round every processed weight to float32. 

1785 if v.dtype != torch.float64: 

1786 state_dict[k] = v.float() 

1787 

1788 # Architectures the decoder-only blocks.{i} walk misses declare their layout. 

1789 layout = adapter.residual_layout() if hasattr(adapter, "residual_layout") else None 

1790 is_layer_norm = getattr(cfg, "normalization_type", "LN") in ["LN", "LNPre"] 

1791 

1792 # Skip fold_ln for adapters that don't support it (e.g., post-LN architectures 

1793 # like BERT where LN placement means folding goes into the wrong sublayer). 

1794 if fold_ln and adapter and not getattr(adapter, "supports_fold_ln", True): 

1795 import warnings 

1796 

1797 warnings.warn( 

1798 f"{type(adapter).__name__} does not support fold_ln; norm weights " 

1799 "stay unfolded and analyses assuming folded LN will be off.", 

1800 UserWarning, 

1801 ) 

1802 fold_ln = False 

1803 if fold_ln and layout is not None: 

1804 state_dict = ProcessWeights.fold_layer_norm_with_layout( 

1805 state_dict, layout, center_weights=is_layer_norm 

1806 ) 

1807 elif fold_ln: 

1808 if getattr(cfg, "normalization_type", "LN") in ["LN", "LNPre"]: 

1809 state_dict = ProcessWeights.fold_layer_norm( 

1810 state_dict, cfg, fold_biases=True, center_weights=True, adapter=adapter 

1811 ) 

1812 elif getattr(cfg, "normalization_type", "LN") in ["RMS", "RMSPre"]: 1812 ↛ 1823line 1812 didn't jump to line 1823 because the condition on line 1812 was always true

1813 state_dict = ProcessWeights.fold_layer_norm( 

1814 state_dict, cfg, fold_biases=False, center_weights=False, adapter=adapter 

1815 ) 

1816 # Note: Each folding function (_fold_layer for attention, _fold_mlp_layer_norm 

1817 # for MLP) sets its own LN weights to 1.0 after successful folding. 

1818 # We must NOT unconditionally set all LN weights to 1.0 here, because 

1819 # models with combined QKV projections (e.g., OpenELM's qkv_proj) may 

1820 # not be able to fold attention LN — setting ln1.w=1.0 without folding 

1821 # destroys the RMS scaling. 

1822 # Some adapters (e.g., post-LN) don't support center_writing_weights. 

1823 if ( 1823 ↛ 1828line 1823 didn't jump to line 1828 because the condition on line 1823 was never true

1824 center_writing_weights 

1825 and adapter 

1826 and not getattr(adapter, "supports_center_writing_weights", True) 

1827 ): 

1828 import warnings 

1829 

1830 warnings.warn( 

1831 f"{type(adapter).__name__} does not support center_writing_weights; " 

1832 "writing weights stay uncentered.", 

1833 UserWarning, 

1834 ) 

1835 center_writing_weights = False 

1836 should_center_writing_weights = ( 

1837 center_writing_weights 

1838 and getattr(cfg, "normalization_type", "LN") in ["LN", "LNPre"] 

1839 and not getattr(cfg, "final_rms", False) 

1840 ) 

1841 if should_center_writing_weights and layout is not None: 

1842 state_dict = ProcessWeights.center_writing_weights_with_layout(state_dict, layout) 

1843 elif should_center_writing_weights: 

1844 state_dict = ProcessWeights.center_writing_weights(state_dict, cfg, adapter=adapter) 

1845 if center_unembed: 

1846 state_dict = ProcessWeights.center_unembed(state_dict, cfg=cfg, adapter=adapter) 

1847 if fold_value_biases and layout is not None: 

1848 state_dict = ProcessWeights.fold_value_biases_with_layout( 

1849 state_dict, layout, center_outputs=should_center_writing_weights 

1850 ) 

1851 elif fold_value_biases: 

1852 state_dict = ProcessWeights.fold_value_biases(state_dict, cfg, adapter=adapter) 

1853 if should_center_writing_weights: 

1854 for layer_idx in range(cfg.n_layers): 

1855 b_O_key = ProcessWeights._get_param_key(f"blocks.{layer_idx}.attn.b_O", adapter) 

1856 if b_O_key in state_dict: 

1857 b_O = ProcessWeights.convert_tensor_to_tl_format( 

1858 b_O_key, state_dict, state_dict.get(b_O_key), cfg, adapter, layer_idx 

1859 ) 

1860 assert b_O is not None, f"Attention b_O not found at key {b_O_key}" 

1861 b_O = b_O - b_O.mean() 

1862 state_dict[b_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

1863 b_O_key, b_O, cfg, adapter, layer_idx 

1864 ) 

1865 if refactor_factored_attn_matrices and layout is not None: 1865 ↛ 1866line 1865 didn't jump to line 1866 because the condition on line 1865 was never true

1866 import warnings 

1867 

1868 warnings.warn( 

1869 f"{type(adapter).__name__} does not support refactor_factored_attn_matrices; " 

1870 "attention matrices stay as they are.", 

1871 UserWarning, 

1872 ) 

1873 elif refactor_factored_attn_matrices: 

1874 state_dict = ProcessWeights.refactor_factored_attn_matrices( 

1875 state_dict, cfg, adapter=adapter 

1876 ) 

1877 

1878 # Downcast back to original dtypes; biases created by folding take their weight's dtype 

1879 for k in state_dict.keys() - original_keys: 

1880 weight_dtype = original_dtypes.get(k.removesuffix(".bias") + ".weight") 

1881 if weight_dtype is not None: 1881 ↛ 1879line 1881 didn't jump to line 1879 because the condition on line 1881 was always true

1882 original_dtypes[k] = weight_dtype 

1883 for k, orig_dtype in original_dtypes.items(): 

1884 if k in state_dict and isinstance(state_dict[k], torch.Tensor): 1884 ↛ 1883line 1884 didn't jump to line 1883 because the condition on line 1884 was always true

1885 state_dict[k] = state_dict[k].to(orig_dtype) 

1886 

1887 return state_dict 

1888 

1889 @staticmethod 

1890 def refactor_factored_attn_matrices( 

1891 state_dict: Dict[str, torch.Tensor], cfg, adapter=None 

1892 ) -> Dict[str, torch.Tensor]: 

1893 """Experimental method for managing queries, keys and values. 

1894 

1895 As argued in [A Mathematical Framework for Transformer 

1896 Circuits](https://transformer-circuits.pub/2021/framework/index.html), queries, keys and 

1897 values are somewhat arbitrary intermediate terms when computing with the low rank factored 

1898 matrices W_QK = W_Q @ W_K.T and W_OV = W_V @ W_O, and these matrices are the only thing 

1899 determining head behaviour. But there are many ways to find a low rank factorization to a 

1900 given matrix, and hopefully some of these are more interpretable than others! This method is 

1901 one attempt, which makes all of the matrices have orthogonal rows or columns, W_O into a 

1902 rotation and W_Q and W_K having the nth column in each having the same norm. The formula is 

1903 $W_V = U @ S,W_O=Vh.T,W_Q=U@S.sqrt(),W_K=Vh@S.sqrt()$. 

1904 

1905 More details: 

1906 

1907 If W_OV = U @ S @ Vh.T in its singular value decomposition, (where S is in R^d_head not 

1908 R^d_model, as W_OV is low rank), W_OV = (U @ S) @ (Vh.T) is an equivalent low rank 

1909 factorisation, where rows/columns of each matrix are orthogonal! So setting $W_V=US$ and 

1910 $W_O=Vh.T$ works just as well. I *think* this is a more interpretable setup, because now 

1911 $W_O$ is just a rotation, and doesn't change the norm, so $z$ has the same norm as the 

1912 result of the head. 

1913 

1914 For $W_QK = W_Q @ W_K.T$ we use the refactor $W_Q = U @ S.sqrt()$ and $W_K = Vh @ S.sqrt()$, 

1915 which is also equivalent ($S==S.sqrt() @ S.sqrt()$ as $S$ is diagonal). Here we keep the 

1916 matrices as having the same norm, since there's not an obvious asymmetry between the keys 

1917 and queries. 

1918 

1919 Biases are more fiddly to deal with. For OV it's pretty easy - we just need (x @ W_V + b_V) 

1920 @ W_O + b_O to be preserved, so we can set b_V' = 0. and b_O' = b_V @ W_O + b_O (note that 

1921 b_V in R^{head_index x d_head} while b_O in R^{d_model}, so we need to sum b_V @ W_O along 

1922 the head_index dimension too). 

1923 

1924 For QK it's messy - we need to preserve the bilinear form of (x @ W_Q + b_Q) * (y @ W_K + 

1925 b_K), which is fairly messy. To deal with the biases, we concatenate them to W_Q and W_K to 

1926 simulate a d_model+1 dimensional input (whose final coordinate is always 1), do the SVD 

1927 factorization on this effective matrix, then separate out into final weights and biases. 

1928 

1929 Args: 

1930 state_dict (Dict[str, torch.Tensor]): State dict of the model. 

1931 cfg: Model configuration object. 

1932 adapter: Optional architecture adapter for parameter key translation. 

1933 

1934 Returns: 

1935 Dict[str, torch.Tensor]: Modified state dict with refactored attention matrices. 

1936 """ 

1937 # Make a deep copy to avoid modifying the original 

1938 state_dict = { 

1939 k: v.clone() if isinstance(v, torch.Tensor) else v for k, v in state_dict.items() 

1940 } 

1941 assert ( 

1942 getattr(cfg, "positional_embedding_type", "standard") != "rotary" 

1943 ), "You can't refactor the QK circuit when using rotary embeddings (as the QK matrix depends on the position of the query and key)" 

1944 

1945 for l in range(cfg.n_layers): 

1946 W_Q_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.W_Q", adapter) 

1947 b_Q_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.b_Q", adapter) 

1948 W_K_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.W_K", adapter) 

1949 b_K_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.b_K", adapter) 

1950 W_V_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.W_V", adapter) 

1951 W_O_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.W_O", adapter) 

1952 b_V_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.b_V", adapter) 

1953 b_O_key = ProcessWeights._get_param_key(f"blocks.{l}.attn.b_O", adapter) 

1954 

1955 # Skip hybrid layers without attention (other loops already guard individually) 

1956 if W_Q_key not in state_dict: 

1957 continue 

1958 # If Q is present, K/V/O must be too 

1959 for _required_key in [W_K_key, W_V_key, W_O_key]: 

1960 if _required_key not in state_dict: 

1961 raise ValueError( 

1962 f"Inconsistent attention weights at layer {l}: " 

1963 f"'{W_Q_key}' found but '{_required_key}' missing. " 

1964 f"All of W_Q, W_K, W_V, W_O must be present together." 

1965 ) 

1966 

1967 # W_QK = W_Q @ W_K.T 

1968 # Concatenate biases to make a d_model+1 input dimension 

1969 W_Q = ProcessWeights.convert_tensor_to_tl_format( 

1970 W_Q_key, state_dict, state_dict.get(W_Q_key), cfg, adapter, l 

1971 ) 

1972 b_Q = ProcessWeights.convert_tensor_to_tl_format( 

1973 b_Q_key, state_dict, state_dict.get(b_Q_key), cfg, adapter, l 

1974 ) 

1975 W_K = ProcessWeights.convert_tensor_to_tl_format( 

1976 W_K_key, state_dict, state_dict.get(W_K_key), cfg, adapter, l 

1977 ) 

1978 b_K = ProcessWeights.convert_tensor_to_tl_format( 

1979 b_K_key, state_dict, state_dict.get(b_K_key), cfg, adapter, l 

1980 ) 

1981 assert W_Q is not None, f"W_Q not found at key {W_Q_key}" 

1982 assert b_Q is not None, f"b_Q not found at key {b_Q_key}" 

1983 assert W_K is not None, f"W_K not found at key {W_K_key}" 

1984 assert b_K is not None, f"b_K not found at key {b_K_key}" 

1985 

1986 W_Q_eff = torch.cat([W_Q, b_Q[:, None, :]], dim=1) 

1987 W_K_eff = torch.cat([W_K, b_K[:, None, :]], dim=1) 

1988 

1989 W_Q_eff_even, W_K_eff_even_T = ( 

1990 FactoredMatrix(W_Q_eff, W_K_eff.transpose(-1, -2)).make_even().pair 

1991 ) 

1992 W_K_eff_even = W_K_eff_even_T.transpose(-1, -2) 

1993 

1994 state_dict[W_Q_key] = ProcessWeights.convert_tensor_to_hf_format( 

1995 W_Q_key, W_Q_eff_even[:, :-1, :], cfg, adapter, l 

1996 ) 

1997 state_dict[b_Q_key] = ProcessWeights.convert_tensor_to_hf_format( 

1998 b_Q_key, W_Q_eff_even[:, -1, :], cfg, adapter, l 

1999 ) 

2000 state_dict[W_K_key] = ProcessWeights.convert_tensor_to_hf_format( 

2001 W_K_key, W_K_eff_even[:, :-1, :], cfg, adapter, l 

2002 ) 

2003 state_dict[b_K_key] = ProcessWeights.convert_tensor_to_hf_format( 

2004 b_K_key, W_K_eff_even[:, -1, :], cfg, adapter, l 

2005 ) 

2006 

2007 # W_OV = W_V @ W_O 

2008 W_V = ProcessWeights.convert_tensor_to_tl_format( 

2009 W_V_key, state_dict, state_dict.get(W_V_key), cfg, adapter, l 

2010 ) 

2011 W_O = ProcessWeights.convert_tensor_to_tl_format( 

2012 W_O_key, state_dict, state_dict.get(W_O_key), cfg, adapter, l 

2013 ) 

2014 

2015 # Factors the bias to be consistent. 

2016 b_V = ProcessWeights.convert_tensor_to_tl_format( 

2017 b_V_key, state_dict, state_dict.get(b_V_key), cfg, adapter, l 

2018 ) 

2019 b_O = ProcessWeights.convert_tensor_to_tl_format( 

2020 b_O_key, state_dict, state_dict.get(b_O_key), cfg, adapter, l 

2021 ) 

2022 assert W_V is not None, f"W_V not found at key {W_V_key}" 

2023 assert W_O is not None, f"W_O not found at key {W_O_key}" 

2024 assert b_V is not None, f"b_V not found at key {b_V_key}" 

2025 assert b_O is not None, f"b_O not found at key {b_O_key}" 

2026 

2027 # Add singleton dimension for broadcasting 

2028 b_V_expanded = einops.rearrange(b_V, "head_index d_head -> head_index d_head 1") 

2029 

2030 b_V_times_W_O = b_V_expanded * W_O 

2031 

2032 # Sum over d_head and head_index dimensions 

2033 b_V_contribution = b_V_times_W_O.sum(1).sum(0) 

2034 

2035 effective_bias = b_O + b_V_contribution 

2036 state_dict[b_V_key] = ProcessWeights.convert_tensor_to_hf_format( 

2037 b_V_key, torch.zeros_like(b_V), cfg, adapter, l 

2038 ) 

2039 state_dict[b_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

2040 b_O_key, effective_bias, cfg, adapter, l 

2041 ) 

2042 

2043 # Helper class to efficiently deal with low rank factored matrices. 

2044 W_OV = FactoredMatrix(W_V, W_O) 

2045 U, S, Vh = W_OV.svd() 

2046 state_dict[W_V_key] = ProcessWeights.convert_tensor_to_hf_format( 

2047 W_V_key, U @ S.diag_embed(), cfg, adapter, l 

2048 ) 

2049 state_dict[W_O_key] = ProcessWeights.convert_tensor_to_hf_format( 

2050 W_O_key, utils.transpose(Vh), cfg, adapter, l 

2051 ) 

2052 

2053 return state_dict 

2054 

2055 @overload 

2056 @staticmethod 

2057 def convert_tensor_to_tl_format( 

2058 param_name: str, 

2059 model_state_dict: Dict[str, torch.Tensor], 

2060 tensor: torch.Tensor, 

2061 cfg: Optional["TransformerLensConfig"], 

2062 adapter: Optional["ArchitectureAdapter"] = None, 

2063 layer_idx: Optional[int] = None, 

2064 ) -> torch.Tensor: 

2065 ... 

2066 

2067 @overload 

2068 @staticmethod 

2069 def convert_tensor_to_tl_format( 

2070 param_name: str, 

2071 model_state_dict: Dict[str, torch.Tensor], 

2072 tensor: None, 

2073 cfg: Optional["TransformerLensConfig"], 

2074 adapter: Optional["ArchitectureAdapter"] = None, 

2075 layer_idx: Optional[int] = None, 

2076 ) -> None: 

2077 ... 

2078 

2079 @staticmethod 

2080 def convert_tensor_to_tl_format( 

2081 param_name: str, 

2082 model_state_dict: Dict[str, torch.Tensor], 

2083 tensor: Optional[torch.Tensor], 

2084 cfg: Optional["TransformerLensConfig"], 

2085 adapter: Optional["ArchitectureAdapter"] = None, 

2086 layer_idx: Optional[int] = None, 

2087 ) -> Optional[torch.Tensor]: 

2088 """Convert a tensor from its original format to TransformerLens format. 

2089 

2090 Args: 

2091 param_name: The parameter name in TransformerLens format (e.g., "blocks.0.attn.W_Q") 

2092 model_state_dict: The model's state dictionary containing the actual tensors 

2093 tensor: The tensor to convert, or None for optional parameters 

2094 cfg: Model configuration 

2095 adapter: Optional architecture adapter for component retrieval and key translation. 

2096 If None, the tensor is returned unchanged. 

2097 layer_idx: Layer index (required for layer-specific parameters) 

2098 

2099 Returns: 

2100 The tensor converted to TransformerLens format, or None if the parameter doesn't exist 

2101 (which is valid for optional parameters like biases in models that don't use them). 

2102 If adapter is None, returns the tensor unchanged. 

2103 """ 

2104 # If no adapter provided, return tensor unchanged (handle None gracefully) 

2105 if adapter is None: 

2106 return tensor 

2107 

2108 if ( 2108 ↛ 2189line 2108 didn't jump to line 2189 because the condition on line 2108 was always true

2109 hasattr(adapter, "weight_processing_conversions") 

2110 and adapter.weight_processing_conversions is not None 

2111 ): 

2112 # Create placeholder param name by replacing layer index with {i} 

2113 placeholder_param_name = param_name 

2114 if "blocks." in param_name: 

2115 placeholder_param_name = re.sub(r"blocks\.(\d+)\.", "blocks.{i}.", param_name) 

2116 

2117 # Check if we have a conversion for this parameter. 

2118 # Try exact match first, then strip .weight suffix for adapters 

2119 # that define conversions without the suffix (e.g. Pythia's "blocks.{i}.attn.q"). 

2120 # NOTE: Only strip .weight, NOT .bias — stripping .bias would incorrectly 

2121 # match bias keys against weight conversions (e.g. "blocks.{i}.attn.q.bias" 

2122 # would match the weight conversion for "blocks.{i}.attn.q"). 

2123 matched_key = None 

2124 if placeholder_param_name in adapter.weight_processing_conversions: 

2125 matched_key = placeholder_param_name 

2126 elif placeholder_param_name.endswith(".weight"): 

2127 stripped = placeholder_param_name[: -len(".weight")] 

2128 if stripped in adapter.weight_processing_conversions: 

2129 matched_key = stripped 

2130 

2131 if matched_key is not None: 

2132 param_conversion = adapter.weight_processing_conversions[matched_key] 

2133 

2134 # Handle both ParamProcessingConversion objects and legacy string mappings 

2135 if isinstance(param_conversion, str): 

2136 # Legacy string mapping - just return the tensor as-is 

2137 # (string mappings are handled elsewhere in the architecture adapter) 

2138 return tensor 

2139 else: 

2140 # Skip conversion for optional parameters that don't exist (e.g. biases) 

2141 if tensor is None and param_name not in model_state_dict: 

2142 return None 

2143 # Try ParamProcessingConversion.convert() first (uses source_key 

2144 # to fetch from state dict — needed for split conversions like 

2145 # GPT-2's QKV). If source_key resolves to a missing key and we 

2146 # already have the tensor, fall back to applying the tensor 

2147 # conversion directly (needed for adapters like GPT-Neo whose 

2148 # source_key references HF keys not in the bridge state dict). 

2149 if ( 

2150 hasattr(param_conversion, "source_key") 

2151 and param_conversion.source_key is not None 

2152 ): 

2153 resolved_key = param_conversion._resolve_key( 

2154 param_name, param_conversion.source_key 

2155 ) 

2156 if resolved_key not in model_state_dict and tensor is not None: 2156 ↛ 2183line 2156 didn't jump to line 2183 because the condition on line 2156 was always true

2157 # Source key not in state dict — the tensor is already in 

2158 # bridge format (e.g. already split from combined QKV). 

2159 # If the conversion is a ChainTensorConversion that includes 

2160 # a SplitTensorConversion, skip the split step since 

2161 # it was already applied during bridge construction. 

2162 from transformer_lens.conversion_utils.conversion_steps.chain_tensor_conversion import ( 

2163 ChainTensorConversion, 

2164 ) 

2165 from transformer_lens.conversion_utils.conversion_steps.split_tensor_conversion import ( 

2166 SplitTensorConversion, 

2167 ) 

2168 

2169 tc = param_conversion.tensor_conversion 

2170 if isinstance(tc, ChainTensorConversion): 

2171 non_split = [ 

2172 c 

2173 for c in tc.conversions 

2174 if not isinstance(c, SplitTensorConversion) 

2175 ] 

2176 if len(non_split) < len(tc.conversions): 2176 ↛ 2182line 2176 didn't jump to line 2182 because the condition on line 2176 was always true

2177 # Apply only the non-split conversions 

2178 result = tensor 

2179 for conv in non_split: 

2180 result = conv.handle_conversion(result, model_state_dict) 

2181 return result 

2182 return tc.convert(tensor, model_state_dict) 

2183 return param_conversion.convert(model_state_dict, param_name) 

2184 else: 

2185 # No conversion defined, return tensor as-is (may be None for optional params) 

2186 return tensor 

2187 else: 

2188 # No conversions defined, return tensor as-is (may be None for optional params) 

2189 return tensor 

2190 

2191 @overload 

2192 @staticmethod 

2193 def convert_tensor_to_hf_format( 

2194 param_name: str, 

2195 tensor: torch.Tensor, 

2196 cfg: Optional["TransformerLensConfig"], 

2197 adapter: Optional["ArchitectureAdapter"] = None, 

2198 layer_idx: Optional[int] = None, 

2199 ) -> torch.Tensor: 

2200 ... 

2201 

2202 @overload 

2203 @staticmethod 

2204 def convert_tensor_to_hf_format( 

2205 param_name: str, 

2206 tensor: None, 

2207 cfg: Optional["TransformerLensConfig"], 

2208 adapter: Optional["ArchitectureAdapter"] = None, 

2209 layer_idx: Optional[int] = None, 

2210 ) -> None: 

2211 ... 

2212 

2213 @staticmethod 

2214 def convert_tensor_to_hf_format( 

2215 param_name: str, 

2216 tensor: Optional[torch.Tensor], 

2217 cfg: Optional["TransformerLensConfig"], 

2218 adapter: Optional["ArchitectureAdapter"] = None, 

2219 layer_idx: Optional[int] = None, 

2220 ) -> Optional[torch.Tensor]: 

2221 """Convert a tensor from TransformerLens format back to its original format. 

2222 

2223 Args: 

2224 param_name: The parameter name in TransformerLens format (e.g., "blocks.0.attn.W_Q") 

2225 tensor: The tensor to convert (in TransformerLens format), or None if parameter is optional 

2226 cfg: Model configuration 

2227 adapter: Optional architecture adapter for component retrieval and key translation. 

2228 If None, the tensor is returned unchanged. 

2229 layer_idx: Layer index (required for layer-specific parameters) 

2230 

2231 Returns: 

2232 The tensor converted back to original format, or None if tensor was None. 

2233 If adapter is None, returns the tensor unchanged. 

2234 """ 

2235 # Handle None tensors (optional parameters) 

2236 if tensor is None: 2236 ↛ 2237line 2236 didn't jump to line 2237 because the condition on line 2236 was never true

2237 return None 

2238 

2239 # If no adapter provided, return tensor unchanged 

2240 if adapter is None: 

2241 return tensor 

2242 

2243 if ( 2243 ↛ 2295line 2243 didn't jump to line 2295 because the condition on line 2243 was always true

2244 hasattr(adapter, "weight_processing_conversions") 

2245 and adapter.weight_processing_conversions is not None 

2246 ): 

2247 # Create placeholder param name by replacing layer index with {i} 

2248 placeholder_param_name = param_name 

2249 if "blocks." in param_name: 

2250 placeholder_param_name = re.sub(r"blocks\.(\d+)\.", "blocks.{i}.", param_name) 

2251 

2252 # Check if we have a conversion for this parameter. 

2253 # Try exact match first, then strip .weight suffix (not .bias — see convert_tensor_to_tl_format). 

2254 matched_key = None 

2255 if placeholder_param_name in adapter.weight_processing_conversions: 

2256 matched_key = placeholder_param_name 

2257 elif placeholder_param_name.endswith(".weight"): 

2258 stripped = placeholder_param_name[: -len(".weight")] 

2259 if stripped in adapter.weight_processing_conversions: 

2260 matched_key = stripped 

2261 

2262 if matched_key is not None: 

2263 param_conversion = adapter.weight_processing_conversions[matched_key] 

2264 

2265 # Handle both ParamProcessingConversion objects and legacy string mappings 

2266 if isinstance(param_conversion, str): 

2267 # Legacy string mapping - just return the tensor as-is 

2268 return tensor 

2269 else: 

2270 # Revert the conversion. For ChainTensorConversions that include 

2271 # SplitTensorConversion, skip the split revert step (which is a 

2272 # no-op anyway) to match the forward conversion path. 

2273 from transformer_lens.conversion_utils.conversion_steps.chain_tensor_conversion import ( 

2274 ChainTensorConversion, 

2275 ) 

2276 from transformer_lens.conversion_utils.conversion_steps.split_tensor_conversion import ( 

2277 SplitTensorConversion, 

2278 ) 

2279 

2280 tc = param_conversion.tensor_conversion 

2281 if isinstance(tc, ChainTensorConversion): 

2282 non_split = [ 

2283 c for c in tc.conversions if not isinstance(c, SplitTensorConversion) 

2284 ] 

2285 if len(non_split) < len(tc.conversions): 2285 ↛ 2291line 2285 didn't jump to line 2291 because the condition on line 2285 was always true

2286 # Revert only the non-split conversions in reverse order 

2287 result = tensor 

2288 for conv in reversed(non_split): 

2289 result = conv.revert(result) 

2290 return result 

2291 return param_conversion.revert(tensor) 

2292 else: 

2293 return tensor 

2294 else: 

2295 return tensor 

2296 

2297 @staticmethod 

2298 def distribute_weights_to_components( 

2299 state_dict: Dict[str, torch.Tensor], 

2300 component_mapping: Dict[str, Any], 

2301 verbose: bool = False, 

2302 ) -> None: 

2303 """Distribute processed weights from state_dict to generalized components. 

2304 

2305 This function loops through the component_mapping and extracts relevant weights 

2306 for each component using filter_dict_by_prefix, then calls set_processed_weights 

2307 on each component. For list components (like blocks), it determines the number 

2308 of items and distributes weights to each indexed component. 

2309 

2310 Args: 

2311 state_dict: Dictionary of processed weights in MODERN TransformerLens format 

2312 (e.g., blocks.0.attn.q.weight, not transformer.h.0.attn.q.weight) 

2313 component_mapping: Dictionary (real_components) mapping TL keys to tuples of 

2314 (remote_path, component_instance), where component_instance can be either 

2315 a single component or a list of components 

2316 verbose: If True, print detailed information about weight distribution 

2317 

2318 Example: 

2319 For a real_components mapping like: 

2320 { 

2321 "embed": ("transformer.wte", <EmbeddingBridge instance>), 

2322 "blocks": ("transformer.h", [<BlockBridge 0>, <BlockBridge 1>, ...]), 

2323 "unembed": ("lm_head", <UnembeddingBridge instance>) 

2324 } 

2325 

2326 With modern TL keys in state_dict like "embed.weight", "blocks.0.attn.q.weight": 

2327 1. Extract weights starting with "embed" and pass to embed component 

2328 2. For blocks, extract all "blocks.*" weights, determine the number of blocks, 

2329 then for each block index, extract weights for that specific block 

2330 3. Extract "unembed" weights and pass to unembed component 

2331 """ 

2332 if verbose: 2332 ↛ 2333line 2332 didn't jump to line 2333 because the condition on line 2332 was never true

2333 print(f"\n{'='*80}") 

2334 print(f"distribute_weights_to_components: Starting weight distribution") 

2335 print(f"State dict has {len(state_dict)} keys") 

2336 print(f"Component mapping has {len(component_mapping)} components") 

2337 print(f"{'='*80}\n") 

2338 

2339 for component_name, component_tuple in component_mapping.items(): 

2340 # component_mapping is real_components format: (remote_path, instance) 

2341 # instance can be either a single component or a list of components 

2342 if not isinstance(component_tuple, tuple): 2342 ↛ 2343line 2342 didn't jump to line 2343 because the condition on line 2342 was never true

2343 raise ValueError( 

2344 f"Expected tuple for component '{component_name}' in real_components, " 

2345 f"but got {type(component_tuple).__name__}: {component_tuple}" 

2346 ) 

2347 remote_key, component = component_tuple 

2348 is_list = isinstance(component, list) 

2349 

2350 # Use the component_name (TL format) as prefix instead of remote_key (HF format) 

2351 # since state_dict now has modern TL keys 

2352 tl_prefix = component_name 

2353 

2354 if verbose: 2354 ↛ 2355line 2354 didn't jump to line 2355 because the condition on line 2354 was never true

2355 print(f"\nProcessing component: {component_name}") 

2356 print(f" Remote key (HF): {remote_key}") 

2357 print(f" TL prefix: {tl_prefix}") 

2358 print(f" Is list: {is_list}") 

2359 

2360 if is_list: 

2361 # This is a list component like "blocks" 

2362 # Extract all weights that start with this prefix 

2363 all_list_weights = filter_dict_by_prefix(state_dict, tl_prefix) 

2364 

2365 if verbose: 2365 ↛ 2366line 2365 didn't jump to line 2366 because the condition on line 2365 was never true

2366 print(f" Found {len(all_list_weights)} weights for list component") 

2367 print(f" List has {len(component)} instances") 

2368 

2369 # Component is a list of actual instances 

2370 for i, instance in enumerate(component): 

2371 # Extract weights for this specific index 

2372 # This will get keys like "0.attn.q.weight" and strip the "0." to get "attn.q.weight" 

2373 indexed_weights = filter_dict_by_prefix(all_list_weights, str(i)) 

2374 

2375 if verbose: 2375 ↛ 2376line 2375 didn't jump to line 2376 because the condition on line 2375 was never true

2376 print(f" Instance {i}: Found {len(indexed_weights)} weights") 

2377 for key in indexed_weights.keys(): 

2378 print(f" - {key}") 

2379 

2380 # Skip if no weights found for this component (e.g., Q/K/V Linear sub-components 

2381 # that get their weights from parent JointQKVAttentionBridge) 

2382 if len(indexed_weights) == 0: 2382 ↛ 2383line 2382 didn't jump to line 2383 because the condition on line 2382 was never true

2383 if verbose: 

2384 print(f" Skipping instance {i} - no weights found") 

2385 continue 

2386 

2387 instance.set_processed_weights(indexed_weights, verbose=verbose) 

2388 else: 

2389 # This is a single component (not a list) 

2390 component_weights = filter_dict_by_prefix(state_dict, tl_prefix) 

2391 

2392 if verbose: 2392 ↛ 2393line 2392 didn't jump to line 2393 because the condition on line 2392 was never true

2393 print(f" Found {len(component_weights)} weights for single component") 

2394 for key in component_weights.keys(): 

2395 print(f" - {key}") 

2396 

2397 # Skip if no weights found for this component 

2398 if len(component_weights) == 0: 

2399 if verbose: 2399 ↛ 2400line 2399 didn't jump to line 2400 because the condition on line 2399 was never true

2400 print(f" Skipping component - no weights found") 

2401 continue 

2402 

2403 component.set_processed_weights(component_weights, verbose=verbose)