@@ -176,6 +176,7 @@ def reset_inputs_from_texts(self) -> None:
176176class LossTextAccessMixin (TextAccessMixin ):
177177 """Mixin for models that compute losses based on text-level inputs (black-box access)."""
178178
179+ @torch .no_grad ()
179180 def compute_loss_from_texts (
180181 self ,
181182 candidate_trigger_strs : List [str ],
@@ -213,35 +214,26 @@ def _compute_loss_batched(batch_size, template_idx=template_idx):
213214 end = min (start + batch_size , n_candidates )
214215 chunk_strs = candidate_trigger_strs [start :end ]
215216
216- curr_model_input = input_manager .get_triggered_inputs (
217+ model_input : ModelInput = input_manager .get_triggered_inputs (
217218 chosen_template_idx = template_idx , trigger_strs = chunk_strs ,
218219 )
219- curr_texts , curr_targets = (
220- curr_model_input .input_texts ,
221- curr_model_input .message_targets ,
222- )
223-
224- # Forward pass for this candidate chunk
225- model_output = self .invoke_from_texts (
226- input_texts = curr_texts ,
227- message_targets = curr_targets ,
228- require_target_prefill = loss_func .require_target_prefill ,
229- require_generation = loss_func .require_generation ,
230- require_first_token_logprobs = loss_func .require_first_token_logprobs ,
231- ) # Returns ModelOutput with available data
232-
233- # Create ModelInput wrapper
234- model_input = ModelInput (
235- input_texts = curr_texts ,
236- input_trigger_strs = chunk_strs ,
237- message_targets = curr_targets ,
238- )
239220
240- # Use unified loss resolution
241- chunk_loss = resolve_and_compute_loss (
242- model_output , model_input , loss_func
243- ) # shape: (chunk_size,)
244- chunk_losses .append (chunk_loss )
221+ # Only enable gradient is it's required by the loss (e.g. for gradient matching losses); mostly false.
222+ with torch .set_grad_enabled (loss_func .require_gradients ):
223+ # Forward pass for this candidate chunk
224+ model_output : ModelOutput = self .invoke_from_texts (
225+ input_texts = model_input .input_texts ,
226+ message_targets = model_input .message_targets ,
227+ require_target_prefill = loss_func .require_target_prefill ,
228+ require_generation = loss_func .require_generation ,
229+ require_first_token_logprobs = loss_func .require_first_token_logprobs ,
230+ )
231+
232+ # Use unified loss resolution
233+ chunk_loss = resolve_and_compute_loss (
234+ model_output , model_input , loss_func
235+ ) # shape: (chunk_size,)
236+ chunk_losses .append (chunk_loss )
245237
246238 return torch .cat (chunk_losses , dim = 0 ) # shape: (n_candidates,)
247239
0 commit comments