fix: 🐛 llama2 tokenizer save_pretrained issue JSON serialization error
Author: sidhartha-roy
Pull request: yes

# What does this PR do?
Fixes the issue where the SFTTrainer fails while LoRA fine-tuning of Llama2 model because of JSON serialization error of the llama 2 tokenizer. The issue was that cuda device was not JSON serializable and converting the cuda device to string fixes the issue.
<!--
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)
The code snippet to recreate this error:
```

LLAMA_CHAT_BASE_WEIGHTS_PATH: Final[str] = "/models/huggingface/meta-llama/llama-2-7b-chat-hf"

tokenizer = transformers.AutoTokenizer.from_pretrained(
    LLAMA_CHAT_BASE_WEIGHTS_PATH, local_files_only=True, use_safetensors=True, 
   device_map=torch.device("cuda"),
)

tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"

# base model loading
model = llama.LlamaForCausalLM.from_pretrained(LLAMA_CHAT_BASE_WEIGHTS_PATH, use_safetensors=True, device_map=torch.device("cuda"))

lora_config = LoraConfig(
    lora_alpha=16,
    lora_dropout=0.1,
    r=64,
    bias="none",
    task_type="CAUSAL_LM",
)

dataset = datasets.load_dataset("gbharti/finance-alpaca", split="train[:2%]").train_test_split(test_size=0.05)

training_params = TrainingArguments(
    output_dir="./results",
    label_names=["labels"], 
    num_train_epochs=5,
    per_device_train_batch_size=1,
    per_device_eval_batch_size=1,
    gradient_accumulation_steps=4,
    evaluation_strategy="steps",
    eval_steps=50,
    optim="paged_adamw_32bit",
    save_steps=25,
    logging_steps=25,
    learning_rate=5e-4,
    weight_decay=0.001,
    fp16=False,
    bf16=False,
    max_grad_norm=0.3,
    max_steps=-1,
    warmup_ratio=0.03,
    group_by_length=True,
    lr_scheduler_type="constant",
    remove_unused_columns=False,
    disable_tqdm=True,
    gradient_checkpointing=True,
    eval_accumulation_steps=1,  # to avoid cuda oom during training
)

trainer = SFTTrainer(
    model=model,
    train_dataset=dataset["train"],
    eval_dataset=dataset["test"],
    peft_config=lora_config,
    max_seq_length=512,
    tokenizer=tokenizer,
    args=training_params,
    packing=True,
    formatting_func=format_llama_instruction,
    compute_metrics=compute_metrics,
)

trainer.train()
```

Below is the log trace of the error that is fixed with this PR.
```
Traceback (most recent call last):
  File "/home/sid/llama-2-experiment/scratch/lora_finetuning.py", line 262, in <module>
    trainer.train()
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/trl/trainer/sft_trainer.py", line 323, in train
    output = super().train(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/transformers/trainer.py", line 1624, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/transformers/trainer.py", line 2029, in _inner_training_loop
    self._maybe_log_save_evaluate(tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval)
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/transformers/trainer.py", line 2423, in _maybe_log_save_evaluate
    self._save_checkpoint(model, trial, metrics=metrics)
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/transformers/trainer.py", line 2499, in _save_checkpoint
    self.save_model(staging_output_dir, _internal_call=True)
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/transformers/trainer.py", line 3016, in save_model
    self._save(output_dir)
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/transformers/trainer.py", line 3094, in _save
    self.tokenizer.save_pretrained(output_dir)
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/site-packages/transformers/tokenization_utils_base.py", line 2457, in save_pretrained
    out_str = json.dumps(tokenizer_config, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
          ^^^^^^^^^^^
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/json/encoder.py", line 202, in encode
    chunks = list(chunks)
             ^^^^^^^^^^^^
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/json/encoder.py", line 432, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/json/encoder.py", line 406, in _iterencode_dict
    yield from chunks
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/json/encoder.py", line 439, in _iterencode
    o = _default(o)
        ^^^^^^^^^^^
  File "/home/sid/llama-2-experiment/llama-env/lib/python3.11/json/encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type device is not JSON serializable
```
## 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?
- [ ] 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?
@ArthurZucker and @younesbelkada
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 and @younesbelkada
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @gante
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @pacman100

Integrations:

- deepspeed: HF Trainer/Accelerate: @pacman100
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc and @younesbelkada

Documentation: @stevhliu and @MKhalusova

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: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
@amyeroberts any chance you could take a look here? 🙏🏼 

Hey, the `device_map` should never be passed to the `tokenizer_config` where did this happen? 

I was able to pass the device map in the following way:
```
tokenizer = transformers.AutoTokenizer.from_pretrained(
    LLAMA_CHAT_BASE_WEIGHTS_PATH, local_files_only=True, use_safetensors=True, 
   device_map=torch.device("cuda"),
)
```

A tokenizer does not live on any device. You should not pass it to the `from_pretrained` call