Optimize `to_py_obj` for python-native numeric lists and scalars
Author: n0gu-furiosa
Pull request: yes

# What does this PR do?

This PR optimizes `to_py_obj` by adding early returns for python-native numeric scalars and 1D lists/tuples of numbers. This avoids unnecessary recursive conversions, which can significantly impact performance of `decode()`.

Fixes #36872

In the provided example from #36872, the runtime decreased from approximately 11 seconds to 0.8 seconds.

## 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.
- [x] 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).
- [x] 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.

@Rocketknight1 @ArthurZucker

<!-- 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: @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: @Rocketknight1
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
Hi 👋, thank you for opening this pull request! The pull request is converted to draft by default. When it is ready for review, please click the `Ready for review` button (at the bottom of the PR page).

This seems like a good idea, but I worry that there might be some edge cases where it fails because it only tests the first element!

One idea would be to use a conversion like `np.array()` as a test, without actually returning its output. For example, if:

- `np.array()` succeeds
- The returned array has 1 dimension
- The returned array has `int`/`float` dtype

Then we can guarantee that the input list/tuple was a flat list of numbers and just return the original list. It would guarantee correctness without needing to recursively call `to_py_obj()`. WDYT?

@Rocketknight1 Great idea. Thanks for the suggestion!

I ran some benchmarks comparing different approaches (using the same example code, but with an increased number of iterations). Here are the results:

* Baseline before this PR: ~29.5s per 3000 iterations
* Initial optimization ([63bfca8](https://github.com/huggingface/transformers/pull/36885/commits/63bfca83ac589b8a8d0456e53d592208d9d74a96)): ~2.3s per 3000 iterations
* Initial optimization _without_ the `obj[0]` bypass hack (code as follows): ~3.0s per 3000 iterations
  ```python
  elif isinstance(obj, (list, tuple)):
      return [to_py_obj(o) for o in obj]
  ```
  This version was tested to serve as a baseline for approaches that traverse all elements.
* And finally, the suggested `np.array` approach ([4d4baa7](https://github.com/huggingface/transformers/pull/36885/commits/4d4baa71f531cbb90117c17be23368cbe7cba692)): ~2.7s

As you see, the `np.array`-based check seems to offer a nice balance between type safety and performance.

Also, instead of checking whether the array has 1 dimension and returning `obj` (a), I opted to return `arr.tolist()` regardless of the array's dimension (b). This allows the same optimization to apply to native multi-dimensional python lists as well. I benchmarked both options using the same example code, and the results were not significantly different (~2.47s for (a) and ~2.49s for (b)). Since this test used a 1D array - which favors (a) - I believe (b) is generally a more flexible and equally performant option.

Let me know if you have any feedback or further suggestions.

Also, one more thought: I think this should still work even if `obj` is a list/tuple containing e.g. Torch/TF arrays. However, we should be careful around that case, since I think `np.array()` will convert lists of those too.

This looks good to me now! Ping me whenever you're ready for me to merge it @n0gu-furiosa 

@Rocketknight1 Everything’s ready on my end. Please feel free to merge whenever you get a chance. Thanks in advance!

thanks 🤗