utils.py 214 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# coding=utf-8
# Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

17
import copy
18
19
20
import inspect
import warnings
from dataclasses import dataclass
21
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
22
23
24
25
26

import torch
import torch.distributed as dist
from torch import nn

27
from ..cache_utils import Cache, DynamicCache, StaticCache
28
from ..integrations.deepspeed import is_deepspeed_zero3_enabled
29
30
31
32
33
34
35
36
from ..modeling_outputs import CausalLMOutputWithPast, Seq2SeqLMOutput
from ..models.auto import (
    MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING,
    MODEL_FOR_CAUSAL_LM_MAPPING,
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
    MODEL_FOR_VISION_2_SEQ_MAPPING,
)
37
from ..utils import ModelOutput, is_accelerate_available, is_torchdynamo_compiling, logging
38
from .beam_constraints import DisjunctiveConstraint, PhrasalConstraint
39
from .beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
40
41
42
from .candidate_generator import (
    AssistedCandidateGenerator,
    CandidateGenerator,
43
    PromptLookupCandidateGenerator,
44
45
46
47
    _crop_past_key_values,
    _prepare_attention_mask,
    _prepare_token_type_ids,
)
48
from .configuration_utils import GenerationConfig, GenerationMode
49
50
from .logits_process import (
    EncoderNoRepeatNGramLogitsProcessor,
Karim Foda's avatar
Karim Foda committed
51
    EncoderRepetitionPenaltyLogitsProcessor,
52
53
    EpsilonLogitsWarper,
    EtaLogitsWarper,
54
55
56
57
58
59
60
61
62
    ExponentialDecayLengthPenalty,
    ForcedBOSTokenLogitsProcessor,
    ForcedEOSTokenLogitsProcessor,
    ForceTokensLogitsProcessor,
    HammingDiversityLogitsProcessor,
    InfNanRemoveLogitsProcessor,
    LogitNormalization,
    LogitsProcessorList,
    MinLengthLogitsProcessor,
63
    MinNewTokensLengthLogitsProcessor,
64
    MinPLogitsWarper,
65
66
67
68
    NoBadWordsLogitsProcessor,
    NoRepeatNGramLogitsProcessor,
    PrefixConstrainedLogitsProcessor,
    RepetitionPenaltyLogitsProcessor,
69
    SequenceBiasLogitsProcessor,
70
71
72
73
74
75
    SuppressTokensAtBeginLogitsProcessor,
    SuppressTokensLogitsProcessor,
    TemperatureLogitsWarper,
    TopKLogitsWarper,
    TopPLogitsWarper,
    TypicalLogitsWarper,
76
    UnbatchedClassifierFreeGuidanceLogitsProcessor,
77
78
)
from .stopping_criteria import (
79
    EosTokenCriteria,
80
81
82
83
    MaxLengthCriteria,
    MaxTimeCriteria,
    StoppingCriteria,
    StoppingCriteriaList,
84
    StopStringCriteria,
85
86
87
)


88
if TYPE_CHECKING:
89
    from ..modeling_utils import PreTrainedModel
90
    from ..tokenization_utils_base import PreTrainedTokenizerBase
91
92
    from .streamers import BaseStreamer

93
94
logger = logging.get_logger(__name__)

Marc Sun's avatar
Marc Sun committed
95
96
97
if is_accelerate_available():
    from accelerate.hooks import AlignDevicesHook, add_hook_to_module

98
99
100
101
NEED_SETUP_CACHE_CLASSES_MAPPING = {
    "static": StaticCache,
}

102
103

@dataclass
104
class GenerateDecoderOnlyOutput(ModelOutput):
105
    """
106
    Outputs of decoder-only generation models, when using non-beam methods.
107
108
109
110
111
112
113
114
115

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
            Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
116
117
118
119
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True` is passed or when `config.output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
120
121
122
123
124
125
        attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
126
127
128
129
130
131
132
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            NOTE: some models have a different `past_key_values` format, confirm with the model's documentation.
            Usually a Tuple (one element for each layer of the decoder) of tuples (two elements, key tensor and value
            tensor). The first Tuple is of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.
133
134
135
136
    """

    sequences: torch.LongTensor = None
    scores: Optional[Tuple[torch.FloatTensor]] = None
137
    logits: Optional[Tuple[torch.FloatTensor]] = None
138
139
    attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
    hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
140
    past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
141
142
143


@dataclass
144
class GenerateEncoderDecoderOutput(ModelOutput):
145
    """
146
    Outputs of encoder-decoder generation models, when using non-beam methods.
147
148

    Args:
149
        sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
150
151
152
153
154
155
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
            Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
156
157
158
159
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True` is passed or when `config.output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
        encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
            sequence_length, sequence_length)`.
        encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.
        decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
175
176
177
178
179
180
181
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            NOTE: some models have a different `past_key_values` format, confirm with the model's documentation.
            Usually a Tuple (one element for each layer of the decoder) of tuples (two elements, key tensor and value
            tensor). The first Tuple is of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.
182
183
184
185
    """

    sequences: torch.LongTensor = None
    scores: Optional[Tuple[torch.FloatTensor]] = None
186
    logits: Optional[Tuple[torch.FloatTensor]] = None
187
188
189
190
191
    encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
    encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
    decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
    cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
    decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
192
    past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
193
194
195


@dataclass
196
class GenerateBeamDecoderOnlyOutput(ModelOutput):
197
    """
198
    Outputs of decoder-only generation models, when using beam methods.
199
200
201
202
203
204
205
206
207
208
209

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
            Final beam scores of the generated `sequences`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
            Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
            of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
            Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
210
            with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
211
212
213
214
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True` is passed or when `config.output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
215
        beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
216
            Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
217
            `(batch_size*num_return_sequences, sequence_length)`.
218
219
220
221
222
223
        attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`.
        hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
224
225
226
227
228
229
230
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            NOTE: some models have a different `past_key_values` format, confirm with the model's documentation.
            Usually a Tuple (one element for each layer of the decoder) of tuples (two elements, key tensor and value
            tensor). The first Tuple is of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.
231
232
233
234
235
    """

    sequences: torch.LongTensor = None
    sequences_scores: Optional[torch.FloatTensor] = None
    scores: Optional[Tuple[torch.FloatTensor]] = None
236
    logits: Optional[Tuple[torch.FloatTensor]] = None
237
238
239
    beam_indices: Optional[torch.LongTensor] = None
    attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
    hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
240
    past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
241
242
243


@dataclass
244
class GenerateBeamEncoderDecoderOutput(ModelOutput):
245
    """
246
    Outputs of encoder-decoder generation models, when using beam methods.
247
248
249
250
251
252
253
254
255
256
257
258

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
            Final beam scores of the generated `sequences`.
        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
            Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting
            of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
            Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
            with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
259
260
261
262
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True` is passed or when `config.output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
263
        beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True` is passed or when `config.output_scores=True`):
264
            Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
265
            `(batch_size*num_return_sequences, sequence_length)`.
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
        encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer of the decoder) of shape `(batch_size, num_heads,
            sequence_length, sequence_length)`.
        encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size*num_beams*num_return_sequences, sequence_length, hidden_size)`.
        decoder_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, num_heads, generated_length,
            sequence_length)`.
        cross_attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True` is passed or `config.output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        decoder_hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`.
282
283
284
285
286
287
288
        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            NOTE: some models have a different `past_key_values` format, confirm with the model's documentation.
            Usually a Tuple (one element for each layer of the decoder) of tuples (two elements, key tensor and value
            tensor). The first Tuple is of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if
            `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,
            encoder_sequence_length, embed_size_per_head)`.
289
290
291
292
293
    """

    sequences: torch.LongTensor = None
    sequences_scores: Optional[torch.FloatTensor] = None
    scores: Optional[Tuple[torch.FloatTensor]] = None
294
    logits: Optional[Tuple[torch.FloatTensor]] = None
295
296
297
298
299
300
    beam_indices: Optional[torch.LongTensor] = None
    encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
    encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
    decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
    cross_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
    decoder_hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
301
    past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None
302
303


304
305
306
307
# Equivalent classes (kept for retrocompatibility purposes)
GreedySearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
ContrastiveSearchDecoderOnlyOutput = GenerateDecoderOnlyOutput
SampleDecoderOnlyOutput = GenerateDecoderOnlyOutput
308

309
310
311
ContrastiveSearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
GreedySearchEncoderDecoderOutput = GenerateEncoderDecoderOutput
SampleEncoderDecoderOutput = GenerateEncoderDecoderOutput
312

313
314
BeamSearchDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
BeamSampleDecoderOnlyOutput = GenerateBeamDecoderOnlyOutput
315

316
317
BeamSearchEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
BeamSampleEncoderDecoderOutput = GenerateBeamEncoderDecoderOutput
318

319
320
321
322
323
GreedySearchOutput = Union[GreedySearchEncoderDecoderOutput, GreedySearchDecoderOnlyOutput]
SampleOutput = Union[SampleEncoderDecoderOutput, SampleDecoderOnlyOutput]
BeamSearchOutput = Union[BeamSearchEncoderDecoderOutput, BeamSearchDecoderOnlyOutput]
BeamSampleOutput = Union[BeamSampleEncoderDecoderOutput, BeamSampleDecoderOnlyOutput]
ContrastiveSearchOutput = Union[ContrastiveSearchEncoderDecoderOutput, ContrastiveSearchDecoderOnlyOutput]
324

325
326
327
328
# Typing shortcuts
GenerateNonBeamOutput = Union[GenerateDecoderOnlyOutput, GenerateEncoderDecoderOutput]
GenerateBeamOutput = Union[GenerateBeamDecoderOnlyOutput, GenerateBeamEncoderDecoderOutput]
GenerateOutput = Union[GenerateNonBeamOutput, GenerateBeamOutput]
329
330
331
332
333
334
335


class GenerationMixin:
    """
    A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].

    The class exposes [`~generation.GenerationMixin.generate`], which can be used for:
336
337
338
339
340
341
342
343
344
345
        - *greedy decoding* if `num_beams=1` and `do_sample=False`
        - *contrastive search* if `penalty_alpha>0` and `top_k>1`
        - *multinomial sampling* if `num_beams=1` and `do_sample=True`
        - *beam-search decoding* if `num_beams>1` and `do_sample=False`
        - *beam-search multinomial sampling* if `num_beams>1` and `do_sample=True`
        - *diverse beam-search decoding* if `num_beams>1` and `num_beam_groups>1`
        - *constrained beam-search decoding* if `constraints!=None` or `force_words_ids!=None`
        - *assisted decoding* if `assistant_model` or `prompt_lookup_num_tokens` is passed to `.generate()`

    To learn more about decoding strategies refer to the [text generation strategies guide](../generation_strategies).
346
347
    """

348
349
    def prepare_inputs_for_generation(self, *args, **kwargs):
        raise NotImplementedError(
350
            "A model class needs to define a `prepare_inputs_for_generation` method in order to use `.generate()`."
351
352
        )

353
354
355
    def _prepare_model_inputs(
        self,
        inputs: Optional[torch.Tensor] = None,
356
        bos_token_id: Optional[torch.Tensor] = None,
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
        model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
    ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:
        """
        This function extracts the model-specific `inputs` for generation.
        """
        # 1. retrieve all kwargs that are non-None or non-model input related.
        # some encoder-decoder models have different names for model and encoder
        if (
            self.config.is_encoder_decoder
            and hasattr(self, "encoder")
            and self.encoder.main_input_name != self.main_input_name
        ):
            input_name = self.encoder.main_input_name
        else:
            input_name = self.main_input_name

        model_kwargs = {k: v for k, v in model_kwargs.items() if v is not None or k != input_name}

        # 2. check whether model_input_name is passed as kwarg
        # if yes and `inputs` is None use kwarg inputs
        inputs_kwarg = model_kwargs.pop(input_name, None)
        if inputs_kwarg is not None and inputs is not None:
            raise ValueError(
380
                f"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. "
381
382
383
384
385
                f"Make sure to either pass {inputs} or {input_name}=..."
            )
        elif inputs_kwarg is not None:
            inputs = inputs_kwarg

386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
        # 3. In the presence of `inputs_embeds` for text models:
        # - decoder-only models should complain if the user attempts to pass `inputs_embeds`, but the model
        # doesn't have its forwarding implemented. `inputs_embeds` is kept in `model_kwargs` and can coexist with
        # input_ids (`inputs_embeds` will be used in the 1st generation step, as opposed to `input_ids`)
        # - encoder-decoder models should complain if the user attempts to pass `inputs_embeds` and `input_ids`, and
        # pull the former to inputs. It will be used in place of `input_ids` to get the encoder hidden states.
        if input_name == "input_ids" and "inputs_embeds" in model_kwargs:
            if not self.config.is_encoder_decoder:
                has_inputs_embeds_forwarding = "inputs_embeds" in set(
                    inspect.signature(self.prepare_inputs_for_generation).parameters.keys()
                )
                if not has_inputs_embeds_forwarding:
                    raise ValueError(
                        f"You passed `inputs_embeds` to `.generate()`, but the model class {self.__class__.__name__} "
                        "doesn't have its forwarding implemented. See the GPT2 implementation for an example "
                        "(https://github.com/huggingface/transformers/pull/21405), and feel free to open a PR with it!"
                    )
403
404
405
                # In this case, `input_ids` is moved to the `model_kwargs`, so a few automations (like the creation of
                # the attention mask) can rely on the actual model input.
                model_kwargs["input_ids"] = self._maybe_initialize_input_ids_for_generation(
406
                    inputs, bos_token_id, model_kwargs=model_kwargs
407
                )
408
409
410
            else:
                if inputs is not None:
                    raise ValueError("You passed `inputs_embeds` and `input_ids` to `.generate()`. Please pick one.")
411
            inputs, input_name = model_kwargs["inputs_embeds"], "inputs_embeds"
412
413

        # 4. if `inputs` is still None, try to create `input_ids` from BOS token
414
        inputs = self._maybe_initialize_input_ids_for_generation(inputs, bos_token_id, model_kwargs)
415
416
        return inputs, input_name, model_kwargs

417
418
419
    def _maybe_initialize_input_ids_for_generation(
        self,
        inputs: Optional[torch.Tensor] = None,
420
        bos_token_id: Optional[torch.Tensor] = None,
421
        model_kwargs: Optional[Dict[str, torch.Tensor]] = None,
422
    ) -> torch.LongTensor:
423
424
425
426
        """Initializes input ids for generation, if necessary."""
        if inputs is not None:
            return inputs

427
        encoder_outputs = model_kwargs.get("encoder_outputs")
428
429
430
431
432
        if self.config.is_encoder_decoder and encoder_outputs is not None:
            # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding
            shape = encoder_outputs.last_hidden_state.size()[:-1]
            return torch.ones(shape, dtype=torch.long, device=self.device) * -100

433
434
435
436
437
438
439
        # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with
        # soft-prompting or in multimodal implementations built on top of decoder-only language models.
        batch_size = 1
        for value in model_kwargs.values():
            if isinstance(value, torch.Tensor):
                batch_size = value.shape[0]
                break
440
441
442

        if "inputs_embeds" in model_kwargs:
            return torch.ones((batch_size, 0), dtype=torch.long, device=self.device)
443
444
445
446

        if bos_token_id is None:
            raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.")

447
        return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id
448
449
450
451

    def _prepare_attention_mask_for_generation(
        self,
        inputs: torch.Tensor,
452
453
        pad_token_id: Optional[torch.Tensor],
        eos_token_id: Optional[torch.Tensor],
454
    ) -> torch.LongTensor:
455
456
457
458
459
        # No information for attention mask inference -> return default attention mask
        default_attention_mask = torch.ones(inputs.shape[:2], dtype=torch.long, device=inputs.device)
        if pad_token_id is None:
            return default_attention_mask

460
        is_input_ids = len(inputs.shape) == 2 and inputs.dtype in [torch.int, torch.long]
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
        if not is_input_ids:
            return default_attention_mask

        # Otherwise we have may have information -> try to infer the attention mask
        if inputs.device.type == "mps":
            # mps does not support torch.isin (https://github.com/pytorch/pytorch/issues/77764)
            raise ValueError(
                "Can't infer missing attention mask on `mps` device. Please provide an `attention_mask` or use a different device."
            )

        is_pad_token_in_inputs = (pad_token_id is not None) and (
            torch.isin(elements=inputs, test_elements=pad_token_id).any()
        )
        is_pad_token_not_equal_to_eos_token_id = (eos_token_id is None) or ~(
            torch.isin(elements=eos_token_id, test_elements=pad_token_id).any()
        )
        can_infer_attention_mask = is_pad_token_in_inputs * is_pad_token_not_equal_to_eos_token_id
        attention_mask_from_padding = inputs.ne(pad_token_id).long()
        attention_mask = (
            attention_mask_from_padding * can_infer_attention_mask + default_attention_mask * ~can_infer_attention_mask
        )
        return attention_mask
483
484

    def _prepare_encoder_decoder_kwargs_for_generation(
485
486
487
488
489
        self,
        inputs_tensor: torch.Tensor,
        model_kwargs,
        model_input_name: Optional[str],
        generation_config: GenerationConfig,
490
491
492
    ) -> Dict[str, Any]:
        # 1. get encoder
        encoder = self.get_encoder()
493
494
        # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device
        # as the inputs.
Marc Sun's avatar
Marc Sun committed
495
496
497
498
499
        if hasattr(self, "hf_device_map"):
            if hasattr(encoder, "_hf_hook"):
                encoder._hf_hook.io_same_device = True
            else:
                add_hook_to_module(encoder, AlignDevicesHook(io_same_device=True))
500

501
        # 2. Prepare encoder args and encoder kwargs from model kwargs and generation config.
502
503
504
505
506
507
        irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"]
        encoder_kwargs = {
            argument: value
            for argument, value in model_kwargs.items()
            if not any(argument.startswith(p) for p in irrelevant_prefix)
        }
508
509
510
511
512
513
        encoder_signature = set(inspect.signature(encoder.forward).parameters)
        encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature
        if not encoder_accepts_wildcard:
            encoder_kwargs = {
                argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature
            }
514
515
        encoder_kwargs["output_attentions"] = generation_config.output_attentions
        encoder_kwargs["output_hidden_states"] = generation_config.output_hidden_states
516
517
518
519
520
521
522
523
524
525
526
527

        # 3. make sure that encoder returns `ModelOutput`
        model_input_name = model_input_name if model_input_name is not None else self.main_input_name
        encoder_kwargs["return_dict"] = True
        encoder_kwargs[model_input_name] = inputs_tensor
        model_kwargs["encoder_outputs"]: ModelOutput = encoder(**encoder_kwargs)

        return model_kwargs

    def _prepare_decoder_input_ids_for_generation(
        self,
        batch_size: int,
528
529
        model_input_name: str,
        model_kwargs: Dict[str, torch.Tensor],
530
        decoder_start_token_id: torch.Tensor,
531
        device: torch.device = None,
532
533
534
535
    ) -> Tuple[torch.LongTensor, Dict[str, torch.Tensor]]:
        """Prepares `decoder_input_ids` for generation with encoder-decoder models"""
        # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming,
        # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input.
536
        if model_kwargs is not None and "decoder_input_ids" in model_kwargs:
537
538
539
            decoder_input_ids = model_kwargs.pop("decoder_input_ids")
        elif "input_ids" in model_kwargs and model_input_name != "input_ids":
            decoder_input_ids = model_kwargs.pop("input_ids")
540
        else:
541
542
            decoder_input_ids = None

543
        # 2. `decoder_start_token_id` must have shape (batch_size, 1)
544
545
        if device is None:
            device = self.device
546
547
        if decoder_start_token_id.ndim == 1:
            if decoder_start_token_id.shape[0] != batch_size:
548
                raise ValueError(
549
                    f"`decoder_start_token_id` expected to have length {batch_size} but got {decoder_start_token_id.shape[0]}"
550
                )
551
            decoder_start_token_id = decoder_start_token_id.view(-1, 1)
552
        else:
553
            decoder_start_token_id = (
554
555
                torch.ones((batch_size, 1), dtype=torch.long, device=device) * decoder_start_token_id
            )
556

557
        # 3. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that.
558
559
        # no user input -> use decoder_start_token_id as decoder_input_ids
        if decoder_input_ids is None:
560
            decoder_input_ids = decoder_start_token_id
561
562
563
        # exception: Donut checkpoints have task-specific decoder starts and don't expect a BOS token
        elif self.config.model_type == "vision-encoder-decoder" and "donut" in self.name_or_path.lower():
            pass
564
565
        elif self.config.model_type in ["whisper"]:
            pass
566
567
        # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust
        # decoder_attention_mask if provided)
568
569
        elif (decoder_input_ids[:, 0] != decoder_start_token_id[:, 0]).all().item():
            decoder_input_ids = torch.cat([decoder_start_token_id, decoder_input_ids], dim=-1)
570
571
572
573
574
575
576
577
578
            if "decoder_attention_mask" in model_kwargs:
                decoder_attention_mask = model_kwargs["decoder_attention_mask"]
                decoder_attention_mask = torch.cat(
                    (torch.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask),
                    dim=-1,
                )
                model_kwargs["decoder_attention_mask"] = decoder_attention_mask

        return decoder_input_ids, model_kwargs
579
580
581
582
583
584
585
586
587

    @staticmethod
    def _expand_inputs_for_generation(
        expand_size: int = 1,
        is_encoder_decoder: bool = False,
        input_ids: Optional[torch.LongTensor] = None,
        **model_kwargs,
    ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
        """Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
588
589
590

        def _expand_dict_for_generation(dict_to_expand):
            for key in dict_to_expand:
tomeras91's avatar
tomeras91 committed
591
592
593
594
595
                if (
                    key != "cache_position"
                    and dict_to_expand[key] is not None
                    and isinstance(dict_to_expand[key], torch.Tensor)
                ):
596
597
598
                    dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
            return dict_to_expand

599
600
601
        if input_ids is not None:
            input_ids = input_ids.repeat_interleave(expand_size, dim=0)

602
        model_kwargs = _expand_dict_for_generation(model_kwargs)
603
604

        if is_encoder_decoder:
605
            if model_kwargs.get("encoder_outputs") is None:
606
                raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
607
            model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
608
609
610

        return input_ids, model_kwargs

611
    def _extract_past_from_model_output(self, outputs: ModelOutput, standardize_cache_format: bool = False):
612
        past_key_values = None
613
        if "past_key_values" in outputs:
614
            past_key_values = outputs.past_key_values
615
        elif "mems" in outputs:
616
            past_key_values = outputs.mems
617
        elif "past_buckets_states" in outputs:
618
            past_key_values = outputs.past_buckets_states
619
620
621
622

        # Bloom fix: standardizes the cache format when requested
        if standardize_cache_format and hasattr(self, "_convert_to_standard_cache"):
            batch_size = outputs.logits.shape[0]
623
624
            past_key_values = self._convert_to_standard_cache(past_key_values, batch_size=batch_size)
        return past_key_values
625
626

    def _update_model_kwargs_for_generation(
627
628
629
630
631
        self,
        outputs: ModelOutput,
        model_kwargs: Dict[str, Any],
        is_encoder_decoder: bool = False,
        standardize_cache_format: bool = False,
632
        num_new_tokens: int = 1,
633
    ) -> Dict[str, Any]:
634
635
        # update past_key_values
        model_kwargs["past_key_values"] = self._extract_past_from_model_output(
636
637
            outputs, standardize_cache_format=standardize_cache_format
        )
Sylvain Gugger's avatar
Sylvain Gugger committed
638
639
        if getattr(outputs, "state", None) is not None:
            model_kwargs["state"] = outputs.state
640
641
642
643
644
645
646

        # update token_type_ids with last value
        if "token_type_ids" in model_kwargs:
            token_type_ids = model_kwargs["token_type_ids"]
            model_kwargs["token_type_ids"] = torch.cat([token_type_ids, token_type_ids[:, -1].unsqueeze(-1)], dim=-1)

        if not is_encoder_decoder:
647
            # update attention mask
648
649
650
651
652
            if "attention_mask" in model_kwargs:
                attention_mask = model_kwargs["attention_mask"]
                model_kwargs["attention_mask"] = torch.cat(
                    [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
                )
653
654
655
656
657
658
659
660
        else:
            # update decoder attention mask
            if "decoder_attention_mask" in model_kwargs:
                decoder_attention_mask = model_kwargs["decoder_attention_mask"]
                model_kwargs["decoder_attention_mask"] = torch.cat(
                    [decoder_attention_mask, decoder_attention_mask.new_ones((decoder_attention_mask.shape[0], 1))],
                    dim=-1,
                )
661

662
663
664
665
666
        if (
            model_kwargs.get("use_cache", True)
            and "cache_position" in model_kwargs
            and model_kwargs["cache_position"] is not None
        ):
667
            model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
668

669
670
        return model_kwargs

671
    def _reorder_cache(self, past_key_values, beam_idx):
672
673
674
675
676
        raise NotImplementedError(
            f"Make sure that a `_reorder_cache` function is correctly implemented in {self.__class__.__module__} to"
            f" enable beam search for {self.__class__}"
        )

677
678
679
680
681
682
683
684
685
686
687
688
    def _get_candidate_generator(
        self,
        generation_config: GenerationConfig,
        input_ids: torch.LongTensor,
        inputs_tensor: torch.Tensor,
        assistant_model: "PreTrainedModel",
        logits_processor: LogitsProcessorList,
        model_kwargs: Dict,
    ) -> CandidateGenerator:
        """
        Returns the candidate generator to be used in `assisted_generation`
        """
689
690
691
        if generation_config.prompt_lookup_num_tokens is not None:
            candidate_generator = PromptLookupCandidateGenerator(
                num_output_tokens=generation_config.prompt_lookup_num_tokens,
692
                max_matching_ngram_size=generation_config.max_matching_ngram_size,
693
                max_length=generation_config.max_length,
694
695
696
697
698
699
700
701
            )
        else:
            candidate_generator = AssistedCandidateGenerator(
                input_ids=input_ids,
                assistant_model=assistant_model,
                generation_config=generation_config,
                model_kwargs=model_kwargs,
                inputs_tensor=inputs_tensor,
702
                logits_processor=logits_processor,
703
            )
704
705
        return candidate_generator

706
707
    def _get_logits_warper(
        self,
708
        generation_config: GenerationConfig,
709
710
711
712
713
714
715
716
717
    ) -> LogitsProcessorList:
        """
        This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`] instances
        used for multinomial sampling.
        """

        # instantiate warpers list
        warpers = LogitsProcessorList()

718
719
720
721
722
        # In beam methods, we need to keep at least one non-eos token to explore continuations that might have a
        # better score (i.e. keep len(list(generation_config.eos_token_id)) + 1)
        if generation_config.num_beams > 1:
            if isinstance(generation_config.eos_token_id, list):
                min_tokens_to_keep = len(generation_config.eos_token_id) + 1
723
724
            elif isinstance(generation_config.eos_token_id, torch.Tensor):
                min_tokens_to_keep = generation_config.eos_token_id.shape[0] + 1
725
726
727
728
729
            else:
                min_tokens_to_keep = 2
        else:
            min_tokens_to_keep = 1

730
731
        # the following idea is largely copied from this PR: https://github.com/huggingface/transformers/pull/5420/files
        # all samplers can be found in `generation_utils_samplers.py`
732
733
734
        if generation_config.temperature is not None and generation_config.temperature != 1.0:
            warpers.append(TemperatureLogitsWarper(generation_config.temperature))
        if generation_config.top_k is not None and generation_config.top_k != 0:
735
736
737
            warpers.append(TopKLogitsWarper(top_k=generation_config.top_k, min_tokens_to_keep=min_tokens_to_keep))
        if generation_config.top_p is not None and generation_config.top_p < 1.0:
            warpers.append(TopPLogitsWarper(top_p=generation_config.top_p, min_tokens_to_keep=min_tokens_to_keep))
738
739
740
        if generation_config.min_p is not None:
            # Applied after temperature scaling (see https://github.com/ggerganov/llama.cpp/pull/3841#issuecomment-2073826084)
            warpers.append(MinPLogitsWarper(min_p=generation_config.min_p, min_tokens_to_keep=min_tokens_to_keep))
741
        if generation_config.typical_p is not None and generation_config.typical_p < 1.0:
742
            warpers.append(
743
                TypicalLogitsWarper(mass=generation_config.typical_p, min_tokens_to_keep=min_tokens_to_keep)
744
            )
745
        if generation_config.epsilon_cutoff is not None and 0.0 < generation_config.epsilon_cutoff < 1.0:
746
            warpers.append(
747
                EpsilonLogitsWarper(epsilon=generation_config.epsilon_cutoff, min_tokens_to_keep=min_tokens_to_keep)
748
            )
749
        if generation_config.eta_cutoff is not None and 0.0 < generation_config.eta_cutoff < 1.0:
750
            warpers.append(
751
                EtaLogitsWarper(epsilon=generation_config.eta_cutoff, min_tokens_to_keep=min_tokens_to_keep)
752
            )
753
        # `LogitNormalization` should always be the last logit processor, when present
754
        if generation_config.renormalize_logits is True:
755
756
757
758
759
            warpers.append(LogitNormalization())
        return warpers

    def _get_logits_processor(
        self,
760
        generation_config: GenerationConfig,
761
762
763
764
        input_ids_seq_length: int,
        encoder_input_ids: torch.LongTensor,
        prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]],
        logits_processor: Optional[LogitsProcessorList],
765
766
767
        model_kwargs: Optional[Dict[str, Any]] = None,
        negative_prompt_ids: Optional[torch.Tensor] = None,
        negative_prompt_attention_mask: Optional[torch.Tensor] = None,
768
769
770
771
772
773
    ) -> LogitsProcessorList:
        """
        This class returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsProcessor`]
        instances used to modify the scores of the language model head.
        """
        # instantiate processors list
774
        processors = LogitsProcessorList()
775

776
        if generation_config.guidance_scale is not None and generation_config.guidance_scale != 1:
777
778
779
780
781
782
783
784
785
            processors.append(
                UnbatchedClassifierFreeGuidanceLogitsProcessor(
                    generation_config.guidance_scale,
                    self,
                    unconditional_ids=negative_prompt_ids,
                    unconditional_attention_mask=negative_prompt_attention_mask,
                    use_cache=model_kwargs["use_cache"],
                )
            )
786
787
788
        if generation_config.sequence_bias is not None:
            processors.append(SequenceBiasLogitsProcessor(sequence_bias=generation_config.sequence_bias))

789
        if generation_config.diversity_penalty is not None and generation_config.diversity_penalty > 0.0:
790
791
            processors.append(
                HammingDiversityLogitsProcessor(
792
793
794
                    diversity_penalty=generation_config.diversity_penalty,
                    num_beams=generation_config.num_beams,
                    num_beam_groups=generation_config.num_beam_groups,
795
796
                )
            )
Karim Foda's avatar
Karim Foda committed
797
798
799
800
801
802
803
804
805
        if (
            generation_config.encoder_repetition_penalty is not None
            and generation_config.encoder_repetition_penalty != 1.0
        ):
            processors.append(
                EncoderRepetitionPenaltyLogitsProcessor(
                    penalty=generation_config.encoder_repetition_penalty, encoder_input_ids=encoder_input_ids
                )
            )
806
807
808
809
810
811
812
813
        if generation_config.repetition_penalty is not None and generation_config.repetition_penalty != 1.0:
            processors.append(RepetitionPenaltyLogitsProcessor(penalty=generation_config.repetition_penalty))
        if generation_config.no_repeat_ngram_size is not None and generation_config.no_repeat_ngram_size > 0:
            processors.append(NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size))
        if (
            generation_config.encoder_no_repeat_ngram_size is not None
            and generation_config.encoder_no_repeat_ngram_size > 0
        ):
814
815
816
            processors.append(
                EncoderNoRepeatNGramLogitsProcessor(generation_config.encoder_no_repeat_ngram_size, encoder_input_ids)
            )
817
818
819
820
821
822
823
824
825
826
        if generation_config.bad_words_ids is not None:
            processors.append(
                NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)
            )
        if (
            generation_config.min_length is not None
            and generation_config.eos_token_id is not None
            and generation_config.min_length > 0
        ):
            processors.append(MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id))
827
828
829
830
831
832
833
834
835
836
        if (
            generation_config.min_new_tokens is not None
            and generation_config.eos_token_id is not None
            and generation_config.min_new_tokens > 0
        ):
            processors.append(
                MinNewTokensLengthLogitsProcessor(
                    input_ids_seq_length, generation_config.min_new_tokens, generation_config.eos_token_id
                )
            )
837
        if prefix_allowed_tokens_fn is not None:
838
839
840
841
842
843
844
845
846
847
848
849
            processors.append(
                PrefixConstrainedLogitsProcessor(
                    prefix_allowed_tokens_fn, generation_config.num_beams // generation_config.num_beam_groups
                )
            )
        if generation_config.forced_bos_token_id is not None:
            processors.append(ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id))
        if generation_config.forced_eos_token_id is not None:
            processors.append(
                ForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id)
            )
        if generation_config.remove_invalid_values is True:
850
            processors.append(InfNanRemoveLogitsProcessor())
851
        if generation_config.exponential_decay_length_penalty is not None:
852
            processors.append(
853
854
855
                ExponentialDecayLengthPenalty(
                    generation_config.exponential_decay_length_penalty,
                    generation_config.eos_token_id,
856
                    input_ids_seq_length,
857
                )
858
            )
859
860
861
        if generation_config.suppress_tokens is not None:
            processors.append(SuppressTokensLogitsProcessor(generation_config.suppress_tokens))
        if generation_config.begin_suppress_tokens is not None:
862
            begin_index = input_ids_seq_length
863
864
865
866
867
868
869
870
871
872
873
874
            begin_index = (
                begin_index
                if (input_ids_seq_length > 1 or generation_config.forced_bos_token_id is None)
                else begin_index + 1
            )
            if generation_config.forced_decoder_ids is not None:
                # generation starts after the last token that is forced
                begin_index += generation_config.forced_decoder_ids[-1][0]
            processors.append(
                SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)
            )
        if generation_config.forced_decoder_ids is not None:
875
876
877
878
879
880
            # TODO(Sanchit): deprecate in v4.40 by removing this logic
            warnings.warn(
                "You have explicitly specified `forced_decoder_ids`. This functionality has been deprecated and will throw an error in v4.40. Please remove the `forced_decoder_ids` argument in favour of `input_ids` or `decoder_input_ids` respectively.",
                FutureWarning,
            )
            processors.append(ForceTokensLogitsProcessor(generation_config.forced_decoder_ids, _has_warned=True))
881
882
        processors = self._merge_criteria_processor_list(processors, logits_processor)
        # `LogitNormalization` should always be the last logit processor, when present
883
        if generation_config.renormalize_logits is True:
884
885
886
887
            processors.append(LogitNormalization())
        return processors

    def _get_stopping_criteria(
888
889
890
891
892
        self,
        generation_config: GenerationConfig,
        stopping_criteria: Optional[StoppingCriteriaList],
        tokenizer: Optional["PreTrainedTokenizerBase"] = None,
        **kwargs,
893
894
    ) -> StoppingCriteriaList:
        criteria = StoppingCriteriaList()
895
        if generation_config.max_length is not None:
896
897
898
899
900
901
902
            max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
            criteria.append(
                MaxLengthCriteria(
                    max_length=generation_config.max_length,
                    max_position_embeddings=max_position_embeddings,
                )
            )
903
904
        if generation_config.max_time is not None:
            criteria.append(MaxTimeCriteria(max_time=generation_config.max_time))
905
906
907
908
909
910
911
912
        if generation_config.stop_strings is not None:
            if tokenizer is None:
                raise ValueError(
                    "There are one or more stop strings, either in the arguments to `generate` or in the "
                    "model's generation config, but we could not locate a tokenizer. When generating with "
                    "stop strings, you must pass the model's tokenizer to the `tokenizer` argument of `generate`."
                )
            criteria.append(StopStringCriteria(stop_strings=generation_config.stop_strings, tokenizer=tokenizer))
913
914
        if generation_config.eos_token_id is not None:
            criteria.append(EosTokenCriteria(eos_token_id=generation_config.eos_token_id))
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
        criteria = self._merge_criteria_processor_list(criteria, stopping_criteria)
        return criteria

    def _merge_criteria_processor_list(
        self,
        default_list: Union[LogitsProcessorList, StoppingCriteriaList],
        custom_list: Union[LogitsProcessorList, StoppingCriteriaList],
    ) -> Union[LogitsProcessorList, StoppingCriteriaList]:
        if len(custom_list) == 0:
            return default_list
        for default in default_list:
            for custom in custom_list:
                if type(custom) is type(default):
                    object_type = "stopping criteria" if isinstance(custom, StoppingCriteria) else "logits processor"
                    raise ValueError(
                        f"A custom {object_type} of type {type(custom)} with values {custom} has been passed to"
931
                        f" `.generate()`, but it has already been created with the values {default}. {default} has been"
932
933
                        " created by passing the corresponding arguments to generate or by the model's config default"
                        f" values. If you just want to change the default values of {object_type} consider passing"
934
                        f" them as arguments to `.generate()` instead of using a custom {object_type}."
935
936
937
938
                    )
        default_list.extend(custom_list)
        return default_list

939
    def compute_transition_scores(
940
941
942
        self,
        sequences: torch.Tensor,
        scores: Tuple[torch.Tensor],
943
944
945
946
947
948
949
950
951
952
953
954
955
        beam_indices: Optional[torch.Tensor] = None,
        normalize_logits: bool = False,
    ) -> torch.Tensor:
        """
        Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
        used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.

        Parameters:
            sequences (`torch.LongTensor`):
                The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or
                shorter if all batches finished early due to the `eos_token_id`.
            scores (`tuple(torch.FloatTensor)`):
                Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
956
957
958
                of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam.
                Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token),
                with each tensor of shape `(batch_size*num_beams, config.vocab_size)`.
959
            beam_indices (`torch.LongTensor`, *optional*):
960
                Beam indices of generated token id at each generation step. `torch.LongTensor` of shape
961
                `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
                generate-time.
            normalize_logits (`bool`, *optional*, defaults to `False`):
                Whether to normalize the logits (which, for legacy reasons, may be unnormalized).

        Return:
            `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length)` containing
                the transition scores (logits)

        Examples:

        ```python
        >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
        >>> import numpy as np

        >>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
977
        >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
978
979
980
981
982
983
984
985
        >>> tokenizer.pad_token_id = tokenizer.eos_token_id
        >>> inputs = tokenizer(["Today is"], return_tensors="pt")

        >>> # Example 1: Print the scores for each token generated with Greedy Search
        >>> outputs = model.generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
        >>> transition_scores = model.compute_transition_scores(
        ...     outputs.sequences, outputs.scores, normalize_logits=True
        ... )
986
987
988
        >>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
        >>> # encoder-decoder models, like BART or T5.
        >>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
989
990
        >>> generated_tokens = outputs.sequences[:, input_length:]
        >>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
991
        ...     # | token | token string | log probability | probability
992
993
994
995
996
997
        ...     print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
        |   262 |  the     | -1.414 | 24.33%
        |  1110 |  day     | -2.609 | 7.36%
        |   618 |  when    | -2.010 | 13.40%
        |   356 |  we      | -1.859 | 15.58%
        |   460 |  can     | -2.508 | 8.14%
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011

        >>> # Example 2: Reconstruct the sequence scores from Beam Search
        >>> outputs = model.generate(
        ...     **inputs,
        ...     max_new_tokens=5,
        ...     num_beams=4,
        ...     num_return_sequences=4,
        ...     return_dict_in_generate=True,
        ...     output_scores=True,
        ... )
        >>> transition_scores = model.compute_transition_scores(
        ...     outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
        ... )
        >>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
1012
        >>> # Tip 1: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
1013
        >>> # use case, you might want to recompute it with `normalize_logits=True`.
1014
1015
        >>> # Tip 2: the output length does NOT include the input length
        >>> output_length = np.sum(transition_scores.numpy() < 0, axis=1)
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
        >>> length_penalty = model.generation_config.length_penalty
        >>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
        >>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
        True
        ```"""
        # 1. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent
        # to a beam search approach were the first (and only) beam is always selected
        if beam_indices is None:
            beam_indices = torch.arange(scores[0].shape[0]).view(-1, 1).to(sequences.device)
            beam_indices = beam_indices.expand(-1, len(scores))

        # 2. reshape scores as [batch_size*vocab_size, # generation steps] with # generation steps being
1028
1029
1030
        # seq_len - input_length
        scores = torch.stack(scores).reshape(len(scores), -1).transpose(0, 1)

1031
1032
1033
1034
1035
1036
1037
        # 3. Optionally normalize the logits (across the vocab dimension)
        if normalize_logits:
            scores = scores.reshape(-1, self.config.vocab_size, scores.shape[-1])
            scores = torch.nn.functional.log_softmax(scores, dim=1)
            scores = scores.reshape(-1, scores.shape[-1])

        # 4. cut beam_indices to longest beam length
1038
1039
        beam_indices_mask = beam_indices < 0
        max_beam_length = (1 - beam_indices_mask.long()).sum(-1).max()
1040
        beam_indices = beam_indices.clone()[:, :max_beam_length]
1041
1042
        beam_indices_mask = beam_indices_mask[:, :max_beam_length]

1043
        # 5. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards
1044
1045
        beam_indices[beam_indices_mask] = 0

1046
        # 6. multiply beam_indices with vocab size to gather correctly from scores
1047
1048
        beam_sequence_indices = beam_indices * self.config.vocab_size

1049
        # 7. Define which indices contributed to scores
1050
1051
1052
        cut_idx = sequences.shape[-1] - max_beam_length
        indices = sequences[:, cut_idx:] + beam_sequence_indices

1053
        # 8. Compute scores
1054
1055
        transition_scores = scores.gather(0, indices)

1056
        # 9. Mask out transition_scores of beams that stopped early
1057
1058
1059
1060
1061
1062
1063
1064
1065
        transition_scores[beam_indices_mask] = 0

        return transition_scores

    def _validate_model_class(self):
        """
        Confirms that the model class is compatible with generation. If not, raises an exception that points to the
        right class to use.
        """
1066
        if not self.can_generate():
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
            generate_compatible_mappings = [
                MODEL_FOR_CAUSAL_LM_MAPPING,
                MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING,
                MODEL_FOR_VISION_2_SEQ_MAPPING,
                MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
                MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING,
            ]
            generate_compatible_classes = set()
            for model_mapping in generate_compatible_mappings:
                supported_models = model_mapping.get(type(self.config), default=None)
                if supported_models is not None:
                    generate_compatible_classes.add(supported_models.__name__)
            exception_message = (
                f"The current model class ({self.__class__.__name__}) is not compatible with `.generate()`, as "
                "it doesn't have a language model head."
            )
            if generate_compatible_classes:
                exception_message += f" Please use one of the following classes instead: {generate_compatible_classes}"
            raise TypeError(exception_message)

    def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
        """Validates model kwargs for generation. Generate argument typos will also be caught here."""
1089
1090
1091
1092
1093
1094
1095
        # If a `Cache` instance is passed, checks whether the model is compatible with it
        if isinstance(model_kwargs.get("past_key_values", None), Cache) and not self._supports_cache_class:
            raise ValueError(
                f"{self.__class__.__name__} does not support an instance of `Cache` as `past_key_values`. Please "
                "check the model documentation for supported cache formats."
            )

1096
1097
1098
1099
1100
1101
1102
        # Excludes arguments that are handled before calling any model function
        if self.config.is_encoder_decoder:
            for key in ["decoder_input_ids"]:
                model_kwargs.pop(key, None)

        unused_model_args = []
        model_args = set(inspect.signature(self.prepare_inputs_for_generation).parameters)
1103
1104
1105
        # `kwargs`/`model_kwargs` is often used to handle optional forward pass inputs like `attention_mask`. If
        # `prepare_inputs_for_generation` doesn't accept them, then a stricter check can be made ;)
        if "kwargs" in model_args or "model_kwargs" in model_args:
1106
            model_args |= set(inspect.signature(self.forward).parameters)
1107
1108
1109
1110
1111
1112
1113

        # Encoder-Decoder models may also need Encoder arguments from `model_kwargs`
        if self.config.is_encoder_decoder:
            base_model = getattr(self, self.base_model_prefix, None)

            # allow encoder kwargs
            encoder = getattr(self, "encoder", None)
1114
1115
1116
1117
1118
            # `MusicgenForConditionalGeneration` has `text_encoder` and `audio_encoder`.
            # Also, it has `base_model_prefix = "encoder_decoder"` but there is no `self.encoder_decoder`
            # TODO: A better way to handle this.
            if encoder is None and base_model is not None:
                encoder = getattr(base_model, "encoder", None)
1119

1120
1121
1122
            if encoder is not None:
                encoder_model_args = set(inspect.signature(encoder.forward).parameters)
                model_args |= encoder_model_args
1123
1124
1125

            # allow decoder kwargs
            decoder = getattr(self, "decoder", None)
1126
1127
            if decoder is None and base_model is not None:
                decoder = getattr(base_model, "decoder", None)
1128

1129
1130
1131
            if decoder is not None:
                decoder_model_args = set(inspect.signature(decoder.forward).parameters)
                model_args |= {f"decoder_{x}" for x in decoder_model_args}
1132

1133
1134
1135
1136
            # allow assistant_encoder_outputs to be passed if we're doing assisted generating
            if "assistant_encoder_outputs" in model_kwargs:
                model_args |= {"assistant_encoder_outputs"}

1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
        for key, value in model_kwargs.items():
            if value is not None and key not in model_args:
                unused_model_args.append(key)

        if unused_model_args:
            raise ValueError(
                f"The following `model_kwargs` are not used by the model: {unused_model_args} (note: typos in the"
                " generate arguments will also show up in this list)"
            )

1147
1148
1149
1150
    def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
        """Performs validation related to the resulting generated length"""

        # 1. Max length warnings related to poor parameterization
1151
        if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
1152
1153
            # 20 is the default max_length of the generation config
            warnings.warn(
1154
                f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
1155
1156
1157
1158
1159
1160
                "generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
                "generation.",
                UserWarning,
            )
        if input_ids_length >= generation_config.max_length:
            input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
1161
            raise ValueError(
1162
1163
                f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
                f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
1164
                " increasing `max_length` or, better yet, setting `max_new_tokens`."
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
            )

        # 2. Min length warnings due to unfeasible parameter combinations
        min_length_error_suffix = (
            " Generation will stop at the defined maximum length. You should decrease the minimum length and/or "
            "increase the maximum length."
        )
        if has_default_max_length:
            min_length_error_suffix += (
                f" Note that `max_length` is set to {generation_config.max_length}, its default value."
            )
        if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length:
            warnings.warn(
                f"Unfeasible length constraints: `min_length` ({generation_config.min_length}) is larger than"
                f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
                UserWarning,
            )
        if generation_config.min_new_tokens is not None:
            min_length = generation_config.min_new_tokens + input_ids_length
            if min_length > generation_config.max_length:
                warnings.warn(
                    f"Unfeasible length constraints: `min_new_tokens` ({generation_config.min_new_tokens}), when "
                    f"added to the prompt length ({input_ids_length}), is larger than"
                    f" the maximum possible length ({generation_config.max_length})." + min_length_error_suffix,
                    UserWarning,
                )

1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
    def _prepare_generated_length(
        self,
        generation_config,
        has_default_max_length,
        has_default_min_length,
        model_input_name,
        input_ids_length,
        inputs_tensor,
    ):
        """Prepared max and min length in generaion configs to avoid clashes between similar attributes"""

        if generation_config.max_new_tokens is not None:
            if not has_default_max_length and generation_config.max_length is not None:
                logger.warning(
                    f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
                    f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
                    "Please refer to the documentation for more information. "
                    "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
                )
            generation_config.max_length = generation_config.max_new_tokens + input_ids_length

        # if both `inputs_embeds` and `input_ids` are passed, we do not correct the length
        # otherwise we need total length [inputs-embeds-len + new-tokens-len] to not go beyond indicated `max_length``
        elif (
            model_input_name == "inputs_embeds"
            and input_ids_length != inputs_tensor.shape[1]
            and not self.config.is_encoder_decoder
        ):
            generation_config.max_length -= inputs_tensor.shape[1]

        # same for min length
        if generation_config.min_new_tokens is not None:
            if not has_default_min_length:
                logger.warning(
                    f"Both `min_new_tokens` (={generation_config.min_new_tokens}) and `min_length`(="
                    f"{generation_config.min_length}) seem to have been set. `min_new_tokens` will take precedence. "
                    "Please refer to the documentation for more information. "
                    "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
                )
            generation_config.min_length = generation_config.min_new_tokens + input_ids_length

        elif (
            model_input_name == "inputs_embeds"
            and input_ids_length != inputs_tensor.shape[1]
            and not self.config.is_encoder_decoder
        ):
            generation_config.min_length = max(generation_config.min_length - inputs_tensor.shape[1], 0)

        return generation_config

1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
    def _prepare_generation_config(
        self, generation_config: GenerationConfig, **kwargs: Dict
    ) -> Tuple[GenerationConfig, Dict]:
        """
        Prepares the base generation config, then applies any generation configuration options from kwargs.
        """
        # TODO joao: when we can detect `fullgraph=True` in `torch.compile` (https://github.com/pytorch/pytorch/pull/120400)
        # replace `is_torchdynamo_compiling` by the corresponding check. As it is, we are being too restrictive with
        # the parameterization in `fullgraph=False` so as to enable `fullgraph=True`.

        # priority: `generation_config` argument > `model.generation_config` (the default generation config)
        if generation_config is None:
            # legacy: users may modify the model configuration to control generation. To trigger this legacy behavior,
            # three conditions must be met
            # 1) the generation config must have been created from the model config (`_from_model_config` field);
            # 2) the generation config must have seen no modification since its creation (the hash is the same);
            # 3) the user must have set generation parameters in the model config.
            # NOTE: `torch.compile` can't compile `hash`, this legacy support is disabled with compilation.
            if (
                not is_torchdynamo_compiling()
                and self.generation_config._from_model_config
                and self.generation_config._original_object_hash == hash(self.generation_config)
                and self.config._has_non_default_generation_parameters()
            ):
                new_generation_config = GenerationConfig.from_model_config(self.config)
                if new_generation_config != self.generation_config:
                    warnings.warn(
                        "You have modified the pretrained model configuration to control generation. This is a"
                        " deprecated strategy to control generation and will be removed soon, in a future version."
                        " Please use and modify the model generation configuration (see"
                        " https://huggingface.co/docs/transformers/generation_strategies#default-text-generation-configuration )"
                    )
                    self.generation_config = new_generation_config
            generation_config = self.generation_config

        # `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
        # will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled.
        if is_torchdynamo_compiling():
            model_kwargs = kwargs
            generate_attributes_in_kwargs = [
                key for key, value in kwargs.items() if getattr(generation_config, key, None) != value
            ]
            if len(generate_attributes_in_kwargs) > 0:
                raise ValueError(
                    "`torch.compile` exception: all generation configuration attributes must be passed within a "
                    f"`generation_config` instance passed to `generate` (found: {generate_attributes_in_kwargs})."
                )
        else:
            generation_config = copy.deepcopy(generation_config)
            model_kwargs = generation_config.update(**kwargs)

        return generation_config, model_kwargs

1295
1296
    def _get_initial_cache_position(self, input_ids, model_kwargs):
        """Calculates `cache_position` for the pre-fill stage based on `input_ids` and optionally past length"""
1297
1298
1299
1300
        if not model_kwargs.get("use_cache", True):
            model_kwargs["cache_position"] = None
            return model_kwargs

1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
        past_length = 0
        if "past_key_values" in model_kwargs:
            if isinstance(model_kwargs["past_key_values"], Cache):
                past_length = model_kwargs["past_key_values"].get_seq_length()
            else:
                past_length = model_kwargs["past_key_values"][0][0].shape[2]
        if "inputs_embeds" in model_kwargs:
            cur_len = model_kwargs["inputs_embeds"].shape[1]
        else:
            cur_len = input_ids.shape[-1]
        model_kwargs["cache_position"] = torch.arange(past_length, cur_len, device=input_ids.device)
        return model_kwargs

1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
    def _get_static_cache(self, max_batch_size: int, max_cache_len: int) -> StaticCache:
        """
        Sets a static cache for `generate`, that will persist across calls. A new cache will only be initialized a
        new `generate` call requires a larger cache.

        Returns the resulting static cache object.
        """
        needs_new_cache = (
            not hasattr(self, "_static_cache")
            or self._static_cache.max_batch_size < max_batch_size
            or self._static_cache.max_cache_len < max_cache_len
        )
        if needs_new_cache:
            if hasattr(self.config, "_pre_quantization_dtype"):
                cache_dtype = self.config._pre_quantization_dtype
            else:
                cache_dtype = self.dtype
            self._static_cache = StaticCache(
                config=self.config,
                max_batch_size=max_batch_size,
                max_cache_len=max_cache_len,
                device=self.device,
                dtype=cache_dtype,
            )
        else:
            self._static_cache.reset()  # reset the cache for a new generation
        return self._static_cache

1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
    def _prepare_special_tokens(
        self, generation_config: GenerationConfig, kwargs_has_attention_mask: Optional[bool] = None
    ):
        """
        Prepares the special tokens for generation, overwriting the generation config with their processed versions
        converted to tensor.

        Note that `generation_config` is changed in place and stops being serializable after this method is called.
        That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
        function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
        """

        # Convert special tokens to tensors (if they exist)
        def _tensor_or_none(token):
            if token is None or isinstance(token, torch.Tensor):
                return token
            return torch.tensor(token, device=self.device, dtype=torch.long)

        bos_token_id = _tensor_or_none(generation_config.bos_token_id)
        eos_token_id = _tensor_or_none(generation_config.eos_token_id)
        pad_token_id = _tensor_or_none(generation_config.pad_token_id)
        decoder_start_token_id = _tensor_or_none(generation_config.decoder_start_token_id)
        decoder_start_token_id = decoder_start_token_id if decoder_start_token_id is not None else bos_token_id

        # We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
        if eos_token_id is not None and eos_token_id.ndim == 0:
            eos_token_id = eos_token_id.unsqueeze(0)

        # Set pad token if unset (and there are conditions to do so)
        if pad_token_id is None and eos_token_id is not None:
            if kwargs_has_attention_mask is not None and not kwargs_has_attention_mask:
                logger.warning(
                    "The attention mask and the pad token id were not set. As a consequence, you may observe "
                    "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
                )
            pad_token_id = eos_token_id[0]
            logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_id} for open-end generation.")

        # Sanity checks/warnings
        if self.config.is_encoder_decoder and decoder_start_token_id is None:
            raise ValueError(
                "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation."
            )
        if eos_token_id is not None and (torch.is_floating_point(eos_token_id) or (eos_token_id < 0).any()):
            logger.warning(
                f"`eos_token_id` should consist of positive integers, but is {eos_token_id}. Your generation will not "
                "stop until the maximum length is reached. Depending on other flags, it may even crash."
            )

        # Update generation config with the updated special tokens tensors
        generation_config.bos_token_id = bos_token_id
        generation_config.eos_token_id = eos_token_id
        generation_config.pad_token_id = pad_token_id
        generation_config.decoder_start_token_id = decoder_start_token_id

1397
1398
1399
1400
    @torch.no_grad()
    def generate(
        self,
        inputs: Optional[torch.Tensor] = None,
1401
        generation_config: Optional[GenerationConfig] = None,
1402
1403
        logits_processor: Optional[LogitsProcessorList] = None,
        stopping_criteria: Optional[StoppingCriteriaList] = None,
1404
        prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
1405
        synced_gpus: Optional[bool] = None,
1406
        assistant_model: Optional["PreTrainedModel"] = None,
1407
        streamer: Optional["BaseStreamer"] = None,
1408
1409
        negative_prompt_ids: Optional[torch.Tensor] = None,
        negative_prompt_attention_mask: Optional[torch.Tensor] = None,
1410
        **kwargs,
1411
1412
1413
    ) -> Union[GenerateOutput, torch.LongTensor]:
        r"""

1414
        Generates sequences of token ids for models with a language modeling head.
1415
1416
1417

        <Tip warning={true}>

1418
1419
        Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
        model's default generation configuration. You can override any `generation_config` by passing the corresponding
1420
        parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
1421

1422
        For an overview of generation strategies and code examples, check out the [following
1423
        guide](../generation_strategies).
1424

1425
        </Tip>
1426
1427
1428
1429
1430

        Parameters:
            inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
                The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
                method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
1431
                should be in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
1432
                `input_ids`, `input_values`, `input_features`, or `pixel_values`.
1433
            generation_config ([`~generation.GenerationConfig`], *optional*):
1434
1435
                The generation configuration to be used as base parametrization for the generation call. `**kwargs`
                passed to generate matching the attributes of `generation_config` will override them. If
1436
                `generation_config` is not provided, the default will be used, which has the following loading
1437
1438
1439
1440
1441
1442
1443
1444
                priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
                configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
                default values, whose documentation should be checked to parameterize generation.
            logits_processor (`LogitsProcessorList`, *optional*):
                Custom logits processors that complement the default logits processors built from arguments and
                generation config. If a logit processor is passed that is already created with the arguments or a
                generation config an error is thrown. This feature is intended for advanced users.
            stopping_criteria (`StoppingCriteriaList`, *optional*):
1445
                Custom stopping criteria that complements the default stopping criteria built from arguments and a
1446
                generation config. If a stopping criteria is passed that is already created with the arguments or a
1447
1448
1449
                generation config an error is thrown. If your stopping criteria depends on the `scores` input, make
                sure you pass `return_dict_in_generate=True, output_scores=True` to `generate`. This feature is
                intended for advanced users.
1450
1451
1452
1453
1454
1455
1456
            prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
                If provided, this function constraints the beam search to allowed tokens only at each step. If not
                provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
                `input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
                on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
                for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
                Retrieval](https://arxiv.org/abs/2010.00904).
1457
1458
1459
1460
            synced_gpus (`bool`, *optional*):
                Whether to continue running the while loop until max_length. Unless overridden this flag will be set to
                `True` under DeepSpeed ZeRO Stage 3 multiple GPUs environment to avoid hanging if one GPU finished
                generating before other GPUs. Otherwise it'll be set to `False`.
1461
1462
1463
1464
1465
            assistant_model (`PreTrainedModel`, *optional*):
                An assistant model that can be used to accelerate generation. The assistant model must have the exact
                same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistent model
                is much faster than running generation with the model you're calling generate from. As such, the
                assistant model should be much smaller.
1466
1467
1468
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
1469
1470
1471
1472
1473
            negative_prompt_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                The negative prompt needed for some processors such as CFG. The batch size must match the input batch
                size. This is an experimental feature, subject to breaking API changes in future versions.
            negative_prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Attention_mask for `negative_prompt_ids`.
1474
            kwargs (`Dict[str, Any]`, *optional*):
1475
                Ad hoc parametrization of `generation_config` and/or additional model-specific kwargs that will be
1476
1477
                forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
                specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
1478
1479
1480

        Return:
            [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
1481
            or when `config.return_dict_in_generate=True`) or a `torch.LongTensor`.
1482
1483
1484
1485

                If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
                [`~utils.ModelOutput`] types are:

1486
1487
                    - [`~generation.GenerateDecoderOnlyOutput`],
                    - [`~generation.GenerateBeamDecoderOnlyOutput`]
1488
1489
1490
1491

                If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
                [`~utils.ModelOutput`] types are:

1492
1493
                    - [`~generation.GenerateEncoderDecoderOutput`],
                    - [`~generation.GenerateBeamEncoderDecoderOutput`]
1494
        """
1495
1496
        # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
        self._validate_model_class()
1497
        tokenizer = kwargs.pop("tokenizer", None)  # Pull this out first, we only use it for stopping criteria
1498
1499
        generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)
        self._validate_model_kwargs(model_kwargs.copy())
1500

1501
        # 2. Set generation parameters if not already defined
1502
        if synced_gpus is None:
1503
            if is_deepspeed_zero3_enabled() and dist.get_world_size() > 1:
1504
1505
1506
                synced_gpus = True
            else:
                synced_gpus = False
1507

1508
1509
1510
        logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
        stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()

1511
1512
1513
1514
        accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
        requires_attention_mask = "encoder_outputs" not in model_kwargs
        kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None
        self._prepare_special_tokens(generation_config, kwargs_has_attention_mask)
1515

1516
1517
1518
1519
        # 3. Define model inputs
        inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
            inputs, generation_config.bos_token_id, model_kwargs
        )
1520
1521
        batch_size = inputs_tensor.shape[0]

1522
1523
        # decoder-only models must use left-padding for batched generation.
        if not self.config.is_encoder_decoder and not is_torchdynamo_compiling():
1524
1525
            # If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
            # Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
1526
1527
            if (
                generation_config.pad_token_id is not None
1528
                and batch_size > 1
1529
                and len(inputs_tensor.shape) == 2
1530
1531
                and torch.sum(inputs_tensor[:, -1] == generation_config.pad_token_id) > 0
            ):
1532
1533
1534
1535
1536
                logger.warning(
                    "A decoder-only architecture is being used, but right-padding was detected! For correct "
                    "generation results, please set `padding_side='left'` when initializing the tokenizer."
                )

1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
        # 4. Define other model kwargs
        # decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
        # generating the first new token or not, and we only want to use the embeddings for the first new token)
        if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
            model_kwargs["use_cache"] = True
        else:
            model_kwargs["use_cache"] = generation_config.use_cache

        if not kwargs_has_attention_mask and requires_attention_mask and accepts_attention_mask:
            model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
                inputs_tensor, generation_config.pad_token_id, generation_config.eos_token_id
            )

1550
        if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
1551
            # if model is encoder decoder encoder_outputs are created and added to `model_kwargs`
1552
            model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
1553
                inputs_tensor, model_kwargs, model_input_name, generation_config
1554
1555
            )

1556
        # 5. Prepare `input_ids` which will be used for auto-regressive generation
1557
        if self.config.is_encoder_decoder:
1558
1559
1560
1561
            input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
                batch_size=batch_size,
                model_input_name=model_input_name,
                model_kwargs=model_kwargs,
1562
                decoder_start_token_id=generation_config.decoder_start_token_id,
1563
1564
1565
                device=inputs_tensor.device,
            )
        else:
1566
            input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
1567

1568
1569
1570
        if streamer is not None:
            streamer.put(input_ids.cpu())

1571
        # 6. Prepare `max_length` depending on other stopping criteria.
1572
        input_ids_length = input_ids.shape[-1]
1573
        has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
1574
1575
1576
1577
1578
1579
1580
1581
1582
        has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None
        generation_config = self._prepare_generated_length(
            generation_config=generation_config,
            has_default_max_length=has_default_max_length,
            has_default_min_length=has_default_min_length,
            model_input_name=model_input_name,
            inputs_tensor=inputs_tensor,
            input_ids_length=input_ids_length,
        )
1583

1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
        if generation_config.cache_implementation is not None and model_kwargs.get("past_key_values") is not None:
            raise ValueError(
                "Passing both `cache_implementation` (used to initialize certain caches) and `past_key_values` (a "
                "Cache object) is unsupported. Please use only one of the two."
            )
        elif generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING:
            if not self._supports_cache_class:
                raise ValueError(
                    "This model does not support the `cache_implementation` argument. Please check the following "
                    "issue: https://github.com/huggingface/transformers/issues/28981."
                )
1595
            if generation_config.cache_implementation == "static":
1596
                model_kwargs["past_key_values"] = self._get_static_cache(batch_size, generation_config.max_length)
1597

1598
        self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
1599

1600
        # 7. determine generation mode
1601
        generation_mode = generation_config.get_generation_mode(assistant_model)
1602

1603
1604
1605
1606
1607
        if streamer is not None and (generation_config.num_beams > 1):
            raise ValueError(
                "`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."
            )

1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
        if self.device.type != input_ids.device.type:
            warnings.warn(
                "You are calling .generate() with the `input_ids` being on a device type different"
                f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
                f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
                " Please make sure that you have put `input_ids` to the"
                f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
                " running `.generate()`.",
                UserWarning,
            )

1619
        # 8. prepare distribution pre_processing samplers
1620
        prepared_logits_processor = self._get_logits_processor(
1621
            generation_config=generation_config,
1622
            input_ids_seq_length=input_ids_length,
1623
1624
1625
            encoder_input_ids=inputs_tensor,
            prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
            logits_processor=logits_processor,
1626
1627
1628
            model_kwargs=model_kwargs,
            negative_prompt_ids=negative_prompt_ids,
            negative_prompt_attention_mask=negative_prompt_attention_mask,
1629
1630
        )

1631
        # 9. prepare stopping criteria
1632
        prepared_stopping_criteria = self._get_stopping_criteria(
1633
            generation_config=generation_config, stopping_criteria=stopping_criteria, tokenizer=tokenizer, **kwargs
1634
        )
1635

1636
        # 10. go into different generation modes
1637
        if generation_mode == GenerationMode.ASSISTED_GENERATION:
1638
1639
            if generation_config.num_return_sequences > 1:
                raise ValueError(
1640
                    "num_return_sequences has to be 1 when doing assisted generate, "
1641
1642
1643
                    f"but is {generation_config.num_return_sequences}."
                )
            if batch_size > 1:
1644
                raise ValueError("assisted generate is only supported for batch_size = 1")
1645
            if not model_kwargs["use_cache"]:
1646
                raise ValueError("assisted generate requires `use_cache=True`")
1647
1648
            if generation_config.cache_implementation == "static":
                raise ValueError("assisted generate is not supported with `static_cache`")
1649

1650
1651
1652
1653
1654
1655
1656
1657
            # 11. Get the candidate generator, given the parameterization
            candidate_generator = self._get_candidate_generator(
                generation_config=generation_config,
                input_ids=input_ids,
                inputs_tensor=inputs_tensor,
                assistant_model=assistant_model,
                logits_processor=logits_processor,
                model_kwargs=model_kwargs,
1658
1659
            )

1660
1661
1662
1663
1664
1665
            # 12. prepare logits warper (if `do_sample` is `True`)
            prepared_logits_warper = (
                self._get_logits_warper(generation_config) if generation_config.do_sample else None
            )

            # 13. run assisted generate
1666
            result = self._assisted_decoding(
1667
                input_ids,
1668
                candidate_generator=candidate_generator,
1669
                logits_processor=prepared_logits_processor,
1670
                logits_warper=prepared_logits_warper,
1671
                stopping_criteria=prepared_stopping_criteria,
1672
                generation_config=generation_config,
1673
1674
1675
1676
                synced_gpus=synced_gpus,
                streamer=streamer,
                **model_kwargs,
            )
1677
        if generation_mode == GenerationMode.GREEDY_SEARCH:
1678
            # 11. run greedy search
1679
            result = self._greedy_search(
1680
                input_ids,
1681
1682
                logits_processor=prepared_logits_processor,
                stopping_criteria=prepared_stopping_criteria,
1683
                generation_config=generation_config,
1684
                synced_gpus=synced_gpus,
1685
                streamer=streamer,
1686
1687
1688
                **model_kwargs,
            )

1689
        elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:
1690
1691
            if not model_kwargs["use_cache"]:
                raise ValueError("Contrastive search requires `use_cache=True`")
1692

1693
            result = self._contrastive_search(
1694
                input_ids,
1695
1696
                logits_processor=prepared_logits_processor,
                stopping_criteria=prepared_stopping_criteria,
1697
                generation_config=generation_config,
1698
                synced_gpus=synced_gpus,
1699
                streamer=streamer,
1700
1701
1702
                **model_kwargs,
            )

1703
        elif generation_mode == GenerationMode.SAMPLE:
1704
1705
            # 11. prepare logits warper
            logits_warper = self._get_logits_warper(generation_config)
1706

1707
            # 12. expand input_ids with `num_return_sequences` additional sequences per batch
1708
1709
            input_ids, model_kwargs = self._expand_inputs_for_generation(
                input_ids=input_ids,
1710
                expand_size=generation_config.num_return_sequences,
1711
1712
1713
1714
                is_encoder_decoder=self.config.is_encoder_decoder,
                **model_kwargs,
            )

1715
            # 13. run sample
1716
            result = self._sample(
1717
                input_ids,
1718
                logits_processor=prepared_logits_processor,
1719
                logits_warper=logits_warper,
1720
                stopping_criteria=prepared_stopping_criteria,
1721
                generation_config=generation_config,
1722
                synced_gpus=synced_gpus,
1723
                streamer=streamer,
1724
1725
1726
                **model_kwargs,
            )

1727
        elif generation_mode == GenerationMode.BEAM_SEARCH:
1728
            # 11. prepare beam search scorer
1729
1730
            beam_scorer = BeamSearchScorer(
                batch_size=batch_size,
1731
                num_beams=generation_config.num_beams,
1732
                device=inputs_tensor.device,
1733
1734
1735
                length_penalty=generation_config.length_penalty,
                do_early_stopping=generation_config.early_stopping,
                num_beam_hyps_to_keep=generation_config.num_return_sequences,
1736
                max_length=generation_config.max_length,
1737
            )
1738
            # 12. interleave input_ids with `num_beams` additional sequences per batch
1739
1740
            input_ids, model_kwargs = self._expand_inputs_for_generation(
                input_ids=input_ids,
1741
                expand_size=generation_config.num_beams,
1742
1743
1744
                is_encoder_decoder=self.config.is_encoder_decoder,
                **model_kwargs,
            )
1745
            # 13. run beam search
1746
            result = self._beam_search(
1747
1748
                input_ids,
                beam_scorer,
1749
1750
                logits_processor=prepared_logits_processor,
                stopping_criteria=prepared_stopping_criteria,
1751
                generation_config=generation_config,
1752
1753
1754
1755
                synced_gpus=synced_gpus,
                **model_kwargs,
            )

1756
        elif generation_mode == GenerationMode.BEAM_SAMPLE:
1757
1758
            # 11. prepare logits warper
            logits_warper = self._get_logits_warper(generation_config)
1759

1760
            # 12. prepare beam search scorer
1761
            beam_scorer = BeamSearchScorer(
1762
                batch_size=batch_size,
1763
                num_beams=generation_config.num_beams,
1764
                device=inputs_tensor.device,
1765
1766
                length_penalty=generation_config.length_penalty,
                do_early_stopping=generation_config.early_stopping,
1767
                num_beam_hyps_to_keep=generation_config.num_return_sequences,
1768
                max_length=generation_config.max_length,
1769
1770
            )

1771
            # 13. interleave input_ids with `num_beams` additional sequences per batch
1772
1773
            input_ids, model_kwargs = self._expand_inputs_for_generation(
                input_ids=input_ids,
1774
                expand_size=generation_config.num_beams,
1775
1776
1777
1778
                is_encoder_decoder=self.config.is_encoder_decoder,
                **model_kwargs,
            )

1779
            # 14. run beam sample
1780
            result = self._beam_sample(
1781
1782
                input_ids,
                beam_scorer,
1783
                logits_processor=prepared_logits_processor,
1784
                logits_warper=logits_warper,
1785
                stopping_criteria=prepared_stopping_criteria,
1786
                generation_config=generation_config,
1787
1788
1789
1790
                synced_gpus=synced_gpus,
                **model_kwargs,
            )

1791
        elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:
1792
            # 11. prepare beam search scorer
1793
1794
            beam_scorer = BeamSearchScorer(
                batch_size=batch_size,
1795
                num_beams=generation_config.num_beams,
1796
                device=inputs_tensor.device,
1797
1798
1799
1800
                length_penalty=generation_config.length_penalty,
                do_early_stopping=generation_config.early_stopping,
                num_beam_hyps_to_keep=generation_config.num_return_sequences,
                num_beam_groups=generation_config.num_beam_groups,
1801
                max_length=generation_config.max_length,
1802
            )
1803
            # 12. interleave input_ids with `num_beams` additional sequences per batch
1804
1805
            input_ids, model_kwargs = self._expand_inputs_for_generation(
                input_ids=input_ids,
1806
                expand_size=generation_config.num_beams,
1807
1808
1809
                is_encoder_decoder=self.config.is_encoder_decoder,
                **model_kwargs,
            )
1810
            # 13. run beam search
1811
            result = self._group_beam_search(
1812
1813
                input_ids,
                beam_scorer,
1814
1815
                logits_processor=prepared_logits_processor,
                stopping_criteria=prepared_stopping_criteria,
1816
                generation_config=generation_config,
1817
1818
1819
1820
                synced_gpus=synced_gpus,
                **model_kwargs,
            )

1821
        elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:
1822
            final_constraints = []
1823
1824
            if generation_config.constraints is not None:
                final_constraints = generation_config.constraints
1825

1826
            if generation_config.force_words_ids is not None:
1827
1828
1829

                def typeerror():
                    raise ValueError(
1830
                        "`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]` "
1831
                        f"of positive integers, but is {generation_config.force_words_ids}."
1832
1833
                    )

1834
1835
1836
1837
                if (
                    not isinstance(generation_config.force_words_ids, list)
                    or len(generation_config.force_words_ids) == 0
                ):
1838
1839
                    typeerror()

1840
                for word_ids in generation_config.force_words_ids:
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
                    if isinstance(word_ids[0], list):
                        if not isinstance(word_ids, list) or len(word_ids) == 0:
                            typeerror()
                        if any(not isinstance(token_ids, list) for token_ids in word_ids):
                            typeerror()
                        if any(
                            any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
                            for token_ids in word_ids
                        ):
                            typeerror()

                        constraint = DisjunctiveConstraint(word_ids)
                    else:
                        if not isinstance(word_ids, list) or len(word_ids) == 0:
                            typeerror()
                        if any((not isinstance(token_id, int) or token_id < 0) for token_id in word_ids):
                            typeerror()

                        constraint = PhrasalConstraint(word_ids)
                    final_constraints.append(constraint)

1862
            # 11. prepare beam search scorer
1863
1864
1865
            constrained_beam_scorer = ConstrainedBeamSearchScorer(
                constraints=final_constraints,
                batch_size=batch_size,
1866
                num_beams=generation_config.num_beams,
1867
                device=inputs_tensor.device,
1868
1869
1870
                length_penalty=generation_config.length_penalty,
                do_early_stopping=generation_config.early_stopping,
                num_beam_hyps_to_keep=generation_config.num_return_sequences,
1871
                max_length=generation_config.max_length,
1872
            )
1873
            # 12. interleave input_ids with `num_beams` additional sequences per batch
1874
1875
            input_ids, model_kwargs = self._expand_inputs_for_generation(
                input_ids=input_ids,
1876
                expand_size=generation_config.num_beams,
1877
1878
1879
                is_encoder_decoder=self.config.is_encoder_decoder,
                **model_kwargs,
            )
1880
            # 13. run beam search
1881
            result = self._constrained_beam_search(
1882
1883
                input_ids,
                constrained_beam_scorer=constrained_beam_scorer,
1884
1885
                logits_processor=prepared_logits_processor,
                stopping_criteria=prepared_stopping_criteria,
1886
                generation_config=generation_config,
1887
1888
1889
1890
                synced_gpus=synced_gpus,
                **model_kwargs,
            )

1891
1892
        return result

1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
    def _has_unfinished_sequences(self, this_peer_finished: bool, synced_gpus: bool, device: torch.device) -> bool:
        """
        Returns whether there are still unfinished sequences in the device. The existence of unfinished sequences is
        fed through `this_peer_finished`. ZeRO stage 3-friendly.
        """
        if synced_gpus:
            # Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
            # The following logic allows an early break if all peers finished generating their sequence
            this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(device)
            # send 0.0 if we finished, 1.0 otherwise
            dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
            # did all peers finish? the reduced sum will be 0.0 then
            if this_peer_finished_flag.item() == 0.0:
                return False
        elif this_peer_finished:
            return False
        return True

1911
    @torch.no_grad()
1912
    def _contrastive_search(
1913
1914
        self,
        input_ids: torch.LongTensor,
1915
1916
1917
1918
1919
        logits_processor: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
        streamer: Optional["BaseStreamer"],
1920
        **model_kwargs,
1921
    ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
1922
1923
1924
1925
1926
1927
1928
        r"""
        Generates sequences of token ids for models with a language modeling head using **contrastive search** and can
        be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
1929
            logits_processor (`LogitsProcessorList`):
1930
1931
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
1932
            stopping_criteria (`StoppingCriteriaList`):
1933
1934
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
1935
1936
1937
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
1938
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
1939
1940
1941
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
1942
1943
1944
1945
1946
            model_kwargs:
                Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
                If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
1947
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`]
1948
            or `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
1949
1950
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
1951
            `model.config.is_encoder_decoder=True`.
1952
        """
1953
        # init values
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
        has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
        top_k = generation_config.top_k
        penalty_alpha = generation_config.penalty_alpha
        pad_token_id = generation_config.pad_token_id
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
        sequential = generation_config.low_memory
1964
1965

        # init attention / hidden states / scores tuples
1966
        raw_logits = () if (return_dict_in_generate and output_logits) else None
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
        scores = () if (return_dict_in_generate and output_scores) else None
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        # keep track of which sequences are already finished
1980
        batch_size = input_ids.shape[0]
1981
        unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
1982
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
1983

1984
        this_peer_finished = False
1985

1986
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
1987
1988
            # if the first step in the loop, encode all the prefix and obtain: (1) past_key_values;
            # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
1989
            if model_kwargs.get("past_key_values") is None:
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
                # prepare inputs
                model_kwargs["use_cache"] = True
                model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)

                # encode the given prefix and prepare model inputs; encoder-decoder model process the prefix and save
                # the `encoder_outputs`
                outputs = self(
                    **model_inputs, return_dict=True, output_hidden_states=True, output_attentions=output_attentions
                )

                # last decoder hidden states will be used to compute the degeneration penalty (cosine similarity with
                # previous tokens)
                if self.config.is_encoder_decoder:
                    last_hidden_states = outputs.decoder_hidden_states[-1]
                else:
                    last_hidden_states = outputs.hidden_states[-1]
2006

2007
2008
2009
2010
                # next logit for contrastive search to select top-k candidate tokens
                logit_for_next_step = outputs.logits[:, -1, :]

                model_kwargs = self._update_model_kwargs_for_generation(
2011
2012
2013
2014
                    outputs,
                    model_kwargs,
                    is_encoder_decoder=self.config.is_encoder_decoder,
                    standardize_cache_format=True,
2015
                )
2016
2017
2018
2019
2020
                if not sequential:
                    # Expands model inputs top_k times, for batched forward passes (akin to beam search).
                    _, model_kwargs = self._expand_inputs_for_generation(
                        expand_size=top_k, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs
                    )
2021

2022
2023
                past_key_values = model_kwargs.get("past_key_values")
                if past_key_values is None:
2024
2025
2026
2027
                    raise ValueError(
                        f"{self.__class__.__name__} does not support caching and therefore **can't** be used "
                        "for contrastive search."
                    )
2028
2029
2030
2031
                elif (
                    not isinstance(past_key_values[0], (tuple, torch.Tensor))
                    or past_key_values[0][0].shape[0] != batch_size
                ):
2032
2033
2034
2035
2036
2037
2038
2039
                    raise ValueError(
                        f"{self.__class__.__name__} does not have a standard cache format and therefore **can't** be "
                        "used for contrastive search without further modifications."
                    )

            # contrastive_search main logic start:
            # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
            # degeneration penalty
2040
2041
2042
            processed_logit_for_next_step = logits_processor(input_ids, logit_for_next_step)
            next_probs = nn.functional.softmax(processed_logit_for_next_step, dim=-1)

2043
2044
2045
2046
            top_k_probs, top_k_ids = torch.topk(next_probs, dim=-1, k=top_k)

            # Store scores, attentions and hidden_states when required
            if return_dict_in_generate:
2047
2048
                if output_logits:
                    raw_logits += (logit_for_next_step,)
2049
                if output_scores:
2050
                    scores += (processed_logit_for_next_step,)
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
                if output_attentions:
                    decoder_attentions += (
                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
                    )
                    if self.config.is_encoder_decoder:
                        cross_attentions += (outputs.cross_attentions,)

                if output_hidden_states:
                    decoder_hidden_states += (
                        (outputs.decoder_hidden_states,)
                        if self.config.is_encoder_decoder
                        else (outputs.hidden_states,)
                    )

            # Replicates the new past_key_values to match the `top_k` candidates
            new_key_values = []
tomeras91's avatar
tomeras91 committed
2067
2068
            past = model_kwargs["past_key_values"]
            for layer in past:
2069
2070
2071
                items = []
                # item is either the key or the value matrix
                for item in layer:
2072
2073
2074
2075
                    if sequential:
                        items.append(item.repeat_interleave(1, dim=0))
                    else:
                        items.append(item.repeat_interleave(top_k, dim=0))
2076
                new_key_values.append(tuple(items))
tomeras91's avatar
tomeras91 committed
2077
2078
2079
2080
2081
2082
2083
            if not isinstance(past, DynamicCache):
                past = tuple(new_key_values)
            else:
                for layer_idx in range(len(new_key_values)):
                    past.key_cache[layer_idx] = new_key_values[layer_idx][0]
                    past.value_cache[layer_idx] = new_key_values[layer_idx][1]
            model_kwargs["past_key_values"] = past
2084

2085
            if sequential:
2086
                all_outputs = []
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
                for i in range(top_k):
                    # compute the candidate tokens by the language model and collect their hidden_states
                    next_model_inputs = self.prepare_inputs_for_generation(top_k_ids[:, i].view(-1, 1), **model_kwargs)

                    outputs = self(
                        **next_model_inputs,
                        return_dict=True,
                        output_hidden_states=True,
                        output_attentions=output_attentions,
                    )
2097
2098
                    all_outputs.append(outputs)
                outputs = stack_model_outputs(all_outputs)
2099
2100

            else:
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
                # compute the candidate tokens by the language model and collect their hidden_states
                # assembles top_k_ids into batch of size k
                next_model_inputs = self.prepare_inputs_for_generation(top_k_ids.view(-1, 1), **model_kwargs)

                outputs = self(
                    **next_model_inputs,
                    return_dict=True,
                    output_hidden_states=True,
                    output_attentions=output_attentions,
                )
2111
2112
2113
2114
2115
2116
2117
            # name is different for encoder-decoder and decoder-only models
            if self.config.is_encoder_decoder:
                next_hidden = outputs.decoder_hidden_states[-1]
                full_hidden_states = outputs.decoder_hidden_states
            else:
                next_hidden = outputs.hidden_states[-1]
                full_hidden_states = outputs.hidden_states
2118

2119
            logits = outputs.logits[:, -1, :]
2120

2121
2122
2123
            context_hidden = last_hidden_states.repeat_interleave(top_k, dim=0)

            # compute the degeneration penalty and re-rank the candidates based on the degeneration penalty and the
2124
2125
            # model confidence. Keeping `selected_idx` on CPU enables multi-device contrastive search and doesn't
            # introduce (noticeable) slowdowns on single-device runs.
2126
            selected_idx = _ranking_fast(context_hidden, next_hidden, top_k_probs, penalty_alpha, top_k)
2127
            selected_idx = selected_idx.to("cpu")
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141

            # prepare for the next step: (1) next token_id; (2) past_key_values; (3) last_hidden_states for computing
            # the degeneration penalty; (4) logits for selecting next top-k candidates; (5) selected tokens scores
            # (model confidence minus degeneration penalty); (6) decoder hidden_states
            next_tokens = top_k_ids[range(len(top_k_ids)), selected_idx]
            next_hidden = torch.stack(torch.split(next_hidden.squeeze(dim=1), top_k))
            next_hidden = next_hidden[range(batch_size), selected_idx, :]
            last_hidden_states = torch.cat([last_hidden_states, next_hidden.unsqueeze(1)], dim=1)

            next_decoder_hidden_states = ()
            for layer in full_hidden_states:
                layer = torch.stack(torch.split(layer, top_k))[range(batch_size), selected_idx, :]
                next_decoder_hidden_states += (layer,)

2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
            # generate past_key_values cache of only the selected token
            if sequential:
                next_model_input = self.prepare_inputs_for_generation(
                    top_k_ids[:, selected_idx].view(-1, 1), **model_kwargs
                )

                selected_outputs = self(
                    **next_model_input,
                    return_dict=True,
                    output_hidden_states=False,
                    output_attentions=False,
                )
                next_past_key_values = selected_outputs["past_key_values"]

            else:
                next_past_key_values = self._extract_past_from_model_output(outputs, standardize_cache_format=True)
tomeras91's avatar
tomeras91 committed
2158
                new_key_values = []
2159
                for layer in next_past_key_values:
tomeras91's avatar
tomeras91 committed
2160
                    items = []
2161
2162
2163
2164
                    # item is either the key or the value matrix
                    for item in layer:
                        item = torch.stack(torch.split(item, top_k, dim=0))  # [B, K, num_head, seq_len, esz]
                        item = item[range(batch_size), selected_idx, ...]  # [B, num_head, seq_len, esz]
tomeras91's avatar
tomeras91 committed
2165
2166
2167
2168
2169
2170
2171
2172
2173
                        items += [item]
                    new_key_values += [items]

                if not isinstance(next_past_key_values, DynamicCache):
                    next_past_key_values = tuple(new_key_values)
                else:
                    for layer_idx in range(len(new_key_values)):
                        next_past_key_values.key_cache[layer_idx] = new_key_values[layer_idx][0]
                        next_past_key_values.value_cache[layer_idx] = new_key_values[layer_idx][1]
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210

            logit_for_next_step = torch.stack(torch.split(logits, top_k))[range(batch_size), selected_idx, :]

            # Rebuilds the relevant parts of the model output for the selected token, for use in the next iteration
            if self.config.is_encoder_decoder:
                next_step_cross_attentions = ()
                next_step_decoder_attentions = ()
                if output_attentions:
                    for layer in outputs.cross_attentions:
                        layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
                        next_step_cross_attentions += (layer,)
                    for layer in outputs.decoder_attentions:
                        layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
                        next_step_decoder_attentions += (layer,)
                outputs = Seq2SeqLMOutput(
                    past_key_values=next_past_key_values,
                    decoder_hidden_states=next_decoder_hidden_states,
                    decoder_attentions=next_step_decoder_attentions or None,
                    cross_attentions=next_step_cross_attentions or None,
                )
            else:
                next_step_attentions = ()
                if output_attentions:
                    for layer in outputs.attentions:
                        layer = torch.stack(torch.split(layer, top_k, dim=0))[range(batch_size), selected_idx, ...]
                        next_step_attentions += (layer,)
                outputs = CausalLMOutputWithPast(
                    past_key_values=next_past_key_values,
                    hidden_states=next_decoder_hidden_states,
                    attentions=next_step_attentions or None,
                )
            # contrastive_search main logic end

            if synced_gpus and this_peer_finished:
                continue  # don't waste resources running the code we don't need

            # finished sentences should have their next token be a padding token
2211
            if has_eos_stopping_criteria:
2212
2213
2214
2215
                next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)

            # update generated ids, model inputs, and length for next step
            input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
2216
2217
            if streamer is not None:
                streamer.put(next_tokens.cpu())
2218
            model_kwargs = self._update_model_kwargs_for_generation(
2219
2220
2221
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
2222
2223
            )

2224
2225
            # stop when each sentence is finished
            unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
2226
            this_peer_finished = unfinished_sequences.max() == 0
2227

2228
2229
2230
        if streamer is not None:
            streamer.end()

2231
        if return_dict_in_generate:
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
            # Contrastive search works by forward looking at the next token, so we need to exclude it from
            # `past_key_values` to be consistent with the other decoding methods
            if model_kwargs.get("past_key_values") is not None:
                past_key_values = []
                for layer in model_kwargs["past_key_values"]:
                    layer_past_key_values = []
                    for item in layer:
                        layer_past_key_values.append(item[..., :-1, :])
                    past_key_values.append(tuple(layer_past_key_values))
                model_kwargs["past_key_values"] = tuple(past_key_values)

2243
            if self.config.is_encoder_decoder:
2244
                return GenerateEncoderDecoderOutput(
2245
2246
                    sequences=input_ids,
                    scores=scores,
2247
                    logits=raw_logits,
2248
2249
2250
2251
2252
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
2253
                    past_key_values=model_kwargs.get("past_key_values"),
2254
2255
                )
            else:
2256
                return GenerateDecoderOnlyOutput(
2257
2258
                    sequences=input_ids,
                    scores=scores,
2259
                    logits=raw_logits,
2260
2261
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
2262
                    past_key_values=model_kwargs.get("past_key_values"),
2263
2264
2265
2266
                )
        else:
            return input_ids

2267
    def _greedy_search(
2268
2269
        self,
        input_ids: torch.LongTensor,
2270
2271
2272
2273
2274
        logits_processor: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
        streamer: Optional["BaseStreamer"],
2275
        **model_kwargs,
2276
    ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
2277
2278
2279
2280
2281
2282
2283
        r"""
        Generates sequences of token ids for models with a language modeling head using **greedy decoding** and can be
        used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
2284
            logits_processor (`LogitsProcessorList`):
2285
2286
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
2287
            stopping_criteria (`StoppingCriteriaList`):
2288
2289
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
2290
2291
2292
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
2293
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
2294
2295
2296
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
2297
2298
2299
2300
2301
            model_kwargs:
                Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
                If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
2302
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or
2303
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
2304
2305
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
2306
            `model.config.is_encoder_decoder=True`.
2307
        """
2308
        # init values
2309
2310
2311
2312
2313
2314
2315
        pad_token_id = generation_config.pad_token_id
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
        has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
2316
2317

        # init attention / hidden states / scores tuples
2318
        raw_logits = () if (return_dict_in_generate and output_logits) else None
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
        scores = () if (return_dict_in_generate and output_scores) else None
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        # keep track of which sequences are already finished
2332
        batch_size = input_ids.shape[0]
2333
        this_peer_finished = False
2334
        unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
2335
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
2336

2337
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
            # prepare model inputs
            model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)

            # forward pass to get next token
            outputs = self(
                **model_inputs,
                return_dict=True,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
            )

            if synced_gpus and this_peer_finished:
                continue  # don't waste resources running the code we don't need

            next_token_logits = outputs.logits[:, -1, :]

            # pre-process distribution
            next_tokens_scores = logits_processor(input_ids, next_token_logits)

            # Store scores, attentions and hidden_states when required
            if return_dict_in_generate:
                if output_scores:
                    scores += (next_tokens_scores,)
2361
2362
                if output_logits:
                    raw_logits += (next_token_logits,)
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
                if output_attentions:
                    decoder_attentions += (
                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
                    )
                    if self.config.is_encoder_decoder:
                        cross_attentions += (outputs.cross_attentions,)

                if output_hidden_states:
                    decoder_hidden_states += (
                        (outputs.decoder_hidden_states,)
                        if self.config.is_encoder_decoder
                        else (outputs.hidden_states,)
                    )

            # argmax
            next_tokens = torch.argmax(next_tokens_scores, dim=-1)

            # finished sentences should have their next token be a padding token
2381
            if has_eos_stopping_criteria:
2382
2383
2384
2385
                next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)

            # update generated ids, model inputs, and length for next step
            input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
2386
2387
            if streamer is not None:
                streamer.put(next_tokens.cpu())
2388
            model_kwargs = self._update_model_kwargs_for_generation(
2389
2390
2391
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
2392
2393
            )

2394
            unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
2395
            this_peer_finished = unfinished_sequences.max() == 0
2396

2397
2398
2399
        if streamer is not None:
            streamer.end()

2400
2401
        if return_dict_in_generate:
            if self.config.is_encoder_decoder:
2402
                return GenerateEncoderDecoderOutput(
2403
2404
                    sequences=input_ids,
                    scores=scores,
2405
                    logits=raw_logits,
2406
2407
2408
2409
2410
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
2411
                    past_key_values=model_kwargs.get("past_key_values"),
2412
2413
                )
            else:
2414
                return GenerateDecoderOnlyOutput(
2415
2416
                    sequences=input_ids,
                    scores=scores,
2417
                    logits=raw_logits,
2418
2419
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
2420
                    past_key_values=model_kwargs.get("past_key_values"),
2421
2422
2423
2424
                )
        else:
            return input_ids

2425
    def _sample(
2426
2427
        self,
        input_ids: torch.LongTensor,
2428
2429
2430
2431
2432
2433
        logits_processor: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        logits_warper: LogitsProcessorList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
        streamer: Optional["BaseStreamer"],
2434
        **model_kwargs,
2435
    ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
2436
2437
2438
2439
2440
2441
2442
        r"""
        Generates sequences of token ids for models with a language modeling head using **multinomial sampling** and
        can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
2443
            logits_processor (`LogitsProcessorList`):
2444
2445
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
2446
            stopping_criteria (`StoppingCriteriaList`):
2447
2448
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
2449
            logits_warper (`LogitsProcessorList`):
2450
2451
2452
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsWarper`] used
                to warp the prediction score distribution of the language modeling head applied before multinomial
                sampling at each generation step.
2453
2454
2455
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
2456
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
2457
2458
2459
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
2460
2461
2462
2463
2464
            model_kwargs:
                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
                an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
2465
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:
2466
            A `torch.LongTensor` containing the generated tokens (default behaviour) or a
2467
2468
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
2469
            `model.config.is_encoder_decoder=True`.
2470
        """
2471
        # init values
2472
2473
2474
2475
2476
2477
2478
        pad_token_id = generation_config.pad_token_id
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
        has_eos_stopping_criteria = any(hasattr(criteria, "eos_token_id") for criteria in stopping_criteria)
2479
2480
2481

        # init attention / hidden states / scores tuples
        scores = () if (return_dict_in_generate and output_scores) else None
2482
        raw_logits = () if (return_dict_in_generate and output_logits) else None
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        # keep track of which sequences are already finished
2495
        batch_size = input_ids.shape[0]
2496
        this_peer_finished = False
2497
        unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
2498
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
2499

2500
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
            # prepare model inputs
            model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)

            # forward pass to get next token
            outputs = self(
                **model_inputs,
                return_dict=True,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
            )

            if synced_gpus and this_peer_finished:
                continue  # don't waste resources running the code we don't need

            next_token_logits = outputs.logits[:, -1, :]

            # pre-process distribution
            next_token_scores = logits_processor(input_ids, next_token_logits)
            next_token_scores = logits_warper(input_ids, next_token_scores)

            # Store scores, attentions and hidden_states when required
            if return_dict_in_generate:
                if output_scores:
                    scores += (next_token_scores,)
2525
2526
                if output_logits:
                    raw_logits += (next_token_logits,)
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
                if output_attentions:
                    decoder_attentions += (
                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
                    )
                    if self.config.is_encoder_decoder:
                        cross_attentions += (outputs.cross_attentions,)

                if output_hidden_states:
                    decoder_hidden_states += (
                        (outputs.decoder_hidden_states,)
                        if self.config.is_encoder_decoder
                        else (outputs.hidden_states,)
                    )

            # sample
            probs = nn.functional.softmax(next_token_scores, dim=-1)
            next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)

            # finished sentences should have their next token be a padding token
2546
            if has_eos_stopping_criteria:
2547
2548
2549
2550
                next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)

            # update generated ids, model inputs, and length for next step
            input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
2551
2552
            if streamer is not None:
                streamer.put(next_tokens.cpu())
2553
            model_kwargs = self._update_model_kwargs_for_generation(
2554
2555
2556
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
2557
2558
            )

2559
            unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
2560
            this_peer_finished = unfinished_sequences.max() == 0
2561

2562
2563
2564
        if streamer is not None:
            streamer.end()

2565
2566
        if return_dict_in_generate:
            if self.config.is_encoder_decoder:
2567
                return GenerateEncoderDecoderOutput(
2568
2569
                    sequences=input_ids,
                    scores=scores,
2570
                    logits=raw_logits,
2571
2572
2573
2574
2575
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
2576
                    past_key_values=model_kwargs.get("past_key_values"),
2577
2578
                )
            else:
2579
                return GenerateDecoderOnlyOutput(
2580
2581
                    sequences=input_ids,
                    scores=scores,
2582
                    logits=raw_logits,
2583
2584
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
2585
                    past_key_values=model_kwargs.get("past_key_values"),
2586
2587
2588
2589
                )
        else:
            return input_ids

2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
    def _temporary_reorder_cache(self, past_key_values, beam_idx):
        """
        Temporary function to handle the different types of cache reordering processes while we roll out `Cache`.

        TODO: standardize cache formats and make all models compatible with `Cache`. It would remove the need
        for this function, with `Cache.reorder_cache` being the sole remaining code path
        """
        model_class = self.__class__.__name__.lower()
        # Exception 1: code path for models using the legacy cache format
        if isinstance(past_key_values, (tuple, list)):
            past_key_values = self._reorder_cache(past_key_values, beam_idx)
        # Exception 2: models with different cache formats. These are limited to `DynamicCache` until their
        # cache format is standardized, to avoid adding complexity to the codebase.
        elif "bloom" in model_class or "gptbigcode" in model_class:
            if not isinstance(past_key_values, DynamicCache):
                raise ValueError(
                    f"Using an unsupported cache format with {model_class}. Currently, it only supports the "
                    "legacy tuple format or `DynamicCache`"
                )
            past_key_values = self._reorder_cache(past_key_values, beam_idx)
            past_key_values = DynamicCache.from_legacy_cache(past_key_values)
        # Standard code path: use the `Cache.reorder_cache`
        else:
            past_key_values.reorder_cache(beam_idx)
        return past_key_values

2616
    def _beam_search(
2617
2618
2619
        self,
        input_ids: torch.LongTensor,
        beam_scorer: BeamScorer,
2620
2621
2622
2623
        logits_processor: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
2624
        **model_kwargs,
2625
    ) -> Union[GenerateBeamOutput, torch.LongTensor]:
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
        r"""
        Generates sequences of token ids for models with a language modeling head using **beam search decoding** and
        can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            beam_scorer (`BeamScorer`):
                An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
                sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
2636
            logits_processor (`LogitsProcessorList`):
2637
2638
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
2639
            stopping_criteria (`StoppingCriteriaList`:
2640
2641
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
2642
2643
2644
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
2645
2646
2647
2648
2649
2650
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
            model_kwargs:
                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
                an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
2651
            [`generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
2652
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
2653
2654
            [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
2655
            `model.config.is_encoder_decoder=True`.
2656
        """
2657
        # init values
2658
2659
2660
2661
2662
2663
2664
2665
        pad_token_id = generation_config.pad_token_id
        eos_token_id = generation_config.eos_token_id
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
        sequential = generation_config.low_memory
2666

2667
2668
2669
2670
        batch_size = len(beam_scorer._beam_hyps)
        num_beams = beam_scorer.num_beams

        batch_beam_size, cur_len = input_ids.shape
2671
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
2672
2673
2674
2675
2676
2677
2678
2679

        if num_beams * batch_size != batch_beam_size:
            raise ValueError(
                f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
            )

        # init attention / hidden states / scores tuples
        scores = () if (return_dict_in_generate and output_scores) else None
2680
        raw_logits = () if (return_dict_in_generate and output_logits) else None
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
        beam_indices = (
            tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
        )
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
        # of the first beam are considered to avoid sampling the exact same tokens across all beams.
        beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
        beam_scores[:, 1:] = -1e9
        beam_scores = beam_scores.view((batch_size * num_beams,))

2701
        this_peer_finished = False
2702
2703

        decoder_prompt_len = input_ids.shape[-1]  # record the prompt length of decoder
2704

2705
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
2706
2707
            model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)

2708
2709
2710
2711
            # if sequential is True, split the input to batches of batch_size and run sequentially
            if sequential:
                if any(
                    model_name in self.__class__.__name__.lower()
2712
2713
2714
2715
2716
2717
2718
2719
2720
                    for model_name in [
                        "fsmt",
                        "reformer",
                        "bloom",
                        "ctrl",
                        "gpt_bigcode",
                        "transo_xl",
                        "xlnet",
                        "cpm",
tomeras91's avatar
tomeras91 committed
2721
                        "jamba",
2722
                    ]
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
                ):
                    raise RuntimeError(
                        f"Currently generation for {self.__class__.__name__} is not supported "
                        f"for `low_memory beam_search`. Please open an issue on GitHub if you need this feature."
                    )

                inputs_per_sub_batches = _split_model_inputs(
                    model_inputs, split_size=batch_size, full_batch_size=batch_beam_size
                )
                outputs_per_sub_batch = [
                    self(
                        **inputs_per_sub_batch,
                        return_dict=True,
                        output_attentions=output_attentions,
                        output_hidden_states=output_hidden_states,
                    )
                    for inputs_per_sub_batch in inputs_per_sub_batches
                ]

                outputs = stack_model_outputs(outputs_per_sub_batch)

            else:  # Unchanged original behavior
                outputs = self(
                    **model_inputs,
                    return_dict=True,
                    output_attentions=output_attentions,
                    output_hidden_states=output_hidden_states,
                )
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761

            if synced_gpus and this_peer_finished:
                cur_len = cur_len + 1
                continue  # don't waste resources running the code we don't need

            next_token_logits = outputs.logits[:, -1, :]
            next_token_scores = nn.functional.log_softmax(
                next_token_logits, dim=-1
            )  # (batch_size * num_beams, vocab_size)

            next_token_scores_processed = logits_processor(input_ids, next_token_scores)
2762
2763
2764
            next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
                next_token_scores_processed
            )
2765
2766
2767
2768
2769

            # Store scores, attentions and hidden_states when required
            if return_dict_in_generate:
                if output_scores:
                    scores += (next_token_scores_processed,)
2770
2771
                if output_logits:
                    raw_logits += (next_token_logits,)
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
                if output_attentions:
                    decoder_attentions += (
                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
                    )
                    if self.config.is_encoder_decoder:
                        cross_attentions += (outputs.cross_attentions,)
                if output_hidden_states:
                    decoder_hidden_states += (
                        (outputs.decoder_hidden_states,)
                        if self.config.is_encoder_decoder
                        else (outputs.hidden_states,)
                    )

            # reshape for beam search
            vocab_size = next_token_scores.shape[-1]
            next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)

2789
            # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
2790
            n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
2791
            next_token_scores, next_tokens = torch.topk(
2792
                next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True
2793
2794
            )

2795
            next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
            next_tokens = next_tokens % vocab_size

            # stateless
            beam_outputs = beam_scorer.process(
                input_ids,
                next_token_scores,
                next_tokens,
                next_indices,
                pad_token_id=pad_token_id,
                eos_token_id=eos_token_id,
                beam_indices=beam_indices,
2807
                decoder_prompt_len=decoder_prompt_len,
2808
2809
2810
2811
2812
2813
2814
2815
2816
            )

            beam_scores = beam_outputs["next_beam_scores"]
            beam_next_tokens = beam_outputs["next_beam_tokens"]
            beam_idx = beam_outputs["next_beam_indices"]

            input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)

            model_kwargs = self._update_model_kwargs_for_generation(
2817
2818
2819
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
2820
            )
2821
            if model_kwargs.get("past_key_values", None) is not None:
2822
2823
2824
                model_kwargs["past_key_values"] = self._temporary_reorder_cache(
                    model_kwargs["past_key_values"], beam_idx
                )
2825
2826
2827
2828
2829
2830
2831

            if return_dict_in_generate and output_scores:
                beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))

            # increase cur_len
            cur_len = cur_len + 1

2832
            if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
2833
                this_peer_finished = True
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843

        sequence_outputs = beam_scorer.finalize(
            input_ids,
            beam_scores,
            next_tokens,
            next_indices,
            pad_token_id=pad_token_id,
            eos_token_id=eos_token_id,
            max_length=stopping_criteria.max_length,
            beam_indices=beam_indices,
2844
            decoder_prompt_len=decoder_prompt_len,
2845
2846
2847
2848
2849
2850
2851
        )

        if return_dict_in_generate:
            if not output_scores:
                sequence_outputs["sequence_scores"] = None

            if self.config.is_encoder_decoder:
2852
                return GenerateBeamEncoderDecoderOutput(
2853
2854
2855
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
2856
                    logits=raw_logits,
2857
2858
2859
2860
2861
2862
                    beam_indices=sequence_outputs["beam_indices"],
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
2863
                    past_key_values=model_kwargs.get("past_key_values"),
2864
2865
                )
            else:
2866
                return GenerateBeamDecoderOnlyOutput(
2867
2868
2869
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
2870
                    logits=raw_logits,
2871
2872
2873
                    beam_indices=sequence_outputs["beam_indices"],
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
2874
                    past_key_values=model_kwargs.get("past_key_values"),
2875
2876
2877
2878
                )
        else:
            return sequence_outputs["sequences"]

2879
    def _beam_sample(
2880
2881
2882
        self,
        input_ids: torch.LongTensor,
        beam_scorer: BeamScorer,
2883
2884
2885
2886
2887
        logits_processor: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        logits_warper: LogitsProcessorList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
2888
        **model_kwargs,
2889
    ) -> Union[GenerateBeamOutput, torch.LongTensor]:
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
        r"""
        Generates sequences of token ids for models with a language modeling head using **beam search multinomial
        sampling** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            beam_scorer (`BeamScorer`):
                A derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
                sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
2900
            logits_processor (`LogitsProcessorList`):
2901
2902
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
2903
            stopping_criteria (`StoppingCriteriaList`):
2904
2905
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
2906
            logits_warper (`LogitsProcessorList`):
2907
2908
2909
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsWarper`] used
                to warp the prediction score distribution of the language modeling head applied before multinomial
                sampling at each generation step.
2910
2911
2912
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
2913
2914
2915
2916
2917
2918
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
            model_kwargs:
                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
                an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
2919
            [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
2920
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
2921
2922
            [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
2923
            `model.config.is_encoder_decoder=True`.
2924
        """
2925
        # init values
2926
2927
2928
2929
2930
2931
2932
        pad_token_id = generation_config.pad_token_id
        eos_token_id = generation_config.eos_token_id
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
2933

2934
2935
2936
2937
        batch_size = len(beam_scorer._beam_hyps)
        num_beams = beam_scorer.num_beams

        batch_beam_size, cur_len = input_ids.shape
2938
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
2939
2940
2941

        # init attention / hidden states / scores tuples
        scores = () if (return_dict_in_generate and output_scores) else None
2942
        raw_logits = () if (return_dict_in_generate and output_logits) else None
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
        beam_indices = (
            tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
        )
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
        beam_scores = beam_scores.view((batch_size * num_beams,))

2960
        this_peer_finished = False
2961
2962

        decoder_prompt_len = input_ids.shape[-1]  # record the prompt length of decoder
2963
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
            model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)

            outputs = self(
                **model_inputs,
                return_dict=True,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
            )

            if synced_gpus and this_peer_finished:
                cur_len = cur_len + 1
                continue  # don't waste resources running the code we don't need

            next_token_logits = outputs.logits[:, -1, :]

            next_token_scores = nn.functional.log_softmax(
                next_token_logits, dim=-1
            )  # (batch_size * num_beams, vocab_size)

            next_token_scores_processed = logits_processor(input_ids, next_token_scores)
2984
            next_token_scores_processed = logits_warper(input_ids, next_token_scores_processed)
2985
2986
2987
            next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
                next_token_scores_processed
            )
2988
2989
2990
2991

            # Store scores, attentions and hidden_states when required
            if return_dict_in_generate:
                if output_scores:
2992
                    scores += (next_token_scores_processed,)
2993
2994
                if output_logits:
                    raw_logits += (next_token_logits,)
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
                if output_attentions:
                    decoder_attentions += (
                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
                    )
                    if self.config.is_encoder_decoder:
                        cross_attentions += (outputs.cross_attentions,)

                if output_hidden_states:
                    decoder_hidden_states += (
                        (outputs.decoder_hidden_states,)
                        if self.config.is_encoder_decoder
                        else (outputs.hidden_states,)
                    )

            # reshape for beam search
            vocab_size = next_token_scores.shape[-1]
            next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)

            probs = nn.functional.softmax(next_token_scores, dim=-1)

            next_tokens = torch.multinomial(probs, num_samples=2 * num_beams)
            next_token_scores = torch.gather(next_token_scores, -1, next_tokens)

            next_token_scores, _indices = torch.sort(next_token_scores, descending=True, dim=1)
            next_tokens = torch.gather(next_tokens, -1, _indices)

3021
            next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
            next_tokens = next_tokens % vocab_size

            # stateless
            beam_outputs = beam_scorer.process(
                input_ids,
                next_token_scores,
                next_tokens,
                next_indices,
                pad_token_id=pad_token_id,
                eos_token_id=eos_token_id,
                beam_indices=beam_indices,
3033
                decoder_prompt_len=decoder_prompt_len,
3034
3035
3036
3037
3038
3039
3040
3041
            )
            beam_scores = beam_outputs["next_beam_scores"]
            beam_next_tokens = beam_outputs["next_beam_tokens"]
            beam_idx = beam_outputs["next_beam_indices"]

            input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)

            model_kwargs = self._update_model_kwargs_for_generation(
3042
3043
3044
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
3045
            )
3046
            if model_kwargs.get("past_key_values", None) is not None:
3047
3048
3049
                model_kwargs["past_key_values"] = self._temporary_reorder_cache(
                    model_kwargs["past_key_values"], beam_idx
                )
3050
3051
3052
3053
3054
3055
3056

            if return_dict_in_generate and output_scores:
                beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))

            # increase cur_len
            cur_len = cur_len + 1

3057
            if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
3058
                this_peer_finished = True
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068

        sequence_outputs = beam_scorer.finalize(
            input_ids,
            beam_scores,
            next_tokens,
            next_indices,
            pad_token_id=pad_token_id,
            eos_token_id=eos_token_id,
            max_length=stopping_criteria.max_length,
            beam_indices=beam_indices,
3069
            decoder_prompt_len=decoder_prompt_len,
3070
3071
3072
3073
3074
3075
3076
        )

        if return_dict_in_generate:
            if not output_scores:
                sequence_outputs["sequence_scores"] = None

            if self.config.is_encoder_decoder:
3077
                return GenerateBeamEncoderDecoderOutput(
3078
3079
3080
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
3081
                    logits=raw_logits,
3082
3083
3084
3085
3086
3087
                    beam_indices=sequence_outputs["beam_indices"],
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
3088
                    past_key_values=model_kwargs.get("past_key_values"),
3089
3090
                )
            else:
3091
                return GenerateBeamDecoderOnlyOutput(
3092
3093
3094
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
3095
                    logits=raw_logits,
3096
3097
3098
                    beam_indices=sequence_outputs["beam_indices"],
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
3099
                    past_key_values=model_kwargs.get("past_key_values"),
3100
3101
3102
3103
                )
        else:
            return sequence_outputs["sequences"]

3104
    def _group_beam_search(
3105
3106
3107
        self,
        input_ids: torch.LongTensor,
        beam_scorer: BeamScorer,
3108
3109
3110
3111
        logits_processor: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
        **model_kwargs,
    ):
        r"""
        Generates sequences of token ids for models with a language modeling head using **diverse beam search
        decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            beam_scorer (`BeamScorer`):
                An derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
                sorted during generation. For more information, the documentation of [`BeamScorer`] should be read.
3124
            logits_processor (`LogitsProcessorList`):
3125
3126
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
3127
            stopping_criteria (`StoppingCriteriaList`):
3128
3129
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
3130
3131
3132
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
3133
3134
3135
3136
3137
3138
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
            model_kwargs:
                Additional model specific kwargs that will be forwarded to the `forward` function of the model. If
                model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
3139
            [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
3140
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
3141
3142
3143
            [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
            `model.config.is_encoder_decoder=True`.
3144
        """
3145
        # init values
3146
3147
3148
3149
3150
3151
3152
        pad_token_id = generation_config.pad_token_id
        eos_token_id = generation_config.eos_token_id
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
3153

3154
3155
3156
        num_beams = beam_scorer.num_beams
        num_beam_groups = beam_scorer.num_beam_groups
        num_sub_beams = num_beams // num_beam_groups
3157
        batch_size = len(beam_scorer._beam_hyps) // num_beam_groups
3158
3159
3160
        device = input_ids.device

        batch_beam_size, cur_len = input_ids.shape
3161
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174

        if return_dict_in_generate and output_scores:
            beam_indices = [tuple(() for _ in range(num_sub_beams * batch_size)) for _ in range(num_beam_groups)]
        else:
            beam_indices = None

        if num_beams * batch_size != batch_beam_size:
            raise ValueError(
                f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
            )

        # init attention / hidden states / scores tuples
        scores = () if (return_dict_in_generate and output_scores) else None
3175
        raw_logits = () if (return_dict_in_generate and output_logits) else None
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        # initialise score of first beam of each group with 0 and the rest with -1e9. This ensures that the beams in
        # the same group don't produce same tokens everytime.
        beam_scores = torch.full((batch_size, num_beams), -1e9, dtype=torch.float, device=device)
        beam_scores[:, ::num_sub_beams] = 0
        beam_scores = beam_scores.view((batch_size * num_beams,))

3193
        this_peer_finished = False
3194
3195

        decoder_prompt_len = input_ids.shape[-1]  # record the prompt length of decoder
3196
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
            # predicted tokens in cur_len step
            current_tokens = torch.zeros(batch_size * num_beams, dtype=input_ids.dtype, device=device)

            # indices which will form the beams in the next time step
            reordering_indices = torch.zeros(batch_size * num_beams, dtype=torch.long, device=device)

            # do one decoder step on all beams of all sentences in batch
            model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
            outputs = self(
                **model_inputs,
                return_dict=True,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
            )

            if synced_gpus and this_peer_finished:
                cur_len = cur_len + 1
                continue  # don't waste resources running the code we don't need

            if output_scores:
                processed_score = torch.zeros_like(outputs.logits[:, -1, :])
3218
3219
            if output_logits:
                raw_logit_score = outputs.logits[:, -1, :]
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254

            for beam_group_idx in range(num_beam_groups):
                group_start_idx = beam_group_idx * num_sub_beams
                group_end_idx = min(group_start_idx + num_sub_beams, num_beams)
                group_size = group_end_idx - group_start_idx

                # indices of beams of current group among all sentences in batch
                batch_group_indices = []

                for batch_idx in range(batch_size):
                    batch_group_indices.extend(
                        [batch_idx * num_beams + idx for idx in range(group_start_idx, group_end_idx)]
                    )
                group_input_ids = input_ids[batch_group_indices]

                # select outputs of beams of current group only
                next_token_logits = outputs.logits[batch_group_indices, -1, :]

                next_token_scores = nn.functional.log_softmax(
                    next_token_logits, dim=-1
                )  # (batch_size * group_size, vocab_size)
                vocab_size = next_token_scores.shape[-1]

                next_token_scores_processed = logits_processor(
                    group_input_ids, next_token_scores, current_tokens=current_tokens, beam_group_idx=beam_group_idx
                )
                next_token_scores = next_token_scores_processed + beam_scores[batch_group_indices].unsqueeze(-1)
                next_token_scores = next_token_scores.expand_as(next_token_scores_processed)

                if output_scores:
                    processed_score[batch_group_indices] = next_token_scores_processed

                # reshape for beam search
                next_token_scores = next_token_scores.view(batch_size, group_size * vocab_size)

3255
                # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
3256
                n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
3257
                next_token_scores, next_tokens = torch.topk(
3258
                    next_token_scores, max(2, 1 + n_eos_tokens) * group_size, dim=1, largest=True, sorted=True
3259
3260
                )

3261
                next_indices = torch.div(next_tokens, vocab_size, rounding_mode="floor")
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
                next_tokens = next_tokens % vocab_size

                # stateless
                process_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
                beam_outputs = beam_scorer.process(
                    group_input_ids,
                    next_token_scores,
                    next_tokens,
                    next_indices,
                    pad_token_id=pad_token_id,
                    eos_token_id=eos_token_id,
                    beam_indices=process_beam_indices,
3274
                    group_index=beam_group_idx,
3275
                    decoder_prompt_len=decoder_prompt_len,
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
                )
                beam_scores[batch_group_indices] = beam_outputs["next_beam_scores"]
                beam_next_tokens = beam_outputs["next_beam_tokens"]
                beam_idx = beam_outputs["next_beam_indices"]

                if return_dict_in_generate and output_scores:
                    beam_indices[beam_group_idx] = tuple(
                        beam_indices[beam_group_idx][beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices[0]))
                    )

                input_ids[batch_group_indices] = group_input_ids[beam_idx]
                group_input_ids = torch.cat([group_input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
                current_tokens[batch_group_indices] = group_input_ids[:, -1]

                # (beam_idx // group_size) -> batch_idx
                # (beam_idx % group_size) -> offset of idx inside the group
                reordering_indices[batch_group_indices] = (
3293
3294
3295
                    num_beams * torch.div(beam_idx, group_size, rounding_mode="floor")
                    + group_start_idx
                    + (beam_idx % group_size)
3296
3297
3298
3299
3300
3301
                )

            # Store scores, attentions and hidden_states when required
            if return_dict_in_generate:
                if output_scores:
                    scores += (processed_score,)
3302
3303
                if output_logits:
                    raw_logits += (raw_logit_score,)
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
                if output_attentions:
                    decoder_attentions += (
                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
                    )
                    if self.config.is_encoder_decoder:
                        cross_attentions += (outputs.cross_attentions,)

                if output_hidden_states:
                    decoder_hidden_states += (
                        (outputs.decoder_hidden_states,)
                        if self.config.is_encoder_decoder
                        else (outputs.hidden_states,)
                    )

            input_ids = torch.cat([input_ids, current_tokens.unsqueeze(-1)], dim=-1)

            model_kwargs = self._update_model_kwargs_for_generation(
3321
3322
3323
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
3324
            )
3325
            if model_kwargs.get("past_key_values", None) is not None:
3326
                model_kwargs["past_key_values"] = self._temporary_reorder_cache(
3327
3328
                    model_kwargs["past_key_values"], reordering_indices
                )
3329
3330
3331
3332

            # increase cur_len
            cur_len = cur_len + 1

3333
            if beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
3334
                this_peer_finished = True
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345

        final_beam_indices = sum(beam_indices, ()) if beam_indices is not None else None
        sequence_outputs = beam_scorer.finalize(
            input_ids,
            beam_scores,
            next_tokens,
            next_indices,
            pad_token_id=pad_token_id,
            eos_token_id=eos_token_id,
            max_length=stopping_criteria.max_length,
            beam_indices=final_beam_indices,
3346
            decoder_prompt_len=decoder_prompt_len,
3347
3348
3349
3350
3351
3352
3353
        )

        if return_dict_in_generate:
            if not output_scores:
                sequence_outputs["sequence_scores"] = None

            if self.config.is_encoder_decoder:
3354
                return GenerateBeamEncoderDecoderOutput(
3355
3356
3357
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
3358
                    logits=raw_logits,
3359
3360
3361
3362
3363
3364
                    beam_indices=sequence_outputs["beam_indices"],
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
3365
                    past_key_values=model_kwargs.get("past_key_values"),
3366
3367
                )
            else:
3368
                return GenerateBeamDecoderOnlyOutput(
3369
3370
3371
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
3372
                    logits=raw_logits,
3373
3374
3375
                    beam_indices=sequence_outputs["beam_indices"],
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
3376
                    past_key_values=model_kwargs.get("past_key_values"),
3377
3378
3379
3380
                )
        else:
            return sequence_outputs["sequences"]

3381
    def _constrained_beam_search(
3382
3383
3384
        self,
        input_ids: torch.LongTensor,
        constrained_beam_scorer: ConstrainedBeamSearchScorer,
3385
3386
3387
3388
        logits_processor: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
3389
        **model_kwargs,
3390
    ) -> Union[GenerateBeamOutput, torch.LongTensor]:
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
        r"""
        Generates sequences of token ids for models with a language modeling head using **constrained beam search
        decoding** and can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
            constrained_beam_scorer (`ConstrainedBeamSearchScorer`):
                A derived instance of [`BeamScorer`] that defines how beam hypotheses are constructed, stored and
                sorted during generation, while satisfying a list of positive constraints. For more information, the
                documentation of [`ConstrainedBeamSearchScorer`] should be read.
3402
            logits_processor (`LogitsProcessorList`):
3403
3404
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
3405
            stopping_criteria (`StoppingCriteriaList`):
3406
3407
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
3408
            logits_warper (`LogitsProcessorList`):
3409
3410
3411
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsWarper`] used
                to warp the prediction score distribution of the language modeling head applied before multinomial
                sampling at each generation step.
3412
3413
3414
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
3415
3416
3417
3418
3419
3420
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
            model_kwargs:
                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is
                an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
3421
            [`~generation.GenerateBeamDecoderOnlyOutput`], [`~generation.GenerateBeamEncoderDecoderOutput`] or
3422
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
3423
3424
            [`~generation.GenerateBeamDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateBeamEncoderDecoderOutput`] if
3425
            `model.config.is_encoder_decoder=True`.
3426
        """
3427
        # init values
3428
3429
3430
3431
3432
3433
3434
        pad_token_id = generation_config.pad_token_id
        eos_token_id = generation_config.eos_token_id
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
3435

3436
3437
3438
3439
        batch_size = len(constrained_beam_scorer._beam_hyps)
        num_beams = constrained_beam_scorer.num_beams

        batch_beam_size, cur_len = input_ids.shape
3440
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
3441
3442
3443
3444
3445
3446

        if num_beams * batch_size != batch_beam_size:
            raise ValueError(
                f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}."
            )

3447
3448
        # init attention / hidden states / scores tuples
        scores = () if (return_dict_in_generate and output_scores) else None
3449
        raw_logits = () if (return_dict_in_generate and output_logits) else None
3450
3451
3452
        beam_indices = (
            tuple(() for _ in range(batch_beam_size)) if (return_dict_in_generate and output_scores) else None
        )
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        # initialise score of first beam with 0 and the rest with -1e9. This makes sure that only tokens
        # of the first beam are considered to avoid sampling the exact same tokens across all beams.
        beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device)
        beam_scores[:, 1:] = -1e9
        beam_scores = beam_scores.view((batch_size * num_beams,))

3470
        this_peer_finished = False
3471
3472

        decoder_prompt_len = input_ids.shape[-1]  # record the prompt length of decoder
3473
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
            model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)

            outputs = self(
                **model_inputs,
                return_dict=True,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
            )

            if synced_gpus and this_peer_finished:
                cur_len = cur_len + 1
                continue  # don't waste resources running the code we don't need

            next_token_logits = outputs.logits[:, -1, :]
            next_token_scores = nn.functional.log_softmax(
                next_token_logits, dim=-1
            )  # (batch_size * num_beams, vocab_size)

            next_token_scores_processed = logits_processor(input_ids, next_token_scores)

3494
3495
3496
            next_token_scores = next_token_scores_processed + beam_scores[:, None].expand_as(
                next_token_scores_processed
            )
3497
3498
3499
3500
3501
3502
3503

            scores_for_all_vocab = next_token_scores.clone()

            # Store scores, attentions and hidden_states when required
            if return_dict_in_generate:
                if output_scores:
                    scores += (next_token_scores,)
3504
3505
                if output_logits:
                    raw_logits += (next_token_logits,)
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
                if output_attentions:
                    decoder_attentions += (
                        (outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
                    )
                    if self.config.is_encoder_decoder:
                        cross_attentions += (outputs.cross_attentions,)

                if output_hidden_states:
                    decoder_hidden_states += (
                        (outputs.decoder_hidden_states,)
                        if self.config.is_encoder_decoder
                        else (outputs.hidden_states,)
                    )

            # reshape for beam search
            vocab_size = next_token_scores.shape[-1]
            next_token_scores = next_token_scores.view(batch_size, num_beams * vocab_size)

3524
            # Sample 1 + len(eos_token_id) next tokens for each beam so we have at least 1 non eos token per beam.
3525
            n_eos_tokens = eos_token_id.shape[0] if eos_token_id is not None else 0
3526
            next_token_scores, next_tokens = torch.topk(
3527
                next_token_scores, max(2, 1 + n_eos_tokens) * num_beams, dim=1, largest=True, sorted=True
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
            )

            next_indices = (next_tokens / vocab_size).long()
            next_tokens = next_tokens % vocab_size

            # stateless
            beam_outputs = constrained_beam_scorer.process(
                input_ids,
                next_token_scores,
                next_tokens,
                next_indices,
                scores_for_all_vocab,
                pad_token_id=pad_token_id,
                eos_token_id=eos_token_id,
3542
                beam_indices=beam_indices,
3543
                decoder_prompt_len=decoder_prompt_len,
3544
3545
3546
3547
3548
3549
3550
            )
            beam_scores = beam_outputs["next_beam_scores"]
            beam_next_tokens = beam_outputs["next_beam_tokens"]
            beam_idx = beam_outputs["next_beam_indices"]

            input_ids = torch.cat([input_ids[beam_idx, :], beam_next_tokens.unsqueeze(-1)], dim=-1)
            model_kwargs = self._update_model_kwargs_for_generation(
3551
3552
3553
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
3554
            )
3555
            if model_kwargs.get("past_key_values", None) is not None:
3556
3557
3558
                model_kwargs["past_key_values"] = self._temporary_reorder_cache(
                    model_kwargs["past_key_values"], beam_idx
                )
3559

3560
3561
3562
            if return_dict_in_generate and output_scores:
                beam_indices = tuple((beam_indices[beam_idx[i]] + (beam_idx[i],) for i in range(len(beam_indices))))

3563
3564
3565
            # increase cur_len
            cur_len = cur_len + 1

3566
            if constrained_beam_scorer.is_done or all(stopping_criteria(input_ids, scores)):
3567
                this_peer_finished = True
3568
3569
3570
3571
3572
3573
3574
3575
3576

        sequence_outputs = constrained_beam_scorer.finalize(
            input_ids,
            beam_scores,
            next_tokens,
            next_indices,
            pad_token_id=pad_token_id,
            eos_token_id=eos_token_id,
            max_length=stopping_criteria.max_length,
3577
            beam_indices=beam_indices,
3578
            decoder_prompt_len=decoder_prompt_len,
3579
3580
3581
3582
3583
3584
        )

        if return_dict_in_generate:
            if not output_scores:
                sequence_outputs["sequence_scores"] = None
            if self.config.is_encoder_decoder:
3585
                return GenerateBeamEncoderDecoderOutput(
3586
3587
3588
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
3589
                    logits=raw_logits,
3590
                    beam_indices=sequence_outputs["beam_indices"],
3591
3592
3593
3594
3595
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
3596
                    past_key_values=model_kwargs.get("past_key_values"),
3597
3598
                )
            else:
3599
                return GenerateBeamDecoderOnlyOutput(
3600
3601
3602
                    sequences=sequence_outputs["sequences"],
                    sequences_scores=sequence_outputs["sequence_scores"],
                    scores=scores,
3603
                    logits=raw_logits,
3604
                    beam_indices=sequence_outputs["beam_indices"],
3605
3606
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
3607
                    past_key_values=model_kwargs.get("past_key_values"),
3608
3609
3610
3611
                )
        else:
            return sequence_outputs["sequences"]

3612
    def _assisted_decoding(
3613
3614
        self,
        input_ids: torch.LongTensor,
3615
3616
3617
3618
3619
3620
3621
        candidate_generator: CandidateGenerator,
        logits_processor: LogitsProcessorList,
        logits_warper: LogitsProcessorList,
        stopping_criteria: StoppingCriteriaList,
        generation_config: GenerationConfig,
        synced_gpus: bool,
        streamer: Optional["BaseStreamer"],
3622
        **model_kwargs,
3623
    ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:
3624
        r"""
3625
        Generates sequences of token ids for models with a language modeling head using **greedy decoding** or
3626
3627
3628
        **sample** (depending on `do_sample`), assisted by candidate sequences. Assisted generation is an example of a
        candidate decoding strategy. Can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text
        models.
3629
3630
3631
3632

        Parameters:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                The sequence used as a prompt for the generation.
3633
            candidate_generator (`CandidateGenerator`):
3634
                A derived instance of [`CandidateGenerator`] that defines how candidate sequences are generated. For
3635
                more information, the documentation of [`CandidateGenerator`] should be read.
3636
            logits_processor (`LogitsProcessorList`):
3637
3638
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
                used to modify the prediction scores of the language modeling head applied at each generation step.
3639
            logits_warper (`LogitsProcessorList`):
3640
3641
                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsWarper`] used
                to warp the prediction score distribution of the language modeling head applied before multinomial
3642
3643
                sampling at each generation step. Only used if sampling is active.
            stopping_criteria (`StoppingCriteriaList`):
3644
3645
                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
                used to tell if the generation loop should stop.
3646
3647
3648
            generation_config ([`~generation.GenerationConfig`]):
                The generation configuration to be used as parametrization of the decoding method.
            synced_gpus (`bool`):
3649
3650
3651
3652
3653
3654
3655
3656
3657
                Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
            streamer (`BaseStreamer`, *optional*):
                Streamer object that will be used to stream the generated sequences. Generated tokens are passed
                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
            model_kwargs:
                Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
                If model is an encoder-decoder model the kwargs should include `encoder_outputs`.

        Return:
3658
            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or
3659
            `torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
3660
3661
            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if
3662
            `model.config.is_encoder_decoder=True`.
3663
        """
3664
        # init values
3665
3666
3667
3668
3669
3670
        do_sample = logits_warper is not None
        output_attentions = generation_config.output_attentions
        output_hidden_states = generation_config.output_hidden_states
        output_scores = generation_config.output_scores
        output_logits = generation_config.output_logits
        return_dict_in_generate = generation_config.return_dict_in_generate
3671
3672
3673

        # init attention / hidden states / scores tuples
        scores = () if (return_dict_in_generate and output_scores) else None
3674
        raw_logits = () if (return_dict_in_generate and output_logits) else None
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
        cross_attentions = () if (return_dict_in_generate and output_attentions) else None
        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None

        # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
        if return_dict_in_generate and self.config.is_encoder_decoder:
            encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
            encoder_hidden_states = (
                model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
            )

        # keep track of which sequences are already finished
3687
        batch_size = input_ids.shape[0]
3688
        unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
3689
        model_kwargs = self._get_initial_cache_position(input_ids, model_kwargs)
3690

3691
3692
        this_peer_finished = False
        while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
3693
3694
            cur_len = input_ids.shape[-1]

3695
            #  1. Fetch candidate sequences from a `CandidateGenerator`
3696
            candidate_input_ids, candidate_logits = candidate_generator.get_candidates(input_ids)
3697
            candidate_input_ids = candidate_input_ids.to(self.device)
3698
3699
            if candidate_logits is not None:
                candidate_logits = candidate_logits.to(self.device)
3700

3701
            candidate_length = candidate_input_ids.shape[1] - input_ids.shape[1]
3702
            is_done_candidate = stopping_criteria(candidate_input_ids, None)
3703
3704

            # 2. Use the original model to obtain the next token logits given the candidate sequence. We obtain
3705
3706
            # `candidate_length + 1` relevant logits from this process: in the event that all candidates are correct,
            # we use this forward pass to also pick the subsequent logits in the original model.
3707

3708
            # 2.1. Prepare the model inputs
3709
3710
3711
            candidate_kwargs = copy.copy(model_kwargs)
            candidate_kwargs = _prepare_attention_mask(
                candidate_kwargs, candidate_input_ids.shape[1], self.config.is_encoder_decoder
3712
            )
3713
3714
3715
            candidate_kwargs = _prepare_token_type_ids(candidate_kwargs, candidate_input_ids.shape[1])
            if "cache_position" in candidate_kwargs:
                candidate_kwargs["cache_position"] = torch.cat(
3716
                    (
3717
                        candidate_kwargs["cache_position"],
3718
3719
3720
3721
                        torch.arange(cur_len, cur_len + candidate_length, device=input_ids.device, dtype=torch.long),
                    ),
                    dim=0,
                )
3722

3723
            model_inputs = self.prepare_inputs_for_generation(candidate_input_ids, **candidate_kwargs)
tomeras91's avatar
tomeras91 committed
3724
3725
            if "num_logits_to_keep" in model_inputs:
                model_inputs["num_logits_to_keep"] = candidate_length + 1
3726
3727
3728
3729
3730
3731
3732

            # 2.2. Run a forward pass on the candidate sequence
            outputs = self(
                **model_inputs,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
            )
3733

3734
            # 2.3. Process the new logits
3735
            new_logits = outputs.logits[:, -candidate_length - 1 :]  # excludes the input prompt if present
3736
            next_token_logits = new_logits.clone()
3737
            if len(logits_processor) > 0:
3738
                for i in range(candidate_length + 1):
3739
                    new_logits[:, i, :] = logits_processor(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])
3740
            if do_sample and len(logits_warper) > 0:
3741
                for i in range(candidate_length + 1):
3742
3743
                    new_logits[:, i, :] = logits_warper(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])

3744
3745
3746
3747
            # 3. Select the accepted tokens. There are two possible cases:
            # Case 1: `do_sample=True` and we have logits for the candidates (originally from speculative decoding)
            # 👉 Apply algorithm 1 from the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf).
            if do_sample and candidate_logits is not None:
3748
                valid_tokens, n_matches = _speculative_sampling(
3749
3750
3751
3752
                    candidate_input_ids,
                    candidate_logits,
                    candidate_length,
                    new_logits,
3753
                    is_done_candidate,
3754
3755
3756
3757
3758
                )

            # Case 2: all other cases (originally from assisted generation) 👉 Compare the tokens selected from the
            # original model logits with the candidate tokens. We can keep the candidate tokens until the first
            # mismatch, or until the max length is reached.
3759
            else:
3760
3761
3762
3763
3764
                if do_sample:
                    probs = new_logits.softmax(dim=-1)
                    selected_tokens = torch.multinomial(probs[0, :, :], num_samples=1).squeeze(1)[None, :]
                else:
                    selected_tokens = new_logits.argmax(dim=-1)
3765

3766
                candidate_new_tokens = candidate_input_ids[:, cur_len:]
3767
                n_matches = ((~(candidate_new_tokens == selected_tokens[:, :-1])).cumsum(dim=-1) < 1).sum()
3768

3769
                # Ensure we don't generate beyond max_len or an EOS token
3770
                if is_done_candidate and n_matches == candidate_length:
3771
                    n_matches -= 1
3772
                valid_tokens = selected_tokens[:, : n_matches + 1]
3773
3774

            # 4. Update variables according to the number of matching assistant tokens. Remember: the token generated
3775
3776
3777
            # by the model after the last candidate match is also valid, as it is generated from a correct sequence.
            # Because of this last token, assisted generation search reduces to a normal greedy search/sample if there
            # is no match.
3778

3779
            # 4.1. Get the valid continuation, after the matching tokens
3780
            input_ids = torch.cat((input_ids, valid_tokens), dim=-1)
3781
            if streamer is not None:
3782
3783
                streamer.put(valid_tokens.cpu())
            new_cur_len = input_ids.shape[-1]
3784

3785
            # 4.2. Discard past key values relative to unused assistant tokens
3786
3787
            new_cache_size = new_cur_len - 1
            outputs.past_key_values = _crop_past_key_values(self, outputs.past_key_values, new_cache_size)
3788

3789
            # 5. Update the candidate generation strategy if needed
3790
3791
            candidate_generator.update_candidate_strategy(input_ids, new_logits, n_matches)

3792
3793
3794
3795
3796
3797
3798
3799
            if synced_gpus and this_peer_finished:
                continue  # don't waste resources running the code we don't need

            # Store scores, attentions and hidden_states when required
            # Assistant: modified to append one tuple element per token, as in the other generation methods.
            if return_dict_in_generate:
                if output_scores:
                    scores += tuple(new_logits[:, i, :] for i in range(n_matches + 1))
3800
3801
                if output_logits:
                    raw_logits += (next_token_logits,)
3802
3803

                if "past_key_values" not in model_kwargs:
3804
                    added_len = new_cur_len
3805
                else:
3806
                    added_len = n_matches + 1
3807
3808
3809
3810

                if output_attentions:
                    if self.config.is_encoder_decoder:
                        cross_attentions = _split_model_outputs(
3811
                            cross_attentions, outputs.cross_attentions, cur_len, added_len
3812
3813
3814
3815
                        )
                        decoder_attentions = _split_model_outputs(
                            decoder_attentions,
                            outputs.decoder_attentions,
3816
                            cur_len,
3817
                            added_len,
3818
3819
3820
3821
3822
3823
                            is_decoder_attention=True,
                        )
                    else:
                        decoder_attentions = _split_model_outputs(
                            decoder_attentions,
                            outputs.attentions,
3824
                            cur_len,
3825
                            added_len,
3826
3827
3828
3829
3830
                            is_decoder_attention=True,
                        )
                if output_hidden_states:
                    if self.config.is_encoder_decoder:
                        decoder_hidden_states = _split_model_outputs(
3831
                            decoder_hidden_states, outputs.decoder_hidden_states, cur_len, added_len
3832
3833
3834
                        )
                    else:
                        decoder_hidden_states = _split_model_outputs(
3835
                            decoder_hidden_states, outputs.hidden_states, cur_len, added_len
3836
3837
3838
                        )

            model_kwargs = self._update_model_kwargs_for_generation(
3839
3840
3841
                outputs,
                model_kwargs,
                is_encoder_decoder=self.config.is_encoder_decoder,
3842
                num_new_tokens=n_matches + 1,
3843
3844
            )

3845
            unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
3846
            this_peer_finished = unfinished_sequences.max() == 0
3847

3848
3849
3850
        if streamer is not None:
            streamer.end()

3851
3852
3853
3854
3855
3856
3857
        if (
            hasattr(candidate_generator, "assistant_model")
            and candidate_generator.assistant_model.generation_config.num_assistant_tokens_schedule == "heuristic"
        ):
            candidate_generator.assistant_model.generation_config.num_assistant_tokens = (
                candidate_generator.num_assistant_tokens
            )
3858
3859
        if return_dict_in_generate:
            if self.config.is_encoder_decoder:
3860
                return GenerateEncoderDecoderOutput(
3861
3862
                    sequences=input_ids,
                    scores=scores,
3863
                    logits=raw_logits,
3864
3865
3866
3867
3868
                    encoder_attentions=encoder_attentions,
                    encoder_hidden_states=encoder_hidden_states,
                    decoder_attentions=decoder_attentions,
                    cross_attentions=cross_attentions,
                    decoder_hidden_states=decoder_hidden_states,
3869
                    past_key_values=model_kwargs.get("past_key_values"),
3870
3871
                )
            else:
3872
                return GenerateDecoderOnlyOutput(
3873
3874
                    sequences=input_ids,
                    scores=scores,
3875
                    logits=raw_logits,
3876
3877
                    attentions=decoder_attentions,
                    hidden_states=decoder_hidden_states,
3878
                    past_key_values=model_kwargs.get("past_key_values"),
3879
3880
3881
3882
3883
                )
        else:
            return input_ids


3884
3885
3886
3887
3888
def _speculative_sampling(
    candidate_input_ids,
    candidate_logits,
    candidate_length,
    new_logits,
3889
    is_done_candidate,
3890
3891
3892
):
    """
    Applies sampling as in the speculative decoding paper (https://arxiv.org/pdf/2211.17192.pdf, algorithm 1). Returns
3893
    the selected tokens, as well as the number of candidate matches.
3894
3895
3896

    NOTE: Unless otherwise stated, the variable names match those in the paper.
    """
3897
    new_candidate_input_ids = candidate_input_ids[:, -candidate_length:]
3898
3899
3900
    # Gets the probabilities from the logits. q_i and p_i denote the assistant and model probabilities of the tokens
    # selected by the assistant, respectively.
    q = candidate_logits.softmax(dim=-1)
3901
    q_i = q[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
3902
    p = new_logits.softmax(dim=-1)
3903
    p_i = p[:, torch.arange(candidate_length), new_candidate_input_ids].squeeze(0, 1)
3904
3905
3906
3907
3908
3909
3910
    probability_ratio = p_i / q_i

    # When probability_ratio > 1 (i.e. q_i(x) < p_i(x), or "assistant probability of the candidate token is smaller
    # than the model probability for the same token"), keep the token. Otherwise reject with p = 1 - probability_ratio
    # (= keep with p = probability_ratio). Keep all the tokens until the first rejection
    r_i = torch.rand_like(probability_ratio)
    is_accepted = r_i <= probability_ratio
3911
    n_matches = ((~is_accepted).cumsum(dim=-1) < 1).sum()  # this is `n` in algorithm 1
3912
3913

    # Ensure we don't generate beyond max_len or an EOS token (not in algorithm 1, but needed for correct behavior)
3914
    if is_done_candidate and n_matches == candidate_length:
3915
3916
        # Output length is assumed to be `n_matches + 1`. Since we won't generate another token with the target model
        # due to acceptance on EOS we fix `n_matches`
3917
        n_matches -= 1
3918
        valid_tokens = new_candidate_input_ids[:, : n_matches + 1]
3919
    else:
3920
        # Next token selection: if there is a rejection, adjust the distribution from the main model before sampling.
3921
        gamma = candidate_logits.shape[1]
3922
3923
3924
3925
3926
3927
3928
3929
        p_n_plus_1 = p[:, n_matches, :]
        if n_matches < gamma:
            q_n_plus_1 = q[:, n_matches, :]
            p_prime = torch.clamp((p_n_plus_1 - q_n_plus_1), min=0)
            p_prime.div_(p_prime.sum())
        else:
            p_prime = p_n_plus_1
        t = torch.multinomial(p_prime, num_samples=1).squeeze(1)[None, :]
3930

3931
3932
3933
3934
3935
        # The selected tokens include the matches (if any) plus the next sampled tokens
        if n_matches > 0:
            valid_tokens = torch.cat((new_candidate_input_ids[:, :n_matches], t), dim=-1)
        else:
            valid_tokens = t
3936
3937

    return valid_tokens, n_matches
3938
3939


3940
def _split_model_outputs(outputs, new_outputs, cur_len, added_len, is_decoder_attention=False):
3941
3942
3943
3944
3945
3946
    """
    Given the (decoder/cross attentions)/(decoder hidden states) for multiple generated tokens, splits it into a tuple
    where each member corresponds to a single generated token.
    """
    # Retrocompatibility: in our generation functions, the first iteration includes the attention/hidden states for the
    # prompt.
3947
    if len(outputs) == 0:
3948
3949
        new_tuple = ()
        for layer in new_outputs:
3950
3951
            last_dim_size = cur_len if is_decoder_attention else layer.shape[-1]
            new_tuple += (layer[..., :cur_len, :last_dim_size],)
3952
        outputs += (new_tuple,)
3953
3954
3955
        # The first iteration contains the prompt + 1 generated token, let's update the length variables accordingly
        cur_len += 1
        added_len -= cur_len
3956

3957
    for i in range(added_len):
3958
3959
        new_tuple = ()
        for layer in new_outputs:
3960
            last_dim_size = cur_len + i if is_decoder_attention else layer.shape[-1]
3961
3962
3963
3964
            new_tuple += (layer[..., i : i + 1, :last_dim_size],)
        outputs += (new_tuple,)
    return outputs

3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986

def _ranking_fast(
    context_hidden: torch.FloatTensor,
    next_hidden: torch.FloatTensor,
    next_top_k_probs: torch.FloatTensor,
    alpha: float,
    beam_width: int,
) -> torch.FloatTensor:
    """
    Reranks the top_k candidates based on a degeneration penalty (cosine similarity with previous tokens), as described
    in the paper "A Contrastive Framework for Neural Text Generation". Returns the index of the best candidate for each
    row in the batch.
    """
    norm_context_hidden = context_hidden / context_hidden.norm(dim=2, keepdim=True)
    norm_next_hidden = next_hidden / next_hidden.norm(dim=2, keepdim=True)
    cosine_matrix = torch.matmul(norm_context_hidden, norm_next_hidden.transpose(1, 2)).squeeze(-1)  # [B*K, S]
    degeneration_penalty, _ = torch.max(cosine_matrix, dim=-1)  # [B*K]
    next_top_k_probs = next_top_k_probs.view(-1)  # [B*K]
    contrastive_score = (1.0 - alpha) * next_top_k_probs - alpha * degeneration_penalty
    contrastive_score = torch.stack(torch.split(contrastive_score, beam_width))  # [B, K]
    _, selected_idx = contrastive_score.max(dim=-1)  # [B]
    return selected_idx
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050


def _split(data, full_batch_size: int, split_size: int = None):
    """
    Takes care of three cases:
    1. data is a tensor: e.g. last_hidden_state, pooler_output etc. split them on the batch_size dim
    2. data is a tuple: e.g. hidden_states, attentions etc. Keep the tuple as it is and split each tensor in it and
       return a list of tuples
    3. data is a tuple of tuples, e.g. past_key_values. Keep the tuple as it is and split each tuple in it and
       return a list of tuples of tuples
    (see documentation of ModelOutput)
    """
    if data is None:
        return [None] * (full_batch_size // split_size)
    if isinstance(data, torch.Tensor):
        return [data[i : i + split_size] for i in range(0, full_batch_size, split_size)]
    elif isinstance(data, tuple):
        # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
        if isinstance(data[0], tuple):
            return [
                tuple(tuple(tensor[i : i + split_size] for tensor in inner_tuple) for inner_tuple in data)
                for i in range(0, full_batch_size, split_size)
            ]

        else:
            return [
                tuple(sub_tensor[i : i + split_size] for sub_tensor in data)
                for i in range(0, full_batch_size, split_size)
            ]
    else:
        raise ValueError(f"Unexpected attribute type: {type(data)}")


def _split_model_inputs(
    model_input: Union[ModelOutput, Dict], split_size: int, full_batch_size: int
) -> List[Union[ModelOutput, Dict]]:
    """
    Split a ModelOutput object (or its subclasses) or Dict into a list of same-class objects based on a specified split
    size. The input object is dict when it was prepared for forward pass and ModelOutput when it was returned from
    previous forward pass.
    """
    # Edge case: if model_input is None, return a list of Nones
    # this happens with Whisper where encoder_outputs is None
    if model_input is None:
        return [model_input] * (full_batch_size // split_size)
    # Infer the class from the object
    model_output_cls = type(model_input)
    if (full_batch_size % split_size) != 0:
        raise ValueError("`full_batch_size` must be divisible by `split_size`")

    if split_size > full_batch_size:
        raise ValueError("`split_size` must be smaller or equal to `full_batch_size`")

    # Helper function to split tensors or tuples of tensors

    # Find all the dataclass fields (e.g., last_hidden_state, pooler_output etc.) and split them
    keys = (
        model_input.__dataclass_fields__.keys() if hasattr(model_input, "__dataclass_fields__") else model_input.keys()
    )
    # We only keep keys that are in the model_input
    keys = [k for k in keys if k in model_input]
    # Here we can have four types of values: tensors, tuples of tensors and booleans, and encoder_outputs which is a
    # ModelOutput object.
    # bool should not be split but replicated for each split
4051
    bool_keys = [k for k in keys if isinstance(model_input[k], bool) or k == "cache_position"]
tomeras91's avatar
tomeras91 committed
4052
    keys_to_ignore = ["cache_position", "encoder_outputs", "num_logits_to_keep"]
4053
    non_bool_keys = [k for k in keys if not isinstance(model_input[k], bool) and k not in keys_to_ignore]
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067

    # we split the tensors and tuples of tensors
    data_split_list = [
        {k: _split(model_input[k], full_batch_size, split_size)[i] for k in non_bool_keys}
        for i in range(full_batch_size // split_size)
    ]
    # bool values are the same and replicated for each split
    bool_data = {k: model_input[k] for k in bool_keys}
    # encoder_outputs is a ModelOutput object and should be split by its own
    if "encoder_outputs" in model_input:
        encoder_outputs_split = _split_model_inputs(model_input["encoder_outputs"], split_size, full_batch_size)
        data_split_list = [
            {**data_split, "encoder_outputs": encoder_outputs_split[i]} for i, data_split in enumerate(data_split_list)
        ]
tomeras91's avatar
tomeras91 committed
4068
4069
4070
4071
4072
    # num_logits_to_keep should be replicated for each split, similar to bool values
    if "num_logits_to_keep" in model_input:
        data_split_list = [
            {**data_split, "num_logits_to_keep": model_input["num_logits_to_keep"]} for data_split in data_split_list
        ]
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128

    # Convert each dictionary in the list to an object of the inferred class
    split_model_inputs: List[Union[ModelOutput, Dict]] = [
        model_output_cls(**data_split, **bool_data) for data_split in data_split_list
    ]

    return split_model_inputs


def stack_model_outputs(model_outputs: List[ModelOutput]) -> ModelOutput:
    """
    Stack a list of ModelOutput objects (or its subclasses) along the batch_size dimension. The function infers the
    specific ModelOutput subclass from the list provided.
    """
    if not model_outputs:
        raise ValueError("Input list is empty.")

    # Infer the class from the first object in the list
    model_output_cls = type(model_outputs[0])

    # Ensure all objects are of the same type
    if not all(isinstance(obj, model_output_cls) for obj in model_outputs):
        raise ValueError("All elements in the list should be of the same type.")

    # Helper function to concat tensors or tuples of tensors
    def _concat(data):
        """
        Reverse of `_split` function above.
        """
        if any(data is None for data in data):
            return None
        if isinstance(data[0], torch.Tensor):
            return torch.cat(data, dim=0)
        elif isinstance(data[0], tuple):
            # If the elements of the tuple are also tuples (e.g., past_key_values in our earlier example)
            if isinstance(data[0][0], tuple):
                return tuple(
                    tuple(torch.cat([attr[i][j] for attr in data], dim=0) for j in range(len(data[0][0])))
                    for i in range(len(data[0]))
                )
            else:
                return tuple(torch.cat([attr[i] for attr in data], dim=0) for i in range(len(data[0])))
        elif isinstance(data[0], (int, float)):
            # If the elements are integers or floats, return a tensor
            return torch.tensor(data)
        else:
            raise ValueError(f"Unexpected attribute type: {type(data[0])}")

    # Use a dictionary comprehension to gather attributes from all objects and concatenate them
    concatenated_data = {
        k: _concat([getattr(model_output, k) for model_output in model_outputs])
        for k in model_output_cls.__dataclass_fields__.keys()
    }

    # Return a new object of the inferred class with the concatenated attributes
    return model_output_cls(**concatenated_data)