Coverage for transformer_lens/benchmarks/forward_pass.py: 44%

103 statements  

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

1"""Forward pass benchmarks for TransformerBridge.""" 

2 

3from typing import Optional, Union 

4 

5import torch 

6 

7from transformer_lens.benchmarks.utils import ( 

8 BenchmarkResult, 

9 BenchmarkSeverity, 

10 bridge_self_target_loss, 

11 compare_scalars, 

12 compare_tensors, 

13) 

14from transformer_lens.model_bridge import TransformerBridge 

15 

16 

17def _compute_self_target_loss(bridge: TransformerBridge, test_text: str) -> torch.Tensor: 

18 """Compute loss with the tokenized input supplied as explicit labels.""" 

19 return bridge_self_target_loss(bridge, test_text) 

20 

21 

22def _is_encoder_decoder(model: torch.nn.Module) -> bool: 

23 """Check if a model is an encoder-decoder architecture.""" 

24 config = getattr(model, "config", None) 

25 if config is None: 25 ↛ 26line 25 didn't jump to line 26 because the condition on line 25 was never true

26 return False 

27 return getattr(config, "is_encoder_decoder", False) 

28 

29 

30def _get_decoder_input_ids(model: torch.nn.Module, batch_size: int = 1) -> torch.Tensor: 

31 """Get decoder_input_ids for encoder-decoder models. 

32 

33 Args: 

34 model: The model to get decoder_start_token_id from 

35 batch_size: Batch size for the decoder_input_ids 

36 

37 Returns: 

38 Tensor of shape [batch_size, 1] with decoder_start_token_id 

39 """ 

40 config = getattr(model, "config", None) 

41 decoder_start_token_id = getattr(config, "decoder_start_token_id", None) if config else None 

42 if decoder_start_token_id is None: 42 ↛ 45line 42 didn't jump to line 45 because the condition on line 42 was never true

43 # HF fallback chain: bos, then eos (MBart-family checkpoints leave 

44 # decoder_start unset and start from EOS). 

45 decoder_start_token_id = getattr(config, "bos_token_id", None) if config else None 

46 if decoder_start_token_id is None: 46 ↛ 47line 46 didn't jump to line 47 because the condition on line 46 was never true

47 decoder_start_token_id = getattr(config, "eos_token_id", None) if config else None 

48 if isinstance(decoder_start_token_id, (list, tuple)): 48 ↛ 49line 48 didn't jump to line 49 because the condition on line 48 was never true

49 decoder_start_token_id = decoder_start_token_id[0] 

50 if decoder_start_token_id is None: 50 ↛ 51line 50 didn't jump to line 51 because the condition on line 50 was never true

51 decoder_start_token_id = 0 

52 return torch.tensor([[decoder_start_token_id]] * batch_size) 

53 

54 

55def benchmark_forward_pass( 

56 bridge: TransformerBridge, 

57 test_input: Union[str, torch.Tensor], 

58 reference_model: Optional[torch.nn.Module] = None, 

59 reference_logits: Optional[torch.Tensor] = None, 

60 atol: float = 1e-3, 

61 rtol: float = 3e-2, 

62) -> BenchmarkResult: 

63 """Benchmark forward pass between TransformerBridge and reference model. 

64 

65 Args: 

66 bridge: TransformerBridge model to test 

67 test_input: Input text string or audio waveform tensor for testing 

68 reference_model: Optional live HF reference model (audio / encoder-decoder paths) 

69 reference_logits: Optional pre-computed reference logits/hidden states tensor 

70 (e.g., saved from a prior HF forward pass to avoid needing both models in memory) 

71 atol: Absolute tolerance for comparison 

72 rtol: Relative tolerance for comparison 

73 

74 Returns: 

75 BenchmarkResult with comparison details 

76 """ 

77 try: 

78 _is_audio = getattr(bridge.cfg, "is_audio_model", False) 

79 

80 is_enc_dec = _is_encoder_decoder(bridge.original_model) 

81 

82 # Prepare extra kwargs for encoder-decoder models 

83 extra_kwargs = {} 

84 if is_enc_dec and isinstance(test_input, str): 84 ↛ 85line 84 didn't jump to line 85 because the condition on line 84 was never true

85 tokens = bridge.to_tokens(test_input) 

86 batch_size = tokens.shape[0] 

87 decoder_input_ids = _get_decoder_input_ids(bridge.original_model, batch_size) 

88 decoder_input_ids = decoder_input_ids.to(tokens.device) 

89 extra_kwargs["decoder_input_ids"] = decoder_input_ids 

90 elif getattr(bridge.cfg, "is_audio_seq2seq", False) and isinstance( 

91 test_input, torch.Tensor 

92 ): 

93 decoder_input_ids = _get_decoder_input_ids(bridge.original_model, test_input.shape[0]) 

94 extra_kwargs["decoder_input_ids"] = decoder_input_ids.to(test_input.device) 

95 

96 # Run bridge forward pass (use no_grad to match HF reference context — 

97 # MPS SDPA can produce different results with vs without gradient tracking) 

98 with torch.no_grad(): 

99 if _is_audio and isinstance(test_input, torch.Tensor): 

100 # Audio models: pass waveform, extract tensor from output 

101 bridge_output_raw = bridge(test_input, return_type="logits", **extra_kwargs) 

102 if isinstance(bridge_output_raw, torch.Tensor): 102 ↛ 104line 102 didn't jump to line 104 because the condition on line 102 was always true

103 bridge_output = bridge_output_raw 

104 elif hasattr(bridge_output_raw, "logits") and bridge_output_raw.logits is not None: 

105 bridge_output = bridge_output_raw.logits 

106 elif hasattr(bridge_output_raw, "last_hidden_state"): 

107 bridge_output = bridge_output_raw.last_hidden_state 

108 else: 

109 bridge_output = bridge_output_raw 

110 else: 

111 bridge_output = bridge(test_input, return_type="logits", **extra_kwargs) 

112 

113 if reference_model is None and reference_logits is None: 113 ↛ 115line 113 didn't jump to line 115 because the condition on line 113 was never true

114 # No reference model or logits - just verify output shape and validity 

115 if not isinstance(bridge_output, torch.Tensor): 

116 return BenchmarkResult( 

117 name="forward_pass", 

118 severity=BenchmarkSeverity.DANGER, 

119 message="Bridge output is not a tensor", 

120 passed=False, 

121 ) 

122 

123 if bridge_output.numel() == 0: 

124 return BenchmarkResult( 

125 name="forward_pass", 

126 severity=BenchmarkSeverity.DANGER, 

127 message="Bridge output is empty", 

128 passed=False, 

129 ) 

130 

131 return BenchmarkResult( 

132 name="forward_pass", 

133 severity=BenchmarkSeverity.INFO, 

134 message=f"Bridge forward pass successful (shape: {bridge_output.shape})", 

135 details={"output_shape": str(bridge_output.shape)}, 

136 ) 

137 

138 # Get reference logits from a pre-computed tensor or a live HF model 

139 if reference_logits is not None: 

140 reference_output = reference_logits.to(bridge_output.device) 

141 elif _is_audio and isinstance(test_input, torch.Tensor): 141 ↛ 153line 141 didn't jump to line 153 because the condition on line 141 was always true

142 # Audio HF reference model: pass the prepared audio input positionally 

143 # (input_values for wav2vec2-style, input_features for AST-style) 

144 assert reference_model is not None 

145 with torch.no_grad(): 

146 hf_output = reference_model(test_input, **extra_kwargs) 

147 if hasattr(hf_output, "logits") and hf_output.logits is not None: 147 ↛ 150line 147 didn't jump to line 150 because the condition on line 147 was always true

148 reference_output = hf_output.logits 

149 else: 

150 reference_output = hf_output.last_hidden_state 

151 else: 

152 # reference_model is non-None here: the both-None case returns early above 

153 assert reference_model is not None 

154 assert isinstance(test_input, str), "Text model requires string input" 

155 tokens = bridge.to_tokens(test_input) 

156 with torch.no_grad(): 

157 if is_enc_dec: 

158 # Encoder-decoder models need decoder_input_ids 

159 batch_size = tokens.shape[0] 

160 decoder_input_ids = _get_decoder_input_ids(reference_model, batch_size) 

161 decoder_input_ids = decoder_input_ids.to(tokens.device) 

162 hf_output = reference_model(tokens, decoder_input_ids=decoder_input_ids) 

163 else: 

164 hf_output = reference_model(tokens) 

165 reference_output = hf_output.logits 

166 

167 return compare_tensors( 

168 bridge_output, 

169 reference_output, 

170 atol=atol, 

171 rtol=rtol, 

172 name="forward_pass_logits", 

173 ) 

174 

175 except Exception as e: 

176 return BenchmarkResult( 

177 name="forward_pass", 

178 severity=BenchmarkSeverity.ERROR, 

179 message=f"Forward pass failed: {str(e)}", 

180 passed=False, 

181 ) 

182 

183 

184def benchmark_loss_equivalence( 

185 bridge: TransformerBridge, 

186 test_text: str, 

187 reference_loss: Optional[float] = None, 

188 atol: float = 1e-3, 

189) -> BenchmarkResult: 

190 """Benchmark loss computation against a pre-computed reference value. 

191 

192 Args: 

193 bridge: TransformerBridge model to test 

194 test_text: Input text for testing 

195 reference_loss: Optional pre-computed reference loss value (e.g., the HF 

196 loss captured in Phase 1, or a golden fixture). Self-check only if None. 

197 atol: Absolute tolerance for comparison 

198 

199 Returns: 

200 BenchmarkResult with comparison details 

201 """ 

202 try: 

203 bridge_loss = _compute_self_target_loss(bridge, test_text) 

204 

205 if reference_loss is None: 205 ↛ 207line 205 didn't jump to line 207 because the condition on line 205 was never true

206 # No reference - just verify loss is valid 

207 if not isinstance(bridge_loss, torch.Tensor): 

208 return BenchmarkResult( 

209 name="loss_equivalence", 

210 severity=BenchmarkSeverity.DANGER, 

211 message="Bridge loss is not a tensor", 

212 passed=False, 

213 ) 

214 

215 loss_value = bridge_loss.item() 

216 if torch.isnan(bridge_loss) or torch.isinf(bridge_loss): 

217 return BenchmarkResult( 

218 name="loss_equivalence", 

219 severity=BenchmarkSeverity.DANGER, 

220 message=f"Bridge loss is invalid: {loss_value}", 

221 passed=False, 

222 ) 

223 

224 return BenchmarkResult( 

225 name="loss_equivalence", 

226 severity=BenchmarkSeverity.INFO, 

227 message=f"Bridge loss computed successfully: {loss_value:.6f}", 

228 details={"loss": loss_value}, 

229 ) 

230 

231 return compare_scalars( 

232 bridge_loss.item(), 

233 reference_loss, 

234 atol=atol, 

235 name="loss_equivalence", 

236 ) 

237 

238 except Exception as e: 

239 return BenchmarkResult( 

240 name="loss_equivalence", 

241 severity=BenchmarkSeverity.ERROR, 

242 message=f"Loss computation failed: {str(e)}", 

243 passed=False, 

244 ) 

245 

246 

247def benchmark_logits_equivalence( 

248 bridge: TransformerBridge, 

249 test_text: str, 

250 reference_logits: Optional[torch.Tensor] = None, 

251 atol: float = 3e-2, 

252 rtol: float = 3e-2, 

253) -> BenchmarkResult: 

254 """Benchmark logits output against a pre-computed reference tensor. 

255 

256 Args: 

257 bridge: TransformerBridge model to test 

258 test_text: Input text for testing 

259 reference_logits: Optional pre-computed reference logits tensor (e.g., the 

260 HF logits captured in Phase 1, or a golden fixture). Self-check only if None. 

261 atol: Absolute tolerance for comparison 

262 rtol: Relative tolerance for comparison 

263 

264 Returns: 

265 BenchmarkResult with comparison details 

266 """ 

267 try: 

268 bridge_logits = bridge(test_text, return_type="logits") 

269 

270 if reference_logits is None: 

271 # No reference - just verify logits shape and validity 

272 if not isinstance(bridge_logits, torch.Tensor): 

273 return BenchmarkResult( 

274 name="logits_equivalence", 

275 severity=BenchmarkSeverity.DANGER, 

276 message="Bridge logits is not a tensor", 

277 passed=False, 

278 ) 

279 

280 if bridge_logits.numel() == 0: 

281 return BenchmarkResult( 

282 name="logits_equivalence", 

283 severity=BenchmarkSeverity.DANGER, 

284 message="Bridge logits is empty", 

285 passed=False, 

286 ) 

287 

288 return BenchmarkResult( 

289 name="logits_equivalence", 

290 severity=BenchmarkSeverity.INFO, 

291 message=f"Bridge logits computed successfully (shape: {bridge_logits.shape})", 

292 details={"output_shape": str(bridge_logits.shape)}, 

293 ) 

294 

295 ref_logits = reference_logits.to(bridge_logits.device) 

296 

297 return compare_tensors( 

298 bridge_logits, 

299 ref_logits, 

300 atol=atol, 

301 rtol=rtol, 

302 name="logits_equivalence", 

303 ) 

304 

305 except Exception as e: 

306 return BenchmarkResult( 

307 name="logits_equivalence", 

308 severity=BenchmarkSeverity.ERROR, 

309 message=f"Logits computation failed: {str(e)}", 

310 passed=False, 

311 )