transition scores can be negative infinity 
Author: myazdani
Pull request: no

### System Info

Running transformers 4.28.1 in google colab:

Collecting environment information...
PyTorch version: 2.0.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: 10.0.0-4ubuntu1 
CMake version: version 3.25.2
Libc version: glibc-2.31

Python version: 3.9.16 (main, Dec  7 2022, 01:11:51)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.10.147+-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.7.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, 48 bits virtual
CPU(s):                          2
On-line CPU(s) list:             0,1
Thread(s) per core:              2
Core(s) per socket:              1
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           79
Model name:                      Intel(R) Xeon(R) CPU @ 2.20GHz
Stepping:                        0
CPU MHz:                         2199.998
BogoMIPS:                        4399.99
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       32 KiB
L1i cache:                       32 KiB
L2 cache:                        256 KiB
L3 cache:                        55 MiB
NUMA node0 CPU(s):               0,1
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Vulnerable; SMT Host state unknown
Vulnerability Meltdown:          Vulnerable
Vulnerability Mmio stale data:   Vulnerable
Vulnerability Retbleed:          Vulnerable
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers
Vulnerability Spectre v2:        Vulnerable, IBPB: disabled, STIBP: disabled, PBRSB-eIBRS: Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Vulnerable
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.22.4
[pip3] torch==2.0.0+cu118
[pip3] torchaudio==2.0.1+cu118
[pip3] torchdata==0.6.0
[pip3] torchsummary==1.5.1
[pip3] torchtext==0.15.1
[pip3] torchvision==0.15.1+cu118
[pip3] triton==2.0.0
[conda] Could not collect

### Who can help?

@gante 

### Information

- [X] The official example scripts
- [ ] 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

The code example is this: 

```
from transformers import GPT2Tokenizer, AutoModelForCausalLM
import torch

tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer.pad_token_id = tokenizer.eos_token_id
inputs = tokenizer(5*["Today is"], return_tensors="pt")

torch.manual_seed(10)
for i in range(100):
    outputs = model.generate(**inputs, max_new_tokens=15, return_dict_in_generate=True, 
                             output_scores=True, 
                             do_sample=True, 
                             temperature=0.9, 
                             top_k=40, 
                             pad_token_id=tokenizer.eos_token_id)
    transition_scores = model.compute_transition_scores(
        outputs.sequences, outputs.scores, normalize_logits=False
    )

    if torch.isinf(transition_scores).any().item():
        print(i)
        break    
        
```
Colab link: https://colab.research.google.com/drive/12KIOKGfZtoChC1ohTlesUWEL6AZT_luo?usp=sharing

### Expected behavior

I expect `transition_scores` to be finite however on my end I see torch.isinf(transition_scores)  == True for i = 0. 

I traced the issue and it is actually not with compute_transition_scores but originates in the original scores returned in outputs.scores. 

The issue specifically happen we use non-greedy sampling approach (ie,  do_sample=True). I looked deeper and I think the issue is because of the torch.multinomial selecting tokens with probability 0 (when it shouldn't) but I'm not sure: https://github.com/pytorch/pytorch/issues/48841


Comments:
cc @gante 

I have found that this problem also occurs when running on GPU, but torch.multinomial behaves as expected on GPU (erroneously sampling elements with prob 0 only happens on CPU with float data type). So I'm not sure why we are seeing -inf scores here. 

Hey @myazdani 👋 Thank you for raising the issue!

Uhmmm this is a very annoying PyTorch problem. In practice, we have two options:
1. Wait for PT to fix the issue;
2. Add a workaround ourselves, e.g. sample N tokens at each step and select the first non-`-inf` token. Any workaround will add an execution time overhead, which is also undesirable.

Given that the number of problematic tokens is very high (~0.158%[CPU]/~0.000%[GPU] of the tokens in a test run 👀 ), I'll add a workaround ASAP!

________________________________

script used to get the error ratio:
```py
from transformers import GPT2Tokenizer, AutoModelForCausalLM
import torch
from tqdm import tqdm

tokenizer = GPT2Tokenizer.from_pretrained("distilgpt2")
model = AutoModelForCausalLM.from_pretrained("distilgpt2").to("cuda")
tokenizer.pad_token_id = tokenizer.eos_token_id
# batch size == 1, larger batch sizes have nuances that are not relevant here
inputs = tokenizer(["Today is"], return_tensors="pt").to("cuda")

torch.manual_seed(10)
invalid_tokens = 0
for i in tqdm(range(10000)):
    outputs = model.generate(**inputs, max_new_tokens=15, return_dict_in_generate=True,
                             output_scores=True,
                             do_sample=True,
                             temperature=0.9,
                             top_k=40,
                             pad_token_id=tokenizer.eos_token_id)
    transition_scores = model.compute_transition_scores(
        outputs.sequences, outputs.scores, normalize_logits=False
    )

    invalid_tokens += torch.isinf(transition_scores).sum().item()

print(f"invalid token ratio: {(invalid_tokens / (10000 * 15))*100:.4f}%", )
```

We got in touch with the PT team, which should give a hand on the problem :)

This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.

It looks like the PyTorch multinomial issue has been fixed: https://github.com/pytorch/pytorch/pull/101720

I verified with the nightly build that the torch.multinomial works as expected. 

However, I am still getting -inf values in the transition scores `compute_transition_scores`, cc: @gante @sgugger 

Hey @myazdani -- is the script to reproduce the issue with PT nightly still the same as the one at the top?

Yes @gante I'm running:
```
from transformers import GPT2Tokenizer, AutoModelForCausalLM
import torch
from tqdm import tqdm


tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer.pad_token_id = tokenizer.eos_token_id
inputs = tokenizer(5*["Today is"], return_tensors="pt")

torch.manual_seed(10)
for i in range(100):
    outputs = model.generate(**inputs, max_new_tokens=15, return_dict_in_generate=True, 
                             output_scores=True, 
                             do_sample=True, 
                             temperature=0.9, 
                             top_k=40, 
                             pad_token_id=tokenizer.eos_token_id)
    transition_scores = model.compute_transition_scores(
        outputs.sequences, outputs.scores, normalize_logits=False
    )

    if torch.isinf(transition_scores).any().item():
        print(i)
        break    
```

Loop breaks at i=22. Below is my env:
```
- huggingface_hub version: 0.15.1
- Platform: Linux-5.15.107+-x86_64-with-glibc2.31
- Python version: 3.10.12
- Running in iPython ?: Yes
- iPython shell: Shell
- Running in notebook ?: Yes
- Running in Google Colab ?: Yes
- Token path ?: /root/.cache/huggingface/token
- Has saved token ?: False
- Configured git credential helpers: 
- FastAI: 2.7.12
- Tensorflow: 2.12.0
- Torch: 2.1.0.dev20230612+cu118
- Jinja2: 3.1.2
- Graphviz: 0.20.1
- Pydot: 1.4.2
- Pillow: 8.4.0
- hf_transfer: N/A
- gradio: N/A
- numpy: 1.25.0rc1
- ENDPOINT: https://huggingface.co/
- HUGGINGFACE_HUB_CACHE: /root/.cache/huggingface/hub
- HUGGINGFACE_ASSETS_CACHE: /root/.cache/huggingface/assets
- HF_TOKEN_PATH: /root/.cache/huggingface/token
- HF_HUB_OFFLINE: False
- HF_HUB_DISABLE_TELEMETRY: False
- HF_HUB_DISABLE_PROGRESS_BARS: None
- HF_HUB_DISABLE_SYMLINKS_WARNING: False
- HF_HUB_DISABLE_EXPERIMENTAL_WARNING: False
- HF_HUB_DISABLE_IMPLICIT_TOKEN: False
- HF_HUB_ENABLE_HF_TRANSFER: False

{'huggingface_hub version': '0.15.1',
 'Platform': 'Linux-5.15.107+-x86_64-with-glibc2.31',
 'Python version': '3.10.12',
 'Running in iPython ?': 'Yes',
 'iPython shell': 'Shell',
 'Running in notebook ?': 'Yes',
 'Running in Google Colab ?': 'Yes',
 'Token path ?': PosixPath('/root/.cache/huggingface/token'),
 'Has saved token ?': False,
 'Configured git credential helpers': '',
 'FastAI': '2.7.12',
 'Tensorflow': '2.12.0',
 'Torch': '2.1.0.dev20230612+cu118',
 'Jinja2': '3.1.2',
 'Graphviz': '0.20.1',
 'Pydot': '1.4.2',
 'Pillow': '8.4.0',
 'hf_transfer': 'N/A',
 'gradio': 'N/A',
 'numpy': '1.25.0rc1',
 'ENDPOINT': 'https://huggingface.co/',
 'HUGGINGFACE_HUB_CACHE': '/root/.cache/huggingface/hub',
 'HUGGINGFACE_ASSETS_CACHE': '/root/.cache/huggingface/assets',
 'HF_TOKEN_PATH': '/root/.cache/huggingface/token',
 'HF_HUB_OFFLINE': False,
 'HF_HUB_DISABLE_TELEMETRY': False,
 'HF_HUB_DISABLE_PROGRESS_BARS': None,
 'HF_HUB_DISABLE_SYMLINKS_WARNING': False,
 'HF_HUB_DISABLE_EXPERIMENTAL_WARNING': False,
 'HF_HUB_DISABLE_IMPLICIT_TOKEN': False,
 'HF_HUB_ENABLE_HF_TRANSFER': False}
```



@myazdani In this case everything is fine :D 

If you print the transition scores for the row with `-inf` you see
```
[-128.0551, -120.1372,  -91.5507,  -70.1001,  -88.0797, -100.0098,
  -82.7555,  -34.6997,      -inf,      -inf,      -inf,      -inf,  -inf,      -inf,      -inf],
```
and, if you print the sequence, you see
```
[ 8888,   318,   257,  6507,   640,   329,   262,  1499,   526, 50256,
 50256, 50256, 50256, 50256, 50256, 50256, 50256]
```

`50256` is the EOS token, so the `-inf` here only exists due to padding :)


This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.