Update modeling.py
Browse files- modeling.py +267 -86
modeling.py
CHANGED
|
@@ -1,122 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import math
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
| 4 |
-
from
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
self.vocab_size = vocab_size
|
| 30 |
-
self.d_model = d_model
|
| 31 |
-
self.nhead = nhead
|
| 32 |
-
self.num_encoder_layers = num_encoder_layers
|
| 33 |
-
self.num_decoder_layers = num_decoder_layers
|
| 34 |
-
self.dim_feedforward = dim_feedforward
|
| 35 |
-
self.dropout = dropout
|
| 36 |
-
self.max_position_embeddings = max_position_embeddings
|
| 37 |
-
|
| 38 |
-
# Add a placeholder for decoder_start_token_id, which is needed for generation
|
| 39 |
-
if not hasattr(self, "decoder_start_token_id"):
|
| 40 |
-
# For a multilingual model, this is often the target language token ID
|
| 41 |
-
# You will set this explicitly during generation in your Gradio app (as shown previously)
|
| 42 |
-
self.decoder_start_token_id = None
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# Use the Hugging Face base model class for compatibility
|
| 46 |
-
class SmallTransformer(PreTrainedModel):
|
| 47 |
-
# Link the model to its configuration class
|
| 48 |
-
config_class = TransformerConfig
|
| 49 |
-
|
| 50 |
-
def __init__(self, config):
|
| 51 |
super().__init__(config)
|
| 52 |
self.config = config
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
self.pos_encoder = nn.Embedding(config.max_position_embeddings, config.d_model)
|
| 57 |
self.pos_decoder = nn.Embedding(config.max_position_embeddings, config.d_model)
|
| 58 |
self.embed_scale = math.sqrt(config.d_model)
|
| 59 |
|
| 60 |
-
enc_layer = nn.TransformerEncoderLayer(
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
self.encoder = nn.TransformerEncoder(enc_layer, num_layers=config.num_encoder_layers)
|
| 68 |
self.decoder = nn.TransformerDecoder(dec_layer, num_layers=config.num_decoder_layers)
|
| 69 |
self.output_layer = nn.Linear(config.d_model, config.vocab_size)
|
| 70 |
-
|
| 71 |
# Initialize weights
|
| 72 |
-
self.post_init()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
# Implement the forward pass exactly as you had it
|
| 75 |
-
def forward(self, input_ids=None, decoder_input_ids=None, **kwargs):
|
| 76 |
src = input_ids
|
| 77 |
tgt = decoder_input_ids
|
| 78 |
|
| 79 |
assert src.dim() == 2 and tgt.dim() == 2
|
| 80 |
-
|
| 81 |
-
# Your custom max_token check (omitting for brevity but keep if you need it)
|
| 82 |
|
|
|
|
| 83 |
src_mask = (src == self.config.pad_token_id)
|
| 84 |
tgt_mask_pad = (tgt == self.config.pad_token_id)
|
| 85 |
|
| 86 |
T = tgt.size(1)
|
| 87 |
-
# Create Causal Mask
|
| 88 |
causal_mask = torch.triu(torch.ones((T, T), device=tgt.device), diagonal=1).bool()
|
| 89 |
|
| 90 |
-
# Positional
|
| 91 |
-
src_pos = torch.arange(0, src.size(1), device=src.device).unsqueeze(0).expand(src.size(0), -1).clamp(
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
|
|
|
| 94 |
src_emb = self.embedding(src) * self.embed_scale + self.pos_encoder(src_pos)
|
| 95 |
tgt_emb = self.embedding(tgt) * self.embed_scale + self.pos_decoder(tgt_pos)
|
| 96 |
|
|
|
|
| 97 |
memory = self.encoder(src_emb, src_key_padding_mask=src_mask)
|
| 98 |
-
output = self.decoder(
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
logits = self.output_layer(output)
|
| 104 |
-
|
| 105 |
-
# Return a dictionary/tuple of outputs compatible with PreTrainedModel
|
| 106 |
-
return (logits,) # Return logits in a tuple for compatibility
|
| 107 |
-
|
| 108 |
-
# Implement the mandatory generate method (minimal implementation)
|
| 109 |
-
def prepare_inputs_for_generation(self, decoder_input_ids, **kwargs):
|
| 110 |
-
# This method is required by the .generate() function
|
| 111 |
-
return {"input_ids": kwargs.get("input_ids"), "decoder_input_ids": decoder_input_ids}
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
warnings.warn("Using decoder_start_token_id from config. This should be manually set during generation.")
|
| 118 |
-
decoder_input_ids = torch.ones((kwargs["input_ids"].shape[0], 1), dtype=torch.long, device=self.device) * self.config.decoder_start_token_id
|
| 119 |
-
return decoder_input_ids
|
| 120 |
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# import math
|
| 2 |
+
# import torch
|
| 3 |
+
# import torch.nn as nn
|
| 4 |
+
# from transformers import PretrainedConfig, PreTrainedModel
|
| 5 |
+
# import warnings
|
| 6 |
+
|
| 7 |
+
# # Use the Hugging Face base configuration class for compatibility
|
| 8 |
+
# class TransformerConfig(PretrainedConfig):
|
| 9 |
+
# # Model type must match the one found in your config.json (small_transformer)
|
| 10 |
+
# model_type = "small_transformer"
|
| 11 |
+
|
| 12 |
+
# def __init__(self,
|
| 13 |
+
# vocab_size=80000,
|
| 14 |
+
# d_model=256,
|
| 15 |
+
# nhead=8,
|
| 16 |
+
# num_encoder_layers=3,
|
| 17 |
+
# num_decoder_layers=3,
|
| 18 |
+
# dim_feedforward=512,
|
| 19 |
+
# dropout=0.1,
|
| 20 |
+
# pad_token_id=0,
|
| 21 |
+
# bos_token_id=1, # Assuming <s> is 1
|
| 22 |
+
# eos_token_id=2, # Assuming </s> is 2
|
| 23 |
+
# max_position_embeddings=512,
|
| 24 |
+
# **kwargs):
|
| 25 |
+
# super().__init__(pad_token_id=pad_token_id,
|
| 26 |
+
# bos_token_id=bos_token_id,
|
| 27 |
+
# eos_token_id=eos_token_id,
|
| 28 |
+
# **kwargs)
|
| 29 |
+
# self.vocab_size = vocab_size
|
| 30 |
+
# self.d_model = d_model
|
| 31 |
+
# self.nhead = nhead
|
| 32 |
+
# self.num_encoder_layers = num_encoder_layers
|
| 33 |
+
# self.num_decoder_layers = num_decoder_layers
|
| 34 |
+
# self.dim_feedforward = dim_feedforward
|
| 35 |
+
# self.dropout = dropout
|
| 36 |
+
# self.max_position_embeddings = max_position_embeddings
|
| 37 |
+
|
| 38 |
+
# # Add a placeholder for decoder_start_token_id, which is needed for generation
|
| 39 |
+
# if not hasattr(self, "decoder_start_token_id"):
|
| 40 |
+
# # For a multilingual model, this is often the target language token ID
|
| 41 |
+
# # You will set this explicitly during generation in your Gradio app (as shown previously)
|
| 42 |
+
# self.decoder_start_token_id = None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# # Use the Hugging Face base model class for compatibility
|
| 46 |
+
# class SmallTransformer(PreTrainedModel):
|
| 47 |
+
# # Link the model to its configuration class
|
| 48 |
+
# config_class = TransformerConfig
|
| 49 |
+
|
| 50 |
+
# def __init__(self, config):
|
| 51 |
+
# super().__init__(config)
|
| 52 |
+
# self.config = config
|
| 53 |
+
|
| 54 |
+
# # --- Model Components (from your training code) ---
|
| 55 |
+
# self.embedding = nn.Embedding(config.vocab_size, config.d_model, padding_idx=config.pad_token_id)
|
| 56 |
+
# self.pos_encoder = nn.Embedding(config.max_position_embeddings, config.d_model)
|
| 57 |
+
# self.pos_decoder = nn.Embedding(config.max_position_embeddings, config.d_model)
|
| 58 |
+
# self.embed_scale = math.sqrt(config.d_model)
|
| 59 |
+
|
| 60 |
+
# enc_layer = nn.TransformerEncoderLayer(d_model=config.d_model, nhead=config.nhead,
|
| 61 |
+
# dim_feedforward=config.dim_feedforward,
|
| 62 |
+
# dropout=config.dropout, batch_first=True)
|
| 63 |
+
# dec_layer = nn.TransformerDecoderLayer(d_model=config.d_model, nhead=config.nhead,
|
| 64 |
+
# dim_feedforward=config.dim_feedforward,
|
| 65 |
+
# dropout=config.dropout, batch_first=True)
|
| 66 |
+
|
| 67 |
+
# self.encoder = nn.TransformerEncoder(enc_layer, num_layers=config.num_encoder_layers)
|
| 68 |
+
# self.decoder = nn.TransformerDecoder(dec_layer, num_layers=config.num_decoder_layers)
|
| 69 |
+
# self.output_layer = nn.Linear(config.d_model, config.vocab_size)
|
| 70 |
+
|
| 71 |
+
# # Initialize weights
|
| 72 |
+
# self.post_init()
|
| 73 |
+
|
| 74 |
+
# # Implement the forward pass exactly as you had it
|
| 75 |
+
# def forward(self, input_ids=None, decoder_input_ids=None, **kwargs):
|
| 76 |
+
# src = input_ids
|
| 77 |
+
# tgt = decoder_input_ids
|
| 78 |
+
|
| 79 |
+
# assert src.dim() == 2 and tgt.dim() == 2
|
| 80 |
+
|
| 81 |
+
# # Your custom max_token check (omitting for brevity but keep if you need it)
|
| 82 |
+
|
| 83 |
+
# src_mask = (src == self.config.pad_token_id)
|
| 84 |
+
# tgt_mask_pad = (tgt == self.config.pad_token_id)
|
| 85 |
+
|
| 86 |
+
# T = tgt.size(1)
|
| 87 |
+
# # Create Causal Mask
|
| 88 |
+
# causal_mask = torch.triu(torch.ones((T, T), device=tgt.device), diagonal=1).bool()
|
| 89 |
+
|
| 90 |
+
# # Positional Encoding
|
| 91 |
+
# src_pos = torch.arange(0, src.size(1), device=src.device).unsqueeze(0).expand(src.size(0), -1).clamp(max=self.config.max_position_embeddings - 1)
|
| 92 |
+
# tgt_pos = torch.arange(0, tgt.size(1), device=tgt.device).unsqueeze(0).expand(tgt.size(0), -1).clamp(max=self.config.max_position_embeddings - 1)
|
| 93 |
+
|
| 94 |
+
# src_emb = self.embedding(src) * self.embed_scale + self.pos_encoder(src_pos)
|
| 95 |
+
# tgt_emb = self.embedding(tgt) * self.embed_scale + self.pos_decoder(tgt_pos)
|
| 96 |
+
|
| 97 |
+
# memory = self.encoder(src_emb, src_key_padding_mask=src_mask)
|
| 98 |
+
# output = self.decoder(tgt_emb, memory, tgt_mask=causal_mask,
|
| 99 |
+
# tgt_key_padding_mask=tgt_mask_pad,
|
| 100 |
+
# memory_key_padding_mask=src_mask)
|
| 101 |
+
|
| 102 |
+
# # The output must be the logits before the final softmax/loss
|
| 103 |
+
# logits = self.output_layer(output)
|
| 104 |
+
|
| 105 |
+
# # Return a dictionary/tuple of outputs compatible with PreTrainedModel
|
| 106 |
+
# return (logits,) # Return logits in a tuple for compatibility
|
| 107 |
+
|
| 108 |
+
# # Implement the mandatory generate method (minimal implementation)
|
| 109 |
+
# def prepare_inputs_for_generation(self, decoder_input_ids, **kwargs):
|
| 110 |
+
# # This method is required by the .generate() function
|
| 111 |
+
# return {"input_ids": kwargs.get("input_ids"), "decoder_input_ids": decoder_input_ids}
|
| 112 |
+
|
| 113 |
+
# def _prepare_decoder_input_ids_for_generation(self, decoder_input_ids, **kwargs):
|
| 114 |
+
# # A simple method to ensure the decoder input starts with the language token
|
| 115 |
+
# # This is typically handled by generation_config, but we include a check here
|
| 116 |
+
# if decoder_input_ids is None and self.config.decoder_start_token_id is not None:
|
| 117 |
+
# warnings.warn("Using decoder_start_token_id from config. This should be manually set during generation.")
|
| 118 |
+
# decoder_input_ids = torch.ones((kwargs["input_ids"].shape[0], 1), dtype=torch.long, device=self.device) * self.config.decoder_start_token_id
|
| 119 |
+
# return decoder_input_ids
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# # No registration needed - auto_map in config.json handles this
|
| 123 |
+
|
| 124 |
+
"""PyTorch Small Transformer model for English to Hindi/Bengali translation."""
|
| 125 |
+
|
| 126 |
import math
|
| 127 |
import torch
|
| 128 |
import torch.nn as nn
|
| 129 |
+
from typing import Optional, Tuple
|
| 130 |
+
from transformers import PreTrainedModel
|
| 131 |
+
from transformers.modeling_outputs import Seq2SeqLMOutput
|
| 132 |
+
from .configuration_small_transformer import SmallTransformerConfig
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class SmallTransformerPreTrainedModel(PreTrainedModel):
|
| 136 |
+
config_class = SmallTransformerConfig
|
| 137 |
+
base_model_prefix = "small_transformer"
|
| 138 |
+
supports_gradient_checkpointing = False
|
| 139 |
+
_no_split_modules = []
|
| 140 |
+
|
| 141 |
+
def _init_weights(self, module):
|
| 142 |
+
if isinstance(module, nn.Linear):
|
| 143 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 144 |
+
if module.bias is not None:
|
| 145 |
+
module.bias.data.zero_()
|
| 146 |
+
elif isinstance(module, nn.Embedding):
|
| 147 |
+
module.weight.data.normal_(mean=0.0, std=0.02)
|
| 148 |
+
if module.padding_idx is not None:
|
| 149 |
+
module.weight.data[module.padding_idx].zero_()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class SmallTransformer(SmallTransformerPreTrainedModel):
|
| 153 |
+
def __init__(self, config: SmallTransformerConfig):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
super().__init__(config)
|
| 155 |
self.config = config
|
| 156 |
|
| 157 |
+
self.embedding = nn.Embedding(
|
| 158 |
+
config.vocab_size,
|
| 159 |
+
config.d_model,
|
| 160 |
+
padding_idx=config.pad_token_id
|
| 161 |
+
)
|
| 162 |
self.pos_encoder = nn.Embedding(config.max_position_embeddings, config.d_model)
|
| 163 |
self.pos_decoder = nn.Embedding(config.max_position_embeddings, config.d_model)
|
| 164 |
self.embed_scale = math.sqrt(config.d_model)
|
| 165 |
|
| 166 |
+
enc_layer = nn.TransformerEncoderLayer(
|
| 167 |
+
d_model=config.d_model,
|
| 168 |
+
nhead=config.nhead,
|
| 169 |
+
dim_feedforward=config.dim_feedforward,
|
| 170 |
+
dropout=config.dropout,
|
| 171 |
+
batch_first=True
|
| 172 |
+
)
|
| 173 |
+
dec_layer = nn.TransformerDecoderLayer(
|
| 174 |
+
d_model=config.d_model,
|
| 175 |
+
nhead=config.nhead,
|
| 176 |
+
dim_feedforward=config.dim_feedforward,
|
| 177 |
+
dropout=config.dropout,
|
| 178 |
+
batch_first=True
|
| 179 |
+
)
|
| 180 |
|
| 181 |
self.encoder = nn.TransformerEncoder(enc_layer, num_layers=config.num_encoder_layers)
|
| 182 |
self.decoder = nn.TransformerDecoder(dec_layer, num_layers=config.num_decoder_layers)
|
| 183 |
self.output_layer = nn.Linear(config.d_model, config.vocab_size)
|
| 184 |
+
|
| 185 |
# Initialize weights
|
| 186 |
+
self.post_init()
|
| 187 |
+
|
| 188 |
+
def get_encoder(self):
|
| 189 |
+
return self.encoder
|
| 190 |
+
|
| 191 |
+
def get_decoder(self):
|
| 192 |
+
return self.decoder
|
| 193 |
+
|
| 194 |
+
def forward(
|
| 195 |
+
self,
|
| 196 |
+
input_ids: torch.LongTensor,
|
| 197 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 198 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 199 |
+
decoder_attention_mask: Optional[torch.Tensor] = None,
|
| 200 |
+
labels: Optional[torch.LongTensor] = None,
|
| 201 |
+
return_dict: Optional[bool] = None,
|
| 202 |
+
**kwargs
|
| 203 |
+
):
|
| 204 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 205 |
+
|
| 206 |
+
# Use decoder_input_ids if provided, otherwise shift labels
|
| 207 |
+
if decoder_input_ids is None and labels is not None:
|
| 208 |
+
decoder_input_ids = labels.clone()
|
| 209 |
|
|
|
|
|
|
|
| 210 |
src = input_ids
|
| 211 |
tgt = decoder_input_ids
|
| 212 |
|
| 213 |
assert src.dim() == 2 and tgt.dim() == 2
|
|
|
|
|
|
|
| 214 |
|
| 215 |
+
# Create masks
|
| 216 |
src_mask = (src == self.config.pad_token_id)
|
| 217 |
tgt_mask_pad = (tgt == self.config.pad_token_id)
|
| 218 |
|
| 219 |
T = tgt.size(1)
|
|
|
|
| 220 |
causal_mask = torch.triu(torch.ones((T, T), device=tgt.device), diagonal=1).bool()
|
| 221 |
|
| 222 |
+
# Positional indices
|
| 223 |
+
src_pos = torch.arange(0, src.size(1), device=src.device).unsqueeze(0).expand(src.size(0), -1).clamp(
|
| 224 |
+
max=self.config.max_position_embeddings - 1
|
| 225 |
+
)
|
| 226 |
+
tgt_pos = torch.arange(0, tgt.size(1), device=tgt.device).unsqueeze(0).expand(tgt.size(0), -1).clamp(
|
| 227 |
+
max=self.config.max_position_embeddings - 1
|
| 228 |
+
)
|
| 229 |
|
| 230 |
+
# Embeddings
|
| 231 |
src_emb = self.embedding(src) * self.embed_scale + self.pos_encoder(src_pos)
|
| 232 |
tgt_emb = self.embedding(tgt) * self.embed_scale + self.pos_decoder(tgt_pos)
|
| 233 |
|
| 234 |
+
# Encode and decode
|
| 235 |
memory = self.encoder(src_emb, src_key_padding_mask=src_mask)
|
| 236 |
+
output = self.decoder(
|
| 237 |
+
tgt_emb,
|
| 238 |
+
memory,
|
| 239 |
+
tgt_mask=causal_mask,
|
| 240 |
+
tgt_key_padding_mask=tgt_mask_pad,
|
| 241 |
+
memory_key_padding_mask=src_mask
|
| 242 |
+
)
|
| 243 |
logits = self.output_layer(output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
+
loss = None
|
| 246 |
+
if labels is not None:
|
| 247 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
|
| 248 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
+
if not return_dict:
|
| 251 |
+
output = (logits,)
|
| 252 |
+
return ((loss,) + output) if loss is not None else output
|
| 253 |
|
| 254 |
+
return Seq2SeqLMOutput(
|
| 255 |
+
loss=loss,
|
| 256 |
+
logits=logits,
|
| 257 |
+
past_key_values=None,
|
| 258 |
+
decoder_hidden_states=None,
|
| 259 |
+
decoder_attentions=None,
|
| 260 |
+
cross_attentions=None,
|
| 261 |
+
encoder_last_hidden_state=memory,
|
| 262 |
+
encoder_hidden_states=None,
|
| 263 |
+
encoder_attentions=None,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
def generate(
|
| 267 |
+
self,
|
| 268 |
+
input_ids: torch.LongTensor,
|
| 269 |
+
max_length: int = 64,
|
| 270 |
+
lang_token_id: int = None,
|
| 271 |
+
eos_token_id: int = None,
|
| 272 |
+
**kwargs
|
| 273 |
+
):
|
| 274 |
+
"""Simple greedy generation for translation."""
|
| 275 |
+
if eos_token_id is None:
|
| 276 |
+
eos_token_id = self.config.eos_token_id
|
| 277 |
+
|
| 278 |
+
batch_size = input_ids.size(0)
|
| 279 |
+
device = input_ids.device
|
| 280 |
+
|
| 281 |
+
# Start with language token
|
| 282 |
+
if lang_token_id is None:
|
| 283 |
+
raise ValueError("lang_token_id must be provided for generation")
|
| 284 |
+
|
| 285 |
+
decoder_input_ids = torch.full((batch_size, 1), lang_token_id, dtype=torch.long, device=device)
|
| 286 |
+
|
| 287 |
+
for _ in range(max_length - 1):
|
| 288 |
+
outputs = self.forward(
|
| 289 |
+
input_ids=input_ids,
|
| 290 |
+
decoder_input_ids=decoder_input_ids,
|
| 291 |
+
return_dict=True
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
next_token_logits = outputs.logits[:, -1, :]
|
| 295 |
+
next_tokens = torch.argmax(next_token_logits, dim=-1, keepdim=True)
|
| 296 |
+
|
| 297 |
+
decoder_input_ids = torch.cat([decoder_input_ids, next_tokens], dim=-1)
|
| 298 |
+
|
| 299 |
+
# Stop if all sequences have generated EOS
|
| 300 |
+
if (next_tokens == eos_token_id).all():
|
| 301 |
+
break
|
| 302 |
+
|
| 303 |
+
return decoder_input_ids
|