how to use a small llm model locally?
- User
how to use a small llm model locally?
- Assistant
how to use a small llm model locally?
Running a small Language Model (LLM) locally can provide benefits such as data privacy, reduced latency, and offline accessibility. Here's a comprehensive guide to help you set up and use a small LLM on your local machine:
Selecting the right model is crucial based on your hardware capabilities and use case. Here are some popular open-source, smaller-scale LLMs:
For beginners, GPT-2 or GPT-Neo 1.3B are recommended due to their balance between capability and resource requirements.
transformers, torch (PyTorch), and optionally accelerate or bitsandbytes for optimizations.Ensure Python 3.7+ is installed. You can download it from the official website.
Creating a virtual environment helps manage dependencies without affecting your system-wide Python installation.
# Create a virtual environment named 'llm_env'
python3 -m venv llm_env
# Activate the virtual environment
# On macOS/Linux:
source llm_env/bin/activate
# On Windows:
llm_env\Scripts\activate
pip install --upgrade pip
pip install transformers torch
If you have a CUDA-compatible GPU and want to leverage it, install the GPU version of PyTorch:
# Visit https://pytorch.org/get-started/locally/ to get the correct command
# Example for CUDA 11.7:
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu117
For CPU-only installations:
pip install torch torchvision torchaudio
Using Hugging Face’s transformers library simplifies model loading.
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
# Specify the model name
model_name = 'gpt2' # Options: 'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'
# Load tokenizer and model
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
# Move model to GPU if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
model_name = 'EleutherAI/gpt-neo-1.3B'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
Once the model and tokenizer are loaded, you can generate text based on a prompt.
def generate_text(prompt, max_length=100):
inputs = tokenizer.encode(prompt, return_tensors='pt').to(device)
outputs = model.generate(
inputs,
max_length=max_length,
num_return_sequences=1,
no_repeat_ngram_size=2,
do_sample=True,
top_k=50,
top_p=0.95,
temperature=0.7
)
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
return text
# Example usage
prompt = "Once upon a time"
generated = generate_text(prompt)
print(generated)
For an interactive experience, you can create a simple loop:
while True:
prompt = input("Enter prompt (or type 'exit' to quit): ")
if prompt.lower() == 'exit':
break
generated = generate_text(prompt)
print(generated)
Reduces memory usage and can speed up inference.
from torch.cuda.amp import autocast
def generate_text_fp16(prompt, max_length=100):
inputs = tokenizer.encode(prompt, return_tensors='pt').to(device)
with autocast(device.type):
outputs = model.generate(
inputs,
max_length=max_length,
num_return_sequences=1,
no_repeat_ngram_size=2,
do_sample=True,
top_k=50,
top_p=0.95,
temperature=0.7
)
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
return text
bitsandbytes:This technique reduces model size and speeds up inference, especially on GPUs.
Install bitsandbytes:
pip install bitsandbytes
Load Model with 8-bit Precision:
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
model_name = 'EleutherAI/gpt-neo-1.3B'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
load_in_8bit=True,
device_map='auto'
)
If you prefer not to write code, several tools provide user-friendly interfaces to interact with LLMs locally:
A web-based interface for running and interacting with language models.
Clone the Repository:
git clone https://github.com/oobabooga/text-generation-webui
cd text-generation-webui
Install Dependencies:
pip install -r requirements.txt
Run the Server:
python server.py
Access the Interface:
Open your browser and navigate to http://localhost:7860.
Use Jupyter for an interactive coding experience.
Install Jupyter:
pip install jupyter
Launch Jupyter:
jupyter notebook
Create a New Notebook and Use the Provided Code Snippets:
Copy the code examples above into notebook cells to interact with the model.
Before deploying any model, ensure that you comply with its licensing terms:
Always verify the licensing to ensure your intended use (especially commercial) is permitted.
transformers, torch, and other libraries are compatible with each other.Here's a step-by-step example to get GPT-2 running locally and generating text.
# Create and activate virtual environment
python3 -m venv llm_env
source llm_env/bin/activate # On Windows: llm_env\Scripts\activate
# Install dependencies
pip install transformers torch
generate_gpt2.py)from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
def main():
model_name = 'gpt2' # Change to 'gpt2-medium', etc., if desired
# Load tokenizer and model
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
# Move to GPU if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
while True:
prompt = input("Enter prompt (or type 'exit' to quit): ")
if prompt.lower() == 'exit':
break
inputs = tokenizer.encode(prompt, return_tensors='pt').to(device)
outputs = model.generate(
inputs,
max_length=100,
num_return_sequences=1,
no_repeat_ngram_size=2,
do_sample=True,
top_k=50,
top_p=0.95,
temperature=0.7
)
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(text)
if __name__ == "__main__":
main()
python generate_gpt2.py
Sample Interaction:
Enter prompt (or type 'exit' to quit): Once upon a time
Once upon a time, in a land far away, there lived a young prince who dreamed of adventure...
Running a small LLM locally is entirely feasible with the right setup and resources. By selecting an appropriate model, ensuring your system meets the necessary requirements, and following the setup steps, you can leverage powerful language generation capabilities on your own machine. Always be mindful of the model’s licensing and optimize based on your hardware to achieve the best performance.
If you encounter challenges or require advanced optimizations, consulting the documentation of libraries like Hugging Face Transformers or engaging with community forums can be highly beneficial.