torch2.1.0 DDP+compile+dynamic_shape cause error

### 🐛 Describe the bug

Excuse me! When I use **torch2.1.0** DDP+compile to wrapper huggingface transformers gpt2 model, it will cause error only for the last batch data (shape is smaller than batch_size). Detailed logs as follows:
```bash
[default0]:10/20/2023 13:45:50 - INFO - __main__ - local_rank=0, rank=0, world_size=2
[default1]:10/20/2023 13:45:50 - INFO - __main__ - local_rank=1, rank=1, world_size=2
[default0]:10/20/2023 13:45:53 - INFO - __main__ - GPT2LMHeadModel(
[default0]:  (transformer): GPT2Model(
[default0]:    (wte): Embedding(50257, 768)
[default0]:    (wpe): Embedding(1024, 768)
[default0]:    (drop): Dropout(p=0.1, inplace=False)
[default0]:    (h): ModuleList(
[default0]:      (0-11): 12 x GPT2Block(
[default0]:        (ln_1): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
[default0]:        (attn): GPT2Attention(
[default0]:          (c_attn): Conv1D()
[default0]:          (c_proj): Conv1D()
[default0]:          (attn_dropout): Dropout(p=0.1, inplace=False)
[default0]:          (resid_dropout): Dropout(p=0.1, inplace=False)
[default0]:        )
[default0]:        (ln_2): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
[default0]:        (mlp): GPT2MLP(
[default0]:          (c_fc): Conv1D()
[default0]:          (c_proj): Conv1D()
[default0]:          (act): NewGELUActivation()
[default0]:          (dropout): Dropout(p=0.1, inplace=False)
[default0]:        )
[default0]:      )
[default0]:    )
[default0]:    (ln_f): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
[default0]:  )
[default0]:  (lm_head): Linear(in_features=768, out_features=50257, bias=False)
[default0]:)

[default0]:10/20/2023 13:35:36 - INFO - __main__ - [rank 0][0/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:[rank0]:[2023-10-20 13:35:36,584] [0/0] torch._dynamo.variables.torch: [WARNING] Profiler function <class 'torch.autograd.profiler.record_function'> will be ignored
[default0]:10/20/2023 13:35:41 - INFO - __main__ - [rank 0][0/9]: workers well
[default0]:10/20/2023 13:35:41 - INFO - __main__ - [rank 0][1/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:35:42 - INFO - __main__ - [rank 0][1/9]: workers well
[default0]:10/20/2023 13:35:42 - INFO - __main__ - [rank 0][2/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:35:42 - INFO - __main__ - [rank 0][2/9]: workers well
[default0]:10/20/2023 13:35:42 - INFO - __main__ - [rank 0][3/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:35:42 - INFO - __main__ - [rank 0][3/9]: workers well
[default1]:10/20/2023 13:35:42 - INFO - __main__ - [rank 1][0/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:[rank1]:[2023-10-20 13:35:43,025] [0/0] torch._dynamo.variables.torch: [WARNING] Profiler function <class 'torch.autograd.profiler.record_function'> will be ignored
[default0]:10/20/2023 13:35:42 - INFO - __main__ - [rank 0][4/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:35:43 - INFO - __main__ - [rank 0][4/9]: workers well
[default0]:10/20/2023 13:35:43 - INFO - __main__ - [rank 0][5/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:35:43 - INFO - __main__ - [rank 0][5/9]: workers well
[default0]:10/20/2023 13:35:43 - INFO - __main__ - [rank 0][6/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:35:44 - INFO - __main__ - [rank 0][6/9]: workers well
[default0]:10/20/2023 13:35:44 - INFO - __main__ - [rank 0][7/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:35:44 - INFO - __main__ - [rank 0][7/9]: workers well
[default0]:10/20/2023 13:35:44 - INFO - __main__ - [rank 0][8/9]: batch_data['input_ids'].shape=torch.Size([7, 1024])
[default0]:[rank0]:[2023-10-20 13:35:44,536] [0/1] torch._dynamo.variables.torch: [WARNING] Profiler function <class 'torch.autograd.profiler.record_function'> will be ignored
[default1]:10/20/2023 13:35:48 - INFO - __main__ - [rank 1][0/9]: workers well
[default1]:10/20/2023 13:35:48 - INFO - __main__ - [rank 1][1/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:10/20/2023 13:35:48 - INFO - __main__ - [rank 1][1/9]: workers well
[default1]:10/20/2023 13:35:48 - INFO - __main__ - [rank 1][2/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:10/20/2023 13:35:48 - INFO - __main__ - [rank 1][2/9]: workers well
[default1]:10/20/2023 13:35:49 - INFO - __main__ - [rank 1][3/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:10/20/2023 13:35:49 - INFO - __main__ - [rank 1][3/9]: workers well
[default1]:10/20/2023 13:35:49 - INFO - __main__ - [rank 1][4/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:10/20/2023 13:35:49 - INFO - __main__ - [rank 1][4/9]: workers well
[default1]:10/20/2023 13:35:49 - INFO - __main__ - [rank 1][5/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:10/20/2023 13:35:50 - INFO - __main__ - [rank 1][5/9]: workers well
[default1]:10/20/2023 13:35:50 - INFO - __main__ - [rank 1][6/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:10/20/2023 13:35:50 - INFO - __main__ - [rank 1][6/9]: workers well
[default1]:10/20/2023 13:35:50 - INFO - __main__ - [rank 1][7/9]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default1]:10/20/2023 13:35:50 - INFO - __main__ - [rank 1][7/9]: workers well
[default1]:10/20/2023 13:35:50 - INFO - __main__ - [rank 1][8/9]: batch_data['input_ids'].shape=torch.Size([7, 1024])

[default0]:Traceback (most recent call last):
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/fx/graph_module.py", line 274, in __call__
[default0]:    return super(self.cls, obj).__call__(*args, **kwargs)  # type: ignore[misc]
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
[default0]:    return self._call_impl(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
[default0]:    return forward_call(*args, **kwargs)
[default0]:  File "<eval_with_key>.63", line 24, in forward
[default0]:    matmul = torch.matmul(permute, transpose);  permute = transpose = None
[default0]:RuntimeError: Cannot call sizes() on tensor with symbolic sizes/strides
[default0]:
[default0]:Call using an FX-traced Module, line 24 of the traced Module's generated forward function:
[default0]:    transpose = permute_1.transpose(-1, -2)
[default0]:    matmul = torch.matmul(permute, transpose);  permute = transpose = None
[default0]:
[default0]:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
[default0]:    full = torch.full([], 8.0, dtype = torch.float32, device = device(type='cuda', index=0))
[default0]:
[default0]:    truediv = matmul / full;  matmul = full = None

[default0]:Traceback (most recent call last):
[default0]:  File "/home/yuzhe.wu/grace-compute-dl-benchmark/nlp/gpt/gpt.py", line 294, in <module>
[default0]:    main()
[default0]:  File "/home/yuzhe.wu/grace-compute-dl-benchmark/nlp/gpt/gpt.py", line 276, in main
[default0]:    validate(args, 0, eval_dataloader, model, world_size, device, summary_writer)
[default0]:  File "/home/yuzhe.wu/grace-compute-dl-benchmark/nlp/gpt/gpt.py", line 114, in validate
[default0]:    outputs = model(**batch_data)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
[default0]:    return self._call_impl(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
[default0]:    return forward_call(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/eval_frame.py", line 328, in _fn
[default0]:    return fn(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/external_utils.py", line 17, in inner
[default0]:    return fn(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
[default0]:    return self._call_impl(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
[default0]:    return forward_call(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/parallel/distributed.py", line 1519, in forward
[default0]:    else self._run_ddp_forward(*inputs, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/parallel/distributed.py", line 1355, in _run_ddp_forward
[default0]:    return self.module(*inputs, **kwargs)  # type: ignore[index]
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
[default0]:    return self._call_impl(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
[default0]:    return forward_call(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/eval_frame.py", line 487, in catch_errors
[default0]:    return hijacked_callback(frame, cache_entry, hooks, frame_state)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 641, in _convert_frame
[default0]:    result = inner_convert(frame, cache_size, hooks, frame_state)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 133, in _fn
[default0]:    return fn(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 389, in _convert_frame_assert
[default0]:    return _compile(
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 569, in _compile
[default0]:    guarded_code = compile_inner(code, one_graph, hooks, transform)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/utils.py", line 189, in time_wrapper
[default0]:    r = func(*args, **kwargs)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 491, in compile_inner
[default0]:    out_code = transform_code_object(code, transform)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/bytecode_transformation.py", line 1028, in transform_code_object
[default0]:    transformations(instructions, code_options)
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 458, in transform
[default0]:    tracer.run()
[default0]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/_dynamo/symbolic_convert.py", line 2074, in run
[default1]:Traceback (most recent call last):
[default1]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/fx/graph_module.py", line 274, in __call__
[default1]:    return super(self.cls, obj).__call__(*args, **kwargs)  # type: ignore[misc]
[default1]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
[default1]:    return self._call_impl(*args, **kwargs)
[default1]:  File "/root/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
[default1]:    return forward_call(*args, **kwargs)
[default1]:  File "<eval_with_key>.63", line 24, in forward
[default1]:    matmul = torch.matmul(permute, transpose);  permute = transpose = None
[default1]:RuntimeError: Cannot call sizes() on tensor with symbolic sizes/strides

```

However, the single gpu (without DDP wrapper) workers well:
```bash
[default0]:10/20/2023 12:00:20 - INFO - __main__ - local_rank=0, rank=0, world_size=1
[default0]:10/20/2023 12:00:24 - INFO - __main__ - GPT2LMHeadModel(
[default0]:  (transformer): GPT2Model(
[default0]:    (wte): Embedding(50257, 768)
[default0]:    (wpe): Embedding(1024, 768)
[default0]:    (drop): Dropout(p=0.1, inplace=False)
[default0]:    (h): ModuleList(
[default0]:      (0-11): 12 x GPT2Block(
[default0]:        (ln_1): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
[default0]:        (attn): GPT2Attention(
[default0]:          (c_attn): Conv1D()
[default0]:          (c_proj): Conv1D()
[default0]:          (attn_dropout): Dropout(p=0.1, inplace=False)
[default0]:          (resid_dropout): Dropout(p=0.1, inplace=False)
[default0]:        )
[default0]:        (ln_2): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
[default0]:        (mlp): GPT2MLP(
[default0]:          (c_fc): Conv1D()
[default0]:          (c_proj): Conv1D()
[default0]:          (act): NewGELUActivation()
[default0]:          (dropout): Dropout(p=0.1, inplace=False)
[default0]:        )
[default0]:      )
[default0]:    )
[default0]:    (ln_f): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
[default0]:  )
[default0]:  (lm_head): Linear(in_features=768, out_features=50257, bias=False)
[default0]:)

[default0]:10/20/2023 13:27:16 - INFO - __main__ - [rank 0][0/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:21 - INFO - __main__ - [rank 0][0/17]: workers well
[default0]:10/20/2023 13:27:21 - INFO - __main__ - [rank 0][1/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:21 - INFO - __main__ - [rank 0][1/17]: workers well
[default0]:10/20/2023 13:27:21 - INFO - __main__ - [rank 0][2/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:22 - INFO - __main__ - [rank 0][2/17]: workers well
[default0]:10/20/2023 13:27:22 - INFO - __main__ - [rank 0][3/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:22 - INFO - __main__ - [rank 0][3/17]: workers well
[default0]:10/20/2023 13:27:22 - INFO - __main__ - [rank 0][4/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:23 - INFO - __main__ - [rank 0][4/17]: workers well
[default0]:10/20/2023 13:27:23 - INFO - __main__ - [rank 0][5/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:23 - INFO - __main__ - [rank 0][5/17]: workers well
[default0]:10/20/2023 13:27:23 - INFO - __main__ - [rank 0][6/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:23 - INFO - __main__ - [rank 0][6/17]: workers well
[default0]:10/20/2023 13:27:23 - INFO - __main__ - [rank 0][7/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:24 - INFO - __main__ - [rank 0][7/17]: workers well
[default0]:10/20/2023 13:27:24 - INFO - __main__ - [rank 0][8/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:24 - INFO - __main__ - [rank 0][8/17]: workers well
[default0]:10/20/2023 13:27:24 - INFO - __main__ - [rank 0][9/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:24 - INFO - __main__ - [rank 0][9/17]: workers well
[default0]:10/20/2023 13:27:24 - INFO - __main__ - [rank 0][10/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:25 - INFO - __main__ - [rank 0][10/17]: workers well
[default0]:10/20/2023 13:27:25 - INFO - __main__ - [rank 0][11/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:25 - INFO - __main__ - [rank 0][11/17]: workers well
[default0]:10/20/2023 13:27:25 - INFO - __main__ - [rank 0][12/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:26 - INFO - __main__ - [rank 0][12/17]: workers well
[default0]:10/20/2023 13:27:26 - INFO - __main__ - [rank 0][13/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:26 - INFO - __main__ - [rank 0][13/17]: workers well
[default0]:10/20/2023 13:27:26 - INFO - __main__ - [rank 0][14/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:26 - INFO - __main__ - [rank 0][14/17]: workers well
[default0]:10/20/2023 13:27:26 - INFO - __main__ - [rank 0][15/17]: batch_data['input_ids'].shape=torch.Size([16, 1024])
[default0]:10/20/2023 13:27:27 - INFO - __main__ - [rank 0][15/17]: workers well
[default0]:10/20/2023 13:27:27 - INFO - __main__ - [rank 0][16/17]: batch_data['input_ids'].shape=torch.Size([13, 1024])
[default0]:10/20/2023 13:27:32 - INFO - __main__ - [rank 0][16/17]: workers well

```

The following is complete code in `demo.py`:
```python
import os
import sys
import math
import logging
import torch
import torch.distributed as dist
from typing import List
from itertools import chain
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from datasets import load_dataset
from transformers import (
    default_data_collator,
    CONFIG_MAPPING,
    AutoConfig,
    AutoModelForCausalLM,
    AutoTokenizer,
)

logging.basicConfig(
      format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
      datefmt="%m/%d/%Y %H:%M:%S",
      level=logging.INFO,
)
logger = logging.getLogger(__name__)

def print_rank_0(message):
    """If distributed is initialized, print only on rank 0."""
    if dist.is_initialized():
        if dist.get_rank() == 0:
            logger.info(message)
    else:
        logger.info(message)

def build_datasets(tokenizer, phase):
    dataset_name = "wikitext"
    dataset_config_name="wikitext-103-raw-v1"
    cache_dir="./.cache/wikitext/wikitext103"
    validation_split_percentage = 5
    raw_datasets = load_dataset(
        dataset_name, dataset_config_name, cache_dir=cache_dir
    )
    if "validation" not in raw_datasets.keys():
        raw_datasets["validation"] = load_dataset(
            dataset_name,
            dataset_config_name,
            split=f"train[:{validation_split_percentage}%]",
        )
        raw_datasets["train"] = load_dataset(
            dataset_name,
            dataset_config_name,
            split=f"train[{validation_split_percentage}%:]",
        )

    # Preprocessing the datasets.
    # First we tokenize all the texts.
    column_names = raw_datasets["train"].column_names
    text_column_name = "text" if "text" in column_names else column_names[0]

    def tokenize_function(examples):
        return tokenizer(examples[text_column_name])

    tokenized_datasets = raw_datasets.map(
        tokenize_function,
        batched=True,
        num_proc=16,
        remove_columns=column_names,
        load_from_cache_file=True,
        desc="Running tokenizer on dataset",
    )

    block_size = tokenizer.model_max_length
    if block_size > 1024:
        logger.warning(
            "The chosen tokenizer supports a `model_max_length` that is longer than the default"
            " `block_size` value of 1024. If you would like to use a longer `block_size` up to"
            " `tokenizer.model_max_length` you can override this with `--block_size xxx`."
        )
        block_size = 1024

    # Main data processing function that will concatenate all texts from our dataset and generate
    # chunks of block_size.
    def group_texts(examples):
        # Concatenate all texts.
        concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
        total_length = len(concatenated_examples[list(examples.keys())[0]])
        # We drop the small remainder, we could add padding if the model supported it
        # instead of this drop, you can
        # customize this part to your needs.
        if total_length >= block_size:
            total_length = (total_length // block_size) * block_size
        # Split by chunks of max_len.
        result = {
            k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
            for k, t in concatenated_examples.items()
        }
        result["labels"] = result["input_ids"].copy()
        return result

    # Note that with `batched=True`, this map processes 1,000 texts together,
    # so group_texts throws away a remainde for each of those groups of 1,000 texts.
    # You can adjust that batch_siz here but a higher value might be slowe to preprocess.
    #
    # To speed up this part, we use multiprocessing.
    # See the documentation of the map method for more information:
    # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map

    lm_datasets = tokenized_datasets.map(
        group_texts,
        batched=True,
        num_proc=16,
        load_from_cache_file=True,
        desc=f"Grouping texts in chunks of {block_size}",
    )

    return lm_datasets[phase]

if __name__ == "__main__":
    local_rank = int(os.environ["LOCAL_RANK"])
    dist.init_process_group(backend="nccl")
    rank = dist.get_rank()
    world_size = dist.get_world_size()
    logger.info(f"local_rank={local_rank}, rank={rank}, world_size={world_size}")
    
    device = torch.device("cuda", local_rank)
    seed = 1234
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.set_device(local_rank)

    ### build model and tokenizer ###
    model_name_or_path = "gpt2"
    config = AutoConfig.from_pretrained(model_name_or_path)
    tokenizer = AutoTokenizer.from_pretrained(
        model_name_or_path, use_fast=True
    )
    model = AutoModelForCausalLM.from_pretrained(
        model_name_or_path,
        from_tf=bool(".ckpt" in model_name_or_path),
        config=config,
        low_cpu_mem_usage=False
    )
    embedding_size = model.get_input_embeddings().weight.shape[0]
    if len(tokenizer) > embedding_size:
        model.resize_token_embeddings(len(tokenizer))
    model.tie_weights()

    print_rank_0(model)
    model = model.to(device)

    # wrapper DDP
    if world_size > 1:
        model = DDP(model, device_ids=[device], output_device=device)

    # wrapper torch compile
    # torch._logging.set_logs(dynamo=logging.INFO)
    # torch._dynamo.config.verbose = True

    def comstom_backend(
        gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor]
    ):
        # gm.graph.print_tabular()
        return gm.forward

    torch._dynamo.reset()
    model = torch.compile(model, backend=comstom_backend)

    ### build data loader ###
    # Downloading and loading a dataset from the hub.
    train_dataset = build_datasets(tokenizer, "train")
    eval_dataset = build_datasets(tokenizer, "test")
    train_dataloader = DataLoader(
        train_dataset,
        collate_fn=default_data_collator,
        shuffle=False,
        batch_size=16,
        sampler=DistributedSampler(train_dataset),
    )
    eval_dataloader = DataLoader(
        eval_dataset,
        collate_fn=default_data_collator,
        shuffle=False,
        batch_size=16,
        sampler=DistributedSampler(eval_dataset),
    )

    ### start eval ###
    model.eval()
    with torch.no_grad():
        for idx, batch_data in enumerate(eval_dataloader):
            # H2D
            batch_data["input_ids"] = batch_data["input_ids"].to(device)
            batch_data["attention_mask"] = batch_data["attention_mask"].to(device)
            batch_data["labels"] = batch_data["labels"].to(device)
            logger.info(f"[rank {rank}][{idx}/{len(eval_dataloader)}]: batch_data['input_ids'].shape={batch_data['input_ids'].shape}")
           
            # forward
            outputs = model(**batch_data)
            logger.info(f"[rank {rank}][{idx}/{len(eval_dataloader)}]: workers well")
```

The launch script `run.sh` is:
```bash
#!/bin/bash
set -e

NUM_GPUS=$1
python -u -m torch.distributed.run --nproc_per_node $NUM_GPUS --nnodes 1 --node_rank 0 --master_port 6777 --master_addr localhost --max_restarts 0 --tee 3 demo.py
``` 
The execute command is `bash run.sh 1 (or 2)`. 

### Versions

Environments:
```bash
Collecting environment information...
PyTorch version: 2.1.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 10.5.0-1ubuntu1~20.04) 10.5.0
Clang version: 10.0.0-4ubuntu1
CMake version: version 3.25.2
Libc version: glibc-2.31

Python version: 3.9.13 (main, Aug 25 2022, 23:26:10)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.4.0-42-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA A100 80GB PCIe
GPU 1: NVIDIA A100 80GB PCIe
GPU 2: NVIDIA A100 80GB PCIe
GPU 3: NVIDIA A100 80GB PCIe
GPU 4: NVIDIA A100 80GB PCIe
GPU 5: NVIDIA A100 80GB PCIe
GPU 6: NVIDIA A100 80GB PCIe
GPU 7: NVIDIA A100 80GB PCIe

Nvidia driver version: 525.85.12
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 57 bits virtual
CPU(s):                          64
On-line CPU(s) list:             0-63
Thread(s) per core:              2
Core(s) per socket:              16
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           106
Model name:                      Intel(R) Xeon(R) Gold 6346 CPU @ 3.10GHz
Stepping:                        6
Frequency boost:                 enabled
CPU MHz:                         799.979
CPU max MHz:                     3600.0000
CPU min MHz:                     800.0000
BogoMIPS:                        6200.00
Virtualization:                  VT-x
L1d cache:                       1.5 MiB
L1i cache:                       1 MiB
L2 cache:                        40 MiB
L3 cache:                        72 MiB
NUMA node0 CPU(s):               0-15,32-47
NUMA node1 CPU(s):               16-31,48-63
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] flake8==4.0.1
[pip3] mypy-extensions==0.4.3
[pip3] numpy==1.21.5
[pip3] numpydoc==1.4.0
[pip3] torch==2.1.0+cu118
[pip3] torchvision==0.16.0
[pip3] triton==2.1.0
[conda] blas                      1.0                         mkl
[conda] mkl                       2021.4.0           h06a4308_640
[conda] mkl-service               2.4.0            py39h7f8727e_0
[conda] mkl_fft                   1.3.1            py39hd3c417c_0
[conda] mkl_random                1.2.2            py39h51133e4_0
[conda] numpy                     1.21.5           py39h6c91a56_3
[conda] numpy-base                1.21.5           py39ha15fc14_3
[conda] numpydoc                  1.4.0            py39h06a4308_0
[conda] torch                     2.1.0+cu118              pypi_0    pypi
[conda] torchvision               0.16.0                   pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi
```

Looking forward to your reply, thanks a lot!