Spaces:
Sleeping
Sleeping
local
Browse filesFiles changed (10)
- .gitignore+2-1
- LOCAL_MODELS_GUIDE.mdAdded+260
- QUICK_LOCAL_SETUP.mdAdded+105
- README.md+29
- config.py+148-4
- download_models.pyAdded+230
- evaluation.py+141
- hf_agent.py+169-18
- local_config.jsonAdded+13
- requirements.txt+6-1
2 unmodified lines3456672 unmodified lines__pycache__/
.cursorrules/.cursor/.cursor/models/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260# Local Models Guide
This guide explains how to run the GAIA evaluation agent with locally downloaded models for enhanced privacy, speed, and offline usage.
## Quick Start
### 1. Choose Your Model Size
Run this command to see available options:```bashpython download_models.py --list-sizes```
**Recommendations:**- **Light models** (~20GB): Best for most users with 8-16GB RAM- **Medium models** (~18GB): Balanced performance for 16-32GB RAM systems - **Full models** (~155GB): Maximum performance for high-end systems with 64GB+ RAM
### 2. Download Models
**For most users (Light models):**```bashpython download_models.py --model-size light```
**With HuggingFace token (for gated models):**```bashpython download_models.py --model-size light --token hf_your_token_here```
**For better performance (Medium models):**```bashpython download_models.py --model-size medium```
### 3. Run Evaluation
After downloading, simply run:```bashpython evaluation.py```
The system will automatically detect and use your local models!
## Advanced Configuration
### Manual Model Paths
If you have models in different locations, you can set custom paths:
```pythonfrom config import set_local_model_paths, set_model_strategy
# Set custom pathsset_local_model_paths( llm_path="/path/to/your/llm/model", fallback_path="/path/to/your/fallback/model", embedding_path="/path/to/your/embedding/model")
# Force local modeset_model_strategy("local")```
### Model Strategy Options
- **`auto`** (default): Try local first, fallback to remote- **`local`**: Use only local models (fails if not available)- **`local_light`**: Use lighter local models- **`remote`**: Use only remote models
```pythonfrom config import set_model_strategy
set_model_strategy("auto") # Recommended```
### Performance Optimization
#### For GPU Systems
The system automatically detects CUDA/MPS and uses appropriate settings:
```python# config.py settings for performanceMODEL_CONFIG = { "device": "auto", # Will use CUDA/MPS if available "torch_dtype": "float16", # Use float16 for speed "load_in_8bit": False, # Enable for memory efficiency "load_in_4bit": False, # Enable for maximum memory savings}```
#### Memory Optimization
For systems with limited RAM, enable quantization:
```pythonfrom config import MODEL_CONFIG
# Enable 8-bit quantization (reduces memory by ~50%)MODEL_CONFIG["load_in_8bit"] = True
# Or enable 4-bit quantization (reduces memory by ~75%) MODEL_CONFIG["load_in_4bit"] = True```
## Downloading Specific Models
### Download Individual Models
```bash# Download a specific modelpython download_models.py --custom-model microsoft/DialoGPT-small
# Download to specific directorypython download_models.py --models-dir /path/to/models --model-size light```
### Popular Model Alternatives
**Lightweight Options:**- `microsoft/DialoGPT-small` (~300MB)- `distilbert-base-uncased` (~250MB)- `TinyLlama/TinyLlama-1.1B-Chat-v1.0` (~2GB)
**Mid-range Options:**- `meta-llama/Llama-3.2-8B-Instruct` (~16GB)- `mistralai/Mistral-7B-Instruct-v0.1` (~14GB)- `microsoft/DialoGPT-medium` (~1.5GB)
**High-performance Options:**- `meta-llama/Llama-3.3-70B-Instruct` (~140GB)- `mistralai/Mixtral-8x7B-Instruct-v0.1` (~90GB)
## System Requirements
### Hardware Requirements by Model Size
| Model Size | Storage | RAM | GPU VRAM | CPU ||------------|---------|-----|----------|-----|| Light | 20GB | 8-16GB | 6GB+ (optional) | 4+ cores || Medium | 18GB | 16-32GB | 12GB+ (optional) | 8+ cores || Full | 155GB | 64GB+ | 80GB+ (recommended) | 16+ cores |
### Supported Platforms
- **Linux**: Full support with CUDA/ROCm- **macOS**: Apple Silicon (M1/M2/M3) with MPS acceleration- **Windows**: CUDA support, CPU fallback
## Troubleshooting
### Common Issues
**1. Out of Memory Errors**```bash# Enable quantizationpython -c "from config import MODEL_CONFIG; MODEL_CONFIG['load_in_8bit'] = True"```
**2. Slow Inference on CPU**```bash# Use lighter modelspython download_models.py --model-size light```
**3. Models Not Found**```bash# Check model pathspython -c "from config import get_model_config; print(get_model_config())"```
**4. CUDA Out of Memory**```bash# Enable 4-bit quantizationpython -c "from config import MODEL_CONFIG; MODEL_CONFIG['load_in_4bit'] = True"```
### Verification Commands
**Check model configuration:**```pythonfrom config import get_model_configconfig = get_model_config()print(f"Using local models: {config.get('use_local', False)}")print(f"LLM path: {config['llm_model']}")```
**Test model loading:**```pythonfrom hf_agent import SmolagentsGAIAAgentagent = SmolagentsGAIAAgent()print("Agent initialized successfully!")```
## Performance Comparison
### Inference Speed (approximate)
| Model Size | CPU (Intel i7) | GPU (RTX 4090) | Apple M2 Max ||------------|----------------|----------------|--------------|| Light | 2-5 tokens/sec | 15-30 tokens/sec | 8-12 tokens/sec || Medium | 1-3 tokens/sec | 10-20 tokens/sec | 5-8 tokens/sec || Full | 0.1-0.5 tokens/sec | 3-8 tokens/sec | N/A |
### GAIA Benchmark Performance
Expected performance on GAIA benchmark:
| Model Size | Expected Score | Reasoning Quality | Tool Usage ||------------|----------------|------------------|------------|| Light | 25-35% | Good | Good || Medium | 30-40% | Very Good | Very Good || Full | 35-45% | Excellent | Excellent |
## Integration with Gradio Interface
The web interface includes a "Local Models" tab with:
1. **Quick Setup**: Download models directly from the interface2. **Manual Setup**: Set custom model paths3. **Status Monitoring**: Track download progress4. **Configuration**: Switch between local and remote modes
## Tips for Best Results
1. **Use appropriate model size** for your hardware2. **Enable GPU acceleration** when available3. **Monitor memory usage** during inference4. **Use quantization** for memory-constrained systems5. **Keep models updated** for best performance6. **Test with simple questions** before running full evaluation
## Support
For issues with local models:
1. Check system requirements2. Verify model downloads completed successfully3. Enable verbose logging in config.py4. Try lighter model variants5. Check available memory and storage
## Advanced: Custom Model Integration
To use your own fine-tuned models:
```pythonfrom config import set_local_model_paths
# Point to your custom modelset_local_model_paths( llm_path="/path/to/your/custom/model", fallback_path="/path/to/fallback/model", embedding_path="/path/to/embedding/model")```
Ensure your models are compatible with the transformers library and include necessary tokenizer files. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105# Quick Local Model Setup
## If You Get "403 Client Error" (Gated Models)
Some models like Llama require access approval. Here's how to fix this:
### Option 1: Use Non-Gated Models (Recommended)
```bash# Download tiny models (650MB, no approval needed)python download_models.py --model-size tiny
# Or download light models with working non-gated alternativespython download_models.py --model-size light```
### Option 2: Get Access to Gated Models
1. Visit the model page (e.g., https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct)2. Request access by clicking "Request access to model"3. Wait for approval (usually instant for Llama models)4. Get your HuggingFace token from https://huggingface.co/settings/tokens5. Download with token:
```bashpython download_models.py --model-size medium --token hf_your_token_here```
### Option 3: Use Already Downloaded Models
If you already have some models downloaded (like in your case), configure manually:
```pythonfrom config import set_local_model_paths, set_model_strategy
# Set paths to your downloaded modelsset_local_model_paths( llm_path="./models/Qwen2.5-7B-Instruct", # Your main model fallback_path="./models/Llama-3.2-3B-Instruct", # Backup model embedding_path="./models/all-MiniLM-L6-v2" # Embedding model)
# Enable local model usageset_model_strategy("local")```
## Current Status (Your Setup)
✅ **You already have working local models!**
Your current setup:- Primary Model: Qwen2.5-7B-Instruct (~14GB) ✅- Fallback Model: Llama-3.2-3B-Instruct (~6GB) ✅ - Embedding Model: all-MiniLM-L6-v2 (~90MB) ✅- Device: Apple Silicon MPS acceleration ✅
## Quick Test
```bash# Test that everything workspython -c "from hf_agent import SmolagentsGAIAAgent; agent = SmolagentsGAIAAgent(); print('✅ Ready!')"
# Run the evaluationpython evaluation.py```
## Model Performance Comparison
| Model Size | Download | Memory | Performance | Privacy ||------------|----------|---------|-------------|---------|| **Tiny** | 650MB | 4-8GB | Basic | 🔒 Full || **Light** | 16GB | 8-16GB | Good | 🔒 Full || **Medium** | 18GB | 16-32GB | Very Good | 🔒 Full || **Remote** | 0MB | 2-4GB | Excellent | ⚠️ Limited |
## Troubleshooting
### Memory Issues```bash# Enable 8-bit quantization (reduces memory by ~50%)python -c "from config import MODEL_CONFIG; MODEL_CONFIG['load_in_8bit'] = True"
# Or enable 4-bit quantization (reduces memory by ~75%)python -c "from config import MODEL_CONFIG; MODEL_CONFIG['load_in_4bit'] = True"```
### Slow Performance- **CPU only**: Use tiny models for better speed- **With GPU**: Models should run much faster- **Apple Silicon**: MPS acceleration is automatically enabled
### Switch Back to Remote```pythonfrom config import set_model_strategyset_model_strategy("remote") # Use cloud models```
## Your Options
1. **Use current setup** (recommended) - You have good local models working2. **Download tiny models** - For faster testing/development 3. **Get gated model access** - For maximum performance4. **Switch to remote** - For convenience without local setup
Your current local setup is actually quite good for GAIA evaluation! 🚀 66 unmodified lines676869707172732 unmodified lines76777879808182838485868788899 unmodified lines9910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812966 unmodified lines - `hf_agent.py` - Smolagents-based agent implementation - `config.py` - Configuration and model settings - `requirements.txt` - Dependencies including smolagents - `download_models.py` - Local model downloader
2. **Environment Variables** (optional): - `HF_TOKEN` - Hugging Face API token for model access2 unmodified lines3. **Dependencies** (automatically installed): - `smolagents` - Core framework - `transformers` - Model loading - `torch` - PyTorch for local models - `gradio` - UI framework - `langchain` - RAG components - Plus web scraping and file processing libraries
### Local Development
#### Quick Start (Remote Models)```bash# Clone the repositorygit clone <repository-url>9 unmodified linespython evaluation.py```
#### Local Models Setup```bash# Install dependencies with local model supportpip install -r requirements.txt
# Download light models (recommended for most users)python download_models.py --model-size light
# Or download medium models for better performancepython download_models.py --model-size medium --token hf_your_token
# Run with local modelspython evaluation.py```
#### System Requirements for Local Models
| Model Size | Storage | RAM | GPU VRAM | Recommended For ||------------|---------|-----|----------|-----------------|| Light | 20GB | 8-16GB | 6GB+ (optional) | Most users || Medium | 18GB | 16-32GB | 12GB+ (optional) | Balanced performance || Full | 155GB | 64GB+ | 80GB+ (recommended) | High-end systems |
See [LOCAL_MODELS_GUIDE.md](LOCAL_MODELS_GUIDE.md) for detailed instructions.
## Usage
### Individual Q&A3 unmodified lines45678910111213141516171819202122232425262728293031323334351112133637383940414243444546474849505152535446 unmodified lines101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139751401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212223 unmodified lines"""
import osimport json
# --- Smolagents Model Configuration ---MODEL_CONFIG = { # Model selection strategy: "local", "remote", or "auto" "model_strategy": "auto", # auto will try local first, then remote # Local model paths (set these to your downloaded model directories) "local_models": { "llm_model": "./models/Llama-3.3-70B-Instruct", # Path to local Llama model "fallback_model": "./models/zephyr-7b-beta", # Path to local Zephyr model "embedding_model": "./models/gte-small", # Path to local embedding model }, # Remote model IDs (used when local models not available) "remote_models": { "llm_model": "meta-llama/Llama-3.3-70B-Instruct", "fallback_model": "HuggingFaceH4/zephyr-7b-beta", "embedding_model": "thenlper/gte-small", }, # For smaller local testing, you can use these lighter models "local_light_models": { "llm_model": "./models/DialoGPT-medium", # No gating required "fallback_model": "./models/Qwen2.5-7B-Instruct", # Alternative smaller model "embedding_model": "./models/all-MiniLM-L6-v2", # Smaller embedding model }, # Primary LLM for the CodeAgent - use a strong reasoning model "llm_model": "meta-llama/Llama-3.3-70B-Instruct", # Primary reasoning model "fallback_model": "HuggingFaceH4/zephyr-7b-beta", # Fallback if primary fails "embedding_model": "thenlper/gte-small", # For RAG/vector search "llm_model": "meta-llama/Llama-3.3-70B-Instruct", # Will be overridden by model selection "fallback_model": "HuggingFaceH4/zephyr-7b-beta", # Will be overridden by model selection "embedding_model": "thenlper/gte-small", # Will be overridden by model selection # Generation parameters "temperature": 0.7, "max_new_tokens": 512, "top_p": 0.9, # Local model specific parameters "device": "auto", # "cuda", "cpu", "mps" (for Mac), or "auto" "torch_dtype": "auto", # "float16", "bfloat16", "float32", or "auto" "load_in_8bit": False, # Enable for memory efficiency "load_in_4bit": False, # Enable for even more memory efficiency "use_cache": True, # Enable KV cache for faster inference # Tool configuration "enable_web_search": True, "enable_article_extraction": True,46 unmodified lines# --- Supported File Types ---SUPPORTED_FILE_TYPES = [".txt", ".pdf", ".csv", ".docx", ".xlsx", ".png", ".jpg", ".jpeg"]
# --- Configuration File Management ---CONFIG_FILE = "local_config.json"
def save_config(): """Save current configuration to file""" try: config_data = { "model_strategy": MODEL_CONFIG["model_strategy"], "local_models": MODEL_CONFIG["local_models"], "local_light_models": MODEL_CONFIG["local_light_models"] } with open(CONFIG_FILE, 'w') as f: json.dump(config_data, f, indent=2) except Exception as e: print(f"Warning: Could not save config: {e}")
def load_config(): """Load configuration from file""" try: if os.path.exists(CONFIG_FILE): with open(CONFIG_FILE, 'r') as f: config_data = json.load(f) MODEL_CONFIG["model_strategy"] = config_data.get("model_strategy", "auto") MODEL_CONFIG["local_models"].update(config_data.get("local_models", {})) MODEL_CONFIG["local_light_models"].update(config_data.get("local_light_models", {})) print(f"Loaded configuration from {CONFIG_FILE}") except Exception as e: print(f"Warning: Could not load config: {e}")
# Load config at import timeload_config()
# --- Utility Functions ---def get_model_config(): """Get the model configuration dictionary""" return MODEL_CONFIG.copy() config = MODEL_CONFIG.copy() # Determine which models to use based on strategy strategy = config["model_strategy"] if strategy == "local" or (strategy == "auto" and _check_local_models_available()): # Use local models config.update(config["local_models"]) config["use_local"] = True print("Using local models") elif strategy == "local_light" or (strategy == "auto" and _check_local_light_models_available()): # Use lighter local models config.update(config["local_light_models"]) config["use_local"] = True print("Using local light models") else: # Use remote models config.update(config["remote_models"]) config["use_local"] = False print("Using remote models") return config
def _check_local_models_available(): """Check if local models are available""" import os local_models = MODEL_CONFIG["local_models"] for model_type, path in local_models.items(): if not os.path.exists(path): return False return True
def _check_local_light_models_available(): """Check if local light models are available""" import os local_models = MODEL_CONFIG["local_light_models"] for model_type, path in local_models.items(): if not os.path.exists(path): return False return True
def set_model_strategy(strategy): """Set the model strategy: 'local', 'local_light', 'remote', or 'auto'""" MODEL_CONFIG["model_strategy"] = strategy save_config()
def set_local_model_paths(llm_path=None, fallback_path=None, embedding_path=None): """Set custom paths for local models""" if llm_path: MODEL_CONFIG["local_models"]["llm_model"] = llm_path if fallback_path: MODEL_CONFIG["local_models"]["fallback_model"] = fallback_path if embedding_path: MODEL_CONFIG["local_models"]["embedding_model"] = embedding_path save_config()
def get_device_config(): """Get device configuration for local models""" import torch config = get_model_config() device = config["device"] if device == "auto": if torch.cuda.is_available(): device = "cuda" elif hasattr(torch.backends, 'mps') and torch.backends.mps.is_available(): device = "mps" # Apple Silicon GPU else: device = "cpu" return { "device": device, "torch_dtype": config["torch_dtype"], "load_in_8bit": config["load_in_8bit"], "load_in_4bit": config["load_in_4bit"], "use_cache": config["use_cache"] }
def get_system_prompt(prompt_type: str = "code_agent") -> str: """Get system prompt for the specified type"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230#!/usr/bin/env python3"""Model downloader for GAIA Evaluation AgentHelps download and set up local models for offline usage"""
import osimport argparsefrom pathlib import Pathfrom huggingface_hub import snapshot_downloadfrom config import set_model_strategy, set_local_model_paths
def download_model(model_id, local_dir, token=None): """Download a model from Hugging Face Hub""" print(f"Downloading {model_id} to {local_dir}...") try: snapshot_download( repo_id=model_id, local_dir=local_dir, token=token, resume_download=True, local_dir_use_symlinks=False ) print(f"✓ Successfully downloaded {model_id}") return True except Exception as e: print(f"✗ Failed to download {model_id}: {e}") return False
def setup_model_directory(base_dir="./models"): """Create model directory structure""" models_dir = Path(base_dir) models_dir.mkdir(exist_ok=True) return models_dir
def download_recommended_models(models_dir, token=None, model_size="light"): """Download recommended models for GAIA evaluation""" if model_size == "tiny": models_to_download = { "llm_model": { "id": "microsoft/DialoGPT-small", "dir": "DialoGPT-small" }, "fallback_model": { "id": "distilbert-base-uncased", "dir": "distilbert-base-uncased" }, "embedding_model": { "id": "sentence-transformers/all-MiniLM-L6-v2", "dir": "all-MiniLM-L6-v2" } } elif model_size == "full": models_to_download = { "llm_model": { "id": "meta-llama/Llama-3.3-70B-Instruct", "dir": "Llama-3.3-70B-Instruct" }, "fallback_model": { "id": "HuggingFaceH4/zephyr-7b-beta", "dir": "zephyr-7b-beta" }, "embedding_model": { "id": "thenlper/gte-small", "dir": "gte-small" } } elif model_size == "medium": models_to_download = { "llm_model": { "id": "meta-llama/Llama-3.2-8B-Instruct", "dir": "Llama-3.2-8B-Instruct" }, "fallback_model": { "id": "microsoft/DialoGPT-medium", "dir": "DialoGPT-medium" }, "embedding_model": { "id": "sentence-transformers/all-MiniLM-L6-v2", "dir": "all-MiniLM-L6-v2" } } else: # light models_to_download = { "llm_model": { "id": "microsoft/DialoGPT-medium", "dir": "DialoGPT-medium" }, "fallback_model": { "id": "Qwen/Qwen2.5-7B-Instruct", "dir": "Qwen2.5-7B-Instruct" }, "embedding_model": { "id": "sentence-transformers/all-MiniLM-L6-v2", "dir": "all-MiniLM-L6-v2" } } downloaded_models = {} for model_type, model_info in models_to_download.items(): model_dir = models_dir / model_info["dir"] if model_dir.exists() and any(model_dir.iterdir()): print(f"✓ {model_info['id']} already exists at {model_dir}") downloaded_models[model_type] = str(model_dir) else: if download_model(model_info["id"], str(model_dir), token): downloaded_models[model_type] = str(model_dir) return downloaded_models
def update_config_for_local_models(downloaded_models): """Update configuration to use downloaded local models""" print("\nUpdating configuration for local models...") set_local_model_paths( llm_path=downloaded_models.get("llm_model"), fallback_path=downloaded_models.get("fallback_model"), embedding_path=downloaded_models.get("embedding_model") ) if downloaded_models.get("llm_model") or downloaded_models.get("fallback_model"): # If we have at least one model, configure to use local if downloaded_models.get("llm_model"): set_model_strategy("local") print("✓ Configuration updated to use local models") else: # Use fallback as primary model set_local_model_paths( llm_path=downloaded_models.get("fallback_model"), fallback_path=downloaded_models.get("llm_model"), embedding_path=downloaded_models.get("embedding_model") ) set_model_strategy("local") print("✓ Configuration updated to use local models (using fallback as primary)") else: print("⚠ No models downloaded successfully, keeping remote configuration")
def main(): parser = argparse.ArgumentParser(description="Download models for GAIA evaluation") parser.add_argument( "--model-size", choices=["tiny", "light", "medium", "full"], default="light", help="Size of models to download (default: light)" ) parser.add_argument( "--models-dir", default="./models", help="Directory to store models (default: ./models)" ) parser.add_argument( "--token", help="Hugging Face API token (for gated models)" ) parser.add_argument( "--custom-model", help="Download a specific model ID" ) parser.add_argument( "--list-sizes", action="store_true", help="Show information about different model sizes" ) args = parser.parse_args() if args.list_sizes: print("""Model Size Information:
TINY (Quick testing, limited capability):- LLM: DialoGPT-small (~300MB, no gating required)- Fallback: distilbert-base-uncased (~250MB)- Embedding: all-MiniLM-L6-v2 (~90MB)- Total: ~650MB- Memory: 4-8GB RAM recommended
LIGHT (Recommended for most users):- LLM: DialoGPT-medium (~1.5GB, no gating required)- Fallback: Qwen2.5-7B-Instruct (~14GB) - Embedding: all-MiniLM-L6-v2 (~90MB)- Total: ~16GB- Memory: 8-16GB RAM recommended
MEDIUM (Balanced performance):- LLM: Llama-3.2-8B-Instruct (~16GB)- Fallback: DialoGPT-medium (~1.5GB)- Embedding: all-MiniLM-L6-v2 (~90MB)- Total: ~18GB- Memory: 16-32GB RAM recommended
FULL (Best performance):- LLM: Llama-3.3-70B-Instruct (~140GB)- Fallback: zephyr-7b-beta (~14GB)- Embedding: gte-small (~130MB)- Total: ~155GB- Memory: 64GB+ RAM recommended or GPU with 80GB+ VRAM """) return # Set up models directory models_dir = setup_model_directory(args.models_dir) print(f"Using models directory: {models_dir}") if args.custom_model: # Download custom model model_name = args.custom_model.split("/")[-1] model_dir = models_dir / model_name download_model(args.custom_model, str(model_dir), args.token) else: # Download recommended models downloaded_models = download_recommended_models( models_dir, args.token, args.model_size ) # Update configuration update_config_for_local_models(downloaded_models) print(f"\nTo use local models, run:") print(f"python -c \"from config import set_model_strategy; set_model_strategy('local')\"") print(f"python evaluation.py")
if __name__ == "__main__": main() 278 unmodified lines2792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214227 unmodified lines430431432433434435436437438439440441442443444445446447448449450278 unmodified lines # Use dummy profile for local development eval_btn.click(lambda: run_evaluation(DummyProfile()), outputs=[status_output, results_table]) with gr.Tab("Local Models"): gr.Markdown(""" ## Local Model Support Run the evaluation with models downloaded locally on your machine for: - **Privacy**: No data sent to external APIs - **Speed**: Faster inference (with proper hardware) - **Offline**: Works without internet connection - **Control**: Full control over model versions """) with gr.Row(): with gr.Column(): gr.Markdown("### Quick Setup") model_size = gr.Radio( choices=["light", "medium", "full"], value="light", label="Model Size", info="Light: ~20GB, Medium: ~18GB, Full: ~155GB" ) hf_token = gr.Textbox( label="HuggingFace Token (optional)", placeholder="hf_...", type="password", info="Required for some gated models" ) download_btn = gr.Button("Download Models", variant="primary") with gr.Column(): gr.Markdown("### Manual Setup") llm_path = gr.Textbox( label="LLM Model Path", placeholder="./models/Llama-3.2-3B-Instruct", info="Path to your local LLM" ) fallback_path = gr.Textbox( label="Fallback Model Path", placeholder="./models/Qwen2.5-7B-Instruct", info="Path to your fallback model" ) embedding_path = gr.Textbox( label="Embedding Model Path", placeholder="./models/all-MiniLM-L6-v2", info="Path to your embedding model" ) set_paths_btn = gr.Button("Set Model Paths", variant="secondary") download_status = gr.Textbox( label="Status", interactive=False, lines=10 ) def download_models_interface(size, token): try: import subprocess import sys # Build command cmd = [sys.executable, "download_models.py", "--model-size", size] if token: cmd.extend(["--token", token]) # Run download script result = subprocess.run( cmd, capture_output=True, text=True, cwd="." ) if result.returncode == 0: return f"✓ Successfully downloaded {size} models!\n\n{result.stdout}" else: return f"✗ Download failed:\n{result.stderr}\n{result.stdout}" except Exception as e: return f"✗ Error running download script: {str(e)}" def set_model_paths_interface(llm, fallback, embedding): try: from config import set_local_model_paths, set_model_strategy paths_set = [] if llm and os.path.exists(llm): paths_set.append(f"LLM: {llm}") if fallback and os.path.exists(fallback): paths_set.append(f"Fallback: {fallback}") if embedding and os.path.exists(embedding): paths_set.append(f"Embedding: {embedding}") if paths_set: set_local_model_paths(llm, fallback, embedding) set_model_strategy("local") return f"✓ Local model paths updated:\n" + "\n".join(paths_set) + "\n\nRestart the application to use local models." else: return "✗ No valid model paths found. Please check that the directories exist." except Exception as e: return f"✗ Error setting model paths: {str(e)}" download_btn.click( download_models_interface, inputs=[model_size, hf_token], outputs=download_status ) set_paths_btn.click( set_model_paths_interface, inputs=[llm_path, fallback_path, embedding_path], outputs=download_status ) gr.Markdown(""" ### Command Line Usage You can also download models via command line: ```bash # Download light models (recommended) python download_models.py --model-size light # Download with HuggingFace token python download_models.py --model-size medium --token hf_your_token # See model size information python download_models.py --list-sizes # Download specific model python download_models.py --custom-model microsoft/DialoGPT-small ``` ### Requirements for Local Models - **Memory**: 8GB+ RAM for light models, 16GB+ for medium, 64GB+ for full - **Storage**: 20GB+ free space for light models - **GPU**: Optional but recommended for faster inference """) with gr.Tab("About Smolagents"): gr.Markdown(""" ## About This Agent7 unmodified lines - **Tool Selection**: Intelligently chooses the right tools for each task - **Code Execution**: Can write and execute Python code for calculations - **Real-time Information**: Access to current web information - **Local & Remote Models**: Support for both local and cloud-based models ### Architecture: - **Primary LLM**: Llama-3.3-70B-Instruct (with fallback to Zephyr-7B) - **Framework**: Smolagents CodeAgent - **Tools**: DuckDuckGo search, Wikipedia, Calculator, File processors - **Execution**: Safe Python code execution environment - **Deployment**: Local or remote model inference ### GAIA Optimization: - Designed specifically for GAIA benchmark requirements - Handles diverse question types from simple facts to complex multi-step problems - Optimized for accuracy and precision in answers - Robust error handling and tool selection - Local model support for privacy and offline usage **Source Code**: Available in this Hugging Face Space """)123456717 unmodified lines2526272728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913034131132133134135136137138414243444546474849505152531391401411421438 unmodified lines152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217717273218219220221222223224225226227"""Smolagents-based GAIA Evaluation AgentUses CodeAgent with custom tools for web search, file processing, and calculationsSupports both local and remote models"""
import os17 unmodified linesfrom langchain_community.vectorstores import FAISSfrom langchain_huggingface import HuggingFaceEmbeddings
from config import get_model_config, get_system_prompt, get_supported_file_types, get_hf_token, get_smolagents_config, get_tools_configfrom config import get_model_config, get_system_prompt, get_supported_file_types, get_hf_token, get_smolagents_config, get_tools_config, get_device_config
# Initialize global variables for toolsconfig = get_model_config()tools_config = get_tools_config()
class LocalModel: """Wrapper for local models to be compatible with smolagents Model interface""" def __init__(self, model_path, device_config): from transformers import AutoTokenizer, AutoModelForCausalLM import torch self.model_path = model_path self.device_config = device_config print(f"Loading local model from: {model_path}") # Load tokenizer self.tokenizer = AutoTokenizer.from_pretrained( model_path, trust_remote_code=True, use_fast=True ) # Add padding token if not present if self.tokenizer.pad_token is None: self.tokenizer.pad_token = self.tokenizer.eos_token # Determine torch dtype torch_dtype = device_config["torch_dtype"] if torch_dtype == "auto": torch_dtype = torch.float16 if device_config["device"] != "cpu" else torch.float32 elif torch_dtype == "float16": torch_dtype = torch.float16 elif torch_dtype == "bfloat16": torch_dtype = torch.bfloat16 else: torch_dtype = torch.float32 # Load model with appropriate settings model_kwargs = { "torch_dtype": torch_dtype, "trust_remote_code": True, "use_cache": device_config["use_cache"] } # Add quantization if requested if device_config["load_in_8bit"]: model_kwargs["load_in_8bit"] = True elif device_config["load_in_4bit"]: model_kwargs["load_in_4bit"] = True # Load model self.model = AutoModelForCausalLM.from_pretrained( model_path, **model_kwargs ) # Move to device if not using quantization if not (device_config["load_in_8bit"] or device_config["load_in_4bit"]): self.model = self.model.to(device_config["device"]) self.device = device_config["device"] print(f"Model loaded on device: {self.device}") def generate(self, prompt, max_new_tokens=512, temperature=0.7, **kwargs): """Generate response compatible with smolagents interface""" import torch # Tokenize input inputs = self.tokenizer( prompt, return_tensors="pt", padding=True, truncation=True ).to(self.device) # Generate response with torch.no_grad(): outputs = self.model.generate( **inputs, max_new_tokens=max_new_tokens, temperature=temperature, do_sample=temperature > 0, pad_token_id=self.tokenizer.eos_token_id, eos_token_id=self.tokenizer.eos_token_id, **kwargs ) # Decode response generated_text = self.tokenizer.decode( outputs[0], skip_special_tokens=True ) # Remove the input prompt from the generated text if generated_text.startswith(prompt): generated_text = generated_text[len(prompt):].strip() return generated_text
class SmolagentsGAIAAgent: """GAIA Evaluation Agent using Smolagents framework""" """GAIA Evaluation Agent using Smolagents framework with local/remote model support""" def __init__(self): self.config = get_smolagents_config() self.model_config = get_model_config() self.tools_config = get_tools_config() self.supported_file_types = get_supported_file_types() # Initialize the model try: self.llm_engine = InferenceClientModel( model_id=self.config["model_id"], token=get_hf_token() ) except Exception as e: # Fallback to a free model if primary fails print(f"Failed to load primary model, using fallback: {e}") self.llm_engine = InferenceClientModel( model_id=config["fallback_model"], token=get_hf_token() ) # Initialize the model (local or remote) self.llm_engine = self._initialize_model() # Initialize Python executor for code execution self.python_executor = LocalPythonExecutor(8 unmodified lines # Create the CodeAgent with tools self._create_agent() def _initialize_model(self): """Initialize either local or remote model based on configuration""" try: if self.model_config.get("use_local", False): # Use local model device_config = get_device_config() model_path = self.model_config["llm_model"] if not os.path.exists(model_path): print(f"Local model path not found: {model_path}") print("Falling back to remote model...") raise FileNotFoundError(f"Local model not found: {model_path}") return LocalModel(model_path, device_config) else: # Use remote model with InferenceClientModel return InferenceClientModel( model_id=self.model_config["llm_model"], token=get_hf_token() ) except Exception as e: print(f"Failed to load primary model: {e}") # Try fallback model try: if self.model_config.get("use_local", False): device_config = get_device_config() fallback_path = self.model_config["fallback_model"] if os.path.exists(fallback_path): print(f"Using local fallback model: {fallback_path}") return LocalModel(fallback_path, device_config) else: print("Local fallback not available, using remote fallback...") return InferenceClientModel( model_id=self.model_config["fallback_model"], token=get_hf_token() ) else: return InferenceClientModel( model_id=self.model_config["fallback_model"], token=get_hf_token() ) except Exception as e2: print(f"Fallback model also failed: {e2}") raise Exception(f"Both primary and fallback models failed to load") def _init_rag(self): """Initialize RAG components for knowledge retrieval""" try: # Use local or remote embedding model if self.model_config.get("use_local", False): embedding_path = self.model_config["embedding_model"] if os.path.exists(embedding_path): embedding_model = HuggingFaceEmbeddings( model_name=embedding_path, model_kwargs={"device": get_device_config()["device"]} ) else: print(f"Local embedding model not found: {embedding_path}") print("Using remote embedding model...") embedding_model = HuggingFaceEmbeddings( model_name=self.tools_config["rag"]["embedding_model"] ) embedding_model = HuggingFaceEmbeddings( model_name=self.tools_config["rag"]["embedding_model"] ) else: embedding_model = HuggingFaceEmbeddings( model_name=self.tools_config["rag"]["embedding_model"] ) # Create a simple knowledge base (can be expanded) knowledge_docs = [12345678910111213{ "model_strategy": "local", "local_models": { "llm_model": "./models/Qwen2.5-7B-Instruct", "fallback_model": "./models/Llama-3.2-3B-Instruct", "embedding_model": "./models/all-MiniLM-L6-v2" }, "local_light_models": { "llm_model": "./models/DialoGPT-medium", "fallback_model": "./models/Qwen2.5-7B-Instruct", "embedding_model": "./models/all-MiniLM-L6-v2" }}1234568 unmodified lines151617171819202122smolagents>=0.5.0transformers>=4.36.0torch>=2.0.0gradio>=4.0.0pandas>=1.5.0pdfplumber>=0.10.08 unmodified lineslangchain>=0.1.0langchain-community>=0.0.13langchain-huggingface>=0.3.0faiss-cpu>=1.7.4faiss-cpu>=1.7.4accelerate>=0.20.0bitsandbytes>=0.41.0safetensors>=0.3.0sentence-transformers>=2.2.2.gitignore+2-1
LOCAL_MODELS_GUIDE.mdAdded+260
QUICK_LOCAL_SETUP.mdAdded+105
README.md+29
config.py+148-4
download_models.pyAdded+230
evaluation.py+141
hf_agent.py+169-18
local_config.jsonAdded+13
requirements.txt+6-1