import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
import math
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset
from collections import Counter
def generate_linear_equations(number_of_samples, max_int=400, seq_len=1):
a_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
x_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
b_values = np.random.randint(1, max_int, size=(number_of_samples, 1))
c_values = a_values ** x_values + b_values - a_values/3 + x_values**2 # Compute c in ax + b = c
# Note the change here: using ‘seq_len’ instead of ‘1’ to make it more flexible
equations = np.concatenate((a_values, b_values, c_values), axis=1).reshape(-1, seq_len, 3)
return equations, x_values.reshape(-1, seq_len, 1)
def generate_complex_equations(number_of_samples, max_int=50, seq_len=1):
a_values = np.random.uniform(1, max_int, size=(number_of_samples, 1))
x_values = np.random.uniform(-max_int, max_int, size=(number_of_samples, 1))
b_values = np.random.uniform(1, max_int, size=(number_of_samples, 1))
# An example of a complex, multi-modal function
c_values = (np.sin(a_values) * (np.exp(x_values) - np.exp(-x_values)) / 2 # sinh function
+ b_values * np.log(x_values**2 + 1) # log with quadratic terms
+ np.cos(b_values) * (x_values**3 - a_values / (x_values + 0.1))) # cubic and reciprocal terms
# Concatenate and reshape to generate sequences
equations = np.concatenate((a_values, b_values, c_values), axis=1).reshape(-1, seq_len, 3)
return equations, x_values.reshape(-1, seq_len, 1)
class TextDataset(Dataset):
def init(self, path, seq_len):
self.seq_len = seq_len
with open(path, "r", encoding="utf-8") as f:
text = f.read()
words = text.split()
self.vocab, self.idx2token = self.build_vocab(words)
self.tokens = [self.vocab.get(w, 0) for w in words] # Default to 0 for unknown tokens
def build_vocab(self, words):
counts = Counter(words)
vocab = {word: i for i, (word, _) in enumerate(counts.most_common(), 1)}
vocab["<pad>"] = 0
idx2token = {i: word for word, i in vocab.items()}
return vocab, idx2token
def __len__(self):
return len(self.tokens) // self.seq_len
def __getitem__(self, idx):
chunk = self.tokens[idx * self.seq_len: (idx + 1) * self.seq_len]
x = chunk[:-1]
y = chunk[1:]
return torch.tensor(x), torch.tensor(y)
def collate_fn(batch):
inputs, targets = zip(*batch)
inputs = pad_sequence(inputs, batch_first=True, padding_value=0)
targets = pad_sequence(targets, batch_first=True, padding_value=0)
return inputs, targets
Set the path to your text file and define sequence length
path_to_text = 'C:/Users/Dell-PC/Desktop/Simple_Transfomer.txt' # replace with the path to your text file
seq_len = 30 # sequence length
Create a dataset and data loader
dataset = TextDataset(path_to_text, seq_len)
data_loader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=collate_fn)
Expert LSTM Model
class LSTMExpert(nn.Module):
def init(self, input_size, hidden_size, output_size):
super(LSTMExpert, self).init()
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h, _ = self.lstm(x)
h = h[:, -1, :] # taking the last sequence output
return self.fc(h)
Gating Network
class GatingNetwork(nn.Module):
def init(self, input_size, num_experts):
super(GatingNetwork, self).init()
self.fc = nn.Linear(input_size, num_experts)
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
# Flatten if needed (in case input comes from LSTM with sequence length)
if x.dim() > 2:
x = x.view(x.size(0), -1)
x = self.fc(x)
return self.softmax(x)
Mixture of Experts Model
class MixtureOfExperts(nn.Module):
def init(self, input_size, hidden_size, output_size, num_experts):
super(MixtureOfExperts, self).init()
self.num_experts = num_experts
self.experts = nn.ModuleList([LSTMExpert(input_size, hidden_size, output_size) for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
def forward(self, x):
# Compute the gating weights
gating_scores = self.gating_network(x).unsqueeze(-1) # [batch_size, num_experts, 1]
# Compute the output from each expert for every example
expert_outputs = [expert(x) for expert in self.experts]
expert_outputs = torch.stack(expert_outputs, dim=-1) # [batch_size, output_size, num_experts]
# Multiply gating scores by expert outputs and sum the result
# torch.bmm expects [batch_size, n, m] and [batch_size, m, p]
# here it will do [batch_size, output_size, num_experts] bmm [batch_size, num_experts, 1]
mixed_output = torch.bmm(expert_outputs, gating_scores)
# Now mixed_output has shape [batch_size, output_size, 1], we should squeeze it to [batch_size, output_size]
mixed_output = mixed_output.squeeze(-1)
return mixed_output
class SingleLSTM(nn.Module):
def init(self, input_size, hidden_size, output_size, num_layers=3): # This model will have more parameters
super(SingleLSTM, self).init()
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h, _ = self.lstm(x)
h = h[:, -1, :] # taking the last sequence output
return self.fc(h)
Simple Positional Encoding (not learnable, for simplicity)
def positional_encoding(seq_len, d_model, device):
# Generate the positions
pos = torch.arange(seq_len).unsqueeze(1) # [seq_len, 1]
# Generate the dividers for the positions
div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)).unsqueeze(0)
# Compute the positional encodings: sinusoids of different frequencies
pe = torch.zeros((seq_len, d_model), device=device)
pe[:, 0::2] = torch.sin(pos.float() * div_term)
pe[:, 1::2] = torch.cos(pos.float() * div_term)
return pe.unsqueeze(0)
class SimpleTransformer(nn.Module):
def init(self, input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers=1):
super(SimpleTransformer, self).init()
self.d_model = d_model
self.input_fc = nn.Linear(input_size, d_model) # Linear layer to project to model dimension
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=dim_feedforward,
batch_first=True) # Added batch_first=True
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_encoder_layers)
self.output_fc = nn.Linear(d_model, output_size)
def forward(self, x):
batch_size, seq_len, _ = x.size()
x = self.input_fc(x) + positional_encoding(seq_len, self.d_model, x.device)
transformer_output = self.transformer_encoder(x)
output = self.output_fc(transformer_output[:, -1, :]) # Taking the result from the last sequence element
return output
class TransformerExpert(nn.Module):
def init(self, input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers=1):
super(TransformerExpert, self).init()
self.d_model = d_model
self.input_fc = nn.Linear(input_size, d_model) # Linear layer to project to model dimension
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True)
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_encoder_layers)
self.output_fc = nn.Linear(d_model, output_size)
def forward(self, x):
x = self.input_fc(x)
x += positional_encoding(x.size(1), self.d_model, x.device)
transformer_output = self.transformer_encoder(x)
transformer_output = transformer_output[:, -1, :]
output = self.output_fc(transformer_output)
return output
class MoETransformer(nn.Module):
def init(self, input_size, d_model, output_size, nhead, dim_feedforward, num_experts, num_encoder_layers=1):
super(MoETransformer, self).init()
self.num_experts = num_experts
self.experts = nn.ModuleList([TransformerExpert(input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers)
for _ in range(num_experts)])
self.gating_network = GatingNetwork(input_size, num_experts)
def forward(self, x):
# Compute the gating weights
gating_scores = self.gating_network(x).unsqueeze(-1) # [batch_size, num_experts, 1]
# Compute the output from each expert for every example
expert_outputs = [expert(x).unsqueeze(2) for expert in self.experts] # [batch_size, output_size, 1]
expert_outputs = torch.cat(expert_outputs, dim=2) # [batch_size, output_size, num_experts]
# Multiply gating scores by expert outputs and sum the result
mixed_output = torch.bmm(expert_outputs, gating_scores) # [batch_size, output_size, 1]
# Now mixed_output has shape [batch_size, output_size, 1], we squeeze it to [batch_size, output_size]
mixed_output = mixed_output.squeeze(-1)
return mixed_output
class SingleLSTM_TXT(nn.Module):
def init(self, input_size, hidden_size, output_size, num_layers=3):
# In a language model, input_size is usually the dimension of the embedding vector,
# and output_size is the size of the vocabulary.
super(SingleLSTM_TXT, self).init()
self.embedding = nn.Embedding(num_embeddings=output_size, embedding_dim=input_size)
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
embedded = self.embedding(x)
h, _ = self.lstm(embedded)
# You may need to reshape h if you want to include more than the last LSTM output
h = h.reshape(-1, h.shape[-1])
return self.fc(h)
def train_model_TXT(model, criterion, optimizer, num_epochs, data_loader):
model.train()
for epoch in range(num_epochs):
total_loss = 0
for inputs, targets in data_loader:
optimizer.zero_grad()
predictions = model(inputs)
loss = criterion(predictions, targets.view(-1))
loss.backward()
optimizer.step()
total_loss += loss.item()
average_loss = total_loss / len(data_loader.dataset)
print(f"Epoch {epoch+1}, Loss: {average_loss}")
def generate_text(model, dataset, seed_text, num_generate, temperature=1.0):
model.eval() # Put the model in evaluation mode
# List to store the generated tokens
generated_tokens = []
# Initial sequence (prefix) to start the generation process
input_sequence = [dataset.vocab.get(word, 0) for word in seed_text.split()] # Convert to token IDs
current_sequence = torch.tensor(input_sequence, dtype=torch.long).unsqueeze(0)
# Generate num_generate tokens
for _ in range(num_generate):
# Forward pass through the model
with torch.no_grad():
output = model(current_sequence)
# Get probabilities, apply temperature scaling, and sample from the distribution
probabilities = F.softmax(output[-1] / temperature, dim=0).detach()
next_token_idx = torch.multinomial(probabilities, 1).item()
# Append token to the current sequence and to the generated tokens
generated_tokens.append(next_token_idx)
current_sequence = torch.cat((current_sequence, torch.tensor([[next_token_idx]])), 1)
# Convert tokens to words
generated_text = " ".join([dataset.idx2token[token] for token in generated_tokens])
return generated_text
Instantiate the SingleLSTM_TXT model
vocab_size = len(dataset.vocab) # The size of the vocabulary
embedding_dim = 128 # Size of embeddings
hidden_size = 256 # Number of features in the hidden state of the LSTM
num_layers = 2 # Number of stacked LSTM layers
single_lstm_txt_model = SingleLSTM_TXT(vocab_size, embedding_dim, hidden_size, num_layers)
def train_model(model, criterion, optimizer, num_epochs, batch_size, equations_tensor, solutions_tensor):
model.train()
training_losses = []
for epoch in range(num_epochs):
total_loss = 0
# Shuffle the data
perm = torch.randperm(equations_tensor.size(0))
equations_shuffled = equations_tensor[perm]
solutions_shuffled = solutions_tensor[perm]
for i in range(0, equations_tensor.size(0), batch_size):
# Slice out the batches
x_batch = equations_shuffled[i:i+batch_size]
y_batch = solutions_shuffled[i:i+batch_size]
optimizer.zero_grad()
predictions = model(x_batch)
predictions = predictions.squeeze() # Ensure predictions and targets have the same size
loss = criterion(predictions, y_batch.view(-1)) # Flatten the target tensor
loss.backward()
optimizer.step()
total_loss += loss.item()
average_loss = total_loss / (equations_tensor.size(0) / batch_size)
training_losses.append(average_loss)
print(f"Epoch {epoch+1}, Loss: {average_loss}")
return training_losses
Parameters for the Transformer model
d_model = 128
nhead = 4
dim_feedforward = 256
input_size = 3 # a, b, and c from equation ax + b = c
hidden_size = 32
output_size = 1 # we are predicting the value of x
num_experts = 10
Training parameters
num_epochs = 10
batch_size = 128
learning_rate = 1e-4
Define Loss Function and Optimizer for TXT dataset
criterion = nn.CrossEntropyLoss() # Use CrossEntropyLoss for classification tasks
optimizer = torch.optim.Adam(single_lstm_txt_model.parameters(), lr=learning_rate)
Train the model with the text data
train_model_TXT(single_lstm_txt_model, criterion, optimizer, num_epochs, data_loader)
Seed text to start the generation
seed_text = "Give me code to define a "
num_generate = 8 # Number of words to generate
temperature = 1.0 # Sampling temperature, higher will increase diversity
Use the trained model to generate text
generated_text = generate_text(single_lstm_txt_model, dataset, seed_text, num_generate, temperature)
print("Generated Text: ", generated_text)
Reshape the equations to (batch_size, seq_length, features)
For simplicity, we consider each equation as a sequence of length 1
Generate the data only once before training
equations_tensor, solutions_tensor = generate_complex_equations(number_of_samples=5000)
Convert numpy arrays to torch tensors
equations_tensor = torch.from_numpy(equations_tensor).float()
solutions_tensor = torch.from_numpy(solutions_tensor).float()
Reshape the equations and solutions to (batch_size, seq_length, features)
train_equations_tensor = equations_tensor.view(-1, 1, input_size) # reshaping once, correctly
train_solutions_tensor = solutions_tensor # reshaping for solutions to match batch size
Instantiate the MoE-Transformer model
moe_transformer_model = MoETransformer(input_size=input_size, d_model=d_model, output_size=output_size, nhead=nhead, dim_feedforward=dim_feedforward, num_experts=num_experts)
moe_transformer_optimizer = torch.optim.Adam(moe_transformer_model.parameters(), lr=learning_rate)
moe_transformer_criterion = nn.MSELoss()
Instantiate the SimpleTransformer model
transformer_model = SimpleTransformer(input_size=input_size, d_model=d_model2, output_size=output_size, nhead=nhead2, dim_feedforward=dim_feedforward)
transformer_optimizer = torch.optim.Adam(transformer_model.parameters(), lr=learning_rate)
transformer_criterion = nn.MSELoss()
Instantiate the MoE model
moe_model = MixtureOfExperts(input_size, hidden_size*8, output_size, num_experts)
moe_optimizer = torch.optim.Adam(moe_model.parameters(), lr=learning_rate)
moe_criterion = nn.MSELoss()
Instantiate the Single General LSTM model
large_model = SingleLSTM(input_size, hidden_size*4, output_size, num_layers=24) # Adjusted to have comparable number of parameters
large_optimizer = torch.optim.Adam(large_model.parameters(), lr=learning_rate)
large_criterion = nn.MSELoss()
Print the parameter count of the MoE-Transformer
print("MoE-Transformer Parameter Count:", sum(p.numel() for p in moe_transformer_model.parameters()))
Print the parameter count of the Transformer
print("Transformer Parameter Count:", sum(p.numel() for p in transformer_model.parameters()))
Print the parameter count of the MoE LSTM
print("MoE LSTM Parameter Count:", sum(p.numel() for p in moe_model.parameters()))
Print the parameter count of the Single LSTM
print("Single LSTM Parameter Count:", sum(p.numel() for p in large_model.parameters()))
Train the MoE Transformer model
print("Training MoE Transformer...")
moe_transformer_losses = train_model(moe_transformer_model, moe_transformer_criterion, moe_transformer_optimizer,num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
print("Training MoE Transformer Done !")
Train the Transformer model
print("Training Transformer...")
transformer_losses = train_model(transformer_model, transformer_criterion, transformer_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
print("Training Transformer Done !")
Train the MoE model
print("Training MoE LSTM...")
moe_losses = train_model(moe_model, moe_criterion, moe_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
print("Training MoE LSTM Done !")
Train the Single LSTM model
print("Training LSTM...")
large_losses = train_model(large_model, large_criterion, large_optimizer, num_epochs, batch_size, train_equations_tensor, train_solutions_tensor)
print("Training LSTM Done !")
Plot the results, as before
plt.figure(figsize=(12, 8))
plt.plot(moe_losses, label="Mixture of Experts Loss")
plt.plot(large_losses, label="Single LSTM Model Loss")
plt.plot(transformer_losses, label="Simple Transformer Model Loss")
plt.plot(moe_transformer_losses, label="MoE Transformer Model Loss")
plt.xlabel("Epoch")
plt.ylabel("MSE Loss")
plt.legend()
plt.title("Model Loss Comparison")
plt.show()