Coverage for transformer_lens/model_bridge/generalized_components/normalization.py: 94%

127 statements  

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

1"""Normalization bridge component implementation.""" 

2import contextlib 

3import warnings 

4from typing import Any, ContextManager, Dict, Optional, cast 

5 

6import torch 

7 

8from transformer_lens.hook_points import HookPoint 

9from transformer_lens.model_bridge.generalized_components.base import ( 

10 GeneralizedComponent, 

11) 

12 

13# The native-autograd path returns HF's own output, so hook edits and backward hooks 

14# can only be honored by switching to the python-norm computation, whose numerics 

15# differ from HF's at float-rounding scale. 

16NATIVE_PATH_BWD_FALLBACK_WARNING = ( 

17 "Backward hooks on hook_scale/hook_normalized require grad-connected hook tensors; " 

18 "falling back from the native-autograd path to the python-norm path. Output numerics " 

19 "may differ from the unhooked forward at float-rounding scale." 

20) 

21NATIVE_PATH_EDIT_FALLBACK_WARNING = ( 

22 "A forward hook edited hook_scale/hook_normalized on the native-autograd path; the " 

23 "output is reconstructed from the hooked values instead of HF's native forward. " 

24 "Output numerics may differ from the unhooked forward at float-rounding scale." 

25) 

26 

27 

28def _run_intermediate_hook(point: HookPoint, value: torch.Tensor) -> tuple[torch.Tensor, bool]: 

29 """Detect replacement and tensor writes while protecting autograd's saved intermediates.""" 

30 if not point.fwd_hooks: 

31 result = point(value) 

32 return result, result is not value 

33 hook_input = value.clone() 

34 # Compare values, not _version: writes through .data skip the version counter 

35 # and inference tensors have none. 

36 before = hook_input.detach().clone() 

37 result = point(hook_input) 

38 mutated = not torch.allclose(hook_input, before, rtol=0, atol=0, equal_nan=True) 

39 return result, result is not hook_input or mutated 

40 

41 

42class NormalizationBridge(GeneralizedComponent): 

43 """Normalization bridge that wraps transformer normalization layers but implements the calculation from scratch. 

44 

45 This component provides standardized input/output hooks. 

46 """ 

47 

48 property_aliases = {"w": "weight", "b": "bias"} 

49 

50 def __init__( 

51 self, 

52 name: str, 

53 config: Any, 

54 submodules: Optional[Dict[str, GeneralizedComponent]] = {}, 

55 use_native_layernorm_autograd: bool = False, 

56 uses_rms_norm: Optional[bool] = None, 

57 optional: bool = False, 

58 uses_weight_offset: Optional[bool] = None, 

59 ): 

60 """Initialize the normalization bridge. 

61 

62 Args: 

63 name: The name of this component 

64 config: Optional configuration 

65 submodules: Dictionary of GeneralizedComponent submodules to register 

66 use_native_layernorm_autograd: If True, use HuggingFace's native LayerNorm 

67 autograd for exact gradient matching. If False, 

68 use custom implementation. Defaults to False. 

69 uses_rms_norm: Force RMSNorm vs LayerNorm; None defers to introspection 

70 then ``config.uses_rms_norm``. 

71 optional: If True, setup skips this subtree when absent (hybrid architectures). 

72 uses_weight_offset: Override the affine weight convention independently of 

73 RMS vs LayerNorm. None uses the RMSNorm configuration flag. 

74 """ 

75 super().__init__(name, config, submodules=submodules, optional=optional) 

76 self.hook_normalized = HookPoint() 

77 self.hook_scale = HookPoint() 

78 self.use_native_layernorm_autograd = use_native_layernorm_autograd 

79 self._uses_rms_norm_override = uses_rms_norm 

80 self._uses_weight_offset_override = uses_weight_offset 

81 

82 @property 

83 def uses_rms_norm(self) -> bool: 

84 """Whether this bridge treats the wrapped module as RMSNorm. 

85 

86 Override > module introspection > config. Introspection guards against 

87 a shared config (RMSNorm LM + LayerNorm vision tower) misclassifying 

88 a real ``nn.LayerNorm``. 

89 """ 

90 if self._uses_rms_norm_override is not None: 

91 return self._uses_rms_norm_override 

92 component = self.original_component 

93 if component is not None: 

94 if isinstance(component, torch.nn.LayerNorm): 

95 return False 

96 if "RMSNorm" in type(component).__name__: 

97 return True 

98 return bool(getattr(self.config, "uses_rms_norm", False)) 

99 

100 @property 

101 def uses_weight_offset(self) -> bool: 

102 """Whether affine scaling uses 1 + weight, including explicit LayerNorm1P slots.""" 

103 if self._uses_weight_offset_override is not None: 

104 return self._uses_weight_offset_override 

105 return self.uses_rms_norm and bool(getattr(self.config, "rmsnorm_uses_offset", False)) 

106 

107 def forward(self, hidden_states: torch.Tensor, **kwargs: Any) -> torch.Tensor: 

108 """Forward pass through the normalization bridge. 

109 

110 Args: 

111 hidden_states: Input hidden states 

112 **kwargs: Additional arguments to pass to the original component 

113 

114 Returns: 

115 Normalized output 

116 """ 

117 if self.original_component is None: 117 ↛ 118line 117 didn't jump to line 118 because the condition on line 117 was never true

118 raise RuntimeError( 

119 f"Original component not set for {self.name}. Call set_original_component() first." 

120 ) 

121 assert self.config is not None 

122 hidden_states = self.hook_in(hidden_states) 

123 if self.use_native_layernorm_autograd: 

124 result = self._hf_autograd_forward_with_hooks(hidden_states) 

125 elif hasattr(self.config, "layer_norm_folding") and self.config.layer_norm_folding: 125 ↛ 126line 125 didn't jump to line 126 because the condition on line 125 was never true

126 result = self._hf_autograd_forward_with_hooks(hidden_states) 

127 else: 

128 result = self._python_norm_forward(hidden_states) 

129 output = self.hook_out(result) 

130 return output 

131 

132 def _python_norm_forward(self, hidden_states: torch.Tensor) -> torch.Tensor: 

133 """From-scratch normalization with live hooks: edits propagate, gradients flow.""" 

134 # Upcast to float32 for normalization precision (matches HT's RMSNorm behavior) 

135 input_dtype = hidden_states.dtype 

136 if input_dtype not in (torch.float32, torch.float64): 

137 hidden_states = hidden_states.float() 

138 if not self.uses_rms_norm: 

139 hidden_states = hidden_states - hidden_states.mean(-1, keepdim=True) 

140 # sqrt saves its output for backward; the clone keeps in-place hook edits off it. 

141 scale = self.hook_scale( 

142 (hidden_states.pow(2).mean(-1, keepdim=True) + getattr(self.config, "eps", 1e-05)) 

143 .sqrt() 

144 .clone() 

145 ) 

146 hidden_states = self.hook_normalized(hidden_states / scale) 

147 return self._apply_weight_and_bias(hidden_states, input_dtype) 

148 

149 def _apply_weight_and_bias( 

150 self, hidden_states: torch.Tensor, input_dtype: torch.dtype 

151 ) -> torch.Tensor: 

152 """Apply weight/bias in float32 before casting back (matches HF precision).""" 

153 # Gemma RMSNorm and LayerNorm1P store affine weight as an offset from 1. 

154 weight = (1.0 + self.weight) if self.uses_weight_offset else self.weight 

155 hidden_states = hidden_states * weight 

156 component = self.original_component 

157 if ( 

158 not self.uses_rms_norm 

159 and component is not None 

160 and hasattr(component, "bias") 

161 and component.bias is not None 

162 ): 

163 hidden_states = hidden_states + cast(torch.Tensor, component.bias) 

164 result = hidden_states.to(input_dtype) 

165 if not self.uses_rms_norm and not result.is_contiguous(): 

166 # F.layer_norm materializes a contiguous output while these 

167 # pointwise ops preserve the input's strides; downstream HF code 

168 # may .view() the result (e.g. Idefics3 pixel_shuffle). 

169 result = result.contiguous() 

170 return result 

171 

172 def _hf_autograd_forward_with_hooks(self, x: torch.Tensor) -> torch.Tensor: 

173 """Forward pass that preserves HF's autograd while firing intermediate hooks. 

174 

175 When hooks only observe (return ``None``, e.g. ``run_with_cache``), the result is 

176 HF's own forward — bit-identical numerics and exact autograd. When a forward hook 

177 edits ``hook_scale`` / ``hook_normalized`` (including in-place edits), the output is 

178 reconstructed from the hooked values so the edit propagates. With backward hooks, the whole 

179 computation takes the python-norm path so hook tensors stay in the autograd graph. 

180 Both fallbacks warn, since their numerics differ from HF's at rounding scale. 

181 

182 Args: 

183 x: Input tensor 

184 

185 Returns: 

186 Normalized output tensor 

187 """ 

188 if self.original_component is None: 188 ↛ 189line 188 didn't jump to line 189 because the condition on line 188 was never true

189 raise RuntimeError(f"Original component not set for {self.name}") 

190 if isinstance(self.original_component, torch.nn.Identity): 

191 # Non-normalizing slot (ModernBertDecoder layer 0): fire hooks with 

192 # pass-through values instead of fabricated LN stats. 

193 _ = self.hook_scale(torch.ones_like(x[..., :1])) 

194 _ = self.hook_normalized(x) 

195 return x 

196 if self.hook_scale.bwd_hooks or self.hook_normalized.bwd_hooks: 

197 warnings.warn(NATIVE_PATH_BWD_FALLBACK_WARNING) 

198 return self._python_norm_forward(x) 

199 has_fwd_hooks = bool(self.hook_scale.fwd_hooks or self.hook_normalized.fwd_hooks) 

200 # No hooks: skip building a graph for observation-only intermediates. With hooks, 

201 # keep grad so an edited value stays connected to the input. 

202 grad_ctx: ContextManager[Any] = ( 

203 contextlib.nullcontext() if has_fwd_hooks else torch.no_grad() 

204 ) 

205 with grad_ctx: 

206 # Upcast to float32 for hook precision (matches HT's RMSNorm/LayerNorm behavior) 

207 x_float = x.float() if x.dtype not in (torch.float32, torch.float64) else x 

208 if not self.uses_rms_norm: 

209 x_centered = x_float - x_float.mean(-1, keepdim=True) 

210 else: 

211 x_centered = x_float 

212 eps_tensor = getattr(self.original_component, "eps", None) 

213 if eps_tensor is None: 

214 eps_tensor = getattr(self.original_component, "variance_epsilon", None) 

215 if eps_tensor is None: 

216 eps_value: float | torch.Tensor = getattr(self.config, "eps", 1e-05) 

217 else: 

218 eps_value = eps_tensor 

219 variance = x_centered.pow(2).mean(-1, keepdim=True) 

220 if isinstance(eps_value, torch.Tensor): 220 ↛ 221line 220 didn't jump to line 221 because the condition on line 220 was never true

221 inv_rms = torch.rsqrt(variance + eps_value) 

222 scale = (variance + eps_value).sqrt() 

223 else: 

224 inv_rms = torch.rsqrt(variance + float(eps_value)) 

225 scale = (variance + float(eps_value)).sqrt() 

226 # Use rsqrt for x_normalized to match HF's actual computation path 

227 # (LlamaRMSNorm uses x * rsqrt(variance + eps)). Keep scale as sqrt 

228 # for hook_scale (denominator convention used by HookedTransformer). 

229 x_normalized = x_centered * inv_rms 

230 hooked_scale, scale_edited = _run_intermediate_hook(self.hook_scale, scale) 

231 if scale_edited: 

232 # Edited scale: recompute with the denominator convention so the edit 

233 # feeds hook_normalized, mirroring the python-norm path's ordering. 

234 x_normalized = x_centered / hooked_scale 

235 hooked_normalized, normalized_edited = _run_intermediate_hook( 

236 self.hook_normalized, x_normalized 

237 ) 

238 input_dtype = x.dtype 

239 if not scale_edited and not normalized_edited: 

240 result = self.original_component(x) 

241 if result.dtype != input_dtype: 241 ↛ 242line 241 didn't jump to line 242 because the condition on line 241 was never true

242 result = result.to(input_dtype) 

243 return result 

244 warnings.warn(NATIVE_PATH_EDIT_FALLBACK_WARNING) 

245 return self._apply_weight_and_bias(hooked_normalized, input_dtype) 

246 

247 

248class LayerNormPreBridge(NormalizationBridge): 

249 """Param-free LayerNorm (LNPre): hook_scale / hook_normalized, no weight or bias.""" 

250 

251 property_aliases: Dict[str, str] = {} 

252 

253 def __init__( 

254 self, 

255 name: str, 

256 config: Any, 

257 submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

258 optional: bool = False, 

259 ): 

260 """Initialize the param-free LayerNorm bridge.""" 

261 super().__init__( 

262 name, 

263 config, 

264 submodules=submodules or {}, 

265 use_native_layernorm_autograd=False, 

266 uses_rms_norm=False, 

267 optional=optional, 

268 ) 

269 

270 def _apply_weight_and_bias( 

271 self, hidden_states: torch.Tensor, input_dtype: torch.dtype 

272 ) -> torch.Tensor: 

273 """No weight or bias to apply — only restore the input dtype.""" 

274 return hidden_states.to(input_dtype) 

275 

276 

277class RMSNormPreBridge(NormalizationBridge): 

278 """Param-free RMSNorm (RMSPre): hook_scale / hook_normalized, no learnable scale.""" 

279 

280 property_aliases: Dict[str, str] = {} 

281 

282 def __init__( 

283 self, 

284 name: str, 

285 config: Any, 

286 submodules: Optional[Dict[str, GeneralizedComponent]] = None, 

287 optional: bool = False, 

288 ): 

289 """Initialize the param-free RMSNorm bridge.""" 

290 super().__init__( 

291 name, 

292 config, 

293 submodules=submodules or {}, 

294 use_native_layernorm_autograd=False, 

295 uses_rms_norm=True, 

296 optional=optional, 

297 ) 

298 

299 def _apply_weight_and_bias( 

300 self, hidden_states: torch.Tensor, input_dtype: torch.dtype 

301 ) -> torch.Tensor: 

302 """No learnable scale to apply — only restore the input dtype.""" 

303 return hidden_states.to(input_dtype)