write the code for a seq2seq model from scratch using pytorch and use this huggingface tokenizer and datasets. tokenizer: deepseek-ai/DeepSeek-R1,
Verah/JParaCrawl-Filtered-English-Japanese-Parallel-Corpus, here's the keywords for the dict: english, japanese.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset, DataLoader
from datasets import load_dataset
from transformers import AutoTokenizer
# --- 1. Define Hyperparameters ---
BATCH_SIZE = 32
EMBED_SIZE = 256
HIDDEN_SIZE = 512
NUM_LAYERS = 2
LEARNING_RATE = 0.001
NUM_EPOCHS = 10
MAX_SEQ_LEN = 128 # Adjust based on your dataset analysis
# --- 2. Load Tokenizer and Dataset ---
tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-R1")
dataset = load_dataset("Verah/JParaCrawl-Filtered-English-Japanese-Parallel-Corpus")
# --- 3. Dataset Class ---
class TranslationDataset(Dataset):
def __init__(self, dataset, tokenizer, src_lang, tgt_lang, max_seq_len):
self.dataset = dataset['train'] # Using 'train' split for simplicity, adjust as needed
self.tokenizer = tokenizer
self.src_lang = src_lang
self.tgt_lang = tgt_lang
self.max_seq_len = max_seq_len
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
item = self.dataset[idx]
src_text = item[self.src_lang]
tgt_text = item[self.tgt_lang]
src_tokens = self.tokenizer(src_text, max_length=self.max_seq_len, truncation=True, padding='max_length', return_tensors='pt')
tgt_tokens = self.tokenizer(tgt_text, max_length=self.max_seq_len, truncation=True, padding='max_length', return_tensors='pt')
return {
"src_input_ids": src_tokens['input_ids'].squeeze(0), # Remove batch dimension
"src_attention_mask": src_tokens['attention_mask'].squeeze(0),
"tgt_input_ids": tgt_tokens['input_ids'].squeeze(0),
"tgt_attention_mask": tgt_tokens['attention_mask'].squeeze(0),
}
# --- 4. Data Loaders ---
train_dataset = TranslationDataset(dataset, tokenizer, 'english', 'japanese', MAX_SEQ_LEN)
train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
# --- 5. Define Seq2Seq Model Components ---
class EncoderRNN(nn.Module):
def __init__(self, input_size, embed_size, hidden_size, num_layers, dropout):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.embedding = nn.Embedding(input_size, embed_size)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, dropout=dropout, batch_first=True, bidirectional=True) # Bidirectional Encoder
self.fc_hidden = nn.Linear(hidden_size * 2, hidden_size) # For decoder initialization
self.fc_cell = nn.Linear(hidden_size * 2, hidden_size)
self.dropout = nn.Dropout(dropout)
def forward(self, input_seq, input_lengths):
# input_seq: (batch_size, seq_len)
embedded = self.dropout(self.embedding(input_seq)) # (batch_size, seq_len, embed_size)
packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, input_lengths.cpu(), batch_first=True, enforce_sorted=False)
packed_output, (hidden, cell) = self.lstm(packed_embedded)
# outputs: (batch_size, seq_len, hidden_size * num_directions) if bidirectional, else (batch_size, seq_len, hidden_size)
# hidden: (num_layers * num_directions, batch_size, hidden_size)
# cell: (num_layers * num_directions, batch_size, hidden_size)
# Sum bidirectional outputs for each layer
hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1) # Take last forward and backward hidden states
cell = torch.cat((cell[-2,:,:], cell[-1,:,:]), dim=1)
# Transform to correct decoder initial state size
hidden = self.fc_hidden(hidden).unsqueeze(0) # (1, batch_size, hidden_size)
cell = self.fc_cell(cell).unsqueeze(0) # (1, batch_size, hidden_size)
outputs, _ = nn.utils.rnn.pad_packed_sequence(packed_output, batch_first=True, total_length=MAX_SEQ_LEN) # Pad back to original length
# outputs: (batch_size, seq_len, hidden_size * num_directions)
return outputs, hidden, cell
class DecoderRNN(nn.Module):
def __init__(self, output_size, embed_size, hidden_size, num_layers, dropout):
super(DecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.embedding = nn.Embedding(output_size, embed_size)
self.lstm = nn.LSTM(embed_size + hidden_size * 2, hidden_size, num_layers, dropout=dropout, batch_first=True) # + attention context
self.fc_out = nn.Linear(hidden_size, output_size)
self.dropout = nn.Dropout(dropout)
self.attention = Attention(hidden_size)
def forward_step(self, input_step, last_hidden, last_cell, encoder_outputs):
# input_step: (batch_size, 1) - single token at each step
# last_hidden: (num_layers, batch_size, hidden_size)
# last_cell: (num_layers, batch_size, hidden_size)
# encoder_outputs: (batch_size, src_seq_len, hidden_size * 2)
embedded = self.dropout(self.embedding(input_step)) # (batch_size, 1, embed_size)
# --- Attention Mechanism ---
context = self.attention(last_hidden[-1].unsqueeze(1), encoder_outputs) # (batch_size, 1, hidden_size * 2)
rnn_input = torch.cat((embedded, context), dim=2) # (batch_size, 1, embed_size + hidden_size * 2)
output, (hidden, cell) = self.lstm(rnn_input, (last_hidden, last_cell))
# output: (batch_size, 1, hidden_size)
# hidden: (num_layers, batch_size, hidden_size)
# cell: (num_layers, batch_size, hidden_size)
prediction = self.fc_out(output.squeeze(1)) # (batch_size, output_size) - Logits
return prediction, hidden, cell
def forward(self, decoder_inputs, encoder_outputs, encoder_hidden, encoder_cell, target_lengths, target_masks, teacher_forcing_ratio=0.5):
# decoder_inputs: (batch_size, tgt_seq_len) - shifted right target
# encoder_outputs: (batch_size, src_seq_len, hidden_size * 2)
# encoder_hidden: (1, batch_size, hidden_size)
# encoder_cell: (1, batch_size, hidden_size)
batch_size, tgt_len = decoder_inputs.size()
tgt_vocab_size = len(tokenizer)
outputs = torch.zeros(tgt_len, batch_size, tgt_vocab_size).to(device) # (tgt_seq_len, batch_size, output_size)
hidden = encoder_hidden.repeat(self.num_layers, 1, 1) # (num_layers, batch_size, hidden_size) - Initialize with encoder last hidden
cell = encoder_cell.repeat(self.num_layers, 1, 1) # (num_layers, batch_size, hidden_size) - Initialize with encoder last cell
# First input is <bos> token (already handled by tokenizer in tgt_input_ids)
input_token = decoder_inputs[:, 0].unsqueeze(1) # (batch_size, 1)
for t in range(1, tgt_len): # Start from 1 because first token is already handled
output, hidden, cell = self.forward_step(input_token, hidden, cell, encoder_outputs) # Get prediction for current step
outputs[t] = output # Store predictions
# Teacher forcing or predicted token as next input
teacher_force = torch.rand(1).item() < teacher_forcing_ratio
top1 = output.argmax(1) # Get predicted token indices
input_token = (decoder_inputs[:, t].unsqueeze(1) if teacher_force else top1.unsqueeze(1)) # (batch_size, 1)
return outputs.transpose(0, 1) # (batch_size, tgt_seq_len, output_size) - For loss calculation
class Attention(nn.Module):
def __init__(self, hidden_size):
super(Attention, self).__init__()
self.attn_W = nn.Linear(hidden_size * 2, hidden_size) # Encoder output is bidirectional
self.attn_U = nn.Linear(hidden_size, hidden_size) # Decoder hidden state
self.attn_v = nn.Linear(hidden_size, 1)
def forward(self, decoder_hidden, encoder_outputs):
# decoder_hidden: (batch_size, 1, hidden_size) - last decoder hidden state
# encoder_outputs: (batch_size, src_seq_len, hidden_size * 2)
seq_len = encoder_outputs.size(1)
decoder_hidden_repeated = decoder_hidden.repeat(1, seq_len, 1) # (batch_size, src_seq_len, hidden_size)
attn_weights = self.attn_v(torch.tanh(self.attn_W(encoder_outputs) + self.attn_U(decoder_hidden_repeated))) # (batch_size, src_seq_len, 1)
attn_weights = attn_weights.squeeze(2).unsqueeze(1) # (batch_size, 1, src_seq_len) - For softmax over seq_len
attn_weights = torch.softmax(attn_weights, dim=2) # Attention probabilities
context = torch.bmm(attn_weights, encoder_outputs) # (batch_size, 1, hidden_size * 2) - Weighted sum of encoder outputs
return context
class Seq2Seq(nn.Module):
def __init__(self, encoder, decoder, target_pad_idx):
super(Seq2Seq, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.target_pad_idx = target_pad_idx
def forward(self, src_input_ids, src_attention_mask, tgt_input_ids, tgt_attention_mask):
# src_input_ids: (batch_size, src_seq_len)
# src_attention_mask: (batch_size, src_seq_len)
# tgt_input_ids: (batch_size, tgt_seq_len)
# tgt_attention_mask: (batch_size, tgt_seq_len)
input_lengths = src_attention_mask.sum(1) # Actual lengths, ignoring padding
target_lengths = tgt_attention_mask.sum(1)
encoder_outputs, encoder_hidden, encoder_cell = self.encoder(src_input_ids, input_lengths)
# Decoder input is shifted right target (already handled by tokenizer in tgt_input_ids - includes <bos>)
decoder_outputs = self.decoder(tgt_input_ids, encoder_outputs, encoder_hidden, encoder_cell, target_lengths, tgt_attention_mask)
# decoder_outputs: (batch_size, tgt_seq_len, output_size) - Logits
return decoder_outputs
# --- 6. Initialize Model, Optimizer, Loss Function ---
src_vocab_size = len(tokenizer) # DeepSeek tokenizer has a large vocab
tgt_vocab_size = len(tokenizer) # Assuming shared tokenizer for simplicity (adjust if needed)
target_pad_idx = tokenizer.pad_token_id
encoder = EncoderRNN(src_vocab_size, EMBED_SIZE, HIDDEN_SIZE, NUM_LAYERS, dropout=0.5)
decoder = DecoderRNN(tgt_vocab_size, EMBED_SIZE, HIDDEN_SIZE, NUM_LAYERS, dropout=0.5)
model = Seq2Seq(encoder, decoder, target_pad_idx).to('cuda' if torch.cuda.is_available() else 'cpu') # Move model to GPU if available
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
criterion = nn.CrossEntropyLoss(ignore_index=target_pad_idx) # Ignore padding tokens in loss
# --- 7. Training Loop ---
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
for epoch in range(NUM_EPOCHS):
model.train()
epoch_loss = 0
for batch_idx, batch in enumerate(train_dataloader):
src_input_ids = batch['src_input_ids'].to(device)
src_attention_mask = batch['src_attention_mask'].to(device)
tgt_input_ids = batch['tgt_input_ids'].to(device)
tgt_attention_mask = batch['tgt_attention_mask'].to(device)
optimizer.zero_grad()
output = model(src_input_ids, src_attention_mask, tgt_input_ids, tgt_attention_mask)
# output: (batch_size, tgt_seq_len, output_size) - Logits
# Reshape for loss calculation
output_reshape = output[:, 1:, :].contiguous().view(-1, tgt_vocab_size) # Exclude <bos> token from target and flatten
tgt_reshape = tgt_input_ids[:, 1:].contiguous().view(-1) # Exclude <bos> token from target and flatten
# output_reshape: (batch_size * (tgt_seq_len - 1), output_size)
# tgt_reshape: (batch_size * (tgt_seq_len - 1))
loss = criterion(output_reshape, tgt_reshape)
loss.backward()
# Clip gradients to prevent exploding gradients
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1) # Adjust max_norm as needed
optimizer.step()
epoch_loss += loss.item()
if batch_idx % 100 == 0:
avg_loss = epoch_loss / (batch_idx + 1)
print(f"Epoch [{epoch+1}/{NUM_EPOCHS}], Batch [{batch_idx}/{len(train_dataloader)}], Loss: {avg_loss:.4f}")
print(f"Epoch [{epoch+1}/{NUM_EPOCHS}], Average Loss: {epoch_loss / len(train_dataloader):.4f}")
# --- 8. Inference / Translation Function (Basic Greedy Decoding) ---
def translate_sentence(model, tokenizer, src_sentence, max_len=MAX_SEQ_LEN, device=device):
model.eval()
with torch.no_grad():
src_tokens = tokenizer(src_sentence, max_length=max_len, truncation=True, padding='max_length', return_tensors='pt').to(device)
src_input_ids = src_tokens['input_ids']
src_attention_mask = src_tokens['attention_mask']
input_lengths = src_attention_mask.sum(1)
encoder_outputs, encoder_hidden, encoder_cell = model.encoder(src_input_ids, input_lengths)
# Decoder input starts with <bos> token
decoder_input_ids = torch.tensor([[tokenizer.bos_token_id]]).to(device) # Start with BOS
decoder_hidden = encoder_hidden
decoder_cell = encoder_cell
predicted_tokens = []
for _ in range(max_len):
output, decoder_hidden, decoder_cell = model.decoder.forward_step(decoder_input_ids, decoder_hidden, decoder_cell, encoder_outputs)
predicted_token_idx = output.argmax(1) # Greedy decoding - take most likely token
predicted_token = predicted_token_idx.item()
if predicted_token == tokenizer.eos_token_id: # Stop if EOS token is predicted
break
predicted_tokens.append(predicted_token)
decoder_input_ids = torch.tensor([[predicted_token]]).to(device) # Use predicted token as next input
translated_text = tokenizer.decode(predicted_tokens, skip_special_tokens=True)
return translated_text
# --- 9. Example Translation ---
model.eval() # Set to evaluation mode before inference
english_sentence = "Hello, how are you doing today?"
japanese_translation = translate_sentence(model, tokenizer, english_sentence)
print(f"English: {english_sentence}")
print(f"Japanese Translation: {japanese_translation}")
Explanation and Key Points:
Hyperparameters: Adjust these based on your resources and dataset size.
Tokenizer and Dataset Loading:
Uses AutoTokenizer from Hugging Face transformers for DeepSeek-R1.
Uses load_dataset from Hugging Face datasets for JParaCrawl.
Specifies 'english' and 'japanese' as the keys for source and target languages.
TranslationDataset Class:
Handles loading data from the Hugging Face dataset.
Tokenizes English and Japanese sentences using the DeepSeek-R1 tokenizer.
Pads sequences to MAX_SEQ_LEN (you can explore dynamic padding for efficiency if needed).
Returns dictionaries of input IDs and attention masks for both source and target.
DataLoader: Creates a data loader for batching and shuffling the training data.
Model Components (EncoderRNN, DecoderRNN, Attention, Seq2Seq):
EncoderRNN:
Embeds the input sequence.
Uses a bidirectional LSTM to encode the sequence into hidden states and cell states.
Uses linear layers to adjust the encoder's final hidden and cell states to be suitable initial states for the decoder (since encoder is bidirectional and decoder is unidirectional in this example).
Packs padded sequences for efficiency in LSTM.
DecoderRNN:
Embeds the target sequence.
Includes an Attention mechanism to focus on relevant parts of the encoder output.
Uses a unidirectional LSTM to generate the output sequence token by token.
forward_step performs decoding for a single time step.
forward handles the entire decoding process, including teacher forcing.
Attention: Implements a Bahdanau-style additive attention mechanism.
Seq2Seq: Wraps the encoder and decoder and manages the forward pass of the entire model.
Model Initialization, Optimizer, Loss:
Instantiates the EncoderRNN, DecoderRNN, and models.
GPU: If you have a GPU, make sure PyTorch is configured to use it (CUDA installation). The code will automatically use the GPU if available.
Dataset Size: The JParaCrawl dataset can be quite large. You might want to start with a smaller subset (e.g., dataset['train'].select(range(1000))) or limit the number of training epochs for initial experiments to save time.
Vocabulary Size: DeepSeek-R1 tokenizer can have a very large vocabulary. Training can be computationally intensive and memory-demanding. Consider reducing EMBED_SIZE and HIDDEN_SIZE if you have limited resources.
Padding: The code currently uses max_length padding in the dataset. You could explore dynamic padding within batches for more efficient training, but this adds complexity.
Further Improvements (Beyond "from scratch"):
Beam Search Decoding: Instead of greedy decoding, implement beam search for better translation quality.
Attention Mechanism: Experiment with different attention mechanisms (e.g., Luong attention).
Transformer Architecture: For state-of-the-art performance, consider implementing a Transformer-based seq2seq model (like in the original Transformer paper or models like BART, T5). This "from scratch" example is RNN-based.
Evaluation Metrics: Implement BLEU score or other machine translation evaluation metrics to assess the translation quality quantitatively.
Hyperparameter Tuning: Experiment with different hyperparameters (learning rate, hidden size, number of layers, dropout, etc.) to optimize performance.
Data Preprocessing: Further clean or preprocess the JParaCrawl dataset if needed (although it's already filtered).
Subword Tokenization: DeepSeek-R1 uses subword tokenization (SentencePiece). Understand how this impacts vocabulary and token handling.