transformers
0c1829dd - Fix loss alignment and Trainer token counting for encoder decoder models (#46903)

Commit
123 days ago
Fix loss alignment and Trainer token counting for encoder decoder models (#46903) Fix encoder-decoder loss alignment and Trainer token counting Encoder-decoder LM heads right-shift their targets into decoder_input_ids, so their logits are already position-aligned with `labels`. Two related bugs mishandle that alignment: - PPFormulaNet (and, pre-#46784, Moonshine) routed `labels` through ForCausalLMLoss without `shift_labels`, so the loss shifted a second time and the model trained against labels[..., 1:]. - Trainer._loss_shifts_labels counted num_items_in_batch over labels[..., 1:] for every ForCausalLMLoss head. Encoder-decoder heads have a real target at every non-`-100` position, so this under-counts targets (one position per sequence) and over-scales the gradient-accumulation loss. Changes: - trainer.py: _loss_shifts_labels additionally requires config.is_encoder_decoder to be false, so encoder-decoder heads count every valid label. Decoder-only heads are unchanged; Csm (decoder-only) is unaffected. - pp_formulanet: compute the loss via self.loss_function with labels=None and the aligned targets passed as shift_labels. shift_labels is popped from kwargs before the inner model call, so a caller-supplied value is honored, does not collide with the derived one, and does not leak into the inner model. - moonshine / moonshine_streaming: same form, replacing a plain CrossEntropyLoss that ignored num_items_in_batch. Tests: - tests/test_modeling_common.py: generic guard test_encoder_decoder_loss_no_double_shift. It supplies the right-shifted decoder_input_ids itself and compares gradients of the reported loss w.r.t. output.logits against the aligned and the shifted cross-entropy, which stays decisive on testers whose initialization makes the logits near-uniform. No per-model branches. - Dia and ProphetNet skip it via @unittest.skip in their own testers. - tests/trainer/test_trainer.py: Bart encoder-decoder num_items_in_batch count. - The Moonshine loss test also covers num_items_in_batch scaling and a caller-supplied shift_labels. Fixes #46901
Parents
Loading