def forward(self, src):
x = self.embedding(src) * (self.embedding.embedding_dim ** 0.5)
x = self.transformer(x)
x = self.fc_out(x)
return x
A generator to simulate data streaming
class TextDatasetIter:
def init(self, file_path):
self.file_path = file_path
with open(file_path, 'r', encoding='utf-8') as f:
self.text = f.read()
self.char2idx = {u: i for i, u in enumerate(set(self.text))}
self.data = [self.char2idx[c] for c in self.text]
code
def __len__(self):
return len(self.data) - SEQ_LENGTH
def __iter__(self):
for i in range(len(self.data) - SEQ_LENGTH):
yield (
torch.tensor(self.data[i:i + SEQ_LENGTH], dtype=torch.long),
torch.tensor(self.data[i + 1:i + SEQ_LENGTH + 1], dtype=torch.long)
)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(VOCAB_SIZE, D_MODEL, NUM_HEADS, NUM_LAYERS, DFF).to(device)
alter this to have better training thing with like a estimation, iterations per second, etc. and make it save the model checkpoint and autodelete older ones, maximum amount of checkpoints is 3 and it saves a new checkpoint once every 1000 iters
Assistant
Enhancing the training loop by including additional performance metrics and features such as iteration speed, checkpoint management, and efficient resource utilization can improve model development and tracking during training. Below is an updated training script with these enhancements:
python
User
show me an example of what i will see when its training?
Assistant
When you run the enhanced training script, the console output during training will provide periodic updates on the model's progress. Assuming the first few iterations and checkpoints, the training log might look something like this:
Step Logging: The script logs periodically, showing:
Current epoch and iterator step (Step).
Loss value for the current batch.
Iterations per second to give you an idea of training speed.
Checkpoint Notifications: A message appears every 1000 iterations (as specified), indicating a checkpoint has been saved with the path to the checkpoint file.
Epoch Completion: After one full pass (epoch) over the dataset, an average loss for the epoch is displayed.
This kind of output helps you monitor the model's training process, see how well loss is improving, and confirm that your checkpoints are being saved correctly. Adjust logging frequency or checkpoint intervals as needed for your specific use case or computational constraints.
User
i want to see something like
1%|##--------------|1234|12it/s|3.2 loss|used: 00:12:16|est: 32:12:32
Assistant
To achieve detailed and visually informative training progress like you've described, you can utilize the tqdm library, which is excellent for creating progress bars in Python. By integrating tqdm, you can display percentage completion, iteration speed, current loss, elapsed time, and estimated time to completion (ETA) in a single progress bar.
First, ensure you have the tqdm library installed. You can install it via pip if it's not already installed:
bash
pip install tqdm
Then, you can modify the training loop to include a tqdm progress bar:
python
User
does it update ever iteration?
Assistant
The progress bar implemented with tqdm in the provided script updates every time a batch is processed, not necessarily at every iteration over individual sequences. Given that the dataset is processed in batches, the progress bar updates after each complete batch is handled. With a batch size of 16, as specified in the script, the update occurs at each batch rather than each sequence (or single iteration).
Here's a brief explanation of the updating mechanism:
Batch Processing: The loop collects a "batch" of samples (in this case, 16 sequences) before running the forward and backward pass through the model.
Progress Bar Update: Immediately after processing this batch and calculating the loss, tqdm updates the progress bar to reflect progress and current statistics (loss, time, etc.).
Update Frequency: This batch-wise update might differ from updating every single sequence, but it optimizes performance by limiting the number of updates to the console, which can be computationally expensive if done per sequence.
If you want the progress bar to update each iteration (i.e., each individual sequence rather than each batch), you would move the progress_bar.update(1) line inside the inner loop, which currently accumulates sequence batches. Keep in mind that this could make the progress bar excessively verbose and slow down execution due to frequent console output updates.
User
ok well for now its good enough. im not getting the checkpoints saved though, not seeing new folders/files and also i want to see the calculation for the param count
Assistant
To ensure checkpoint saving works correctly, you'll want to verify a few things in the script setup:
Checkpoint Directory Existence: Ensure the directory (e.g., ./checkpoints) is correctly specified and that the code attempts to create this directory if it doesn’t already exist.
Checkpoint Saving Conditions: Check that the conditions for saving a checkpoint (e.g., if idx % SAVE_INTERVAL == 0 and idx != 0) are correctly set to trigger during training.
File Permissions and Paths: Validate that the script is running in a context where it has permission to create and write to the checkpoint directory.
Below is an updated snippet focusing on checkpointing and parameter count calculation:
python
User
i need full code
Assistant
Certainly! Below is the complete script with improvements to handle checkpoint saving, model parameter counting, and using a progress bar with tqdm to better visualize the training process:
python
User
fix the bar on this code, when a print happens in the middle of training from debugging or something it messes up the bar
import os
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
def forward(self, src):
x = self.embedding(src) * (self.embedding.embedding_dim ** 0.5)
x = self.transformer(x)
x = self.fc_out(x)
return x
A generator to simulate data streaming
class TextDatasetIter:
def init(self, file_path):
self.file_path = file_path
with open(file_path, 'r', encoding='utf-8') as f:
self.text = f.read()
self.char2idx = {u: i for i, u in enumerate(set(self.text))}
self.data = [self.char2idx[c] for c in self.text]
code
def __len__(self):
return len(self.data) - SEQ_LENGTH
def __iter__(self):
for i in range(len(self.data) - SEQ_LENGTH):
yield (
torch.tensor(self.data[i:i + SEQ_LENGTH], dtype=torch.long),
torch.tensor(self.data[i + 1:i + SEQ_LENGTH + 1], dtype=torch.long)
)
Function to count parameters
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
Function to save checkpoint
def save_checkpoint(model, optimizer, epoch, idx):
if not os.path.exists(CHECKPOINT_DIR):
os.makedirs(CHECKPOINT_DIR)
code
Assistant
To ensure that the tqdm progress bar remains intact when debugging or other prints are interspersed within the training output, we can use tqdm.write() instead of the standard print() function. The tqdm.write() function is designed to work nicely with the progress bar by correctly handling console output that might otherwise disrupt the progress bar's display.
Here's the adjusted code with tqdm.write() used for messages and prints during training:
python
User
how would i alter the following code to talk to the model?
from typing import Generator
from transformers import GPTNeoForCausalLM, GPT2TokenizerFast
import torch
import gradio as gr
import random
Load the GPT-2 tokenizer (still works for GPT Neo)
Load the saved GPT Neo model from the local checkpoint (adjust the path)
model_path = "elapt1c/ElapticAI-1a" # Replace with your desired GPT Neo model path
model = GPTNeoForCausalLM.from_pretrained(model_path, ignore_mismatched_sizes=True)
Move model to appropriate device (GPU if available, otherwise CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
def generate_token_by_token(message: str, seed: int = None, temperature: float = 1.0, top_k: int = 50) -> Generator[str, None, None]:
global currentOutput
currentOutput = "" # Clear previous output
code
# Prepare input tensor from user message
input_ids = tokenizer.encode(message, return_tensors='pt').to(device)
# Handle empty input after tokenization
if input_ids.size(-1) == 0:
raise ValueError("Input was empty after tokenization. Please try again.")
# Check if seed is provided and ensure it is valid
if seed is None or not isinstance(seed, int) or not (11111 <= seed <= 99999):
seed = random.randint(11111, 99999) # Generate a seed in the range if none is provided
else:
seed = int(seed) # Ensure the seed is an integer
# Set the seed for reproducibility
torch.manual_seed(seed)
print(f"Prompt: {message} Seed: {seed}")
generated_text = ""
with torch.no_grad():
for _ in range(25): # Limit generation to 50 tokens
outputs = model(input_ids)
next_token_logits = outputs.logits[:, -1, :]
# Apply temperature
next_token_logits = next_token_logits / temperature
# Top-k sampling
top_k_values, top_k_indices = torch.topk(next_token_logits, top_k)
probabilities = torch.softmax(top_k_values, dim=-1)
next_token_id = top_k_indices[0, torch.multinomial(probabilities, num_samples=1)]
# Decode the next token
decoded_token = tokenizer.decode(next_token_id.item(), skip_special_tokens=True)
currentOutput += decoded_token
# Yield only the new token
yield currentOutput
# Update input_ids with the newly generated token
input_ids = torch.cat([input_ids, next_token_id.unsqueeze(-1).squeeze(0)], dim=-1)
# Stop if the model generates the end-of-sequence token
if next_token_id.item() == tokenizer.eos_token_id:
break
Assistant
To modify the script for a more conversational interaction with a model using Gradio and ensure it works correctly, let's walk through the changes and implementations needed. This script provides a basic template to expose a text-generation function using token-by-token output and integrates it within a simple Gradio interface.
Here's how you can adjust the current setup:
Streamlined Output: Make sure each generated token is clearly visible as it is generated. This iterative approach involves creating an interface that continuously shows new tokens as they are appended to the current output.
Ensure Clean Interface Reset: Make sure to reset any necessary states or outputs, especially when re-generated outputs are created over multiple sessions.
Here's the implementation:
python
User
no like how would i change it to instead of talking to my old gpt2 model, talk to the model that you are helping me train
Assistant
To modify the script so that it interacts with the custom Transformer model you're training instead of a pre-trained GPT-2 or GPT Neo model, you'll need to replace the parts of the code that load and use the pre-trained transformer model with elements of your custom model. Here's a step-by-step approach:
Adapt the Tokenizer:
You should use the tokenizer that matches your model's vocabulary and encoding approach. If your model is trained using a different tokenization mechanism, you might need to adjust how inputs are prepared.
Model Integration:
Initialize and load your trained model instead of loading the pre-trained GPT Neo model. Ensure your model's weights are loaded if they have been saved after training.
Generate Tokens with Custom Model:
Adjust the generation logic to work with your model's architecture. Here's a simplified implementation based on your existing setup.
Here is how you can adapt the existing script to use your custom Transformer model:
python
User
what!? you lost your conversation memory!? im training the model with the following code
import os
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
def forward(self, src):
x = self.embedding(src) * (self.embedding.embedding_dim ** 0.5)
x = self.transformer(x)
x = self.fc_out(x)
return x
A generator to simulate data streaming
class TextDatasetIter:
def init(self, file_path):
self.file_path = file_path
with open(file_path, 'r', encoding='utf-8') as f:
self.text = f.read()
self.char2idx = {u: i for i, u in enumerate(set(self.text))}
self.data = [self.char2idx[c] for c in self.text]
code
def __len__(self):
return len(self.data) - SEQ_LENGTH
def __iter__(self):
for i in range(len(self.data) - SEQ_LENGTH):
yield (
torch.tensor(self.data[i:i + SEQ_LENGTH], dtype=torch.long),
torch.tensor(self.data[i + 1:i + SEQ_LENGTH + 1], dtype=torch.long)
)
Function to count parameters
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
Function to save checkpoint
def save_checkpoint(model, optimizer, epoch, idx):
if not os.path.exists(CHECKPOINT_DIR):
os.makedirs(CHECKPOINT_DIR)
code
Assistant
I understand now; you want to modify the script to interact with the Transformer model you've trained using the code you provided earlier. The goal is to utilize your custom-trained Transformer model for text generation in a Gradio app. Here's a step-by-step guide to replace the pre-trained model loading and generation to use your custom model instead:
Prepare the Custom Model:
Ensure the model weights are saved after training in a consistent format using torch.save.
Use the same architecture for loading during inference.
Integrate with the Gradio Interface:
Adapt the text generation procedure to your model's architecture and expected input/output formatting.
Convert text prompts to model inputs using the same tokenization logic used during training.
Here's how you can set up your script using the custom Transformer model for generating incremental text outputs in a Gradio app:
python
User
how do i import a model? i didnt make a module!
Assistant
To load your trained model weights into the architecture you defined in your script without creating a separate module, you can integrate the model definition directly into your script file for inference. Here’s an example of how you can accomplish this by reusing your TransformerModel class definition directly in your Gradio application script:
Define the Model Class Directly:
Use the same model class definition you used for training in the inference script.
Load Model Weights:
Load the saved weights into this model instance using torch.load.
Here's how you can set this up in the same script for generating text with Gradio:
import time
import torch, os
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import numpy as np
# Configuration parameters
NUM_LAYERS = 12
D_MODEL = 512
NUM_HEADS = 8
DFF = 2048 # Feed-forward network dimension
VOCAB_SIZE = 50257
SEQ_LENGTH = 128
CHECKPOINT_DIR = './checkpoints' # Directory to save checkpoints
MAX_CHECKPOINTS = 3
SAVE_INTERVAL = 1000
# Define a minimal transformer model
class TransformerModel(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, dff):
super(TransformerModel, self).__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.transformer_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=num_heads, dim_feedforward=dff)
self.transformer = nn.TransformerEncoder(self.transformer_layer, num_layers=num_layers)
self.fc_out = nn.Linear(d_model, vocab_size)
def forward(self, src):
x = self.embedding(src) * (self.embedding.embedding_dim ** 0.5)
x = self.transformer(x)
x = self.fc_out(x)
return x
# A generator to simulate data streaming
class TextDatasetIter:
def __init__(self, file_path):
self.file_path = file_path
with open(file_path, 'r', encoding='utf-8') as f:
self.text = f.read()
self.char2idx = {u: i for i, u in enumerate(set(self.text))}
self.data = [self.char2idx[c] for c in self.text]
def __len__(self):
return len(self.data) - SEQ_LENGTH
def __iter__(self):
for i in range(len(self.data) - SEQ_LENGTH):
yield (
torch.tensor(self.data[i:i + SEQ_LENGTH], dtype=torch.long),
torch.tensor(self.data[i + 1:i + SEQ_LENGTH + 1], dtype=torch.long)
)
def save_checkpoint(model, optimizer, epoch, idx):
if not os.path.exists(CHECKPOINT_DIR):
os.makedirs(CHECKPOINT_DIR)
checkpoint_path = os.path.join(CHECKPOINT_DIR, f'checkpoint_epoch_{epoch}_iter_{idx}.pt')
torch.save({
'epoch': epoch,
'iteration': idx,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, checkpoint_path)
# Remove old checkpoints
checkpoints = sorted(os.listdir(CHECKPOINT_DIR))
if len(checkpoints) > MAX_CHECKPOINTS:
os.remove(os.path.join(CHECKPOINT_DIR, checkpoints[0]))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(VOCAB_SIZE, D_MODEL, NUM_HEADS, NUM_LAYERS, DFF).to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
dataset_iterator = TextDatasetIter("training.txt")
batch_size = 16
# Training loop
def train_model(model, dataset_iterator, optimizer, criterion, num_epochs=10):
model.train()
for epoch in range(num_epochs):
batch_loss = 0
current_batch = []
start_time = time.time()
for idx, (input_seq, target_seq) in enumerate(dataset_iterator):
current_batch.append((input_seq, target_seq))
if len(current_batch) == batch_size: # Process batch
batch_inputs, batch_targets = zip(*current_batch)
batch_inputs = torch.stack(batch_inputs).to(device)
batch_targets = torch.stack(batch_targets).to(device)
optimizer.zero_grad()
output = model(batch_inputs.permute(1, 0))
loss = criterion(output.view(-1, VOCAB_SIZE), batch_targets.view(-1))
loss.backward()
optimizer.step()
batch_loss += loss.item()
current_batch = [] # Reset batch
if idx % SAVE_INTERVAL == 0 and idx != 0:
save_checkpoint(model, optimizer, epoch, idx)
# Print metrics
elapsed_time = time.time() - start_time
iterations_per_second = (idx + 1) / elapsed_time
print(f"[Epoch {epoch+1}, Step {idx}] Loss: {loss.item():.4f}, "
f"Iterations/Sec: {iterations_per_second:.2f}")
print(f"Epoch {epoch+1} Complete with Average Loss: {batch_loss / len(dataset_iterator):.4f}")
train_model(model, dataset_iterator, optimizer, criterion)
Key Enhancements:
Checkpoint Management: The script saves a new checkpoint every SAVE_INTERVAL iterations, deletes the oldest checkpoint if the total exceeds MAX_CHECKPOINTS.
Performance Metrics:
Iterations Per Second: Calculate how many iterations are processed per second during training to evaluate efficiency.
Saving Directories: Checkpoint directory creation ensures that all checkpoints are saved in a designated directory.
Console Feedback: Clear feedback on current training progress with average loss and iteration speed in the console output.
This setup will manage your model training process more effectively, saving only the last few checkpoints to balance between storage space and the ability to resume training.
import time
import torch, os
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import numpy as np
from tqdm import tqdm
# Configuration parameters
NUM_LAYERS = 12
D_MODEL = 512
NUM_HEADS = 8
DFF = 2048 # Feed-forward network dimension
VOCAB_SIZE = 50257
SEQ_LENGTH = 128
CHECKPOINT_DIR = './checkpoints' # Directory to save checkpoints
MAX_CHECKPOINTS = 3
SAVE_INTERVAL = 1000
# Define a minimal transformer model
class TransformerModel(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, dff):
super(TransformerModel, self).__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.transformer_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=num_heads, dim_feedforward=dff)
self.transformer = nn.TransformerEncoder(self.transformer_layer, num_layers=num_layers)
self.fc_out = nn.Linear(d_model, vocab_size)
def forward(self, src):
x = self.embedding(src) * (self.embedding.embedding_dim ** 0.5)
x = self.transformer(x)
x = self.fc_out(x)
return x
# A generator to simulate data streaming
class TextDatasetIter:
def __init__(self, file_path):
self.file_path = file_path
with open(file_path, 'r', encoding='utf-8') as f:
self.text = f.read()
self.char2idx = {u: i for i, u in enumerate(set(self.text))}
self.data = [self.char2idx[c] for c in self.text]
def __len__(self):
return len(self.data) - SEQ_LENGTH
def __iter__(self):
for i in range(len(self.data) - SEQ_LENGTH):
yield (
torch.tensor(self.data[i:i + SEQ_LENGTH], dtype=torch.long),
torch.tensor(self.data[i + 1:i + SEQ_LENGTH + 1], dtype=torch.long)
)
def save_checkpoint(model, optimizer, epoch, idx):
if not os.path.exists(CHECKPOINT_DIR):
os.makedirs(CHECKPOINT_DIR)
checkpoint_path = os.path.join(CHECKPOINT_DIR, f'checkpoint_epoch_{epoch}_iter_{idx}.pt')
torch.save({
'epoch': epoch,
'iteration': idx,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, checkpoint_path)
# Remove old checkpoints
checkpoints = sorted(os.listdir(CHECKPOINT_DIR))
if len(checkpoints) > MAX_CHECKPOINTS:
os.remove(os.path.join(CHECKPOINT_DIR, checkpoints[0]))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(VOCAB_SIZE, D_MODEL, NUM_HEADS, NUM_LAYERS, DFF).to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
dataset_iterator = TextDatasetIter("training.txt")
batch_size = 16
# Training loop with tqdm
def train_model(model, dataset_iterator, optimizer, criterion, num_epochs=10):
model.train()
iter_len = len(dataset_iterator)
for epoch in range(num_epochs):
batch_loss = 0
current_batch = []
# Initialize tqdm progress bar
start_time = time.time()
progress_bar = tqdm(total=iter_len, desc=f"Epoch {epoch + 1}", unit="it", ncols=100)
for idx, (input_seq, target_seq) in enumerate(dataset_iterator):
current_batch.append((input_seq, target_seq))
if len(current_batch) == batch_size: # Process batch
batch_inputs, batch_targets = zip(*current_batch)
batch_inputs = torch.stack(batch_inputs).to(device)
batch_targets = torch.stack(batch_targets).to(device)
optimizer.zero_grad()
output = model(batch_inputs.permute(1, 0))
loss = criterion(output.view(-1, VOCAB_SIZE), batch_targets.view(-1))
loss.backward()
optimizer.step()
batch_loss += loss.item()
current_batch = [] # Reset batch
# Update progress bar
progress_bar.set_postfix(
loss=f"{loss.item():.3f}",
used=time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)),
est=time.strftime("%H:%M:%S", time.gmtime((time.time() - start_time) / (idx + 1) * (iter_len - idx)))
)
progress_bar.update(batch_size)
if idx % SAVE_INTERVAL == 0 and idx != 0:
save_checkpoint(model, optimizer, epoch, idx)
progress_bar.close()
print(f"Epoch {epoch+1} Complete with Average Loss: {batch_loss / len(dataset_iterator):.4f}")
train_model(model, dataset_iterator, optimizer, criterion)
Key Features:
tqdm Progress Bar: A progress bar for tracking training, including batch iterations, using tqdm's capabilities.
Progress Content: Displays iteration rate (it/s), current batch loss, elapsed time (used), and estimated time to completion (est).
Dynamic Updates: Updates the progress bar after processing each batch, adjusting ETA and displaying recent loss.
This should provide a visually richer and more informative snapshot of the training process!
import torch
# ... (Assuming the rest of the earlier code definitions remain)
# Function to count parameters
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
# Updated checkpoint saving function
def save_checkpoint(model, optimizer, epoch, idx):
if not os.path.exists(CHECKPOINT_DIR):
os.makedirs(CHECKPOINT_DIR)
checkpoint_path = os.path.join(CHECKPOINT_DIR, f'checkpoint_epoch_{epoch}_iter_{idx}.pt')
torch.save({
'epoch': epoch,
'iteration': idx,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, checkpoint_path)
# Remove old checkpoints
checkpoints = sorted(os.listdir(CHECKPOINT_DIR))
if len(checkpoints) > MAX_CHECKPOINTS:
os.remove(os.path.join(CHECKPOINT_DIR, checkpoints[0]))
# At the start of training, print the parameter count
print(f"Total trainable parameters in the model: {count_parameters(model)}")
# Training loop
def train_model(model, dataset_iterator, optimizer, criterion, num_epochs=10):
model.train()
iter_len = len(dataset_iterator)
for epoch in range(num_epochs):
batch_loss = 0
current_batch = []
# Initialize tqdm progress bar
start_time = time.time()
progress_bar = tqdm(total=iter_len, desc=f"Epoch {epoch + 1}", unit="it", ncols=100)
for idx, (input_seq, target_seq) in enumerate(dataset_iterator):
current_batch.append((input_seq, target_seq))
if len(current_batch) == batch_size: # Process batch
batch_inputs, batch_targets = zip(*current_batch)
batch_inputs = torch.stack(batch_inputs).to(device)
batch_targets = torch.stack(batch_targets).to(device)
optimizer.zero_grad()
output = model(batch_inputs.permute(1, 0))
loss = criterion(output.view(-1, VOCAB_SIZE), batch_targets.view(-1))
loss.backward()
optimizer.step()
batch_loss += loss.item()
current_batch = [] # Reset batch
# Update progress bar
progress_bar.set_postfix(
loss=f"{loss.item():.3f}",
used=time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)),
est=time.strftime("%H:%M:%S", time.gmtime((time.time() - start_time) / (idx + 1) * (iter_len - idx)))
)
progress_bar.update(batch_size)
if idx % SAVE_INTERVAL == 0 and idx != 0:
save_checkpoint(model, optimizer, epoch, idx)
progress_bar.close()
print(f"Epoch {epoch+1} Complete with Average Loss: {batch_loss / len(dataset_iterator):.4f}")
train_model(model, dataset_iterator, optimizer, criterion)
Checklist:
Ensure CHECKPOINT_DIR: Verify the directory path CHECKPOINT_DIR is correct and reachable.
Parameter Counting Function: Add a count_parameters function to calculate and print the total number of trainable parameters.
Checkpoint Name and Deletion Logic: Ensure torch.save is called with the correct path, and the logic for removing old checkpoints (os.remove) is functional.
This setup should now start printing the total trainable parameters at the beginning and manage checkpoints correctly. If checkpoints still aren't being saved, double-check any file system restrictions or errors that might be occurring (look for any printed stack trace or errors).
import os
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
# Configuration parameters
NUM_LAYERS = 12
D_MODEL = 512
NUM_HEADS = 8
DFF = 2048 # Feed-forward network dimension
VOCAB_SIZE = 50257
SEQ_LENGTH = 128
CHECKPOINT_DIR = './checkpoints' # Directory to save checkpoints
MAX_CHECKPOINTS = 3
SAVE_INTERVAL = 1000
BATCH_SIZE = 16
# Define a minimal transformer model
class TransformerModel(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, dff):
super(TransformerModel, self).__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.transformer_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=num_heads, dim_feedforward=dff)
self.transformer = nn.TransformerEncoder(self.transformer_layer, num_layers=num_layers)
self.fc_out = nn.Linear(d_model, vocab_size)
def forward(self, src):
x = self.embedding(src) * (self.embedding.embedding_dim ** 0.5)
x = self.transformer(x)
x = self.fc_out(x)
return x
# A generator to simulate data streaming
class TextDatasetIter:
def __init__(self, file_path):
self.file_path = file_path
with open(file_path, 'r', encoding='utf-8') as f:
self.text = f.read()
self.char2idx = {u: i for i, u in enumerate(set(self.text))}
self.data = [self.char2idx[c] for c in self.text]
def __len__(self):
return len(self.data) - SEQ_LENGTH
def __iter__(self):
for i in range(len(self.data) - SEQ_LENGTH):
yield (
torch.tensor(self.data[i:i + SEQ_LENGTH], dtype=torch.long),
torch.tensor(self.data[i + 1:i + SEQ_LENGTH + 1], dtype=torch.long)
)
# Function to count parameters
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
# Function to save checkpoint
def save_checkpoint(model, optimizer, epoch, idx):
if not os.path.exists(CHECKPOINT_DIR):
os.makedirs(CHECKPOINT_DIR)
checkpoint_path = os.path.join(CHECKPOINT_DIR, f'checkpoint_epoch_{epoch}_iter_{idx}.pt')
torch.save({
'epoch': epoch,
'iteration': idx,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, checkpoint_path)
# Remove old checkpoints if exceeding max checkpoints
checkpoints = sorted(os.listdir(CHECKPOINT_DIR))
if len(checkpoints) > MAX_CHECKPOINTS:
os.remove(os.path.join(CHECKPOINT_DIR, checkpoints[0]))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(VOCAB_SIZE, D_MODEL, NUM_HEADS, NUM_LAYERS, DFF).to(device)
optimizer = optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
dataset_iterator = TextDatasetIter("training.txt")
# Print model parameter count
print(f"Total trainable parameters in the model: {count_parameters(model)}")
# Training loop with tqdm
def train_model(model, dataset_iterator, optimizer, criterion, num_epochs=10):
model.train()
iter_len = len(dataset_iterator)
for epoch in range(num_epochs):
batch_loss = 0
current_batch = []
# Initialize tqdm progress bar
start_time = time.time()
progress_bar = tqdm(total=iter_len, desc=f"Epoch {epoch + 1}", unit="it", ncols=100)
for idx, (input_seq, target_seq) in enumerate(dataset_iterator):
current_batch.append((input_seq, target_seq))
if len(current_batch) == BATCH_SIZE: # Process batch
batch_inputs, batch_targets = zip(*current_batch)
batch_inputs = torch.stack(batch_inputs).to(device)
batch_targets = torch.stack(batch_targets).to(device)
optimizer.zero_grad()
output = model(batch_inputs.permute(1, 0))
loss = criterion(output.view(-1, VOCAB_SIZE), batch_targets.view(-1))
loss.backward()
optimizer.step()
batch_loss += loss.item()
current_batch = [] # Reset batch
# Update progress bar
progress_bar.set_postfix(
loss=f"{loss.item():.3f}",
used=time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)),
est=time.strftime("%H:%M:%S", time.gmtime((time.time() - start_time) / (idx + 1) * (iter_len - idx)))
)
progress_bar.update(BATCH_SIZE)
if idx % SAVE_INTERVAL == 0 and idx != 0:
save_checkpoint(model, optimizer, epoch, idx)
progress_bar.close()
print(f"Epoch {epoch+1} Complete with Average Loss: {batch_loss / len(dataset_iterator):.4f}")
train_model(model, dataset_iterator, optimizer, criterion)
Key Features:
Save Checkpoints: The script saves model checkpoints at regular iterations and manages checkpoint files, keeping only the latest ones.
Parameter Count: It prints the total number of trainable parameters at the beginning of training.
Progress Tracking: Uses tqdm to provide detailed insights into the progress, including half the details you wanted (loss, time used, ETA, etc.) while keeping it concise.
Ensure the path to your data (training.txt) is correct, the directory for checkpoints is writable, and that tqdm is installed in your Python environment.
checkpoint_path = os.path.join(CHECKPOINT_DIR, f'checkpoint_epoch_{epoch}_iter_{idx}.pt')
torch.save({
'epoch': epoch,
'iteration': idx,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, checkpoint_path)
# Remove old checkpoints if exceeding max checkpoints
checkpoints = sorted(os.listdir(CHECKPOINT_DIR))
if len(checkpoints) > MAX_CHECKPOINTS:
os.remove(os.path.join(CHECKPOINT_DIR, checkpoints[0]))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(VOCAB_SIZE, D_MODEL, NUM_HEADS, NUM_LAYERS, DFF).to(device)
from typing import Generator
from transformers import GPTNeoForCausalLM, GPT2TokenizerFast
import torch
import gradio as gr
import random
# Load the GPT-2 tokenizer (works for GPT Neo as well)
tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
# Load the GPT Neo model from the local or remote checkpoint.
model_path = "elapt1c/ElapticAI-1a" # Replace with your desired GPT Neo model path
model = GPTNeoForCausalLM.from_pretrained(model_path, ignore_mismatched_sizes=True)
# Move model to appropriate device (GPU if available, otherwise CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval() # Set model to evaluation mode
def generate_token_by_token(
message: str,
seed: int = None,
temperature: float = 1.0,
top_k: int = 50
) -> Generator[str, None, None]:
input_ids = tokenizer.encode(message, return_tensors='pt').to(device)
if input_ids.size(-1) == 0:
raise ValueError("Input was empty after tokenization. Please try again.")
if seed is None or not isinstance(seed, int) or not (11111 <= seed <= 99999):
seed = random.randint(11111, 99999)
else:
seed = int(seed)
torch.manual_seed(seed)
generated_text = ""
with torch.no_grad():
for _ in range(25): # Adjust token limit as necessary
outputs = model(input_ids)
next_token_logits = outputs.logits[:, -1, :]
next_token_logits = next_token_logits / temperature
top_k_values, top_k_indices = torch.topk(next_token_logits, top_k)
probabilities = torch.softmax(top_k_values, dim=-1)
next_token_id = top_k_indices[0, torch.multinomial(probabilities, num_samples=1)]
decoded_token = tokenizer.decode(next_token_id.item(), skip_special_tokens=True)
generated_text += decoded_token
# Yield incrementally appended output for streaming effect
yield generated_text
input_ids = torch.cat([input_ids, next_token_id.unsqueeze(-1).squeeze(0)], dim=-1)
if next_token_id.item() == tokenizer.eos_token_id:
break
# Gradio chat interface for token-by-token generation
runningApp = gr.Interface(
fn=generate_token_by_token,
inputs=[
gr.Textbox(placeholder="Enter your prompt here...", lines=2, label="Prompt"),
gr.Slider(11111, 99999, step=1, value=None, label="Seed"),
gr.Slider(0.1, 2.0, step=0.1, default=1.0, label="Temperature"),
gr.Slider(1, 100, step=1, default=50, label="Top-k")
],
outputs=gr.Textbox(lines=8, label="Generated Text", show_progress=True),
live=True
)
if __name__ == "__main__":
runningApp.launch()
Key Adjustments:
Live Interface and Progress: Use live=True in gr.Interface to ensure real-time output during text generation.
Control Slider for Parameters: Added sliders for seed, temperature, and top_k to easily adjust model generation parameters.
Robust Error Handling: Added checks for empty input post-tokenization, and management of potential seed invalid values.
Dynamic Model Output: Show generated tokens progressively, enhancing interaction by displaying text as it's generated.
This setup allows you to run the model with a Gradio interface that provides real-time streamed token-by-token text generation. Adjust parameters as needed to improve the output quality or interaction style according to your application needs.
from typing import Generator
import torch
from torch.utils.data import Dataset, DataLoader
import gradio as gr
import random
from my_custom_transformer import TransformerModel # Import your custom model
# Ensure you have the same configurations as your training setup
VOCAB_SIZE = 50257 # Update if different
SEQ_LENGTH = 128
# Load your trained Transformer model
model_path = './saved_model.pt' # Path to your saved model checkpoint
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize the model
model = TransformerModel(vocab_size=VOCAB_SIZE, d_model=512, num_heads=8, num_layers=12, dff=2048).to(device)
model.load_state_dict(torch.load(model_path, map_location=device))
model.eval()
# Tokenizer function: Adjust it as per your training tokenizer
def encode_text(text, vocab):
return [vocab.get(c, vocab['<unk>']) for c in text]
def decode_tokens(tokens, vocab, rev_vocab):
return ''.join([rev_vocab.get(t, '') for t in tokens])
# Character-level tokenization for demonstration
char_vocab = {char: idx for idx, char in enumerate(list("abcdefghijklmnopqrstuvwxyz "))} # Adjust as needed
rev_char_vocab = {idx: char for char, idx in char_vocab.items()}
def generate_token_by_token(
message: str,
seed: int = None,
temperature: float = 1.0,
top_k: int = 50
) -> Generator[str, None, None]:
input_ids = torch.tensor(encode_text(message, char_vocab), dtype=torch.long).unsqueeze(0).to(device)
if input_ids.size(-1) == 0:
raise ValueError("Input was empty after tokenization. Please try again.")
if seed is None or not isinstance(seed, int) or not (11111 <= seed <= 99999):
seed = random.randint(11111, 99999)
else:
seed = int(seed)
torch.manual_seed(seed)
generated_text = message
with torch.no_grad():
for _ in range(25): # Adjust token limit as necessary
outputs = model(input_ids.permute(1, 0))
next_token_logits = outputs[-1, :]
next_token_logits = next_token_logits / temperature
top_k_values, top_k_indices = torch.topk(next_token_logits, top_k)
probabilities = torch.softmax(top_k_values, dim=0)
next_token_id = top_k_indices[torch.multinomial(probabilities, num_samples=1)].item()
decoded_token = decode_tokens([next_token_id], char_vocab, rev_char_vocab)
generated_text += decoded_token
yield generated_text
input_ids = torch.cat([input_ids, torch.tensor([[next_token_id]], device=device)], dim=-1)
if next_token_id == char_vocab.get('<eos>', -1): # Assuming you have an end-of-sequence token
break
# Gradio chat interface for token-by-token generation
runningApp = gr.Interface(
fn=generate_token_by_token,
inputs=[
gr.Textbox(placeholder="Enter your prompt here...", lines=2, label="Prompt"),
gr.Slider(11111, 99999, step=1, value=None, label="Seed"),
gr.Slider(0.1, 2.0, step=0.1, default=1.0, label="Temperature"),
gr.Slider(1, 100, step=1, default=50, label="Top-k")
],
outputs=gr.Textbox(lines=8, label="Generated Text", show_progress=True),
live=True
)
if __name__ == "__main__":
runningApp.launch()
Important Considerations:
Tokenizer and Vocabulary: Make sure to align with how your model was trained. The demonstration uses a simple character-level tokenizer; adjust for more complex tokenization if applicable.
Loading Model Weights: Ensure the paths and checkpoint loading match how your model was saved.
Temperature and Sampling: These settings affect randomness and creativity, adjust based on your application's requirements.
This code provides a basic framework to connect your custom-trained model with a Gradio interface, enabling interactive text generation. Adjust tokenization, model weights, and configuration options (like top_k and temperature) as necessary based on your training setup and model specifications.
checkpoint_path = os.path.join(CHECKPOINT_DIR, f'checkpoint_epoch_{epoch}_iter_{idx}.pt')
torch.save({
'epoch': epoch,
'iteration': idx,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}, checkpoint_path)
# Remove old checkpoints if exceeding max checkpoints
checkpoints = sorted(os.listdir(CHECKPOINT_DIR))
if len(checkpoints) > MAX_CHECKPOINTS:
os.remove(os.path.join(CHECKPOINT_DIR, checkpoints[0]))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(VOCAB_SIZE, D_MODEL, NUM_HEADS, NUM_LAYERS, DFF).to(device)
from typing import Generator
import torch
import gradio as gr
import random
import os
from transformers import GPT2TokenizerFast # Use a basic tokenizer for simplicity
# Load GPT-2 tokenizer for text input management
tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
# Import your custom Transformer model
from my_custom_transformer import TransformerModel # Import your custom model architecture.
# Load your custom-trained Transformer model from saved checkpoint
checkpoint_path = './checkpoints/checkpoint_epoch_final_iter.pt' # Path to your saved model file
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Initialize your model appropriately
VOCAB_SIZE = 65536 # Ensure this matches your trained model's vocabulary size.
model = TransformerModel(VOCAB_SIZE, D_MODEL=588, NUM_HEADS=12, NUM_LAYERS=12, DFF=2048).to(device)
# Load the model state
model.load_state_dict(torch.load(checkpoint_path, map_location=device))
model.eval() # Set the model to evaluation mode.
def generate_token_by_token(
message: str,
seed: int = None,
temperature: float = 1.0,
top_k: int = 50
) -> Generator[str, None, None]:
input_ids = tokenizer.encode(message, return_tensors='pt').to(device)
if input_ids.size(-1) == 0:
raise ValueError("Input was empty after tokenization. Please try again.")
if seed is None or not isinstance(seed, int) or not (11111 <= seed <= 99999):
seed = random.randint(11111, 99999)
else:
seed = int(seed)
torch.manual_seed(seed)
generated_text = message
with torch.no_grad():
for _ in range(25): # Adjust token limit as necessary
outputs = model(input_ids.permute(1, 0))
next_token_logits = outputs[-1, :]
next_token_logits = next_token_logits / temperature
top_k_values, top_k_indices = torch.topk(next_token_logits, top_k)
probabilities = torch.softmax(top_k_values, dim=0)
next_token_id = top_k_indices[torch.multinomial(probabilities, num_samples=1)].item()
decoded_token = tokenizer.decode(next_token_id, skip_special_tokens=True)
generated_text += decoded_token
yield generated_text
input_ids = torch.cat([input_ids, torch.tensor([[next_token_id]], device=device)], dim=-1)
if next_token_id == tokenizer.eos_token_id:
break
# Gradio chat interface for token-by-token generation
runningApp = gr.Interface(
fn=generate_token_by_token,
inputs=[
gr.Textbox(placeholder="Enter your prompt here...", lines=2, label="Prompt"),
gr.Slider(11111, 99999, step=1, value=None, label="Seed"),
gr.Slider(0.1, 2.0, step=0.1, default=1.0, label="Temperature"),
gr.Slider(1, 100, step=1, default=50, label="Top-k")
],
outputs=gr.Textbox(lines=8, label="Generated Text", show_progress=True),
live=True
)
if __name__ == "__main__":
runningApp.launch()
Key Adjustments:
Custom Model Loading: Load your trained model using torch.load with the model architecture specified and set the model to evaluation mode.
Tokenization and Vocabulary Management: Ensure the tokenizer handles inputs consistently with your model's expected format.
Dynamic Generation: Adjust your model's text generation logic using temperature and top-k filtering as appropriate for a balanced output quality.
Replace "my_custom_transformer" and other configuration settings with what fits your setup. Adjust other generation parameters as needed for your application's need to ensure the best performance and interaction experience.
from typing import Generator
import torch
import torch.nn as nn
import gradio as gr
from transformers import GPT2TokenizerFast
import random
import os
# Define your model architecture (same as in training script)
class TransformerModel(nn.Module):
def __init__(self, vocab_size, d_model, num_heads, num_layers, dff):
super(TransformerModel, self).__init__()
self.embedding = nn.Embedding(vocab_size, d_model)
self.transformer_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=num_heads, dim_feedforward=dff)
self.transformer = nn.TransformerEncoder(self.transformer_layer, num_layers=num_layers)
self.fc_out = nn.Linear(d_model, vocab_size)
def forward(self, src):
x = self.embedding(src) * (self.embedding.embedding_dim ** 0.5)
x = self.transformer(x)
x = self.fc_out(x)
return x
# Setup configurations
VOCAB_SIZE = 65536
D_MODEL = 588
NUM_HEADS = 12
NUM_LAYERS = 12
DFF = 2048
# Load the tokenizer
tokenizer = GPT2TokenizerFast.from_pretrained("gpt2")
# Initialize and load your trained model checkpoint
checkpoint_path = './checkpoints/checkpoint_epoch_final.pt' # Path to your saved model file
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = TransformerModel(VOCAB_SIZE, D_MODEL, NUM_HEADS, NUM_LAYERS, DFF).to(device)
model.load_state_dict(torch.load(checkpoint_path, map_location=device))
model.eval() # Set to evaluation mode
def generate_token_by_token(
message: str,
seed: int = None,
temperature: float = 1.0,
top_k: int = 50
) -> Generator[str, None, None]:
input_ids = tokenizer.encode(message, return_tensors='pt').to(device)
if input_ids.size(-1) == 0:
raise ValueError("Input was empty after tokenization. Please try again.")
if seed is None or not isinstance(seed, int) or not (11111 <= seed <= 99999):
seed = random.randint(11111, 99999)
else:
seed = int(seed)
torch.manual_seed(seed)
generated_text = message
with torch.no_grad():
for _ in range(25): # Adjust token limit as necessary
outputs = model(input_ids.permute(1, 0))
next_token_logits = outputs[-1, :]
next_token_logits = next_token_logits / temperature
top_k_values, top_k_indices = torch.topk(next_token_logits, top_k)
probabilities = torch.softmax(top_k_values, dim=0)
next_token_id = top_k_indices[torch.multinomial(probabilities, num_samples=1)].item()
decoded_token = tokenizer.decode(next_token_id, skip_special_tokens=True)
generated_text += decoded_token
yield generated_text
input_ids = torch.cat([input_ids, torch.tensor([[next_token_id]], device=device)], dim=-1)
if next_token_id == tokenizer.eos_token_id:
break
# Gradio interface to generate text
runningApp = gr.Interface(
fn=generate_token_by_token,
inputs=[
gr.Textbox(placeholder="Enter your prompt here...", lines=2, label="Prompt"),
gr.Slider(11111, 99999, step=1, value=None, label="Seed"),
gr.Slider(0.1, 2.0, step=0.1, default=1.0, label="Temperature"),
gr.Slider(1, 100, step=1, default=50, label="Top-k")
],
outputs=gr.Textbox(lines=8, label="Generated Text", show_progress=True),
live=True
)
if __name__ == "__main__":
runningApp.launch()
Key Steps:
Model Definition: Include your TransformerModel class definition directly in the script.
Loading Weights: Use model.load_state_dict() to load your trained model weights from the checkpoint.
Device Management: Ensure the model and inputs are correctly moved to the correct device (CPU/GPU).
This script integrates your custom-trained model into a Gradio interface for text generation without needing a separate module or package. Adjust paths and any specific configurations as needed for your setup.