class_docstr: A class containing all functions for auto-regressive text generation, to be used as a mixin in [`PreTrainedModel`].
  
  The class exposes [`~generation_utils.GenerationMixin.generate`], which can be used for:
      - *greedy decoding* by calling [`~generation_utils.GenerationMixin.greedy_search`] if `num_beams=1` and
        `do_sample=False`.
      - *contrastive search* by calling [`~generation_utils.GenerationMixin.contrastive_search`] if `penalty_alpha>0`
        and `top_k>1`
      - *multinomial sampling* by calling [`~generation_utils.GenerationMixin.sample`] if `num_beams=1` and
        `do_sample=True`.
      - *beam-search decoding* by calling [`~generation_utils.GenerationMixin.beam_search`] if `num_beams>1` and
        `do_sample=False`.
      - *beam-search multinomial sampling* by calling [`~generation_utils.GenerationMixin.beam_sample`] if
        `num_beams>1` and `do_sample=True`.
      - *diverse beam-search decoding* by calling [`~generation_utils.GenerationMixin.group_beam_search`], if
        `num_beams>1` and `num_beam_groups>1`.
      - *constrained beam-search decoding* by calling [`~generation_utils.GenerationMixin.constrained_beam_search`],
        if `constraints!=None` or `force_words_ids!=None`.
class_docstr_tok: ["A","class","containing","all","functions","for","auto-regressive","text","generation",",","to","be","used","as","a","mixin","in","[","`","PreTrainedModel","`","]",".","The","class","exposes","[","`","~generation_utils.GenerationMixin.generate","`","]",",","which","can","be","used","for",":","-","*","greedy","decoding","*","by","calling","[","`","~generation_utils.GenerationMixin.greedy_search","`","]","if","`","num_beams=1","`","and","`","do_sample=False","`",".","-","*","contrastive","search","*","by","calling","[","`","~generation_utils.GenerationMixin.contrastive_search","`","]","if","`","penalty_alpha",">","0","`","and","`","top_k",">","1","`","-","*","multinomial","sampling","*","by","calling","[","`","~generation_utils.GenerationMixin.sample","`","]","if","`","num_beams=1","`","and","`","do_sample=True","`",".","-","*","beam-search","decoding","*","by","calling","[","`","~generation_utils.GenerationMixin.beam_search","`","]","if","`","num_beams",">","1","`","and","`","do_sample=False","`",".","-","*","beam-search","multinomial","sampling","*","by","calling","[","`","~generation_utils.GenerationMixin.beam_sample","`","]","if","`","num_beams",">","1","`","and","`","do_sample=True","`",".","-","*","diverse","beam-search","decoding","*","by","calling","[","`","~generation_utils.GenerationMixin.group_beam_search","`","]",",","if","`","num_beams",">","1","`","and","`","num_beam_groups",">","1","`",".","-","*","constrained","beam-search","decoding","*","by","calling","[","`","~generation_utils.GenerationMixin.constrained_beam_search","`","]",",","if","`","constraints","!","=None","`","or","`","force_words_ids","!","=None","`","."]
docstr: 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.
      top_k (`int`, *optional*, defaults to 1):
          The size of the candidate set that is used to re-rank for contrastive search
      penalty_alpha (`float`, *optional*, defaults to 0):
          The degeneration penalty for contrastive search; activate when it is larger than 0
      logits_processor (`LogitsProcessorList`, *optional*):
          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.
      logits_warper (`LogitsProcessorList`, *optional*):
          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.
      stopping_criteria (`StoppingCriteriaList`, *optional*):
          An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
          used to tell if the generation loop should stop.
      pad_token_id (`int`, *optional*):
          The id of the *padding* token.
      eos_token_id (`int`, *optional*):
          The id of the *end-of-sequence* token.
      output_attentions (`bool`, *optional*, defaults to `False`):
          Whether or not to return the attentions tensors of all attention layers. See `attentions` under
          returned tensors for more details.
      output_hidden_states (`bool`, *optional*, defaults to `False`):
          Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
          for more details.
      output_scores (`bool`, *optional*, defaults to `False`):
          Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
      return_dict_in_generate (`bool`, *optional*, defaults to `False`):
          Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
      synced_gpus (`bool`, *optional*, defaults to `False`):
          Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
      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:
      [`~generation_utils.ContrastiveSearchDecoderOnlyOutput`],
      [`~generation_utils.ContrastiveSearchEncoderDecoderOutput`] or `torch.LongTensor`: A `torch.LongTensor`
      containing the generated tokens (default behaviour) or a
      [`~generation_utils.ContrastiveSearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
      `return_dict_in_generate=True` or a [`~generation_utils.ContrastiveSearchEncoderDecoderOutput`] if
      `model.config.is_encoder_decoder=True`.
  
  Examples:
  ```python
  >>> from transformers import (
  ...     AutoTokenizer,
  ...     AutoModelForCausalLM,
  ...     StoppingCriteriaList,
  ...     MaxLengthCriteria,
  ... )
  
  >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
  >>> model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
  >>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
  >>> model.config.pad_token_id = model.config.eos_token_id
  >>> input_prompt = "DeepMind Company is"
  >>> input_ids = tokenizer(input_prompt, return_tensors="pt")
  >>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=64)])
  >>> outputs = model.contrastive_search(
  ...     **input_ids, penalty_alpha=0.6, top_k=4, stopping_criteria=stopping_criteria
  ... )
  >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
  ['DeepMind Company is a company that focuses on the development and commercialization of artificial intelligence (AI). DeepMind’s mission is to help people understand and solve problems that are difficult to solve in the world today.\n\nIn this post, we talk about the benefits of deep learning in business and how it']
  ```
docstr_tok: ["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",".","top_k","(","`","int","`",",","*","optional","*",",","defaults","to","1",")",":","The","size","of","the","candidate","set","that","is","used","to","re-rank","for","contrastive","search","penalty_alpha","(","`","float","`",",","*","optional","*",",","defaults","to","0",")",":","The","degeneration","penalty","for","contrastive","search",";","activate","when","it","is","larger","than","0","logits_processor","(","`","LogitsProcessorList","`",",","*","optional","*",")",":","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",".","logits_warper","(","`","LogitsProcessorList","`",",","*","optional","*",")",":","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",".","stopping_criteria","(","`","StoppingCriteriaList","`",",","*","optional","*",")",":","An","instance","of","[","`","StoppingCriteriaList","`","]",".","List","of","instances","of","class","derived","from","[","`","StoppingCriteria","`","]","used","to","tell","if","the","generation","loop","should","stop",".","pad_token_id","(","`","int","`",",","*","optional","*",")",":","The","id","of","the","*","padding","*","token",".","eos_token_id","(","`","int","`",",","*","optional","*",")",":","The","id","of","the","*","end-of-sequence","*","token",".","output_attentions","(","`","bool","`",",","*","optional","*",",","defaults","to","`","False","`",")",":","Whether","or","not","to","return","the","attentions","tensors","of","all","attention","layers",".","See","`","attentions","`","under","returned","tensors","for","more","details",".","output_hidden_states","(","`","bool","`",",","*","optional","*",",","defaults","to","`","False","`",")",":","Whether","or","not","to","return","the","hidden","states","of","all","layers",".","See","`","hidden_states","`","under","returned","tensors","for","more","details",".","output_scores","(","`","bool","`",",","*","optional","*",",","defaults","to","`","False","`",")",":","Whether","or","not","to","return","the","prediction","scores",".","See","`","scores","`","under","returned","tensors","for","more","details",".","return_dict_in_generate","(","`","bool","`",",","*","optional","*",",","defaults","to","`","False","`",")",":","Whether","or","not","to","return","a","[","`","~utils.ModelOutput","`","]","instead","of","a","plain","tuple",".","synced_gpus","(","`","bool","`",",","*","optional","*",",","defaults","to","`","False","`",")",":","Whether","to","continue","running","the","while","loop","until","max_length","(","needed","for","ZeRO","stage","3",")","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",":","[","`","~generation_utils.ContrastiveSearchDecoderOnlyOutput","`","]",",","[","`","~generation_utils.ContrastiveSearchEncoderDecoderOutput","`","]","or","`","torch.LongTensor","`",":","A","`","torch.LongTensor","`","containing","the","generated","tokens","(","default","behaviour",")","or","a","[","`","~generation_utils.ContrastiveSearchDecoderOnlyOutput","`","]","if","`","model.config.is_encoder_decoder=False","`","and","`","return_dict_in_generate=True","`","or","a","[","`","~generation_utils.ContrastiveSearchEncoderDecoderOutput","`","]","if","`","model.config.is_encoder_decoder=True","`",".","Examples",":","``","`","python",">",">",">","from","transformers","import","(","...","AutoTokenizer",",","...","AutoModelForCausalLM",",","...","StoppingCriteriaList",",","...","MaxLengthCriteria",",","...",")",">",">",">","tokenizer","=","AutoTokenizer.from_pretrained","(","``","facebook\/opt-125m","''",")",">",">",">","model","=","AutoModelForCausalLM.from_pretrained","(","``","facebook\/opt-125m","''",")",">",">",">","#","set","pad_token_id","to","eos_token_id","because","GPT2","does","not","have","a","PAD","token",">",">",">","model.config.pad_token_id","=","model.config.eos_token_id",">",">",">","input_prompt","=","``","DeepMind","Company","is","''",">",">",">","input_ids","=","tokenizer","(","input_prompt",",","return_tensors=","''","pt","''",")",">",">",">","stopping_criteria","=","StoppingCriteriaList","(","[","MaxLengthCriteria","(","max_length=64",")","]",")",">",">",">","outputs","=","model.contrastive_search","(","...","*","*","input_ids",",","penalty_alpha=0.6",",","top_k=4",",","stopping_criteria=stopping_criteria","...",")",">",">",">","tokenizer.batch_decode","(","outputs",",","skip_special_tokens=True",")","[","'DeepMind","Company","is","a","company","that","focuses","on","the","development","and","commercialization","of","artificial","intelligence","(","AI",")",".","DeepMind","\u2019","s","mission","is","to","help","people","understand","and","solve","problems","that","are","difficult","to","solve","in","the","world","today.\\n\\nIn","this","post",",","we","talk","about","the","benefits","of","deep","learning","in","business","and","how","it","'","]","``","`"]
code: def contrastive_search(
      self,
      input_ids: torch.LongTensor,
      top_k: Optional[int] = 1,
      penalty_alpha: Optional[float] = 0,
      logits_processor: Optional[LogitsProcessorList] = None,
      logits_warper: Optional[LogitsProcessorList] = None,
      stopping_criteria: Optional[StoppingCriteriaList] = None,
      pad_token_id: Optional[int] = None,
      eos_token_id: Optional[int] = None,
      output_attentions: Optional[bool] = None,
      output_hidden_states: Optional[bool] = None,
      output_scores: Optional[bool] = None,
      return_dict_in_generate: Optional[bool] = None,
      synced_gpus: Optional[bool] = False,
      **model_kwargs,
  ) -> Union[ContrastiveSearchOutput, torch.LongTensor]:
      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.
          top_k (`int`, *optional*, defaults to 1):
              The size of the candidate set that is used to re-rank for contrastive search
          penalty_alpha (`float`, *optional*, defaults to 0):
              The degeneration penalty for contrastive search; activate when it is larger than 0
          logits_processor (`LogitsProcessorList`, *optional*):
              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.
          logits_warper (`LogitsProcessorList`, *optional*):
              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.
          stopping_criteria (`StoppingCriteriaList`, *optional*):
              An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
              used to tell if the generation loop should stop.
          pad_token_id (`int`, *optional*):
              The id of the *padding* token.
          eos_token_id (`int`, *optional*):
              The id of the *end-of-sequence* token.
          output_attentions (`bool`, *optional*, defaults to `False`):
              Whether or not to return the attentions tensors of all attention layers. See `attentions` under
              returned tensors for more details.
          output_hidden_states (`bool`, *optional*, defaults to `False`):
              Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
              for more details.
          output_scores (`bool`, *optional*, defaults to `False`):
              Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
          return_dict_in_generate (`bool`, *optional*, defaults to `False`):
              Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
          synced_gpus (`bool`, *optional*, defaults to `False`):
              Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
          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:
          [`~generation_utils.ContrastiveSearchDecoderOnlyOutput`],
          [`~generation_utils.ContrastiveSearchEncoderDecoderOutput`] or `torch.LongTensor`: A `torch.LongTensor`
          containing the generated tokens (default behaviour) or a
          [`~generation_utils.ContrastiveSearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
          `return_dict_in_generate=True` or a [`~generation_utils.ContrastiveSearchEncoderDecoderOutput`] if
          `model.config.is_encoder_decoder=True`.
  
      Examples:
      ```python
      >>> from transformers import (
      ...     AutoTokenizer,
      ...     AutoModelForCausalLM,
      ...     StoppingCriteriaList,
      ...     MaxLengthCriteria,
      ... )
  
      >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
      >>> model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
      >>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
      >>> model.config.pad_token_id = model.config.eos_token_id
      >>> input_prompt = "DeepMind Company is"
      >>> input_ids = tokenizer(input_prompt, return_tensors="pt")
      >>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=64)])
      >>> outputs = model.contrastive_search(
      ...     **input_ids, penalty_alpha=0.6, top_k=4, stopping_criteria=stopping_criteria
      ... )
      >>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
      ['DeepMind Company is a company that focuses on the development and commercialization of artificial intelligence (AI). DeepMind’s mission is to help people understand and solve problems that are difficult to solve in the world today.\n\nIn this post, we talk about the benefits of deep learning in business and how it']
      ```"""
      # init values
      logits_processor = (
          logits_processor
          if logits_processor is not None
          else LogitsProcessorList()
      )
      logits_warper = (
          logits_warper
          if logits_warper is not None
          else LogitsProcessorList()
      )
      stopping_criteria = (
          stopping_criteria
          if stopping_criteria is not None
          else StoppingCriteriaList()
      )
      pad_token_id = (
          pad_token_id
          if pad_token_id is not None
          else self.config.pad_token_id
      )
      eos_token_id = (
          eos_token_id
          if eos_token_id is not None
          else self.config.eos_token_id
      )
      output_scores = (
          output_scores
          if output_scores is not None
          else self.config.output_scores
      )
      output_attentions = (
          output_attentions
          if output_attentions is not None
          else self.config.output_attentions
      )
      output_hidden_states = (
          output_hidden_states
          if output_hidden_states is not None
          else self.config.output_hidden_states
      )
      return_dict_in_generate = (
          return_dict_in_generate
          if return_dict_in_generate is not None
          else self.config.return_dict_in_generate
      )
  
      # init attention / hidden states / scores tuples
      scores = (
          () if (return_dict_in_generate and output_scores) else None
      )
      decoder_hidden_states = (
          ()
          if (return_dict_in_generate and output_hidden_states)
          else None
      )
  
      # keep track of which sequences are already finished
      unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
  
      this_peer_finished = False  # used by synced_gpus only
  
      while True:
          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(input_ids.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:
                  break
  
          # prepare inputs
          model_kwargs["use_cache"] = True
          model_inputs = self.prepare_inputs_for_generation(
              input_ids, **model_kwargs
          )
  
          # if the first step in the loop, encode all the prefix and obtain three parameters: (1) past_key_values;
          # (2) last_hidden_states; (3) logit_for_next_step; (4) update model kwargs for the next step
          if model_kwargs.get("past") is None:
              # 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,
              )
  
              # past_key_values is required for fast decoding
              if "past_key_values" not in outputs:
                  raise ValueError(
                      f"{self.__class__.__name__} cannot return `past_key_values` and can therefore **not** be used "
                      "for contrastive search."
                  )
              past_key_values = outputs.past_key_values
  
              # 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]
              # 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(
                  outputs,
                  model_kwargs,
                  is_encoder_decoder=self.config.is_encoder_decoder,
              )
  
          # contrastive_search main logic start:
          # contrastive search decoding consists of two steps: (1) candidate tokens recall; (2) candidate re-rank by
          # degeneration penalty
          bsz, seqlen, embed_dim = last_hidden_states.size()
  
          # logits processor
          logit_for_next_step = logits_processor(
              input_ids, logit_for_next_step
          )
          logit_for_next_step = logits_warper(
              input_ids, logit_for_next_step
          )
          next_probs = nn.functional.softmax(
              logit_for_next_step, dim=-1
          )
  
          _, top_k_ids = torch.topk(
              logit_for_next_step, dim=-1, k=top_k
          )
          top_k_probs = torch.gather(next_probs, dim=1, index=top_k_ids)
  
          # Store scores, attentions and hidden_states when required
          if return_dict_in_generate:
              if output_scores:
                  scores += (logit_for_next_step,)
  
              if output_hidden_states:
                  decoder_hidden_states += (
                      (outputs.decoder_hidden_states,)
                      if self.config.is_encoder_decoder
                      else (outputs.hidden_states,)
                  )
  
          # enlarge the past_key_values
          new_key_values = []
          for layer in past_key_values:
              items = []
              # item is either the key or the value matrix
              for item in layer:
                  bsz, num_head, seq_len, esz = item.size()
                  item = (
                      item.unsqueeze(1)
                      .expand(-1, top_k, -1, -1, -1)
                      .reshape(bsz * top_k, num_head, seq_len, esz)
                      .contiguous()
                  )  # [bsz*beam, num_head, seq_len, esz]
                  items.append(item)
              new_key_values.append(items)
          past_key_values = new_key_values
  
          # build next attention mask
          if "attention_mask" in model_inputs:
              attention_mask = model_kwargs["attention_mask"]  # [B, S]
              attention_mask = (
                  attention_mask.unsqueeze(1)
                  .expand(-1, top_k, -1)
                  .reshape(-1, attention_mask.size(-1))
              )
          else:
              attention_mask = None
  
          # encoder-decoder model also contains the `encoder_outputs`
          if (
              self.config.is_encoder_decoder
              and "encoder_outputs" in model_inputs
          ):
              encoder_outputs = model_inputs["encoder_outputs"]
          else:
              encoder_outputs = None
          next_model_inputs = self.prepare_inputs_for_generation(
              top_k_ids.view(-1, 1),
              past=past_key_values,
              attention_mask=attention_mask,
              use_cache=True,
              encoder_outputs=encoder_outputs,
          )
          # compute the candidate tokens by the language model and collects their hidden_states
          outputs = self(
              **next_model_inputs,
              return_dict=True,
              output_hidden_states=True,
              output_attentions=output_attentions,
          )
          past_key_values = outputs.past_key_values
  
          logits = outputs.logits[:, -1, :]
          # 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
          context_hidden = (
              last_hidden_states.unsqueeze(1)
              .expand(-1, top_k, -1, -1)
              .reshape(bsz * top_k, seqlen, embed_dim)
          )
  
          # compute the degeneratin penalty and re-rank the candidates based on the degeneration penalty and the
          # model confidence
          selected_idx = _ranking_fast(
              context_hidden,
              next_hidden,
              top_k_probs,
              penalty_alpha,
              top_k,
          )
  
          # 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(bsz), selected_idx, :]
          last_hidden_states = torch.cat(
              [last_hidden_states, next_hidden.unsqueeze(1)], dim=1
          )
  
          decoder_hidden_states = []
          for layer in full_hidden_states:
              layer = torch.stack(
                  torch.split(layer.squeeze(dim=1), top_k)
              )
              layer = layer[range(bsz), selected_idx, :]
              decoder_hidden_states.append(layer)
  
          # select the past_key_value
          new_key_values = []
          for layer in past_key_values:
              items = []
              # item is either the key or the value matrix
              for item in layer:
                  bsz_and_beam, num_head, seq_len, esz = item.size()
                  bsz = int(bsz_and_beam // top_k)
                  item = torch.stack(
                      torch.split(item, top_k, dim=0)
                  )  # [B, K, num_head, seq_len, esz]
                  item = item[
                      range(bsz), selected_idx, :, :, :
                  ]  # [B, num_head, seq_len, esz]
                  items.append(item)
              new_key_values.append(items)
          past_key_values = new_key_values
  
          logit_for_next_step = torch.stack(torch.split(logits, top_k))[
              range(bsz), 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:
              outputs = Seq2SeqLMOutput(
                  past_key_values=past_key_values,
                  decoder_hidden_states=decoder_hidden_states,
              )
          else:
              outputs = CausalLMOutputWithPast(
                  past_key_values=past_key_values,
                  hidden_states=decoder_hidden_states,
                  attentions=model_kwargs["attention_mask"],
              )
          # 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
          if eos_token_id is not None:
              if pad_token_id is None:
                  raise ValueError(
                      "If `eos_token_id` is defined, make sure that `pad_token_id` is defined."
                  )
              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
          )
          model_kwargs = self._update_model_kwargs_for_generation(
              outputs,
              model_kwargs,
              is_encoder_decoder=self.config.is_encoder_decoder,
          )
  
          # if eos_token was found in one sentence, set sentence to finished
          if eos_token_id is not None:
              unfinished_sequences = unfinished_sequences.mul(
                  (next_tokens != eos_token_id).long()
              )
  
          # stop when each sentence is finished, or if we exceed the maximum length
          if unfinished_sequences.max() == 0 or stopping_criteria(
              input_ids, scores
          ):
              if not synced_gpus:
                  break
              else:
                  this_peer_finished = True
  
      if return_dict_in_generate:
          if self.config.is_encoder_decoder:
              return ContrastiveSearchEncoderDecoderOutput(
                  sequences=input_ids,
                  scores=scores,
                  decoder_hidden_states=decoder_hidden_states,
              )
          else:
              return ContrastiveSearchDecoderOnlyOutput(
                  sequences=input_ids,
                  scores=scores,
                  hidden_states=decoder_hidden_states,
              )
      else:
          return input_ids
  
imports: import inspect
  import warnings
  from dataclasses import dataclass
  from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
  import torch
  import torch.distributed
  from torch import nn
  from flexgen.timer import timers
  from .generation_beam_constraints import Constraint, DisjunctiveConstraint, PhrasalConstraint
  from .generation_beam_search import BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
  from .generation_logits_process import EncoderNoRepeatNGramLogitsProcessor, ExponentialDecayLengthPenalty, ForcedBOSTokenLogitsProcessor, ForcedEOSTokenLogitsProcessor, ForceTokensLogitsProcessor, HammingDiversityLogitsProcessor, InfNanRemoveLogitsProcessor, LogitNormalization, LogitsProcessorList, MinLengthLogitsProcessor, NoBadWordsLogitsProcessor, NoRepeatNGramLogitsProcessor, PrefixConstrainedLogitsProcessor, RepetitionPenaltyLogitsProcessor, SuppressTokensAtBeginLogitsProcessor, SuppressTokensLogitsProcessor, TemperatureLogitsWarper, TopKLogitsWarper, TopPLogitsWarper, TypicalLogitsWarper
  from .generation_stopping_criteria import MaxLengthCriteria, MaxTimeCriteria, StoppingCriteria, StoppingCriteriaList, validate_stopping_criteria
  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
  from .pytorch_utils import torch_int_div
  from .utils import ModelOutput, logging
label_desc: Use image node_id 20 for calling the GenerationMixin obj's underlying member method code with example usage: obj.contrastive_search(input_ids, top_k, penalty_alpha, logits_processor, logits_warper, stopping_criteria, pad_token_id, eos_token_id, output_attentions, output_hidden_states, output_scores, return_dict_in_generate, synced_gpus) and returns: input_ids, ContrastiveSearchEncoderDecoderOutput, ContrastiveSearchDecoderOnlyOutput