Add a loop to the last section of the code where an input is passed to the model to…
- User
Add a loop to the last section of the code where an input is passed to the model to generate text: import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset from collections import Counter
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)
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}") - Assistant
To add a loop to the last section of the code so that text generation can be executed multiple times with different initial seed texts or parameters, you can wrap the text generation and output printing into a function and call it repeatedly in a loop. Below is the modified code with such a loop added at the end:
- User
modify the seed text to be as an input that the user can write to fill and then be passed like a chat
- Assistant
To modify the code to take seed text as user input, you can implement a simple interactive loop that prompts the user to enter seed text which is then used for generating text. This makes the experience similar to a chat, where the user gives an input, and the model responds with generated text. Here's how you can modify the code:
# ... [rest of the existing code above] ... # Train the model with the text data train_model_TXT(single_lstm_txt_model, criterion, optimizer, num_epochs, data_loader) # Start a loop for the interactive chat-like text generation while True: try: # Get user input seed_text = input("Enter seed text (type 'quit' to stop): ") # Check if user wants to quit the interaction if seed_text.lower() == 'quit': print("Exiting text generation chat.") break # User input is not empty and not "quit", generate text if seed_text.strip(): 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) else: print("Seed text cannot be empty.") except KeyboardInterrupt: # Handle KeyboardInterrupt (Ctrl+C) to gracefully exit print("\nExiting text generation chat.") break - User
Epoch 9, Loss: 0.9691575050354004 Epoch 10, Loss: 0.9689987182617188 Enter seed text (type 'quit' to stop): Give me code to Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Mamba\LSTM-Language model.py", line 147, in generated_text = generate_text(single_lstm_txt_model, dataset, seed_text, num_generate, temperature) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\LSTM-Language model.py", line 107, in generate_text generated_text = " ".join([dataset.idx2token[token] for token in generated_tokens]) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\LSTM-Language model.py", line 107, in generated_text = " ".join([dataset.idx2token[token] for token in generated_tokens]) KeyError: 102
- Assistant
- User
- Assistant
The code looks correct now; you have integrated the modifications I suggested earlier, namely:
- Using
.get()to provide a default value for missing keys ("<unk>") in thegenerate_textfunction. - Putting the model into an interactive mode where it accepts seed text from the user and generates text based on that input.
If you've made these changes and you're still encountering an error similar to "
KeyError: 102", then it's likely because there are tokens being generated by the model that do not exist in theidx2tokendictionary. As such, the.get()method with the default"<unk>"placeholder should have resolved this problem. - Using
- User
Can you integrate this MoE architecture into the code for the same task: # 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) - Assistant
- User
- Assistant
- User
I get this error: Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 182, in train_model_TXT(moe_model, criterion, optimizer, num_epochs, data_loader) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 109, in train_model_TXT predictions = model(inputs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 165, in forward output = self.MoE(embedded) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 47, in forward gating_scores = self.gating_network(x).unsqueeze(-1) # [batch_size, num_experts, 1] File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 34, in forward x = self.fc(x) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\linear.py", line 114, in forward return F.linear(input, self.weight, self.bias) RuntimeError: mat1 and mat2 shapes cannot be multiplied (17x3712 and 128x4)
- Assistant
- User
After making the change, i get this error: Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 183, in train_model_TXT(moe_model, criterion, optimizer, num_epochs, data_loader) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 111, in train_model_TXT loss = criterion(predictions, targets.view(-1)) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\loss.py", line 1179, in forward return F.cross_entropy(input, target, weight=self.weight, File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\functional.py", line 3053, in cross_entropy return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing) ValueError: Expected input batch_size (17) to match target batch_size (493).
- Assistant
- User
- Assistant
- User
This is what i got: Batch 0 - inputs shape: torch.Size([17, 29]), targets shape: torch.Size([17, 29]) Batch 0 - predictions shape: torch.Size([17, 239])
Batch 0 - targets flattened shape: torch.Size([493]) Batch 0 - predictions flattened shape: torch.Size([17, 239]) Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 201, in train_model_TXT(moe_model, criterion, optimizer, num_epochs, data_loader) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 129, in train_model_TXT loss = criterion(predictions, targets) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\loss.py", line 1179, in forward return F.cross_entropy(input, target, weight=self.weight, File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\functional.py", line 3053, in cross_entropy return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing) ValueError: Expected input batch_size (17) to match target batch_size (493). - Assistant
- User
- Assistant
- User
- Assistant
- User
I get this now after this change: Batch 0 - inputs shape: torch.Size([17, 29]), targets shape: torch.Size([17, 29]) Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 200, in train_model_TXT(moe_model, criterion, optimizer, num_epochs, data_loader) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 114, in train_model_TXT predictions = model(inputs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 183, in forward output = self.MoE(embedded) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1518, in _wrapped_call_impl return self._call_impl(*args, **kwargs) File "C:\Users\Dell-PC\Desktop\Projets\Mamba\Arithword\lib\site-packages\torch\nn\modules\module.py", line 1527, in _call_impl return forward_call(*args, **kwargs) File "c:\Users\Dell-PC\Desktop\Projets\Mamba\MoE-LSTM_Language Model.py", line 53, in forward expert_outputs = torch.cat(expert_outputs, dim=3) IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3)
- Assistant
The error message
IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3)indicates there is an issue with dimension indices while concatenatingexpert_outputsusing . - User
Look at my conversation with the model just trained, give me your opinion: Enter seed text (type 'quit' to stop): Physics is Generated Text: one of the most fundamental scientific disciplines, with Enter seed text (type 'quit' to stop): Black holes are Generated Text: formed when massive stars collapse at the end Enter seed text (type 'quit' to stop): Physics is a science that Generated Text: generates random text without any human input, just Enter seed text (type 'quit' to stop):
- Assistant
Based on the conversation snippets you've provided, it seems that the model you have trained is capable of generating grammatically coherent and contextually relevant text, which is impressive. Here are some observations:
- The responses, "one of the most fundamental scientific disciplines, with" and "formed when massive stars collapse at the end," are factually correct continuations that show the model has learned some meaningful patterns from the data it was trained on.
- User
- Assistant
- User
Look at the results: Enter seed text (type 'quit' to stop): Physics is Generated Text: one of the most fundamental scientific disciplines, with Enter seed text (type 'quit' to stop): Black holes are Generated Text: formed when massive stars collapse at the end Enter seed text (type 'quit' to stop): Physics is a science that Generated Text: generates random text without any human input, just Enter seed text (type 'quit' to stop): The law of conservation of energy states that Generated Text: generates text without any human input, just a Enter seed text (type 'quit' to stop): One of the most famous experiments in quantum mechanics is Generated Text: takes the csv file, this function should will Enter seed text (type 'quit' to stop): If you could observe a black hole, you would notice Generated Text: not even light, can escape. Black holes are Enter seed text (type 'quit' to stop): In physics, symmetry is important because Generated Text: space where gravity is so strong that nothing, Enter seed text (type 'quit' to stop): Transformers differ from traditional sequential models in that Generated Text: takes the Python Language. Give Give input as
- Assistant
- User
Give me a variable to print the model param count
- Assistant
To print the total number of parameters in the model, you can iterate through the model's parameters using
.parameters()method provided by PyTorch and sum up the number of elements in each parameter tensor. Here's a simple method to achieve that:def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) # Example usage with your model: total_params = count_parameters(moe_model) print(f"Total trainable parameters: {total_params}")The
numel()function returns the total number of elements in the tensor, so by iterating over allparameters()(and ensuring they require gradients, which indicates they are trainable) and summing thenumel()output, you get the total number of trainable parameters in the model. - User
Can you modify the text generation part of the code to only stop token generation when the model produces a point "full sentence stop", here is the part to modify: while True: try: # Get user input seed_text = input("Enter seed text (type 'quit' to stop): ")
# Check if user wants to quit the interaction if seed_text.lower() == "quit": print("Exiting text generation chat.") break # User input is not empty and not “quit”, generate text if seed_text.strip(): num_generate = 8 # Number of words to generate temperature = 0.7 # Sampling temperature, higher will increase diversity # Use the trained model to generate text generated_text = generate_text(moe_model, dataset, seed_text, num_generate, temperature) print("Generated Text:", generated_text) else: print("Seed text cannot be empty.") except KeyboardInterrupt: # Handle KeyboardInterrupt (Ctrl+C) to gracefully exit print("\nExiting text generation chat.") break* - Assistant