import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
from datasets import load_dataset
from transformers import GPT2TokenizerFast
import torch.optim as optim
# Ensure that we are not using MPS (Metal Performance Shaders)
torch.backends.mps.is_available = lambda: False
torch.backends.mps.is_built = lambda: False
# Define a custom linear attention mechanism
class LinearAttention(nn.Module):
def __init__(self, d_model, heads=4, dropout=0.1):
super(LinearAttention, self).__init__()
self.heads = heads
self.d_k = d_model // heads
self.to_qkv = nn.Linear(d_model, d_model * 3, bias=False)
self.to_out = nn.Linear(d_model, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask=None):
batch_size, seq_len, d_model = x.size()
# Compute queries, keys, and values
qkv = self.to_qkv(x) # [batch, seq_len, d_model * 3]
qkv = qkv.reshape(batch_size, seq_len, self.heads, 3 * self.d_k)
qkv = qkv.permute(0, 2, 1, 3) # [batch, heads, seq_len, 3 * d_k]
q, k, v = torch.chunk(qkv, 3, dim=-1) # Each is [batch, heads, seq_len, d_k]
# Apply activation to queries and keys
q = F.elu(q) + 1
k = F.elu(k) + 1
# Compute attention scores using linear attention
# Compute context vectors
kv = torch.einsum('bhld,bhlm->bhmd', k, v) # [batch, heads, d_k, d_k]
z = 1 / torch.einsum('bhld,bhld->bhl', q, k.sum(dim=2)) # [batch, heads, seq_len]
out = torch.einsum('bhl,bhld->bhld', z, torch.einsum('bhmd,bhld->bhml', kv, q)) # [batch, heads, seq_len, d_k]
out = out.permute(0, 2, 1, 3).contiguous().view(batch_size, seq_len, d_model)
out = self.to_out(out)
return out
# Define the Transformer block using the custom attention
class TransformerBlock(nn.Module):
def __init__(self, d_model, heads=4, dropout=0.1):
super(TransformerBlock, self).__init__()
self.attention = LinearAttention(d_model, heads, dropout)
self.norm1 = nn.LayerNorm(d_model)
self.ff = nn.Sequential(
nn.Linear(d_model, d_model * 4),
nn.ReLU(),
nn.Linear(d_model * 4, d_model),
nn.Dropout(dropout)
)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, x):
attended = self.attention(x)
x = self.norm1(x + attended)
fedforward = self.ff(x)
x = self.norm2(x + fedforward)
return x
# Define the overall model
class MyEfficientTransformer(nn.Module):
def __init__(self, vocab_size, max_seq_len=512, d_model=256, N=4, heads=4, dropout=0.1):
super(MyEfficientTransformer, self).__init__()
self.token_embedding = nn.Embedding(vocab_size, d_model)
self.pos_embedding = nn.Parameter(torch.randn(1, max_seq_len, d_model))
self.layers = nn.ModuleList([TransformerBlock(d_model, heads, dropout) for _ in range(N)])
self.norm = nn.LayerNorm(d_model)
self.fc_out = nn.Linear(d_model, vocab_size)
def forward(self, x):
batch_size, seq_len = x.size()
positions = self.pos_embedding[:, :seq_len, :]
x = self.token_embedding(x) + positions
for layer in self.layers:
x = layer(x)
x = self.norm(x)
logits = self.fc_out(x)
return logits
# Load the tokenizer
tokenizer = GPT2TokenizerFast.from_pretrained('gpt2')
tokenizer.pad_token = tokenizer.eos_token
# Load the dataset
dataset = load_dataset('VMware/open-instruct', split='train')
# Function to tokenize the dataset
def tokenize_function(examples):
inputs = examples['instruction']
targets = examples['response']
# Concatenate instruction and response with EOS token
combined = [i + tokenizer.eos_token + t + tokenizer.eos_token for i, t in zip(inputs, targets)]
tokenized = tokenizer(combined, padding='max_length', truncation=True, max_length=512, return_tensors='pt')
return tokenized
# Apply the tokenize function to the dataset
tokenized_dataset = dataset.map(tokenize_function, batched=True, remove_columns=['instruction', 'response'])
# Prepare DataLoader
train_dataset = tokenized_dataset.with_format('torch')
train_dataloader = DataLoader(train_dataset, batch_size=1, shuffle=True)
# Initialize the model
vocab_size = tokenizer.vocab_size
model = MyEfficientTransformer(vocab_size)
# Move model to CPU
device = torch.device('cpu')
model.to(device)
# Define loss function and optimizer
criterion = nn.CrossEntropyLoss(ignore_index=tokenizer.pad_token_id)
optimizer = optim.Adam(model.parameters(), lr=1e-4)
# Training loop
num_epochs = 1 # You can increase this value for actual training
model.train()
for epoch in range(num_epochs):
total_loss = 0
for batch in train_dataloader:
optimizer.zero_grad()
input_ids = batch['input_ids'].squeeze(1).to(device)
attention_mask = batch['attention_mask'].squeeze(1).to(device)
# Shift inputs and labels
inputs = input_ids[:, :-1]
labels = input_ids[:, 1:]
outputs = model(inputs)
# Compute loss
loss = criterion(outputs.view(-1, vocab_size), labels.view(-1))
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1}, Loss: {total_loss/len(train_dataloader)}")
# Save the model
torch.save(model.state_dict(), 'my_efficient_transformer.pth')
# Save the tokenizer
tokenizer.save_pretrained('./tokenizer/')
# The model and tokenizer are saved and can be loaded later for inference or further training
Explanation:
This code defines a new neural network architecture called MyEfficientTransformer, which is a smaller and more efficient alternative to the standard Transformer architecture. It incorporates design elements inspired by Google's Reformer to make the model more memory-efficient and suitable for devices with limited resources, like a MacBook Air with 8GB of memory.
Key Components:
-
Linear Attention (LinearAttention Class):
- Implements a custom attention mechanism that approximates the standard attention but with linear complexity, reducing memory usage from quadratic to linear with respect to the sequence length.
- Uses efficient operations to compute attention scores without constructing large attention matrices.
-
Transformer Block (TransformerBlock Class):
- Utilizes the custom linear attention mechanism.
- Includes layer normalization and a feed-forward network with dropout for regularization.
-
Efficient Transformer Model (MyEfficientTransformer Class):
- Embeds input tokens and adds positional embeddings.
- Stacks multiple
TransformerBlock layers to allow the model to learn complex representations.
- Includes a final linear layer to project the output to the vocabulary size for token prediction.
-
Data Loading and Preprocessing:
- Uses the
VMware/open-instruct dataset, focusing on the instruction and response fields.
- Tokenizes the combined instruction and response, ensuring that the model learns to generate appropriate responses to given instructions.
- Applies padding and truncation to manage sequence lengths compatible with the model's maximum sequence length.
-
Training Loop:
- Defines a simple training loop that iterates over the dataset.
- Uses the
CrossEntropyLoss function with the ignore_index parameter to handle padding tokens.
- Optimizes the model using the Adam optimizer.
- Processes data in small batches to fit within the memory constraints of the MacBook Air.
-
Model Saving:
- After training, the model's state dictionary is saved to a file (
my_efficient_transformer.pth).
- The tokenizer is also saved for future use.
Notes:
- The model is designed to be small and efficient, suitable for machines with limited memory.
- The batch size is set to 1 to ensure the code runs within the 8GB memory constraint.
- The training loop runs for one epoch, but you can increase the number of epochs for better performance.
- MPS (Metal Performance Shaders) is disabled to ensure that the code runs on the CPU and not on any GPU accelerators that may be present.
- The code avoids using any unnecessary components from the sample code and focuses on implementing the new architecture.
Running the Code on a MacBook Air with 8GB Memory:
- Ensure that you have Python and the required libraries installed (
torch, datasets, transformers).
- Run the script in a terminal or an IDE.
- Monitor the memory usage to ensure it stays within limits.
- If you encounter memory issues, consider reducing the
max_seq_len or further decreasing the batch size.
Conclusion:
This code provides a complete implementation of a new neural network architecture that serves as a more efficient alternative to the generative Transformer. It is optimized for environments with limited computational resources and can be trained and run on a MacBook Air with 8GB of memory.