Repository: huggingface/transformers
Pull request: make sure lr is not a tensor

# What does this PR do?
There seems to be a slight regression where using deepspeed is completely broken and saving checkpoints will fail during the trainer state save step because the LR is still a tensor. This is probably also the root cause that also would fix #37704. The is Tensor check is used in the `else` part of the conditional, but not the `if` clause.

This PR makes sure when we grab the learning rate while using deepspeed that it isn't a Tensor type.

Saving the trainer state fails with:

```
[rank0]:   File "/workspace/axolotl/src/axolotl/train.py", line 215, in execute_training
[rank0]:     trainer.train(resume_from_checkpoint=resume_from_checkpoint)
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/site-packages/transformers/trainer.py", line 2245, in train
[rank0]:     return inner_training_loop(
[rank0]:            ^^^^^^^^^^^^^^^^^^^^
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/site-packages/transformers/trainer.py", line 2661, in _inner_training_loop
[rank0]:     self._maybe_log_save_evaluate(
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/site-packages/transformers/trainer.py", line 3103, in _maybe_log_save_evaluate
[rank0]:     self._save_checkpoint(model, trial)
[rank0]:   File "/workspace/axolotl/src/axolotl/core/trainers/base.py", line 612, in _save_checkpoint
[rank0]:     return super()._save_checkpoint(model, trial, **kwargs)
[rank0]:            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/site-packages/transformers/trainer.py", line 3228, in _save_checkpoint
[rank0]:     self.state.save_to_json(os.path.join(output_dir, TRAINER_STATE_NAME))
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/site-packages/transformers/trainer_callback.py", line 146, in save_to_json
[rank0]:     json_string = json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True) + "\n"
[rank0]:                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/__init__.py", line 238, in dumps
[rank0]:     **kw).encode(obj)
[rank0]:           ^^^^^^^^^^^
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/encoder.py", line 202, in encode
[rank0]:     chunks = list(chunks)
[rank0]:              ^^^^^^^^^^^^
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/encoder.py", line 432, in _iterencode
[rank0]:     yield from _iterencode_dict(o, _current_indent_level)
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/encoder.py", line 406, in _iterencode_dict
[rank0]:     yield from chunks
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/encoder.py", line 326, in _iterencode_list
[rank0]:     yield from chunks
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/encoder.py", line 406, in _iterencode_dict
[rank0]:     yield from chunks
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/encoder.py", line 439, in _iterencode
[rank0]:     o = _default(o)
[rank0]:         ^^^^^^^^^^^
[rank0]:   File "/root/miniconda3/envs/py3.11/lib/python3.11/json/encoder.py", line 180, in default
[rank0]:     raise TypeError(f'Object of type {o.__class__.__name__} '
[rank0]: TypeError: Object of type Tensor is not JSON serializable
```
Here's the deepspeed zero-3 config I'm using, but likely not relevant: https://wandb.ai/axolotl-ai/qwen3-distributed/runs/mg3kc9wv/files/tmp/deepspeed_config_d31f2b33.json


<!--
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 # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] 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?

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

 -->


Changed files:
filename: src/transformers/trainer.py
patch: @@ -3079,9 +3079,7 @@ def _maybe_log_save_evaluate(
             if grad_norm is not None:
                 logs["grad_norm"] = grad_norm.item() if isinstance(grad_norm, torch.Tensor) else grad_norm
             if learning_rate is not None:
-                logs["learning_rate"] = (
-                    learning_rate.item() if isinstance(learning_rate, torch.Tensor) else learning_rate
-                )
+                logs["learning_rate"] = learning_rate
             else:
                 logs["learning_rate"] = self._get_learning_rate()
 

filename: src/transformers/trainer_pt_utils.py
patch: @@ -921,8 +921,9 @@ def _get_learning_rate(self):
             last_lr = self.optimizer.param_groups[0]["lr"]
         else:
             last_lr = self.lr_scheduler.get_last_lr()[0]
-        if torch.is_tensor(last_lr):
-            last_lr = last_lr.item()
+
+    if torch.is_tensor(last_lr):
+        last_lr = last_lr.item()
     return last_lr