Fix condition when GA loss bug fix is not performed
Author: techkang
Pull request: yes

# What does this PR do?
<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes https://github.com/huggingface/transformers/issues/35649


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [x] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

@muellerzr @hiyouga @ArthurZucker @SunMarc 
<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts, @qubvel
- speech models: @ylacombe, @eustlb
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
@muellerzr The loss value and gradients can be aligned with the latest main branch after applying this fix. We tested with the Qwen2-VL-7B model and gradient accumulation steps = 8
![image](https://github.com/user-attachments/assets/57316745-23b6-4d53-83e4-ee11dc295950)


I added an extra validation that guarantee the fixed loss and unfixed loss should not vary too much.

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_35651). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@techkang @hiyouga tentatively something seems off here. One of my two tests fail. We succeed with `test_gradient_accumulation_loss_alignment_with_loss_func`, but not `with_model_loss`. 

My modified version of the test I'm working on:

```python
    def test_gradient_accumulation_loss_alignment_with_model_loss(self):
        set_seed(42)
        import datasets

        model_name = "nickypro/tinyllama-15M"
        dataset_name = "wikitext"
        dataset_config = "wikitext-2-raw-v1"
        dataset = datasets.load_dataset(dataset_name, dataset_config, split="train[:40]")
        dataset = dataset.train_test_split(test_size=0.2)
        tokenizer = AutoTokenizer.from_pretrained(model_name)

        tokenizer.pad_token = tokenizer.eos_token

        def tokenize_function(examples):
            return tokenizer(examples["text"], max_length=16, padding="max_length", truncation=True)

        tokenized_dataset = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)

        data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)

        model = AutoModelForCausalLM.from_pretrained(model_name)
        state_dict = model.state_dict()

        base_loss_callback = StoreLossCallback()

        args_kwargs = {
            "report_to": "none",
            "logging_steps": 1,
            "max_steps": 5,
            "learning_rate": 3e-4,
            "disable_tqdm": True,
        }

        with tempfile.TemporaryDirectory() as tmp_dir:
            args = TrainingArguments(
                tmp_dir,
                **args_kwargs,
            )
            trainer = Trainer(
                model,
                args,
                train_dataset=tokenized_dataset["train"],
                callbacks=[base_loss_callback],
                data_collator=data_collator,
            )
            assert trainer.model_accepts_loss_kwargs
            trainer.train()

        grad_accum_loss_callback = StoreLossCallback()
        with tempfile.TemporaryDirectory() as tmp_dir:
            args = TrainingArguments(
                tmp_dir,
                **args_kwargs,
                gradient_accumulation_steps=2,
                per_device_train_batch_size=4,
            )
            set_seed(42)
            model.load_state_dict(state_dict)
            trainer = Trainer(
                model,
                args,
                train_dataset=tokenized_dataset["train"],
                callbacks=[grad_accum_loss_callback],
                data_collator=data_collator,
            )
            trainer.train()

            set_seed(42)
            model.load_state_dict(state_dict)
            broken_loss_callback = StoreLossCallback()
            trainer = Trainer(
                model,
                args,
                train_dataset=tokenized_dataset["train"],
                callbacks=[broken_loss_callback],
                data_collator=data_collator,
            )
            # disable model_accepts_loss_kwargs
            trainer.model_accepts_loss_kwargs = False
            trainer.train()

            # Calculate the difference between the base loss and the grad_accum loss
            diff_truth = [
                abs(base - grad) for base, grad in zip(base_loss_callback.losses, grad_accum_loss_callback.losses)
            ]
            diff_broken = [
                abs(base - grad) for base, grad in zip(base_loss_callback.losses, broken_loss_callback.losses)
            ]

            # all diff truth should be quite close
            self.assertLess(max(diff_truth), 0.01, f"Difference {max(diff_truth)} is not within 0.01")

            # max diff broken should be very off
            self.assertGreater(max(diff_broken), 2, f"Difference {max(diff_broken)} is not greater than 2")
```

Hi @muellerzr , I am not very familiar with your test cases, but we tried fine-tuning the Llama3 model and FYI the loss and gradients look good to me

![image](https://github.com/user-attachments/assets/e1dcf2e8-d8d8-4b6f-9749-450897bede64)


@techkang @hiyouga  yeah the issue was the `load_state_dict`. For some reason one chunk of it is sensitive. 

Post fixing my own tests, we're fully green on both ✅ 

(I'll make a PR with these new tests after!)

@muellerzr It might be better to also add test cases for model does not accept `loss_kwargs`, WDYT?

@hiyouga sure if you'd like to build on what I have started with #35668 :)

@hiyouga The model used in `test_gradient_accumulation_loss_alignment_with_loss_func` doesn't accept `loss_kwargs`.

@SunMarc @ArthurZucker I think the PR is ready for launch. Could you please merge this pull request?

Hi! Is this fix expected to arrive in 4.48.1? If yes when is 4.48.1 expected to be released? 

`transformers==4.48.0`

Is the following code still correct if the model accepts loss kwargs but if no custom loss function is provided?
`if not self.model_accepts_loss_kwargs and self.compute_loss_func is None`
Should it not be 
`if not self.model_accepts_loss_kwargs or self.compute_loss_func is None`

For example, when using meta-llama/Llama-3.2-1B-Instruct, self.model_accepts_loss_kwargs is True because of 
line 631-633 in `trainer.py` and KwargsForCausalLM in lines 742 and 792 of `models/llama/modeling_llama.py`

In your test code, you seem to manually turn off model_accepts_loss_kwargs before running trainer.train() but this shouldn't be assumed of every user right?

@parksimon0808 
1. The condition should be `and` because if either `self.model_accepts_loss_kwargs` is True or `self.compute_loss_func` is not `None`, the GA loss bug should be fixed. Only if both conditions fail, the fix is invalid and we should scale the loss."
2. I manually turn off `model_accepts_loss_kwargs` to demonstrate that if the model doesn't accept loss kwargs, the loss will be broken.

Sorry releasing the patch in a bit

I'm still getting high reported losses when using gradient accumulation. I am on version 4.51.3. The below code helps, however, incorrect numbers are still being reported to wandb:
```python
import torch

from transformers import TrainerCallback


class NormalizeMetricsCallback(TrainerCallback):
    def on_log(self, args, state, control, logs=None, **kwargs):
        if logs is None or args.gradient_accumulation_steps <= 1:
            return

        # Normalize the loss
        if "loss" in logs:
            logs["loss"] = logs["loss"] / args.gradient_accumulation_steps

        # Normalize the grad norm (handles both float and Tensor)
        if "grad_norm" in logs:
            gn = logs["grad_norm"]
            # If it's a Tensor, convert to float first
            if isinstance(gn, torch.Tensor):
                gn = gn.item()
            logs["grad_norm"] = gn / args.gradient_accumulation_steps

trainer = Trainer(
    ...,
    callbacks=[NormalizeMetricsCallback()],
)
```

Hey @umarbutler, we take care of normalizing the loss in Trainer, so you shouldn't need to do by yourself !