A class contraining all of the functions supporting generation, to be used as a mixin in PreTrainedModel.
| 26 | |
| 27 | |
| 28 | class GenerationMixin: |
| 29 | """ |
| 30 | A class contraining all of the functions supporting generation, to be used as a mixin in PreTrainedModel. |
| 31 | """ |
| 32 | |
| 33 | def prepare_inputs_for_generation(self, input_ids, **kwargs): |
| 34 | return {"input_ids": input_ids} |
| 35 | |
| 36 | def adjust_logits_during_generation(self, logits, **kwargs): |
| 37 | return logits |
| 38 | |
| 39 | def _use_cache(self, outputs, use_cache): |
| 40 | """During generation, decide whether to pass the `past` variable to the next forward pass.""" |
| 41 | if len(outputs) <= 1 or use_cache is False: |
| 42 | return False |
| 43 | if hasattr(self.config, "mem_len") and self.config.mem_len == 0: |
| 44 | return False |
| 45 | return True |
| 46 | |
| 47 | def enforce_repetition_penalty_(self, lprobs, batch_size, num_beams, prev_output_tokens, repetition_penalty): |
| 48 | """repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858). """ |
| 49 | for i in range(batch_size * num_beams): |
| 50 | for previous_token in set(prev_output_tokens[i].tolist()): |
| 51 | # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability |
| 52 | if lprobs[i, previous_token] < 0: |
| 53 | lprobs[i, previous_token] *= repetition_penalty |
| 54 | else: |
| 55 | lprobs[i, previous_token] /= repetition_penalty |
| 56 | |
| 57 | def postprocess_next_token_scores( |
| 58 | self, |
| 59 | scores, |
| 60 | input_ids, |
| 61 | no_repeat_ngram_size, |
| 62 | bad_words_ids, |
| 63 | cur_len, |
| 64 | min_length, |
| 65 | max_length, |
| 66 | eos_token_id, |
| 67 | repetition_penalty, |
| 68 | batch_size, |
| 69 | num_beams, |
| 70 | ): |
| 71 | # repetition penalty (from CTRL paper https://arxiv.org/abs/1909.05858) |
| 72 | if repetition_penalty != 1.0: |
| 73 | self.enforce_repetition_penalty_( |
| 74 | scores, batch_size, num_beams, input_ids, repetition_penalty, |
| 75 | ) |
| 76 | |
| 77 | # set eos token prob to zero if min_length is not reached |
| 78 | if eos_token_id is not None and cur_len < min_length: |
| 79 | scores[:, eos_token_id] = -float("inf") |
| 80 | |
| 81 | if no_repeat_ngram_size > 0: |
| 82 | # calculate a list of banned tokens to prevent repetitively generating the same ngrams |
| 83 | num_batch_hypotheses = batch_size * num_beams |
| 84 | # from fairseq: https://github.com/pytorch/fairseq/blob/a07cb6f40480928c9e0548b737aadd36ee66ac76/fairseq/sequence_generator.py#L345 |
| 85 | banned_batch_tokens = calc_banned_ngram_tokens( |
nothing calls this directly
no outgoing calls
no test coverage detected