Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK : robustness , scable , generalised , code , zero hard coding
Visualize all possible token generations from a single token_id input into the model using Plotly. The graph should dynamically plot the top k probable tokens based on the model's output, showing the token distribution and probabilities as a bar chart, with labels for each token. Include title, axis labels, and a legend for clarity.
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "gpt2"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
prompt = "Give me a short introduction to large language model."
messages = [
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
{"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
generated_ids = model.generate(
**model_inputs,
max_new_tokens=512
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
Certainly! Below is a Python script that visualizes the top k probable token generations from a single token_id input into a language model using Plotly. The script adheres to PEP-8 standards, includes type hints, is optimized for scalability and robustness, and avoids hard-coded values by utilizing configurable parameters.
Overview
Functionality:
Load a pre-trained language model and tokenizer.
Take a single token_id as input.
Generate the probability distribution for all possible next tokens.
Select the top k probable tokens.
Visualize these probabilities using a dynamic Plotly bar chart.
Key Features:
PEP-8 Compliant: Ensures readability and maintainability.
Type Hints: Enhances code clarity and aids in debugging.
Configurability: Parameters like model_name, top_k, and token_id can be easily modified.
Error Handling: Comprehensive try-except blocks to gracefully handle unexpected scenarios.
Scalability: Efficient handling of large vocabularies and adaptable to different models.
Prerequisites
Before running the script, ensure you have the necessary libraries installed:
bash
pip install transformers torch plotly
Script
python
import logging
from typing import Any, Dict, List, Tuple
import torch
from plotly import graph_objs as go
from transformers import AutoModelForCausalLM, AutoTokenizer
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def load_model_and_tokenizer(model_name: str) -> Tuple[Any, AutoTokenizer]:
"""
Load the pre-trained language model and tokenizer.
Args:
model_name (str): Name of the pre-trained model.
Returns:
Tuple containing the model and tokenizer instances.
Raises:
ValueError: If the model or tokenizer cannot be loaded.
"""
try:
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float32,
device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
logger.info(f"Successfully loaded model '{model_name}' and tokenizer.")
return model, tokenizer
except Exception as e:
logger.error(f"Error loading model or tokenizer: {e}")
raise ValueError(f"Failed to load model or tokenizer: {e}")
def get_token_distribution(model: Any, tokenizer: AutoTokenizer, token_id: int) -> Dict[int, float]:
"""
Get the probability distribution of next tokens given a single token_id.
Args:
model (Any): The pre-trained language model.
tokenizer (AutoTokenizer): The tokenizer associated with the model.
token_id (int): The input token ID.
Returns:
Dictionary mapping token IDs to their probabilities.
Raises:
ValueError: If the token_id is invalid or distribution cannot be computed.
"""
try:
input_ids = torch.tensor([[token_id]]).to(model.device)
with torch.no_grad():
outputs = model(input_ids)
logits = outputs.logits[:, -1, :] # Get logits for the last token
probabilities = torch.softmax(logits, dim=-1).squeeze().cpu().numpy()
token_probs = {idx: float(prob) for idx, prob in enumerate(probabilities)}
logger.info(f"Computed token distribution for token_id {token_id}.")
return token_probs
except Exception as e:
logger.error(f"Error computing token distribution: {e}")
raise ValueError(f"Failed to compute token distribution: {e}")
def get_top_k_tokens(token_probs: Dict[int, float], tokenizer: AutoTokenizer, top_k: int) -> List[Tuple[str, float]]:
"""
Retrieve the top k tokens with the highest probabilities.
Args:
token_probs (Dict[int, float]): Mapping of token IDs to probabilities.
tokenizer (AutoTokenizer): Tokenizer to convert IDs to tokens.
top_k (int): Number of top tokens to retrieve.
Returns:
List of tuples containing token strings and their probabilities.
Raises:
ValueError: If top_k is invalid.
"""
if top_k <= 0:
raise ValueError("top_k must be a positive integer.")
try:
sorted_tokens = sorted(token_probs.items(), key=lambda item: item[1], reverse=True)
top_tokens = sorted_tokens[:top_k]
top_tokens_named = [(tokenizer.decode([token_id]).strip(), prob) for token_id, prob in top_tokens]
logger.info(f"Retrieved top {top_k} tokens.")
return top_tokens_named
except Exception as e:
logger.error(f"Error retrieving top {top_k} tokens: {e}")
raise ValueError(f"Failed to retrieve top {top_k} tokens: {e}")
def plot_token_distribution(top_tokens: List[Tuple[str, float]], token_id: int) -> None:
"""
Plot the top k token probabilities using Plotly.
Args:
top_tokens (List[Tuple[str, float]]): List of tuples with token strings and probabilities.
token_id (int): The input token ID.
Raises:
ValueError: If plotting fails.
"""
try:
tokens, probs = zip(*top_tokens)
fig = go.Figure(
data=[
go.Bar(
x=tokens,
y=probs,
text=[f"{prob:.4f}" for prob in probs],
textposition='auto'
)
]
)
fig.update_layout(
title=f"Top {len(top_tokens)} Token Probabilities for Token ID {token_id}",
xaxis_title="Tokens",
yaxis_title="Probability",
legend_title="Probability",
template="plotly_white"
)
fig.show()
logger.info("Displayed token distribution plot.")
except Exception as e:
logger.error(f"Error plotting token distribution: {e}")
raise ValueError(f"Failed to plot token distribution: {e}")
def visualize_token_generations(
model_name: str,
token_id: int,
top_k: int = 10
) -> None:
"""
Complete pipeline to visualize top k token generations from a single token_id.
Args:
model_name (str): Name of the pre-trained model.
token_id (int): The input token ID.
top_k (int, optional): Number of top tokens to visualize. Defaults to 10.
Raises:
ValueError: If any step in the pipeline fails.
"""
model, tokenizer = load_model_and_tokenizer(model_name)
token_probs = get_token_distribution(model, tokenizer, token_id)
top_tokens = get_top_k_tokens(token_probs, tokenizer, top_k)
plot_token_distribution(top_tokens, token_id)
def main() -> None:
"""
Entry point for the script.
"""
# Configuration parameters
MODEL_NAME = "gpt2" # Replace with desired model name
TOP_K = 10 # Number of top tokens to visualize
INPUT_TOKEN = "The" # Example input token
try:
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
input_ids = tokenizer.encode(INPUT_TOKEN, add_special_tokens=False)
if not input_ids:
raise ValueError(f"The input token '{INPUT_TOKEN}' is invalid or empty.")
token_id = input_ids[-1]
logger.info(f"Input token '{INPUT_TOKEN}' has token_id {token_id}.")
visualize_token_generations(MODEL_NAME, token_id, TOP_K)
except Exception as e:
logger.error(f"An error occurred in the main process: {e}")
print(f"Error: {e}")
if __name__ == "__main__":
main()
Explanation
Logging Configuration:
Utilizes Python's built-in logging module to provide informative messages throughout the script's execution, aiding in debugging and monitoring.
Function Breakdown:
load_model_and_tokenizer: Loads the specified pre-trained model and tokenizer. Raises an error if loading fails.
get_token_distribution: Computes the probability distribution for the next tokens given a single token_id. It ensures that the input is valid and handles any computation errors gracefully.
get_top_k_tokens: Sorts the token probabilities in descending order and retrieves the top k tokens. It also decodes token IDs to their string representations using the tokenizer.
plot_token_distribution: Uses Plotly to create an interactive bar chart of the top k token probabilities. It includes titles and labels for clarity.
visualize_token_generations: Orchestrates the entire process by calling the above functions in sequence.
main: Serves as the entry point of the script, where configuration parameters are defined. It includes an example input token ("The") and handles any exceptions that occur during execution.
Configurability:
The MODEL_NAME, TOP_K, and INPUT_TOKEN variables in the main function can be easily modified to adapt the script to different scenarios without changing the core logic.
Error Handling:
Each function includes try-except blocks to catch and log exceptions, providing meaningful error messages to the user without exposing internal stack traces.
Type Hints:
All functions include type annotations, enhancing code clarity and facilitating static type checking.
PEP-8 Compliance:
The script follows PEP-8 guidelines for naming conventions, indentation, line lengths, and other stylistic aspects to ensure readability and maintainability.
Usage Example
By default, the script uses the "gpt2" model and visualizes the top 10 probable tokens following the input token "The". To customize:
Change the Model:
Update the MODEL_NAME variable in the main function to any other compatible model available in the Hugging Face repository.
Change the Input Token:
Modify the INPUT_TOKEN variable to any other token or word of interest.
Adjust Top K:
Set the TOP_K variable to visualize a different number of top tokens.
Sample Output
Running the script will display an interactive Plotly bar chart similar to the following:
code
INFO:__main__:Successfully loaded model 'gpt2' and tokenizer.
INFO:__main__:Input token 'The' has token_id 464.
INFO:__main__:Computed token distribution for token_id 464.
INFO:__main__:Retrieved top 10 tokens.
INFO:__main__:Displayed token distribution plot.
A Plotly window will open showing the top 10 tokens that the model predicts can follow the word "The", along with their respective probabilities.
Conclusion
This script provides a robust, scalable, and maintainable solution for visualizing token probabilities from language models. By adhering to best practices and incorporating comprehensive error handling, it ensures reliability and ease of use for developers and researchers alike.