Encoder-Decoder Gemma
Author: bzhangGo
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 -->

Add support for encoder-decoder Gemma (https://arxiv.org/abs/2504.06225)

## Before submitting
- [ ] 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).
   * Documentation is not updated yet.
- [ ] Did you write any new necessary tests?
   * Nope. Instead, I tested the code locally.


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- 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: @eustlb
- graph models: @clefourrier

Library:

- flax: @gante and @Rocketknight1
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @zach-huggingface and @SunMarc
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @SunMarc @zach-huggingface
- 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: @Rocketknight1
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
> Hey! thanks for the PR! Would be nice to split encoder and decoder. Decoder already exist pretty much is Gemma3 no? so simpler to write already! Can you also add the tests! 🤗

@ArthurZucker thanks for your suggestions! I made several updates to this PR. please take another look!

@ArthurZucker I just marked this PR as ready for review. could you please take another look?

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

The Token Classification implementation was not tested End-to-End:

```bash
[INFO|trainer.py:4352] 2025-07-12 12:27:59,071 >> 
***** Running Evaluation *****
[INFO|trainer.py:4354] 2025-07-12 12:27:59,071 >>   Num examples = 3250
[INFO|trainer.py:4357] 2025-07-12 12:27:59,071 >>   Batch size = 8
                                                                                                                                                                                              Traceback (most recent call last):██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▏ | 402/407 [00:06<00:00, 58.28it/s]
  File "/home/stefan/Repositories/transformers-t5gemma/examples/pytorch/token-classification/run_ner.py", line 653, in <module>
    main()
  File "/home/stefan/Repositories/transformers-t5gemma/examples/pytorch/token-classification/run_ner.py", line 584, in main
    train_result = trainer.train(resume_from_checkpoint=checkpoint)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/Repositories/transformers-t5gemma/src/transformers/trainer.py", line 2206, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/Repositories/transformers-t5gemma/src/transformers/trainer.py", line 2656, in _inner_training_loop
    self._maybe_log_save_evaluate(
  File "/home/stefan/Repositories/transformers-t5gemma/src/transformers/trainer.py", line 3095, in _maybe_log_save_evaluate
    metrics = self._evaluate(trial, ignore_keys_for_eval)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/Repositories/transformers-t5gemma/src/transformers/trainer.py", line 3044, in _evaluate
    metrics = self.evaluate(ignore_keys=ignore_keys_for_eval)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/Repositories/transformers-t5gemma/src/transformers/trainer.py", line 4198, in evaluate
    output = eval_loop(
             ^^^^^^^^^^
  File "/home/stefan/Repositories/transformers-t5gemma/src/transformers/trainer.py", line 4488, in evaluation_loop
    metrics = self.compute_metrics(
              ^^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/Repositories/transformers-t5gemma/examples/pytorch/token-classification/run_ner.py", line 535, in compute_metrics
    predictions = np.argmax(predictions, axis=2)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/venvs/t5gemma/lib/python3.12/site-packages/numpy/_core/fromnumeric.py", line 1359, in argmax
    return _wrapfunc(a, 'argmax', axis=axis, out=out, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/venvs/t5gemma/lib/python3.12/site-packages/numpy/_core/fromnumeric.py", line 54, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/stefan/venvs/t5gemma/lib/python3.12/site-packages/numpy/_core/fromnumeric.py", line 42, in _wrapit
    conv = _array_converter(obj)
           ^^^^^^^^^^^^^^^^^^^^^
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
  5%|███████▌   
```

Tested with latest `4.54.0.dev0` using the PyTorch token classification example via:

```python
BATCH_SIZE=16
LR=5e-05
EPOCHS=20
SEED=1

python3 run_ner.py \
  --model_name_or_path google/t5gemma-s-s-ul2 \
  --dataset_name conll2003 \
  --output_dir ./t5gemma-bs${BATCH_SIZE}-lr${LR}-e${EPOCHS}-${SEED} \
  --eval_strategy epoch \
  --save_strategy epoch \
  --per_device_train_batch_size ${BATCH_SIZE} \
  --learning_rate ${LR} \
  --num_train_epochs ${EPOCHS} \
  --load_best_model_at_end=True \
  --bf16 \
  --do_train \
  --do_eval
```

Hey, thanks for raising this! There seems some problem with eval as the model returns hidden states as well.

A temporary fix is to disable them in modeling_t5gemma.py, like
```
        return TokenClassifierOutput(
            loss=loss,
            logits=logits,
            hidden_states=None, #hidden_states,
            attentions=None, #attentions,
        )
```

We'll make an update later.