Encoder Decoder
| 12 | |
| 13 | |
| 14 | class EncoderDecoder(LightningModule): |
| 15 | """ |
| 16 | Encoder Decoder |
| 17 | """ |
| 18 | |
| 19 | def __init__(self, config, tokenizer, transformer, dataset_reader): |
| 20 | """ |
| 21 | :param config |
| 22 | """ |
| 23 | super().__init__() |
| 24 | self.config = config |
| 25 | self.tokenizer = tokenizer |
| 26 | self.model = transformer |
| 27 | self.dataset_reader = dataset_reader |
| 28 | |
| 29 | self.use_deepspeed = self.config.compute_strategy.startswith("deepspeed") |
| 30 | self.use_ddp = self.config.compute_strategy.startswith("ddp") |
| 31 | self.load_model() |
| 32 | |
| 33 | self._last_global_step_saved = -1 |
| 34 | |
| 35 | self.best_eval_model_metric = [-1] |
| 36 | self.best_eval_global_step = -1 |
| 37 | |
| 38 | if self.config.fishmask_mode is not None: |
| 39 | fishmask_plugin_on_init(self) |
| 40 | |
| 41 | def training_step(self, batch, batch_idx): |
| 42 | if self.config.model_modifier == "intrinsic": |
| 43 | from .intrinsic import intrinsic_plugin_on_step |
| 44 | intrinsic_plugin_on_step(self) |
| 45 | |
| 46 | if self.config.mc_loss > 0 or self.config.unlikely_loss > 0: |
| 47 | input_ids, choices_ids, labels = batch["input_ids"], batch["answer_choices_ids"], batch["labels"] |
| 48 | bs, num_choices = choices_ids.size()[:2] |
| 49 | |
| 50 | flat_choices_ids = choices_ids.flatten(0, 1) |
| 51 | attention_mask = (input_ids != self.tokenizer.pad_token_id).float() # [bs, max_seq_len] |
| 52 | encoder_hidden_states = self.model.encoder(input_ids=input_ids, attention_mask=attention_mask)[0] |
| 53 | encoder_hidden_states = encoder_hidden_states.unsqueeze(dim=1).repeat(1, num_choices, 1, 1).flatten(0, 1) |
| 54 | attention_mask = attention_mask.unsqueeze(dim=1).repeat(1, num_choices, 1).flatten(0, 1) |
| 55 | decoder_input_ids = torch.cat([torch.zeros_like(flat_choices_ids[:, :1]), flat_choices_ids[:, :-1]], dim=1) |
| 56 | decoder_attention_mask = (decoder_input_ids == decoder_input_ids).float() |
| 57 | lm_target = flat_choices_ids - 100 * (flat_choices_ids == self.tokenizer.pad_token_id).long() |
| 58 | |
| 59 | model_output = self.model( |
| 60 | attention_mask=attention_mask, |
| 61 | encoder_outputs=[encoder_hidden_states], |
| 62 | decoder_input_ids=decoder_input_ids, |
| 63 | decoder_attention_mask=decoder_attention_mask, |
| 64 | ) |
| 65 | choices_scores = ( |
| 66 | F.cross_entropy(model_output.logits.flatten(0, 1), lm_target.flatten(0, 1), reduction="none") |
| 67 | .view(bs, num_choices, -1) |
| 68 | .sum(dim=-1) |
| 69 | ) |
| 70 | # Length normalization |
| 71 | if self.config.length_norm > 0: |
nothing calls this directly
no outgoing calls
no test coverage detected