When i run this code: import torch from torch import nn import transformers import json…
- User
When i run this code: import torch from torch import nn import transformers import json from sklearn.model_selection import train_test_split from torch.nn import TransformerDecoder, TransformerDecoderLayer
Load the JSON dataset
with open('C:/Users/Dell-PC/Desktop/Projets/Datasets/summarization_dataset.json', 'r') as f: dataset = json.load(f)
Split the dataset into training, validation, and testing sets
train_data, val_data = train_test_split(dataset, test_size=0.2, random_state=42) val_data, test_data = train_test_split(val_data, test_size=0.5, random_state=42)
Tokenize the text into words
all_words = [word for text in dataset for word in text['doc'].split()] +
[word for text in dataset for word in text['summary'].split()] vocab = set(all_words) vocab_index = {word: idx for idx, word in enumerate(vocab)}Adjust the preprocess_data function accordingly
def preprocess_data(data): input_seqs = [row['doc'].split() for row in data] # Split into words here target_seqs = [row['summary'].split() for row in data] input_tensors = [torch.tensor([vocab_index[word] for word in input_seq]) for input_seq in input_seqs] target_tensors = [torch.tensor([vocab_index[word] for word in target_seq]) for target_seq in target_seqs] return input_tensors, target_tensors
def generate_square_subsequent_mask(sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask
class DecoderOnlyTransformer(nn.Module): def init(self, n_layers, d_model, n_heads, dim_feedforward, vocab_size): super().init() # Embedding for input tokens self.token_embedding = nn.Embedding(vocab_size, d_model) # Positional encoding is usually needed, however not included in this minimal example # Transformer decoder layers decoder_layer = TransformerDecoderLayer(d_model=d_model, nhead=n_heads, dim_feedforward=dim_feedforward) self.transformer_decoder = TransformerDecoder(decoder_layer, num_layers=n_layers) self.out = nn.Linear(d_model, vocab_size)
codedef forward(self, src): # Get token embeddings src = self.token_embedding(src) # Creating a dummy memory for the decoder since this is a decoder-only model memory = torch.zeros_like(src) # Generating a mask to prevent the model from seeing future tokens tgt_mask = generate_square_subsequent_mask(src.size(0)).to(src.device) # Forward pass through the transformer decoder output = self.transformer_decoder(tgt=src, memory=memory, tgt_mask=tgt_mask) # Pass through the final output layer output = self.out(output) return output - Assistant
- User
I added debugging prints to track the variables to detect the source of the bug, here is the output of these print functions: print("Train Input:", len(train_input)) print("Train Target:", len(train_target)) print("Val Input:", len(val_input)) print("Val Target:", len(val_target)) print("Test Input:", len(test_input)) print("Test Target:", len(test_target)) print("Model:", model) print("Criterion:", criterion) print("Optimizer:", optimizer) here is there output: Train Input: 5078 Train Target: 5078 Val Input: 635 Val Target: 635 Test Input: 635 Test Target: 635 Model: DecoderOnlyTransformer( (token_embedding): Embedding(24555, 512)
(transformer_decoder): TransformerDecoder( (layers): ModuleList( (0-5): 6 x TransformerDecoderLayer(
(self_attn): MultiheadAttention( (out_proj): NonDynamicallyQuantizableLinear(in_features=512, out_features=512, bias=True) ) (multihead_attn): MultiheadAttention( (out_proj): NonDynamicallyQuantizableLinear(in_features=512, out_features=512, bias=True) ) (linear1): Linear(in_features=512, out_features=2048, bias=True) (dropout): Dropout(p=0.1, inplace=False) (linear2): Linear(in_features=2048, out_features=512, bias=True) (norm1): LayerNorm((512,), eps=1e-05, elementwise_affine=True) (norm2): LayerNorm((512,), eps=1e-05, elementwise_affine=True) (norm3): LayerNorm((512,), eps=1e-05, elementwise_affine=True) (dropout1): Dropout(p=0.1, inplace=False) (dropout2): Dropout(p=0.1, inplace=False) (dropout3): Dropout(p=0.1, inplace=False) ) ) ) (out): Linear(in_features=512, out_features=24555, bias=True) ) Criterion: CrossEntropyLoss() Optimizer: AdamW ( Parameter Group 0 amsgrad: False betas: (0.9, 0.999) capturable: False differentiable: False eps: 1e-08 foreach: None fused: None lr: 0.0001 maximize: False weight_decay: 0.01 ) - Assistant
- User
- Assistant
You're correct;
max_seq_lengthis used before thetrain_inputandtrain_targetare available, which would result in an error if you tried to run the code as-is. - User
- Assistant
- User
- Assistant
The IndexError
index out of range in selfsuggests that you are trying to access an index in the embedding layer that does not exist. Two major issues might cause this error: