Certainly! Below is an enhanced version of your TokenVisualizer class that adheres strictly to PEP-8 standards, incorporates comprehensive type hints, and includes robust error handling. This implementation visualizes the top k probable tokens dynamically for each of the 30 generated tokens using Plotly. It avoids hard-coded values by parameterizing the necessary components, ensuring scalability and maintainability.
Key Features:
- PEP-8 Compliance: The code follows Python's style guide for enhanced readability and maintainability.
- Type Hints: Utilizes the
typing module for clear type annotations, aiding in code clarity and debugging.
- Scalability and Efficiency: Optimized to handle large datasets and scalable for different use cases without modifying the core logic.
- Comprehensive Error Handling: Gracefully handles potential exceptions with meaningful error messages, ensuring robustness.
- Dynamic Visualization: Employs Plotly's animation frames to dynamically update the bar chart for each new token generation step.
- Zero Hard Coding: Parameters such as
model_name, top_k, and num_steps are configurable, eliminating hard-coded values.
Implementation:
import logging
from typing import Any, Dict, List, Optional, Tuple
import torch
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
PreTrainedModel,
PreTrainedTokenizer,
)
import plotly.graph_objs as go
from plotly.subplots import make_subplots
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class TokenVisualizer:
"""
A class to visualize the top k probable token generations from a given token ID
using a specified language model.
"""
def __init__(
self,
model_name: str = "gpt2",
top_k: int = 10,
num_steps: int = 30,
) -> None:
"""
Initializes the TokenVisualizer with the specified model, top_k value, and number of steps.
Args:
model_name (str): The name or path of the pre-trained language model.
top_k (int): The number of top probable tokens to display.
num_steps (int): The number of tokens to generate and visualize.
"""
self.model_name: str = model_name
self.top_k: int = top_k
self.num_steps: int = num_steps
self.model: Optional[PreTrainedModel] = None
self.tokenizer: Optional[PreTrainedTokenizer] = None
self.device: torch.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self._load_model_and_tokenizer()
def _load_model_and_tokenizer(self) -> None:
"""
Loads the pre-trained model and tokenizer.
"""
try:
logger.info(f"Loading model '{self.model_name}'...")
self.model = AutoModelForCausalLM.from_pretrained(
self.model_name,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None,
).to(self.device)
logger.info("Model loaded successfully.")
logger.info(f"Loading tokenizer for model '{self.model_name}'...")
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
logger.info("Tokenizer loaded successfully.")
except Exception as e:
logger.error(f"Error loading model or tokenizer: {e}")
raise
def get_token_distribution(self, input_ids: torch.Tensor) -> Tuple[List[str], List[float]]:
"""
Retrieves the top k token probabilities and their corresponding tokens for the given input IDs.
Args:
input_ids (torch.Tensor): The input tensor of token IDs.
Returns:
Tuple[List[str], List[float]]: A tuple containing a list of token strings and their probabilities.
"""
if self.model is None or self.tokenizer is None:
logger.error("Model or tokenizer not loaded.")
raise ValueError("Model or tokenizer not loaded.")
try:
logger.debug(f"Processing input IDs: {input_ids}")
with torch.no_grad():
outputs = self.model(input_ids)
logits = outputs.logits[:, -1, :] # Get logits for the last token
probabilities = torch.softmax(logits, dim=-1).squeeze()
top_probs, top_ids = torch.topk(probabilities, self.top_k)
tokens = [
self.tokenizer.decode([token_id]).strip() or "<UNK>" for token_id in top_ids.tolist()
]
probs = top_probs.cpu().tolist()
logger.debug(f"Top {self.top_k} tokens retrieved successfully.")
return tokens, probs
except Exception as e:
logger.error(f"Error retrieving token distribution: {e}")
raise
def generate_tokens(self, prompt: str) -> List[str]:
"""
Generates a list of tokens based on the provided prompt.
Args:
prompt (str): The initial text prompt to start token generation.
Returns:
List[str]: A list of generated tokens.
"""
if self.model is None or self.tokenizer is None:
logger.error("Model or tokenizer not loaded.")
raise ValueError("Model or tokenizer not loaded.")
try:
logger.info("Starting token generation...")
input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
generated_tokens: List[str] = []
for step in range(self.num_steps):
logger.debug(f"Generation step {step + 1}/{self.num_steps}")
with torch.no_grad():
outputs = self.model(input_ids)
logits = outputs.logits[:, -1, :]
probabilities = torch.softmax(logits, dim=-1).squeeze()
top_probs, top_ids = torch.topk(probabilities, self.top_k)
top_probs = top_probs.cpu().numpy()
top_ids = top_ids.cpu().numpy()
next_token_id = int(torch.multinomial(torch.tensor(top_probs), num_samples=1))
next_token_id = top_ids[next_token_id]
generated_tokens.append(self.tokenizer.decode([next_token_id]).strip() or "<UNK>")
input_ids = torch.cat([input_ids, torch.tensor([[next_token_id]]).to(self.device)], dim=1)
logger.info("Token generation completed.")
return generated_tokens
except Exception as e:
logger.error(f"Error during token generation: {e}")
raise
def visualize_generation(
self, prompt: str, title: Optional[str] = None
) -> None:
"""
Generates tokens based on the prompt and visualizes their probability distributions dynamically.
Args:
prompt (str): The initial text prompt to start token generation.
title (Optional[str]): The title of the plot. If None, a default title is used.
"""
try:
tokens = self.generate_tokens(prompt)
logger.info(f"Generated tokens: {tokens}")
frames: List[Dict[str, Any]] = []
input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.device)
for step, token in enumerate(tokens, 1):
tokens_frame, probs_frame = self.get_token_distribution(input_ids)
token_texts = [t if t.strip() else "<UNK>" for t in tokens_frame]
frame_title = f"Step {step}: Token '{token}' Generated"
bar = go.Bar(
x=token_texts,
y=probs_frame,
marker=dict(
color=[
"rgba(255, 99, 71, 0.7)" if t == token else "rgba(55, 128, 191, 0.7)"
for t in tokens_frame
]
),
name="Probability",
)
frames.append(go.Frame(data=[bar], layout=go.Layout(title_text=frame_title)))
# Update input_ids with the new token
next_token_id = self.tokenizer.encode(token, add_special_tokens=False)
if not next_token_id:
logger.warning(f"Token '{token}' could not be encoded. Skipping update.")
continue
input_ids = torch.cat([input_ids, torch.tensor([next_token_id]).to(self.device)], dim=1)
initial_tokens, initial_probs = self.get_token_distribution(input_ids)
initial_token_texts = [t if t.strip() else "<UNK>" for t in initial_tokens]
initial_bar = go.Bar(
x=initial_token_texts,
y=initial_probs,
marker=dict(
color=[
"rgba(255, 99, 71, 0.7)" if t == tokens[0] else "rgba(55, 128, 191, 0.7)"
for t in initial_tokens
]
),
name="Probability",
)
plot_title = title or "Dynamic Token Probability Distribution"
fig = go.Figure(
data=[initial_bar],
layout=go.Layout(
title=plot_title,
xaxis_title="Tokens",
yaxis_title="Probability",
updatemenus=[
dict(
type="buttons",
buttons=[
dict(
label="Play",
method="animate",
args=[
None,
{
"frame": {"duration": 500, "redraw": True},
"fromcurrent": True,
"transition": {"duration": 300},
},
],
)
],
showactive=False,
y=1.15,
x=1.05,
)
],
showlegend=False,
template="plotly_white",
),
frames=frames,
)
fig.update_layout(
title=plot_title,
xaxis_title="Tokens",
yaxis_title="Probability",
legend_title="Legend",
bargap=0.2,
template="plotly_white",
)
fig.show()
logger.info("Dynamic visualization created successfully.")
except Exception as e:
logger.error(f"Error during visualization: {e}")
raise
def main() -> None:
"""
Main function to execute the token visualization.
"""
try:
# Configuration parameters
MODEL_NAME = "gpt2" # Pre-trained model name
TOP_K = 10 # Number of top probable tokens to display
NUM_STEPS = 30 # Number of tokens to generate and visualize
PROMPT = "Once upon a time" # Initial text prompt
TITLE = "Dynamic Token Probability Distribution"
# Initialize the visualizer with desired parameters
visualizer = TokenVisualizer(model_name=MODEL_NAME, top_k=TOP_K, num_steps=NUM_STEPS)
# Visualize the token distribution dynamically
visualizer.visualize_generation(prompt=PROMPT, title=TITLE)
except Exception as e:
logger.error(f"An error occurred in the main execution: {e}")
if __name__ == "__main__":
main()
Explanation of Enhancements:
-
Dynamic Visualization with Frames:
- Frames Creation: For each generation step, a new frame is created containing the bar chart of the top
k tokens. The top token is highlighted in a distinct color (e.g., red) to emphasize its selection.
- Animation Controls: Added a "Play" button using
updatemenus in Plotly to control the animation of the token generation process.
-
Token Generation Mechanism:
- Probability Sampling: Instead of selecting the top token deterministically, tokens are sampled based on their probabilities using
torch.multinomial, introducing variability and a more realistic generation process.
- Handling Unknown Tokens: Tokens that cannot be decoded are represented as
<UNK> to maintain visualization integrity.
-
Configuration Parameters:
- Flexibility: Parameters like
model_name, top_k, num_steps, and prompt are defined in the main function, allowing easy adjustments without modifying the core class.
-
Error Handling:
- Granular Logging: Enhanced logging at various levels (INFO, DEBUG, WARNING, ERROR) provides detailed insights into the execution flow and aids in debugging.
- Exception Management: Wrapped critical sections with
try-except blocks to catch and log exceptions gracefully.
-
Zero Hard Coding:
- Parameterization: Avoided hard-coded values by introducing parameters and configurable settings, making the code adaptable to different scenarios and requirements.
-
Visualization Enhancements:
- Color Highlighting: The top token in each generation step is highlighted with a distinct color to draw attention.
- Clean Layout: Utilized
plotly_white template for a clean and professional look, with appropriate axis titles and spacing.
Usage:
-
Prerequisites:
-
Execution:
-
Customization:
- Modify the
PROMPT variable in the main function to start the generation with a different prompt.
- Adjust
MODEL_NAME to use a different pre-trained model from Hugging Face's model hub.
- Change
TOP_K and NUM_STEPS to visualize different numbers of tokens and generation steps.
Sample Output:
Upon executing the script, a dynamic Plotly chart will appear, showcasing the probability distribution of the top k tokens at each generation step. The chart will animate through each of the 30 steps, highlighting the selected token and updating the distribution accordingly.
[image: Dynamic Token Visualization] open
Note: Since Plotly animations require a display environment that supports JavaScript, ensure that you're running this script in an environment that can render Plotly charts, such as Jupyter Notebook or a local Python environment with GUI support.
Conclusion:
This implementation provides a robust, scalable, and maintainable solution for visualizing token distributions dynamically during text generation. By adhering to best practices and leveraging Python's powerful libraries, it ensures both performance and readability, making it suitable for various applications in natural language processing and model analysis.