Errors when returning the tensors with PyTorch using AutoImageProcessor
Author: stephenhky
Pull request: no
Labels: name: bug

### System Info

- `transformers` version: 4.48.1
- Platform: macOS-15.2-arm64-arm-64bit
- Python version: 3.12.8
- Huggingface_hub version: 0.27.0
- Safetensors version: 0.4.5
- Accelerate version: not installed
- Accelerate config: not found
- PyTorch version (GPU?): 2.3.1.post100 (False)
- Tensorflow version (GPU?): not installed (NA)
- Flax version (CPU?/GPU?/TPU?): not installed (NA)
- Jax version: not installed
- JaxLib version: not installed
- Using distributed or parallel set-up in script?: No

### Who can help?

_No response_

### Information

- [ ] The official example scripts
- [x] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [x] My own task or dataset (give details below)

### Reproduction

I am using the class `AutoImageProcessor` to process images before putting to any Vision Transformer models. Here it shows how the error can be reproduced:

```
from PIL import Image
from transformers import AutoImageProcessor
import requests

# Load the image processor
image_processor = AutoImageProcessor.from_pretrained('facebook/hiera-large-224-hf')

# Load the image ( two cats, online)
image = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg', stream=True).raw)

# pass through if I need a return as an numpy.ndarray object
parsed_image_np = image_processor(images=image)
# raise an error if I need a return in as an PyTorch.Tensor object
parsed_image_pt = image_processor(images=image, return_tensors='pt')
```

The stacktrace is shown below:
```
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
File /opt/anaconda3/envs/cv/lib/python3.12/site-packages/transformers/feature_extraction_utils.py:193, in BatchFeature.convert_to_tensors(self, tensor_type)
    192 if not is_tensor(value):
--> 193     tensor = as_tensor(value)
    195     self[key] = tensor

File /opt/anaconda3/envs/cv/lib/python3.12/site-packages/transformers/feature_extraction_utils.py:150, in BatchFeature._get_is_as_tensor_fns.<locals>.as_tensor(value)
    149 if isinstance(value, np.ndarray):
--> 150     return torch.from_numpy(value)
    151 else:

TypeError: expected np.ndarray (got numpy.ndarray)

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
Cell In[10], line 1
----> 1 image_processor(images=image, return_tensors='pt')

File /opt/anaconda3/envs/cv/lib/python3.12/site-packages/transformers/image_processing_utils.py:41, in BaseImageProcessor.__call__(self, images, **kwargs)
     39 def __call__(self, images, **kwargs) -> BatchFeature:
     40     """Preprocess an image or a batch of images."""
---> 41     return self.preprocess(images, **kwargs)

File /opt/anaconda3/envs/cv/lib/python3.12/site-packages/transformers/utils/generic.py:854, in filter_out_non_signature_kwargs.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
    845         cls_prefix = ""
    847     warnings.warn(
    848         f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`"
    849         f" and were ignored: {invalid_kwargs_names}",
    850         UserWarning,
    851         stacklevel=2,
    852     )
--> 854 return func(*args, **valid_kwargs)

File /opt/anaconda3/envs/cv/lib/python3.12/site-packages/transformers/models/bit/image_processing_bit.py:321, in BitImageProcessor.preprocess(self, images, do_resize, size, resample, do_center_crop, crop_size, do_rescale, rescale_factor, do_normalize, image_mean, image_std, do_convert_rgb, return_tensors, data_format, input_data_format)
    315 images = [
    316     to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
    317     for image in all_images
    318 ]
    320 data = {"pixel_values": images}
--> 321 return BatchFeature(data=data, tensor_type=return_tensors)

File /opt/anaconda3/envs/cv/lib/python3.12/site-packages/transformers/feature_extraction_utils.py:79, in BatchFeature.__init__(self, data, tensor_type)
     77 def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
     78     super().__init__(data)
---> 79     self.convert_to_tensors(tensor_type=tensor_type)

File /opt/anaconda3/envs/cv/lib/python3.12/site-packages/transformers/feature_extraction_utils.py:199, in BatchFeature.convert_to_tensors(self, tensor_type)
    197         if key == "overflowing_values":
    198             raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
--> 199         raise ValueError(
    200             "Unable to create tensor, you should probably activate padding "
    201             "with 'padding=True' to have batched tensors with the same length."
    202         )
    204 return self

ValueError: Unable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.
```

However, even if I put `padding=True` while processing the image, the error still occurs.

### Expected behavior

I would expect a dictionary would be returned by the last line (`parsed_image_pt = image_processor(images=image, return_tensors='pt')`)

Comments:
@stephenhky hey!

The code doesn't throw an error for me in v4.48.1. From the stacktrace `TypeError: expected np.ndarray (got numpy.ndarray)`, seems like a version mismatch between numpy and torch. Can you try to update your `numpy`?

@zucchini-nlp Thanks. I updated my `numpy`, and it is working now!

Closing as resolved then :)