Certainly! Below is a Python function that loads and tries a Language Model (LLM) from Hugging Face's transformers library. This function will load a pre-trained model, perform a simple text generation task, and print the generated text.
First, ensure you have the necessary libraries installed:
pip install transformers
Here's the function:
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
def load_and_try_llm(model_name="distilgpt2"):
"""
Load a pre-trained LLM from Hugging Face and try generating text.
Args:
- model_name (str): The name of the pre-trained model to load. Default is "distilgpt2".
Returns:
- generated_text (str): The generated text from the model.
"""
# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# Create a text generation pipeline
text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
# Input prompt for text generation
prompt = "Once upon a time,"
# Generate text
generated_text = text_generator(prompt, max_length=100, num_return_sequences=1)[0]["generated_text"]
# Print the generated text
print(f"Generated Text:\n{generated_text}")
return generated_text
# Example usage
load_and_try_llm()
Explanation:
- Imports: The function imports necessary classes from the
transformers library.
- Parameters: The function accepts a
model_name parameter, which defaults to "distilgpt2".
- Loading Tokenizer and Model: It loads the tokenizer and model using
AutoTokenizer.from_pretrained and AutoModelForCausalLM.from_pretrained.
- Text Generation Pipeline: It creates a text generation pipeline using
pipeline.
- Prompt: It defines a simple prompt
"Once upon a time,".
- Generate Text: It generates text using the pipeline and prints the generated text.
- Return: The function returns the generated text.
You can change the model_name parameter to any other pre-trained model available on Hugging Face, such as "gpt2", "EleutherAI/gpt-neo-1.3B", etc.