Use shape_list to safely get shapes for Swin
Author: amyeroberts
Pull request: yes

# What does this PR do?

Refactors some logic in the Swin model to enable `model.fit` calls with a `tf.data.BatchDataset` datasets i.e. datasets returned from `to_tf_dataset` called with `batch_size` argument set, and a common dataset type in TF workflows. 

**Changes**
* `.shape` calls are replaced with `shape_list`, which handles dynamic shapes and batched data cleanly. 
* Test added which would have caught this
* Adapt `reshape` logic in Deberta model to allow it to be run in graph mode

On the current main, the following error would occur (snippet shown): 
```
                File "/Users/aroberts/hf_code/transformers/src/transformers/models/swin/modeling_tf_swin.py", line 296, in call  *
                    embeddings, output_dimensions = self.patch_embeddings(pixel_values, training=training)
                File "/Users/aroberts/.virtualenvs/tenv/lib/python3.9/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler  **
                    raise e.with_traceback(filtered_tb) from None
            
                TypeError: Exception encountered when calling layer "patch_embeddings" (type TFSwinPatchEmbeddings).
                
                in user code:
                
                    File "/Users/aroberts/hf_code/transformers/src/transformers/models/swin/modeling_tf_swin.py", line 363, in call  *
                        embeddings = tf.reshape(embeddings, (embeddings.shape[0], embeddings.shape[1], -1))
                
                    TypeError: Failed to convert elements of (None, 96, -1) to Tensor. Consider casting elements to a supported type. See https://www.tensorflow.org/api_docs/python/tf/dtypes for supported TF dtypes.
```

if running:
```
import tensorflow as tf
from datasets import load_dataset, load_metric

from transformers import AdamWeightDecay, AutoFeatureExtractor, DefaultDataCollator, TFAutoModelForImageClassification

model_checkpoint = "microsoft/swin-tiny-patch4-window7-224" # pre-trained model from which to fine-tune

dataset = load_dataset("imagefolder", data_files="https://madm.dfki.de/files/sentinel/EuroSAT.zip")
metric = load_metric("accuracy")

labels = dataset["train"].features["label"].names
label2id, id2label = dict(), dict()
for i, label in enumerate(labels):
    label2id[label] = i
    id2label[i] = label
feature_extractor = AutoFeatureExtractor.from_pretrained(model_checkpoint)


def train_transforms(image):
    # Placeholder to demo transform pipeline
    image = tf.keras.utils.img_to_array(image)
    image = tf.image.resize(
        image,
        size=(feature_extractor.size, feature_extractor.size),
        method=tf.image.ResizeMethod.BILINEAR
    )
    image = tf.transpose(image, (2, 0, 1))
    return image


def preprocess_train(example_batch):
    example_batch["pixel_values"] = [
        train_transforms(image.convert("RGB")) for image in example_batch["image"]
    ]
    example_batch.pop('image') # Is this OK?
    return example_batch

splits = dataset["train"].train_test_split(test_size=0.1)
train_ds = splits['train']
train_ds.set_transform(preprocess_train)
data_collator = DefaultDataCollator(return_tensors="tf")
train_set = train_ds.to_tf_dataset(
    columns=["image", "label"],
    shuffle=True,
    batch_size=16,
    collate_fn=data_collator
)

optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)

model = TFAutoModelForImageClassification.from_pretrained(
    model_checkpoint,
    label2id=label2id,
    id2label=id2label,
    ignore_mismatched_sizes=True,
)
model.compile(optimizer=optimizer)
model.fit(train_set, epochs=2)
```

With this refactor the training script will run and the tensorflow model will start training. 

Note: the model version on `main` will predict with a batch from the dataset using the `__call__` method e.g. 
```
batch = next(iter(train_ds))
model(batch)
```

However, it fails with the same error if called through the keras API
```
batch = next(iter(train_ds))
model.predict(batch)
```


## 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#start-contributing-pull-requests),
      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).
- [x] Did you write any new necessary tests?


Comments:
_The documentation is not available anymore as the PR was closed or merged._

(Also, I re-read the line I was complaining about and it's actually fine, just a little unclear, so I deleted that comment)