sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
unclecode/crawl4ai:docs/releases_review/demo_v0.7.0.py
""" 🚀 Crawl4AI v0.7.0 Release Demo ================================ This demo showcases all major features introduced in v0.7.0 release. Major Features: 1. ✅ Adaptive Crawling - Intelligent crawling with confidence tracking 2. ✅ Virtual Scroll Support - Handle infinite scroll pages 3. ✅ Link Preview - Advanced link analysis with 3-layer scoring 4. ✅ URL Seeder - Smart URL discovery and filtering 5. ✅ C4A Script - Domain-specific language for web automation 6. ✅ Chrome Extension Updates - Click2Crawl and instant schema extraction 7. ✅ PDF Parsing Support - Extract content from PDF documents 8. ✅ Nightly Builds - Automated nightly releases Run this demo to see all features in action! """ import asyncio import json from typing import List, Dict from rich.console import Console from rich.table import Table from rich.panel import Panel from rich import box from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, BrowserConfig, CacheMode, AdaptiveCrawler, AdaptiveConfig, AsyncUrlSeeder, SeedingConfig, c4a_compile, CompilationResult ) from crawl4ai.async_configs import VirtualScrollConfig, LinkPreviewConfig from crawl4ai.extraction_strategy import JsonCssExtractionStrategy console = Console() def print_section(title: str, description: str = ""): """Print a section header""" console.print(f"\n[bold cyan]{'=' * 60}[/bold cyan]") console.print(f"[bold yellow]{title}[/bold yellow]") if description: console.print(f"[dim]{description}[/dim]") console.print(f"[bold cyan]{'=' * 60}[/bold cyan]\n") async def demo_1_adaptive_crawling(): """Demo 1: Adaptive Crawling - Intelligent content extraction""" print_section( "Demo 1: Adaptive Crawling", "Intelligently learns and adapts to website patterns" ) # Create adaptive crawler with custom configuration config = AdaptiveConfig( strategy="statistical", # or "embedding" confidence_threshold=0.7, max_pages=10, top_k_links=3, min_gain_threshold=0.1 ) # Example: Learn from a product page console.print("[cyan]Learning from product page patterns...[/cyan]") async with AsyncWebCrawler() as crawler: adaptive = AdaptiveCrawler(crawler, config) # Start adaptive crawl console.print("[cyan]Starting adaptive crawl...[/cyan]") result = await adaptive.digest( start_url="https://docs.python.org/3/", query="python decorators tutorial" ) console.print("[green]✓ Adaptive crawl completed[/green]") console.print(f" - Confidence Level: {adaptive.confidence:.0%}") console.print(f" - Pages Crawled: {len(result.crawled_urls)}") console.print(f" - Knowledge Base: {len(adaptive.state.knowledge_base)} documents") # Get most relevant content relevant = adaptive.get_relevant_content(top_k=3) if relevant: console.print("\nMost relevant pages:") for i, page in enumerate(relevant, 1): console.print(f" {i}. {page['url']} (relevance: {page['score']:.2%})") async def demo_2_virtual_scroll(): """Demo 2: Virtual Scroll - Handle infinite scroll pages""" print_section( "Demo 2: Virtual Scroll Support", "Capture content from modern infinite scroll pages" ) # Configure virtual scroll - using body as container for example.com scroll_config = VirtualScrollConfig( container_selector="body", # Using body since example.com has simple structure scroll_count=3, # Just 3 scrolls for demo scroll_by="container_height", # or "page_height" or pixel value wait_after_scroll=0.5 # Wait 500ms after each scroll ) config = CrawlerRunConfig( virtual_scroll_config=scroll_config, cache_mode=CacheMode.BYPASS, wait_until="networkidle" ) console.print("[cyan]Virtual Scroll Configuration:[/cyan]") console.print(f" - Container: {scroll_config.container_selector}") console.print(f" - Scroll count: {scroll_config.scroll_count}") console.print(f" - Scroll by: {scroll_config.scroll_by}") console.print(f" - Wait after scroll: {scroll_config.wait_after_scroll}s") console.print("\n[dim]Note: Using example.com for demo - in production, use this[/dim]") console.print("[dim]with actual infinite scroll pages like social media feeds.[/dim]\n") async with AsyncWebCrawler() as crawler: result = await crawler.arun( "https://example.com", config=config ) if result.success: console.print("[green]✓ Virtual scroll executed successfully![/green]") console.print(f" - Content length: {len(result.markdown)} chars") # Show example of how to use with real infinite scroll sites console.print("\n[yellow]Example for real infinite scroll sites:[/yellow]") console.print(""" # For Twitter-like feeds: scroll_config = VirtualScrollConfig( container_selector="[data-testid='primaryColumn']", scroll_count=20, scroll_by="container_height", wait_after_scroll=1.0 ) # For Instagram-like grids: scroll_config = VirtualScrollConfig( container_selector="main article", scroll_count=15, scroll_by=1000, # Fixed pixel amount wait_after_scroll=1.5 )""") async def demo_3_link_preview(): """Demo 3: Link Preview with 3-layer scoring""" print_section( "Demo 3: Link Preview & Scoring", "Advanced link analysis with intrinsic, contextual, and total scoring" ) # Configure link preview link_config = LinkPreviewConfig( include_internal=True, include_external=False, max_links=10, concurrency=5, query="python tutorial", # For contextual scoring score_threshold=0.3, verbose=True ) config = CrawlerRunConfig( link_preview_config=link_config, score_links=True, # Enable intrinsic scoring cache_mode=CacheMode.BYPASS ) console.print("[cyan]Analyzing links with 3-layer scoring system...[/cyan]") async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://docs.python.org/3/", config=config) if result.success and result.links: # Get scored links internal_links = result.links.get("internal", []) scored_links = [l for l in internal_links if l.get("total_score")] scored_links.sort(key=lambda x: x.get("total_score", 0), reverse=True) # Create a scoring table table = Table(title="Link Scoring Results", box=box.ROUNDED) table.add_column("Link Text", style="cyan", width=40) table.add_column("Intrinsic Score", justify="center") table.add_column("Contextual Score", justify="center") table.add_column("Total Score", justify="center", style="bold green") for link in scored_links[:5]: text = link.get('text', 'No text')[:40] table.add_row( text, f"{link.get('intrinsic_score', 0):.1f}/10", f"{link.get('contextual_score', 0):.2f}/1", f"{link.get('total_score', 0):.3f}" ) console.print(table) async def demo_4_url_seeder(): """Demo 4: URL Seeder - Smart URL discovery""" print_section( "Demo 4: URL Seeder", "Intelligent URL discovery and filtering" ) # Configure seeding seeding_config = SeedingConfig( source="cc+sitemap", # or "crawl" pattern="*tutorial*", # URL pattern filter max_urls=50, extract_head=True, # Get metadata query="python programming", # For relevance scoring scoring_method="bm25", score_threshold=0.2, force = True ) console.print("[cyan]URL Seeder Configuration:[/cyan]") console.print(f" - Source: {seeding_config.source}") console.print(f" - Pattern: {seeding_config.pattern}") console.print(f" - Max URLs: {seeding_config.max_urls}") console.print(f" - Query: {seeding_config.query}") console.print(f" - Scoring: {seeding_config.scoring_method}") # Use URL seeder to discover URLs async with AsyncUrlSeeder() as seeder: console.print("\n[cyan]Discovering URLs from Python docs...[/cyan]") urls = await seeder.urls("docs.python.org", seeding_config) console.print(f"\n[green]✓ Discovered {len(urls)} URLs[/green]") for i, url_info in enumerate(urls[:5], 1): console.print(f" {i}. {url_info['url']}") if url_info.get('relevance_score'): console.print(f" Relevance: {url_info['relevance_score']:.3f}") async def demo_5_c4a_script(): """Demo 5: C4A Script - Domain-specific language""" print_section( "Demo 5: C4A Script Language", "Domain-specific language for web automation" ) # Example C4A script c4a_script = """ # Simple C4A script example WAIT `body` 3 IF (EXISTS `.cookie-banner`) THEN CLICK `.accept` CLICK `.search-button` TYPE "python tutorial" PRESS Enter WAIT `.results` 5 """ console.print("[cyan]C4A Script Example:[/cyan]") console.print(Panel(c4a_script, title="script.c4a", border_style="blue")) # Compile the script compilation_result = c4a_compile(c4a_script) if compilation_result.success: console.print("[green]✓ Script compiled successfully![/green]") console.print(f" - Generated {len(compilation_result.js_code)} JavaScript statements") console.print("\nFirst 3 JS statements:") for stmt in compilation_result.js_code[:3]: console.print(f" • {stmt}") else: console.print("[red]✗ Script compilation failed[/red]") if compilation_result.first_error: error = compilation_result.first_error console.print(f" Error at line {error.line}: {error.message}") async def demo_6_css_extraction(): """Demo 6: Enhanced CSS/JSON extraction""" print_section( "Demo 6: Enhanced Extraction", "Improved CSS selector and JSON extraction" ) # Define extraction schema schema = { "name": "Example Page Data", "baseSelector": "body", "fields": [ { "name": "title", "selector": "h1", "type": "text" }, { "name": "paragraphs", "selector": "p", "type": "list", "fields": [ {"name": "text", "type": "text"} ] } ] } extraction_strategy = JsonCssExtractionStrategy(schema) console.print("[cyan]Extraction Schema:[/cyan]") console.print(json.dumps(schema, indent=2)) async with AsyncWebCrawler() as crawler: result = await crawler.arun( "https://example.com", config=CrawlerRunConfig( extraction_strategy=extraction_strategy, cache_mode=CacheMode.BYPASS ) ) if result.success and result.extracted_content: console.print("\n[green]✓ Content extracted successfully![/green]") console.print(f"Extracted: {json.dumps(json.loads(result.extracted_content), indent=2)[:200]}...") async def demo_7_performance_improvements(): """Demo 7: Performance improvements""" print_section( "Demo 7: Performance Improvements", "Faster crawling with better resource management" ) # Performance-optimized configuration config = CrawlerRunConfig( cache_mode=CacheMode.ENABLED, # Use caching wait_until="domcontentloaded", # Faster than networkidle page_timeout=10000, # 10 second timeout exclude_external_links=True, exclude_social_media_links=True, exclude_external_images=True ) console.print("[cyan]Performance Configuration:[/cyan]") console.print(" - Cache: ENABLED") console.print(" - Wait: domcontentloaded (faster)") console.print(" - Timeout: 10s") console.print(" - Excluding: external links, images, social media") # Measure performance import time start_time = time.time() async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://example.com", config=config) elapsed = time.time() - start_time if result.success: console.print(f"\n[green]✓ Page crawled in {elapsed:.2f} seconds[/green]") async def main(): """Run all demos""" console.print(Panel( "[bold cyan]Crawl4AI v0.7.0 Release Demo[/bold cyan]\n\n" "This demo showcases all major features introduced in v0.7.0.\n" "Each demo is self-contained and demonstrates a specific feature.", title="Welcome", border_style="blue" )) demos = [ demo_1_adaptive_crawling, demo_2_virtual_scroll, demo_3_link_preview, demo_4_url_seeder, demo_5_c4a_script, demo_6_css_extraction, demo_7_performance_improvements ] for i, demo in enumerate(demos, 1): try: await demo() if i < len(demos): console.print("\n[dim]Press Enter to continue to next demo...[/dim]") input() except Exception as e: console.print(f"[red]Error in demo: {e}[/red]") continue console.print(Panel( "[bold green]Demo Complete![/bold green]\n\n" "Thank you for trying Crawl4AI v0.7.0!\n" "For more examples and documentation, visit:\n" "https://github.com/unclecode/crawl4ai", title="Complete", border_style="green" )) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/releases_review/demo_v0.7.0.py", "license": "Apache License 2.0", "lines": 340, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/releases_review/v0_7_0_features_demo.py
""" 🚀 Crawl4AI v0.7.0 Feature Demo ================================ This file demonstrates the major features introduced in v0.7.0 with practical examples. """ import asyncio import json from pathlib import Path from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, BrowserConfig, CacheMode, # New imports for v0.7.0 VirtualScrollConfig, LinkPreviewConfig, AdaptiveCrawler, AdaptiveConfig, AsyncUrlSeeder, SeedingConfig, c4a_compile, ) async def demo_link_preview(): """ Demo 1: Link Preview with 3-Layer Scoring Shows how to analyze links with intrinsic quality scores, contextual relevance, and combined total scores. """ print("\n" + "="*60) print("🔗 DEMO 1: Link Preview & Intelligent Scoring") print("="*60) # Configure link preview with contextual scoring config = CrawlerRunConfig( link_preview_config=LinkPreviewConfig( include_internal=True, include_external=False, max_links=10, concurrency=5, query="machine learning tutorials", # For contextual scoring score_threshold=0.3, # Minimum relevance verbose=True ), score_links=True, # Enable intrinsic scoring cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://scikit-learn.org/stable/", config=config) if result.success: # Get scored links internal_links = result.links.get("internal", []) scored_links = [l for l in internal_links if l.get("total_score")] scored_links.sort(key=lambda x: x.get("total_score", 0), reverse=True) print(f"\nTop 5 Most Relevant Links:") for i, link in enumerate(scored_links[:5], 1): print(f"\n{i}. {link.get('text', 'No text')[:50]}...") print(f" URL: {link['href']}") print(f" Intrinsic Score: {link.get('intrinsic_score', 0):.2f}/10") print(f" Contextual Score: {link.get('contextual_score', 0):.3f}") print(f" Total Score: {link.get('total_score', 0):.3f}") # Show metadata if available if link.get('head_data'): title = link['head_data'].get('title', 'No title') print(f" Title: {title[:60]}...") async def demo_adaptive_crawling(): """ Demo 2: Adaptive Crawling Shows intelligent crawling that stops when enough information is gathered, with confidence tracking. """ print("\n" + "="*60) print("🎯 DEMO 2: Adaptive Crawling with Confidence Tracking") print("="*60) # Configure adaptive crawler config = AdaptiveConfig( strategy="statistical", # or "embedding" for semantic understanding max_pages=10, confidence_threshold=0.7, # Stop at 70% confidence top_k_links=3, # Follow top 3 links per page min_gain_threshold=0.05 # Need 5% information gain to continue ) async with AsyncWebCrawler(verbose=False) as crawler: adaptive = AdaptiveCrawler(crawler, config) print("Starting adaptive crawl about Python decorators...") result = await adaptive.digest( start_url="https://docs.python.org/3/glossary.html", query="python decorators functions wrapping" ) print(f"\n✅ Crawling Complete!") print(f"• Confidence Level: {adaptive.confidence:.0%}") print(f"• Pages Crawled: {len(result.crawled_urls)}") print(f"• Knowledge Base: {len(adaptive.state.knowledge_base)} documents") # Get most relevant content relevant = adaptive.get_relevant_content(top_k=3) print(f"\nMost Relevant Pages:") for i, page in enumerate(relevant, 1): print(f"{i}. {page['url']} (relevance: {page['score']:.2%})") async def demo_virtual_scroll(): """ Demo 3: Virtual Scroll for Modern Web Pages Shows how to capture content from pages with DOM recycling (Twitter, Instagram, infinite scroll). """ print("\n" + "="*60) print("📜 DEMO 3: Virtual Scroll Support") print("="*60) # Configure virtual scroll for a news site virtual_config = VirtualScrollConfig( container_selector="main, article, .content", # Common containers scroll_count=20, # Scroll up to 20 times scroll_by="container_height", # Scroll by container height wait_after_scroll=0.5 # Wait 500ms after each scroll ) config = CrawlerRunConfig( virtual_scroll_config=virtual_config, cache_mode=CacheMode.BYPASS, wait_for="css:article" # Wait for articles to load ) # Example with a real news site async with AsyncWebCrawler() as crawler: result = await crawler.arun( "https://news.ycombinator.com/", config=config ) if result.success: # Count items captured import re items = len(re.findall(r'class="athing"', result.html)) print(f"\n✅ Captured {items} news items") print(f"• HTML size: {len(result.html):,} bytes") print(f"• Without virtual scroll, would only capture ~30 items") async def demo_url_seeder(): """ Demo 4: URL Seeder for Intelligent Discovery Shows how to discover and filter URLs before crawling, with relevance scoring. """ print("\n" + "="*60) print("🌱 DEMO 4: URL Seeder - Smart URL Discovery") print("="*60) async with AsyncUrlSeeder() as seeder: # Discover Python tutorial URLs config = SeedingConfig( source="sitemap", # Use sitemap pattern="*python*", # URL pattern filter extract_head=True, # Get metadata query="python tutorial", # For relevance scoring scoring_method="bm25", score_threshold=0.2, max_urls=10 ) print("Discovering Python async tutorial URLs...") urls = await seeder.urls("https://www.geeksforgeeks.org/", config) print(f"\n✅ Found {len(urls)} relevant URLs:") for i, url_info in enumerate(urls[:5], 1): print(f"\n{i}. {url_info['url']}") if url_info.get('relevance_score'): print(f" Relevance: {url_info['relevance_score']:.3f}") if url_info.get('head_data', {}).get('title'): print(f" Title: {url_info['head_data']['title'][:60]}...") async def demo_c4a_script(): """ Demo 5: C4A Script Language Shows the domain-specific language for web automation with JavaScript transpilation. """ print("\n" + "="*60) print("🎭 DEMO 5: C4A Script - Web Automation Language") print("="*60) # Example C4A script c4a_script = """ # E-commerce automation script WAIT `body` 3 # Handle cookie banner IF (EXISTS `.cookie-banner`) THEN CLICK `.accept-cookies` # Search for product CLICK `.search-box` TYPE "wireless headphones" PRESS Enter # Wait for results WAIT `.product-grid` 10 # Load more products REPEAT (SCROLL DOWN 500, `document.querySelectorAll('.product').length < 50`) # Apply filter IF (EXISTS `.price-filter`) THEN CLICK `input[data-max-price="100"]` """ # Compile the script print("Compiling C4A script...") result = c4a_compile(c4a_script) if result.success: print(f"✅ Successfully compiled to {len(result.js_code)} JavaScript statements!") print("\nFirst 3 JS statements:") for stmt in result.js_code[:3]: print(f" • {stmt}") # Use with crawler config = CrawlerRunConfig( c4a_script=c4a_script, # Pass C4A script directly cache_mode=CacheMode.BYPASS ) print("\n✅ Script ready for use with AsyncWebCrawler!") else: print(f"❌ Compilation error: {result.first_error.message}") async def main(): """Run all demos""" print("\n🚀 Crawl4AI v0.7.0 Feature Demonstrations") print("=" * 60) demos = [ ("Link Preview & Scoring", demo_link_preview), ("Adaptive Crawling", demo_adaptive_crawling), ("Virtual Scroll", demo_virtual_scroll), ("URL Seeder", demo_url_seeder), ("C4A Script", demo_c4a_script), ] for name, demo_func in demos: try: await demo_func() except Exception as e: print(f"\n❌ Error in {name} demo: {str(e)}") # Pause between demos await asyncio.sleep(1) print("\n" + "="*60) print("✅ All demos completed!") print("\nKey Takeaways:") print("• Link Preview: 3-layer scoring for intelligent link analysis") print("• Adaptive Crawling: Stop when you have enough information") print("• Virtual Scroll: Capture all content from modern web pages") print("• URL Seeder: Pre-discover and filter URLs efficiently") print("• C4A Script: Simple language for complex automations") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/releases_review/v0_7_0_features_demo.py", "license": "Apache License 2.0", "lines": 229, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:tests/adaptive/compare_performance.py
""" Compare performance before and after optimizations """ def read_baseline(): """Read baseline performance metrics""" with open('performance_baseline.txt', 'r') as f: content = f.read() # Extract key metrics metrics = {} lines = content.split('\n') for i, line in enumerate(lines): if 'Total Time:' in line: metrics['total_time'] = float(line.split(':')[1].strip().split()[0]) elif 'Memory Used:' in line: metrics['memory_mb'] = float(line.split(':')[1].strip().split()[0]) elif 'validate_coverage:' in line and i+1 < len(lines) and 'Avg Time:' in lines[i+2]: metrics['validate_coverage_ms'] = float(lines[i+2].split(':')[1].strip().split()[0]) elif 'select_links:' in line and i+1 < len(lines) and 'Avg Time:' in lines[i+2]: metrics['select_links_ms'] = float(lines[i+2].split(':')[1].strip().split()[0]) elif 'calculate_confidence:' in line and i+1 < len(lines) and 'Avg Time:' in lines[i+2]: metrics['calculate_confidence_ms'] = float(lines[i+2].split(':')[1].strip().split()[0]) return metrics def print_comparison(before_metrics, after_metrics): """Print performance comparison""" print("\n" + "="*80) print("PERFORMANCE COMPARISON: BEFORE vs AFTER OPTIMIZATIONS") print("="*80) # Total time time_improvement = (before_metrics['total_time'] - after_metrics['total_time']) / before_metrics['total_time'] * 100 print(f"\n📊 Total Time:") print(f" Before: {before_metrics['total_time']:.2f} seconds") print(f" After: {after_metrics['total_time']:.2f} seconds") print(f" Improvement: {time_improvement:.1f}% faster ✅" if time_improvement > 0 else f" Slower: {-time_improvement:.1f}% ❌") # Memory mem_improvement = (before_metrics['memory_mb'] - after_metrics['memory_mb']) / before_metrics['memory_mb'] * 100 print(f"\n💾 Memory Usage:") print(f" Before: {before_metrics['memory_mb']:.2f} MB") print(f" After: {after_metrics['memory_mb']:.2f} MB") print(f" Improvement: {mem_improvement:.1f}% less memory ✅" if mem_improvement > 0 else f" More memory: {-mem_improvement:.1f}% ❌") # Key operations print(f"\n⚡ Key Operations:") # Validate coverage if 'validate_coverage_ms' in before_metrics and 'validate_coverage_ms' in after_metrics: val_improvement = (before_metrics['validate_coverage_ms'] - after_metrics['validate_coverage_ms']) / before_metrics['validate_coverage_ms'] * 100 print(f"\n validate_coverage:") print(f" Before: {before_metrics['validate_coverage_ms']:.1f} ms") print(f" After: {after_metrics['validate_coverage_ms']:.1f} ms") print(f" Improvement: {val_improvement:.1f}% faster ✅" if val_improvement > 0 else f" Slower: {-val_improvement:.1f}% ❌") # Select links if 'select_links_ms' in before_metrics and 'select_links_ms' in after_metrics: sel_improvement = (before_metrics['select_links_ms'] - after_metrics['select_links_ms']) / before_metrics['select_links_ms'] * 100 print(f"\n select_links:") print(f" Before: {before_metrics['select_links_ms']:.1f} ms") print(f" After: {after_metrics['select_links_ms']:.1f} ms") print(f" Improvement: {sel_improvement:.1f}% faster ✅" if sel_improvement > 0 else f" Slower: {-sel_improvement:.1f}% ❌") # Calculate confidence if 'calculate_confidence_ms' in before_metrics and 'calculate_confidence_ms' in after_metrics: calc_improvement = (before_metrics['calculate_confidence_ms'] - after_metrics['calculate_confidence_ms']) / before_metrics['calculate_confidence_ms'] * 100 print(f"\n calculate_confidence:") print(f" Before: {before_metrics['calculate_confidence_ms']:.1f} ms") print(f" After: {after_metrics['calculate_confidence_ms']:.1f} ms") print(f" Improvement: {calc_improvement:.1f}% faster ✅" if calc_improvement > 0 else f" Slower: {-calc_improvement:.1f}% ❌") print("\n" + "="*80) # Overall assessment if time_improvement > 50: print("🎉 EXCELLENT OPTIMIZATION! More than 50% performance improvement!") elif time_improvement > 30: print("✅ GOOD OPTIMIZATION! Significant performance improvement!") elif time_improvement > 10: print("👍 DECENT OPTIMIZATION! Noticeable performance improvement!") else: print("🤔 MINIMAL IMPROVEMENT. Further optimization may be needed.") print("="*80) if __name__ == "__main__": # Example usage - you'll run this after implementing optimizations baseline = read_baseline() print("Baseline metrics loaded:") for k, v in baseline.items(): print(f" {k}: {v}") print("\n⚠️ Run the performance test again after optimizations to compare!") print("Then update this script with the new metrics to see the comparison.")
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/adaptive/compare_performance.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/adaptive/test_adaptive_crawler.py
""" Test and demo script for Adaptive Crawler This script demonstrates the progressive crawling functionality with various configurations and use cases. """ import asyncio import json from pathlib import Path import time from typing import Dict, List from rich.console import Console from rich.table import Table from rich.progress import Progress from rich import print as rprint # Add parent directory to path for imports import sys sys.path.append(str(Path(__file__).parent.parent)) from crawl4ai import ( AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig, CrawlState ) console = Console() def print_relevant_content(crawler: AdaptiveCrawler, top_k: int = 3): """Print most relevant content found""" relevant = crawler.get_relevant_content(top_k=top_k) if not relevant: console.print("[yellow]No relevant content found yet.[/yellow]") return console.print(f"\n[bold cyan]Top {len(relevant)} Most Relevant Pages:[/bold cyan]") for i, doc in enumerate(relevant, 1): console.print(f"\n[green]{i}. {doc['url']}[/green]") console.print(f" Score: {doc['score']:.2f}") # Show snippet content = doc['content'] or "" snippet = content[:200].replace('\n', ' ') + "..." if len(content) > 200 else content console.print(f" [dim]{snippet}[/dim]") async def test_basic_progressive_crawl(): """Test basic progressive crawling functionality""" console.print("\n[bold yellow]Test 1: Basic Progressive Crawl[/bold yellow]") console.print("Testing on Python documentation with query about async/await") config = AdaptiveConfig( confidence_threshold=0.7, max_pages=10, top_k_links=2, min_gain_threshold=0.1 ) # Create crawler async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler( crawler=crawler, config=config ) # Start progressive crawl start_time = time.time() state = await prog_crawler.digest( start_url="https://docs.python.org/3/library/asyncio.html", query="async await context managers" ) elapsed = time.time() - start_time # Print results prog_crawler.print_stats(detailed=False) prog_crawler.print_stats(detailed=True) print_relevant_content(prog_crawler) console.print(f"\n[green]Crawl completed in {elapsed:.2f} seconds[/green]") console.print(f"Final confidence: {prog_crawler.confidence:.2%}") console.print(f"URLs crawled: {list(state.crawled_urls)[:5]}...") # Show first 5 # Test export functionality export_path = "knowledge_base_export.jsonl" prog_crawler.export_knowledge_base(export_path) console.print(f"[green]Knowledge base exported to {export_path}[/green]") # Clean up Path(export_path).unlink(missing_ok=True) async def test_with_persistence(): """Test state persistence and resumption""" console.print("\n[bold yellow]Test 2: Persistence and Resumption[/bold yellow]") console.print("Testing state save/load functionality") state_path = "test_crawl_state.json" config = AdaptiveConfig( confidence_threshold=0.6, max_pages=5, top_k_links=2, save_state=True, state_path=state_path ) # First crawl - partial async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler( crawler=crawler, config=config ) state1 = await prog_crawler.digest( start_url="https://httpbin.org", query="http headers response" ) console.print(f"[cyan]First crawl: {len(state1.crawled_urls)} pages[/cyan]") # Resume crawl config.max_pages = 10 # Increase limit async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler( crawler=crawler, config=config ) state2 = await prog_crawler.digest( start_url="https://httpbin.org", query="http headers response", resume_from=state_path ) console.print(f"[green]Resumed crawl: {len(state2.crawled_urls)} total pages[/green]") # Clean up Path(state_path).unlink(missing_ok=True) async def test_different_domains(): """Test on different types of websites""" console.print("\n[bold yellow]Test 3: Different Domain Types[/bold yellow]") test_cases = [ { "name": "Documentation Site", "url": "https://docs.python.org/3/", "query": "decorators and context managers" }, { "name": "API Documentation", "url": "https://httpbin.org", "query": "http authentication headers" } ] for test in test_cases: console.print(f"\n[cyan]Testing: {test['name']}[/cyan]") console.print(f"URL: {test['url']}") console.print(f"Query: {test['query']}") config = AdaptiveConfig( confidence_threshold=0.6, max_pages=5, top_k_links=2 ) async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler( crawler=crawler, config=config ) start_time = time.time() state = await prog_crawler.digest( start_url=test['url'], query=test['query'] ) elapsed = time.time() - start_time # Summary using print_stats prog_crawler.print_stats(detailed=False) async def test_stopping_criteria(): """Test different stopping criteria""" console.print("\n[bold yellow]Test 4: Stopping Criteria[/bold yellow]") # Test 1: High confidence threshold console.print("\n[cyan]4.1 High confidence threshold (0.9)[/cyan]") config = AdaptiveConfig( confidence_threshold=0.9, # Very high max_pages=20, top_k_links=3 ) async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler(crawler=crawler, config=config) state = await prog_crawler.digest( start_url="https://docs.python.org/3/library/", query="python standard library" ) console.print(f"Pages needed for 90% confidence: {len(state.crawled_urls)}") prog_crawler.print_stats(detailed=False) # Test 2: Page limit console.print("\n[cyan]4.2 Page limit (3 pages max)[/cyan]") config = AdaptiveConfig( confidence_threshold=0.9, max_pages=3, # Very low limit top_k_links=2 ) async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler(crawler=crawler, config=config) state = await prog_crawler.digest( start_url="https://docs.python.org/3/library/", query="python standard library modules" ) console.print(f"Stopped by: {'Page limit' if len(state.crawled_urls) >= 3 else 'Other'}") prog_crawler.print_stats(detailed=False) async def test_crawl_patterns(): """Analyze crawl patterns and link selection""" console.print("\n[bold yellow]Test 5: Crawl Pattern Analysis[/bold yellow]") config = AdaptiveConfig( confidence_threshold=0.7, max_pages=8, top_k_links=2, min_gain_threshold=0.05 ) async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler(crawler=crawler, config=config) # Track crawl progress console.print("\n[cyan]Crawl Progress:[/cyan]") state = await prog_crawler.digest( start_url="https://httpbin.org", query="http methods post get" ) # Show crawl order console.print("\n[green]Crawl Order:[/green]") for i, url in enumerate(state.crawl_order, 1): console.print(f"{i}. {url}") # Show new terms discovered per page console.print("\n[green]New Terms Discovered:[/green]") for i, new_terms in enumerate(state.new_terms_history, 1): console.print(f"Page {i}: {new_terms} new terms") # Final metrics console.print(f"\n[yellow]Saturation reached: {state.metrics.get('saturation', 0):.2%}[/yellow]") async def main(): """Run all tests""" console.print("[bold magenta]Adaptive Crawler Test Suite[/bold magenta]") console.print("=" * 50) try: # Run tests await test_basic_progressive_crawl() # await test_with_persistence() # await test_different_domains() # await test_stopping_criteria() # await test_crawl_patterns() console.print("\n[bold green]✅ All tests completed successfully![/bold green]") except Exception as e: console.print(f"\n[bold red]❌ Test failed with error: {e}[/bold red]") import traceback traceback.print_exc() if __name__ == "__main__": # Run the test suite asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/adaptive/test_adaptive_crawler.py", "license": "Apache License 2.0", "lines": 228, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/adaptive/test_confidence_debug.py
""" Test script for debugging confidence calculation in adaptive crawler Focus: Testing why confidence decreases when crawling relevant URLs """ import asyncio import sys from pathlib import Path from typing import List, Dict import math # Add parent directory to path for imports sys.path.append(str(Path(__file__).parent.parent)) from crawl4ai import AsyncWebCrawler from crawl4ai.adaptive_crawler import CrawlState, StatisticalStrategy from crawl4ai.models import CrawlResult class ConfidenceTestHarness: """Test harness for analyzing confidence calculation""" def __init__(self): self.strategy = StatisticalStrategy() self.test_urls = [ 'https://docs.python.org/3/library/asyncio.html', 'https://docs.python.org/3/library/asyncio-runner.html', 'https://docs.python.org/3/library/asyncio-api-index.html', 'https://docs.python.org/3/library/contextvars.html', 'https://docs.python.org/3/library/asyncio-stream.html' ] self.query = "async await context manager" async def test_confidence_progression(self): """Test confidence calculation as we crawl each URL""" print(f"Testing confidence for query: '{self.query}'") print("=" * 80) # Initialize state state = CrawlState(query=self.query) # Create crawler async with AsyncWebCrawler() as crawler: for i, url in enumerate(self.test_urls, 1): print(f"\n{i}. Crawling: {url}") print("-" * 80) # Crawl the URL result = await crawler.arun(url=url) # Extract markdown content if hasattr(result, '_results') and result._results: result = result._results[0] # Create a mock CrawlResult with markdown mock_result = type('CrawlResult', (), { 'markdown': type('Markdown', (), { 'raw_markdown': result.markdown.raw_markdown if hasattr(result, 'markdown') else '' })(), 'url': url })() # Update state state.knowledge_base.append(mock_result) await self.strategy.update_state(state, [mock_result]) # Calculate metrics confidence = await self.strategy.calculate_confidence(state) # Get individual components coverage = state.metrics.get('coverage', 0) consistency = state.metrics.get('consistency', 0) saturation = state.metrics.get('saturation', 0) # Analyze term frequencies query_terms = self.strategy._tokenize(self.query.lower()) term_stats = {} for term in query_terms: term_stats[term] = { 'tf': state.term_frequencies.get(term, 0), 'df': state.document_frequencies.get(term, 0) } # Print detailed results print(f"State after crawl {i}:") print(f" Total documents: {state.total_documents}") print(f" Unique terms: {len(state.term_frequencies)}") print(f" New terms added: {state.new_terms_history[-1] if state.new_terms_history else 0}") print(f"\nQuery term statistics:") for term, stats in term_stats.items(): print(f" '{term}': tf={stats['tf']}, df={stats['df']}") print(f"\nMetrics:") print(f" Coverage: {coverage:.3f}") print(f" Consistency: {consistency:.3f}") print(f" Saturation: {saturation:.3f}") print(f" → Confidence: {confidence:.3f}") # Show coverage calculation details print(f"\nCoverage calculation details:") self._debug_coverage_calculation(state, query_terms) # Alert if confidence decreased if i > 1 and confidence < state.metrics.get('prev_confidence', 0): print(f"\n⚠️ WARNING: Confidence decreased from {state.metrics.get('prev_confidence', 0):.3f} to {confidence:.3f}") state.metrics['prev_confidence'] = confidence def _debug_coverage_calculation(self, state: CrawlState, query_terms: List[str]): """Debug coverage calculation step by step""" coverage_score = 0.0 max_possible_score = 0.0 for term in query_terms: tf = state.term_frequencies.get(term, 0) df = state.document_frequencies.get(term, 0) if df > 0: idf = math.log((state.total_documents - df + 0.5) / (df + 0.5) + 1) doc_coverage = df / state.total_documents tf_boost = min(tf / df, 3.0) term_score = doc_coverage * idf * (1 + 0.1 * math.log1p(tf_boost)) print(f" '{term}': doc_cov={doc_coverage:.2f}, idf={idf:.2f}, boost={1 + 0.1 * math.log1p(tf_boost):.2f} → score={term_score:.3f}") coverage_score += term_score else: print(f" '{term}': not found → score=0.000") max_possible_score += 1.0 * 1.0 * 1.1 print(f" Total: {coverage_score:.3f} / {max_possible_score:.3f} = {coverage_score/max_possible_score if max_possible_score > 0 else 0:.3f}") # New coverage calculation print(f"\n NEW Coverage calculation (without IDF):") new_coverage = self._calculate_coverage_new(state, query_terms) print(f" → New Coverage: {new_coverage:.3f}") def _calculate_coverage_new(self, state: CrawlState, query_terms: List[str]) -> float: """New coverage calculation without IDF""" if not query_terms or state.total_documents == 0: return 0.0 term_scores = [] max_tf = max(state.term_frequencies.values()) if state.term_frequencies else 1 for term in query_terms: tf = state.term_frequencies.get(term, 0) df = state.document_frequencies.get(term, 0) if df > 0: # Document coverage: what fraction of docs contain this term doc_coverage = df / state.total_documents # Frequency signal: normalized log frequency freq_signal = math.log(1 + tf) / math.log(1 + max_tf) if max_tf > 0 else 0 # Combined score: document coverage with frequency boost term_score = doc_coverage * (1 + 0.5 * freq_signal) print(f" '{term}': doc_cov={doc_coverage:.2f}, freq_signal={freq_signal:.2f} → score={term_score:.3f}") term_scores.append(term_score) else: print(f" '{term}': not found → score=0.000") term_scores.append(0.0) # Average across all query terms coverage = sum(term_scores) / len(term_scores) return coverage async def main(): """Run the confidence test""" tester = ConfidenceTestHarness() await tester.test_confidence_progression() print("\n" + "=" * 80) print("Test complete!") if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/adaptive/test_confidence_debug.py", "license": "Apache License 2.0", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/adaptive/test_embedding_performance.py
""" Performance test for Embedding Strategy optimizations Measures time and memory usage before and after optimizations """ import asyncio import time import tracemalloc import numpy as np from pathlib import Path import sys import os # Add parent directory to path for imports sys.path.append(str(Path(__file__).parent.parent.parent)) from crawl4ai import AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig from crawl4ai.adaptive_crawler import EmbeddingStrategy, CrawlState from crawl4ai.models import CrawlResult class PerformanceMetrics: def __init__(self): self.start_time = 0 self.end_time = 0 self.start_memory = 0 self.peak_memory = 0 self.operation_times = {} def start(self): tracemalloc.start() self.start_time = time.perf_counter() self.start_memory = tracemalloc.get_traced_memory()[0] def end(self): self.end_time = time.perf_counter() current, peak = tracemalloc.get_traced_memory() self.peak_memory = peak tracemalloc.stop() def record_operation(self, name: str, duration: float): if name not in self.operation_times: self.operation_times[name] = [] self.operation_times[name].append(duration) @property def total_time(self): return self.end_time - self.start_time @property def memory_used_mb(self): return (self.peak_memory - self.start_memory) / 1024 / 1024 def print_summary(self, label: str): print(f"\n{'='*60}") print(f"Performance Summary: {label}") print(f"{'='*60}") print(f"Total Time: {self.total_time:.3f} seconds") print(f"Memory Used: {self.memory_used_mb:.2f} MB") if self.operation_times: print("\nOperation Breakdown:") for op, times in self.operation_times.items(): avg_time = sum(times) / len(times) total_time = sum(times) print(f" {op}:") print(f" - Calls: {len(times)}") print(f" - Avg Time: {avg_time*1000:.2f} ms") print(f" - Total Time: {total_time:.3f} s") async def create_mock_crawl_results(n: int) -> list: """Create mock crawl results for testing""" results = [] for i in range(n): class MockMarkdown: def __init__(self, content): self.raw_markdown = content class MockResult: def __init__(self, url, content): self.url = url self.markdown = MockMarkdown(content) self.success = True content = f"This is test content {i} about async await coroutines event loops. " * 50 result = MockResult(f"https://example.com/page{i}", content) results.append(result) return results async def test_embedding_performance(): """Test the performance of embedding strategy operations""" # Configuration n_kb_docs = 30 # Number of documents in knowledge base n_queries = 10 # Number of query variations n_links = 50 # Number of candidate links n_iterations = 5 # Number of calculation iterations print(f"\nTest Configuration:") print(f"- Knowledge Base Documents: {n_kb_docs}") print(f"- Query Variations: {n_queries}") print(f"- Candidate Links: {n_links}") print(f"- Iterations: {n_iterations}") # Create embedding strategy config = AdaptiveConfig( strategy="embedding", max_pages=50, n_query_variations=n_queries, embedding_model="sentence-transformers/all-MiniLM-L6-v2" # 384 dimensions ) # Set up API key if available if os.getenv('OPENAI_API_KEY'): config.embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY'), 'embedding_model': 'text-embedding-3-small' } else: config.embedding_llm_config = { 'provider': 'openai/gpt-4o-mini', 'api_token': 'dummy-key' } strategy = EmbeddingStrategy( embedding_model=config.embedding_model, llm_config=config.embedding_llm_config ) strategy.config = config # Initialize state state = CrawlState() state.query = "async await coroutines event loops tasks" # Start performance monitoring metrics = PerformanceMetrics() metrics.start() # 1. Generate query embeddings print("\n1. Generating query embeddings...") start = time.perf_counter() query_embeddings, expanded_queries = await strategy.map_query_semantic_space( state.query, config.n_query_variations ) state.query_embeddings = query_embeddings state.expanded_queries = expanded_queries metrics.record_operation("query_embedding", time.perf_counter() - start) print(f" Generated {len(query_embeddings)} query embeddings") # 2. Build knowledge base incrementally print("\n2. Building knowledge base...") mock_results = await create_mock_crawl_results(n_kb_docs) for i in range(0, n_kb_docs, 5): # Add 5 documents at a time batch = mock_results[i:i+5] start = time.perf_counter() await strategy.update_state(state, batch) metrics.record_operation("update_state", time.perf_counter() - start) state.knowledge_base.extend(batch) print(f" Knowledge base has {len(state.kb_embeddings)} documents") # 3. Test repeated confidence calculations print(f"\n3. Testing {n_iterations} confidence calculations...") for i in range(n_iterations): start = time.perf_counter() confidence = await strategy.calculate_confidence(state) metrics.record_operation("calculate_confidence", time.perf_counter() - start) print(f" Iteration {i+1}: {confidence:.3f} ({(time.perf_counter() - start)*1000:.1f} ms)") # 4. Test coverage gap calculations print(f"\n4. Testing coverage gap calculations...") for i in range(n_iterations): start = time.perf_counter() gaps = strategy.find_coverage_gaps(state.kb_embeddings, state.query_embeddings) metrics.record_operation("find_coverage_gaps", time.perf_counter() - start) print(f" Iteration {i+1}: {len(gaps)} gaps ({(time.perf_counter() - start)*1000:.1f} ms)") # 5. Test validation print(f"\n5. Testing validation coverage...") for i in range(n_iterations): start = time.perf_counter() val_score = await strategy.validate_coverage(state) metrics.record_operation("validate_coverage", time.perf_counter() - start) print(f" Iteration {i+1}: {val_score:.3f} ({(time.perf_counter() - start)*1000:.1f} ms)") # 6. Create mock links for ranking from crawl4ai.models import Link mock_links = [] for i in range(n_links): link = Link( href=f"https://example.com/new{i}", text=f"Link about async programming {i}", title=f"Async Guide {i}" ) mock_links.append(link) # 7. Test link selection print(f"\n6. Testing link selection with {n_links} candidates...") start = time.perf_counter() scored_links = await strategy.select_links_for_expansion( mock_links, gaps, state.kb_embeddings ) metrics.record_operation("select_links", time.perf_counter() - start) print(f" Scored {len(scored_links)} links in {(time.perf_counter() - start)*1000:.1f} ms") # End monitoring metrics.end() return metrics async def main(): """Run performance tests before and after optimizations""" print("="*80) print("EMBEDDING STRATEGY PERFORMANCE TEST") print("="*80) # Test current implementation print("\n📊 Testing CURRENT Implementation...") metrics_before = await test_embedding_performance() metrics_before.print_summary("BEFORE Optimizations") # Store key metrics for comparison total_time_before = metrics_before.total_time memory_before = metrics_before.memory_used_mb # Calculate specific operation costs calc_conf_avg = sum(metrics_before.operation_times.get("calculate_confidence", [])) / len(metrics_before.operation_times.get("calculate_confidence", [1])) find_gaps_avg = sum(metrics_before.operation_times.get("find_coverage_gaps", [])) / len(metrics_before.operation_times.get("find_coverage_gaps", [1])) validate_avg = sum(metrics_before.operation_times.get("validate_coverage", [])) / len(metrics_before.operation_times.get("validate_coverage", [1])) print(f"\n🔍 Key Bottlenecks Identified:") print(f" - calculate_confidence: {calc_conf_avg*1000:.1f} ms per call") print(f" - find_coverage_gaps: {find_gaps_avg*1000:.1f} ms per call") print(f" - validate_coverage: {validate_avg*1000:.1f} ms per call") print("\n" + "="*80) print("EXPECTED IMPROVEMENTS AFTER OPTIMIZATION:") print("- Distance calculations: 80-90% faster (vectorization)") print("- Memory usage: 20-30% reduction (deduplication)") print("- Overall performance: 60-70% improvement") print("="*80) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/adaptive/test_embedding_performance.py", "license": "Apache License 2.0", "lines": 208, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/adaptive/test_embedding_strategy.py
""" Test and demo script for Embedding-based Adaptive Crawler This script demonstrates the embedding-based adaptive crawling with semantic space coverage and gap-driven expansion. """ import asyncio import os from pathlib import Path import time from rich.console import Console from rich import print as rprint import sys # Add parent directory to path for imports sys.path.append(str(Path(__file__).parent.parent.parent)) from crawl4ai import ( AsyncWebCrawler, AdaptiveCrawler, AdaptiveConfig, CrawlState ) console = Console() async def test_basic_embedding_crawl(): """Test basic embedding-based adaptive crawling""" console.print("\n[bold yellow]Test 1: Basic Embedding-based Crawl[/bold yellow]") console.print("Testing semantic space coverage with query expansion") # Configure with embedding strategy config = AdaptiveConfig( strategy="embedding", confidence_threshold=0.7, # Not used for stopping in embedding strategy min_gain_threshold=0.01, max_pages=15, top_k_links=3, n_query_variations=8, embedding_model="sentence-transformers/all-MiniLM-L6-v2" # Fast, good quality ) # For query expansion, we need an LLM config llm_config = { 'provider': 'openai/gpt-4o-mini', 'api_token': os.getenv('OPENAI_API_KEY') } if not llm_config['api_token']: console.print("[red]Warning: OPENAI_API_KEY not set. Using mock data for demo.[/red]") # Continue with mock for demo purposes config.embedding_llm_config = llm_config # Create crawler async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler( crawler=crawler, config=config ) # Start adaptive crawl start_time = time.time() console.print("\n[cyan]Starting semantic adaptive crawl...[/cyan]") state = await prog_crawler.digest( start_url="https://docs.python.org/3/library/asyncio.html", query="async await coroutines event loops" ) elapsed = time.time() - start_time # Print results console.print(f"\n[green]Crawl completed in {elapsed:.2f} seconds[/green]") prog_crawler.print_stats(detailed=False) # Show semantic coverage details console.print("\n[bold cyan]Semantic Coverage Details:[/bold cyan]") if state.expanded_queries: console.print(f"Query expanded to {len(state.expanded_queries)} variations") console.print("Sample variations:") for i, q in enumerate(state.expanded_queries[:3], 1): console.print(f" {i}. {q}") if state.semantic_gaps: console.print(f"\nSemantic gaps identified: {len(state.semantic_gaps)}") console.print(f"\nFinal confidence: {prog_crawler.confidence:.2%}") console.print(f"Is Sufficient: {'Yes (Validated)' if prog_crawler.is_sufficient else 'No'}") console.print(f"Pages needed: {len(state.crawled_urls)}") async def test_embedding_vs_statistical(use_openai=False): """Compare embedding strategy with statistical strategy""" console.print("\n[bold yellow]Test 2: Embedding vs Statistical Strategy Comparison[/bold yellow]") test_url = "https://httpbin.org" test_query = "http headers authentication api" # Test 1: Statistical strategy console.print("\n[cyan]1. Statistical Strategy:[/cyan]") config_stat = AdaptiveConfig( strategy="statistical", confidence_threshold=0.7, max_pages=10 ) async with AsyncWebCrawler() as crawler: stat_crawler = AdaptiveCrawler(crawler=crawler, config=config_stat) start_time = time.time() state_stat = await stat_crawler.digest(start_url=test_url, query=test_query) stat_time = time.time() - start_time stat_pages = len(state_stat.crawled_urls) stat_confidence = stat_crawler.confidence # Test 2: Embedding strategy console.print("\n[cyan]2. Embedding Strategy:[/cyan]") config_emb = AdaptiveConfig( strategy="embedding", confidence_threshold=0.7, # Not used for stopping max_pages=10, n_query_variations=5, min_gain_threshold=0.01 ) # Use OpenAI if available or requested if use_openai and os.getenv('OPENAI_API_KEY'): config_emb.embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY'), 'embedding_model': 'text-embedding-3-small' } console.print("[cyan]Using OpenAI embeddings[/cyan]") else: # Default config will try sentence-transformers config_emb.embedding_llm_config = { 'provider': 'openai/gpt-4o-mini', 'api_token': os.getenv('OPENAI_API_KEY', 'dummy-key') } async with AsyncWebCrawler() as crawler: emb_crawler = AdaptiveCrawler(crawler=crawler, config=config_emb) start_time = time.time() state_emb = await emb_crawler.digest(start_url=test_url, query=test_query) emb_time = time.time() - start_time emb_pages = len(state_emb.crawled_urls) emb_confidence = emb_crawler.confidence # Compare results console.print("\n[bold green]Comparison Results:[/bold green]") console.print(f"Statistical: {stat_pages} pages in {stat_time:.2f}s, confidence: {stat_confidence:.2%}, sufficient: {stat_crawler.is_sufficient}") console.print(f"Embedding: {emb_pages} pages in {emb_time:.2f}s, confidence: {emb_confidence:.2%}, sufficient: {emb_crawler.is_sufficient}") if emb_pages < stat_pages: efficiency = ((stat_pages - emb_pages) / stat_pages) * 100 console.print(f"\n[green]Embedding strategy used {efficiency:.0f}% fewer pages![/green]") # Show validation info for embedding if hasattr(state_emb, 'metrics') and 'validation_confidence' in state_emb.metrics: console.print(f"Embedding validation score: {state_emb.metrics['validation_confidence']:.2%}") async def test_custom_embedding_provider(): """Test with different embedding providers""" console.print("\n[bold yellow]Test 3: Custom Embedding Provider[/bold yellow]") # Example with OpenAI embeddings config = AdaptiveConfig( strategy="embedding", confidence_threshold=0.8, # Not used for stopping max_pages=10, min_gain_threshold=0.01, n_query_variations=5 ) # Configure to use OpenAI embeddings instead of sentence-transformers config.embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY'), 'embedding_model': 'text-embedding-3-small' } if not config.embedding_llm_config['api_token']: console.print("[yellow]Skipping OpenAI embedding test - no API key[/yellow]") return async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler(crawler=crawler, config=config) console.print("Using OpenAI embeddings for semantic analysis...") state = await prog_crawler.digest( start_url="https://httpbin.org", query="api endpoints json response" ) prog_crawler.print_stats(detailed=False) async def test_knowledge_export_import(): """Test exporting and importing semantic knowledge bases""" console.print("\n[bold yellow]Test 4: Semantic Knowledge Base Export/Import[/bold yellow]") config = AdaptiveConfig( strategy="embedding", confidence_threshold=0.7, # Not used for stopping max_pages=5, min_gain_threshold=0.01, n_query_variations=4 ) # First crawl async with AsyncWebCrawler() as crawler: crawler1 = AdaptiveCrawler(crawler=crawler, config=config) console.print("\n[cyan]Building initial knowledge base...[/cyan]") state1 = await crawler1.digest( start_url="https://httpbin.org", query="http methods headers" ) # Export export_path = "semantic_kb.jsonl" crawler1.export_knowledge_base(export_path) console.print(f"[green]Exported {len(state1.knowledge_base)} documents with embeddings[/green]") # Import and continue async with AsyncWebCrawler() as crawler: crawler2 = AdaptiveCrawler(crawler=crawler, config=config) console.print("\n[cyan]Importing knowledge base...[/cyan]") crawler2.import_knowledge_base(export_path) # Continue with new query - should be faster console.print("\n[cyan]Extending with new query...[/cyan]") state2 = await crawler2.digest( start_url="https://httpbin.org", query="authentication oauth tokens" ) console.print(f"[green]Total knowledge base: {len(state2.knowledge_base)} documents[/green]") # Cleanup Path(export_path).unlink(missing_ok=True) async def test_gap_visualization(): """Visualize semantic gaps and coverage""" console.print("\n[bold yellow]Test 5: Semantic Gap Analysis[/bold yellow]") config = AdaptiveConfig( strategy="embedding", confidence_threshold=0.9, # Not used for stopping max_pages=8, n_query_variations=6, min_gain_threshold=0.01 ) async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler(crawler=crawler, config=config) # Initial crawl state = await prog_crawler.digest( start_url="https://docs.python.org/3/library/", query="concurrency threading multiprocessing" ) # Analyze gaps console.print("\n[bold cyan]Semantic Gap Analysis:[/bold cyan]") console.print(f"Query variations: {len(state.expanded_queries)}") console.print(f"Knowledge documents: {len(state.knowledge_base)}") console.print(f"Identified gaps: {len(state.semantic_gaps)}") if state.semantic_gaps: console.print("\n[yellow]Gap sizes (distance from coverage):[/yellow]") for i, (_, distance) in enumerate(state.semantic_gaps[:5], 1): console.print(f" Gap {i}: {distance:.3f}") # Show crawl progression console.print("\n[cyan]Crawl Order (gap-driven selection):[/cyan]") for i, url in enumerate(state.crawl_order[:5], 1): console.print(f" {i}. {url}") async def test_fast_convergence_with_relevant_query(): """Test that both strategies reach high confidence quickly with relevant queries""" console.print("\n[bold yellow]Test 7: Fast Convergence with Relevant Query[/bold yellow]") console.print("Testing that strategies reach 80%+ confidence within 2-3 batches") # Test scenarios test_cases = [ { "name": "Python Async Documentation", "url": "https://docs.python.org/3/library/asyncio.html", "query": "async await coroutines event loops tasks" } ] for test_case in test_cases: console.print(f"\n[bold cyan]Testing: {test_case['name']}[/bold cyan]") console.print(f"URL: {test_case['url']}") console.print(f"Query: {test_case['query']}") # Test Embedding Strategy console.print("\n[yellow]Embedding Strategy:[/yellow]") config_emb = AdaptiveConfig( strategy="embedding", confidence_threshold=0.8, max_pages=9, top_k_links=3, min_gain_threshold=0.01, n_query_variations=5 ) # Configure embeddings config_emb.embedding_llm_config = { 'provider': 'openai/gpt-4o-mini', 'api_token': os.getenv('OPENAI_API_KEY'), } async with AsyncWebCrawler() as crawler: emb_crawler = AdaptiveCrawler(crawler=crawler, config=config_emb) start_time = time.time() state = await emb_crawler.digest( start_url=test_case['url'], query=test_case['query'] ) # Get batch breakdown total_pages = len(state.crawled_urls) for i in range(0, total_pages, 3): batch_num = (i // 3) + 1 batch_pages = min(3, total_pages - i) pages_so_far = i + batch_pages estimated_confidence = state.metrics.get('confidence', 0) * (pages_so_far / total_pages) console.print(f"Batch {batch_num}: {batch_pages} pages → Confidence: {estimated_confidence:.1%} {'✅' if estimated_confidence >= 0.8 else '❌'}") final_confidence = emb_crawler.confidence console.print(f"[green]Final: {total_pages} pages → Confidence: {final_confidence:.1%} {'✅ (Sufficient!)' if emb_crawler.is_sufficient else '❌'}[/green]") # Show learning metrics for embedding if 'avg_min_distance' in state.metrics: console.print(f"[dim]Avg gap distance: {state.metrics['avg_min_distance']:.3f}[/dim]") if 'validation_confidence' in state.metrics: console.print(f"[dim]Validation score: {state.metrics['validation_confidence']:.1%}[/dim]") # Test Statistical Strategy console.print("\n[yellow]Statistical Strategy:[/yellow]") config_stat = AdaptiveConfig( strategy="statistical", confidence_threshold=0.8, max_pages=9, top_k_links=3, min_gain_threshold=0.01 ) async with AsyncWebCrawler() as crawler: stat_crawler = AdaptiveCrawler(crawler=crawler, config=config_stat) # Track batch progress batch_results = [] current_pages = 0 # Custom batch tracking start_time = time.time() state = await stat_crawler.digest( start_url=test_case['url'], query=test_case['query'] ) # Get batch breakdown (every 3 pages) total_pages = len(state.crawled_urls) for i in range(0, total_pages, 3): batch_num = (i // 3) + 1 batch_pages = min(3, total_pages - i) # Estimate confidence at this point (simplified) pages_so_far = i + batch_pages estimated_confidence = state.metrics.get('confidence', 0) * (pages_so_far / total_pages) console.print(f"Batch {batch_num}: {batch_pages} pages → Confidence: {estimated_confidence:.1%} {'✅' if estimated_confidence >= 0.8 else '❌'}") final_confidence = stat_crawler.confidence console.print(f"[green]Final: {total_pages} pages → Confidence: {final_confidence:.1%} {'✅ (Sufficient!)' if stat_crawler.is_sufficient else '❌'}[/green]") async def test_irrelevant_query_behavior(): """Test how embedding strategy handles completely irrelevant queries""" console.print("\n[bold yellow]Test 8: Irrelevant Query Behavior[/bold yellow]") console.print("Testing embedding strategy with a query that has no semantic relevance to the content") # Test with irrelevant query on Python async documentation test_case = { "name": "Irrelevant Query on Python Docs", "url": "https://docs.python.org/3/library/asyncio.html", "query": "how to cook fried rice with vegetables" } console.print(f"\n[bold cyan]Testing: {test_case['name']}[/bold cyan]") console.print(f"URL: {test_case['url']} (Python async documentation)") console.print(f"Query: '{test_case['query']}' (completely irrelevant)") console.print("\n[dim]Expected behavior: Low confidence, high distances, no convergence[/dim]") # Configure embedding strategy config_emb = AdaptiveConfig( strategy="embedding", confidence_threshold=0.8, max_pages=9, top_k_links=3, min_gain_threshold=0.01, n_query_variations=5, embedding_min_relative_improvement=0.05, # Lower threshold to see more iterations embedding_min_confidence_threshold=0.1 # Will stop if confidence < 10% ) # Configure embeddings using the correct format config_emb.embedding_llm_config = { 'provider': 'openai/gpt-4o-mini', 'api_token': os.getenv('OPENAI_API_KEY'), } async with AsyncWebCrawler() as crawler: emb_crawler = AdaptiveCrawler(crawler=crawler, config=config_emb) start_time = time.time() state = await emb_crawler.digest( start_url=test_case['url'], query=test_case['query'] ) elapsed = time.time() - start_time # Analyze results console.print(f"\n[bold]Results after {elapsed:.1f} seconds:[/bold]") # Basic metrics total_pages = len(state.crawled_urls) final_confidence = emb_crawler.confidence console.print(f"\nPages crawled: {total_pages}") console.print(f"Final confidence: {final_confidence:.1%} {'✅' if emb_crawler.is_sufficient else '❌'}") # Distance metrics if 'avg_min_distance' in state.metrics: console.print(f"\n[yellow]Distance Metrics:[/yellow]") console.print(f" Average minimum distance: {state.metrics['avg_min_distance']:.3f}") console.print(f" Close neighbors (<0.3): {state.metrics.get('avg_close_neighbors', 0):.1f}") console.print(f" Very close neighbors (<0.2): {state.metrics.get('avg_very_close_neighbors', 0):.1f}") # Interpret distances avg_dist = state.metrics['avg_min_distance'] if avg_dist > 0.8: console.print(f" [red]→ Very poor match (distance > 0.8)[/red]") elif avg_dist > 0.6: console.print(f" [yellow]→ Poor match (distance > 0.6)[/yellow]") elif avg_dist > 0.4: console.print(f" [blue]→ Moderate match (distance > 0.4)[/blue]") else: console.print(f" [green]→ Good match (distance < 0.4)[/green]") # Show sample expanded queries if state.expanded_queries: console.print(f"\n[yellow]Sample Query Variations Generated:[/yellow]") for i, q in enumerate(state.expanded_queries[:3], 1): console.print(f" {i}. {q}") # Show crawl progression console.print(f"\n[yellow]Crawl Progression:[/yellow]") for i, url in enumerate(state.crawl_order[:5], 1): console.print(f" {i}. {url}") if len(state.crawl_order) > 5: console.print(f" ... and {len(state.crawl_order) - 5} more") # Validation score if 'validation_confidence' in state.metrics: console.print(f"\n[yellow]Validation:[/yellow]") console.print(f" Validation score: {state.metrics['validation_confidence']:.1%}") # Why it stopped if 'stopped_reason' in state.metrics: console.print(f"\n[yellow]Stopping Reason:[/yellow] {state.metrics['stopped_reason']}") if state.metrics.get('is_irrelevant', False): console.print("[red]→ Query and content are completely unrelated![/red]") elif total_pages >= config_emb.max_pages: console.print(f"\n[yellow]Stopping Reason:[/yellow] Reached max pages limit ({config_emb.max_pages})") # Summary console.print(f"\n[bold]Summary:[/bold]") if final_confidence < 0.2: console.print("[red]✗ As expected: Query is completely irrelevant to content[/red]") console.print("[green]✓ The embedding strategy correctly identified no semantic match[/green]") else: console.print(f"[yellow]⚠ Unexpected: Got {final_confidence:.1%} confidence for irrelevant query[/yellow]") console.print("[yellow] This may indicate the query variations are too broad[/yellow]") async def test_high_dimensional_handling(): """Test handling of high-dimensional embedding spaces""" console.print("\n[bold yellow]Test 6: High-Dimensional Embedding Space Handling[/bold yellow]") console.print("Testing how the system handles 384+ dimensional embeddings") config = AdaptiveConfig( strategy="embedding", confidence_threshold=0.8, # Not used for stopping max_pages=5, n_query_variations=8, # Will create 9 points total min_gain_threshold=0.01, embedding_model="sentence-transformers/all-MiniLM-L6-v2" # 384 dimensions ) # Use OpenAI if available, otherwise mock if os.getenv('OPENAI_API_KEY'): config.embedding_llm_config = { 'provider': 'openai/text-embedding-3-small', 'api_token': os.getenv('OPENAI_API_KEY'), 'embedding_model': 'text-embedding-3-small' } else: config.embedding_llm_config = { 'provider': 'openai/gpt-4o-mini', 'api_token': 'mock-key' } async with AsyncWebCrawler() as crawler: prog_crawler = AdaptiveCrawler(crawler=crawler, config=config) console.print("\n[cyan]Testing with high-dimensional embeddings (384D)...[/cyan]") try: state = await prog_crawler.digest( start_url="https://httpbin.org", query="api endpoints json" ) console.print(f"[green]✓ Successfully handled {len(state.expanded_queries)} queries in 384D space[/green]") console.print(f"Coverage shape type: {type(state.coverage_shape)}") if isinstance(state.coverage_shape, dict): console.print(f"Coverage model: centroid + radius") console.print(f" - Center shape: {state.coverage_shape['center'].shape if 'center' in state.coverage_shape else 'N/A'}") console.print(f" - Radius: {state.coverage_shape.get('radius', 'N/A'):.3f}") except Exception as e: console.print(f"[red]Error: {e}[/red]") console.print("[yellow]This demonstrates why alpha shapes don't work in high dimensions[/yellow]") async def main(): """Run all embedding strategy tests""" console.print("[bold magenta]Embedding-based Adaptive Crawler Test Suite[/bold magenta]") console.print("=" * 60) try: # Check if we have required dependencies has_sentence_transformers = True has_numpy = True try: import numpy console.print("[green]✓ NumPy installed[/green]") except ImportError: has_numpy = False console.print("[red]Missing numpy[/red]") # Try to import sentence_transformers but catch numpy compatibility errors try: import sentence_transformers console.print("[green]✓ Sentence-transformers installed[/green]") except (ImportError, RuntimeError, ValueError) as e: has_sentence_transformers = False console.print(f"[yellow]Warning: sentence-transformers not available[/yellow]") console.print("[yellow]Tests will use OpenAI embeddings if available or mock data[/yellow]") # Run tests based on available dependencies if has_numpy: # Check if we should use OpenAI for embeddings use_openai = not has_sentence_transformers and os.getenv('OPENAI_API_KEY') if not has_sentence_transformers and not os.getenv('OPENAI_API_KEY'): console.print("\n[red]Neither sentence-transformers nor OpenAI API key available[/red]") console.print("[yellow]Please set OPENAI_API_KEY or fix sentence-transformers installation[/yellow]") return # Run all tests # await test_basic_embedding_crawl() # await test_embedding_vs_statistical(use_openai=use_openai) # Run the fast convergence test - this is the most important one # await test_fast_convergence_with_relevant_query() # Test with irrelevant query await test_irrelevant_query_behavior() # Only run OpenAI-specific test if we have API key # if os.getenv('OPENAI_API_KEY'): # await test_custom_embedding_provider() # # Skip tests that require sentence-transformers when it's not available # if has_sentence_transformers: # await test_knowledge_export_import() # await test_gap_visualization() # else: # console.print("\n[yellow]Skipping tests that require sentence-transformers due to numpy compatibility issues[/yellow]") # This test should work with mock data # await test_high_dimensional_handling() else: console.print("\n[red]Cannot run tests without NumPy[/red]") return console.print("\n[bold green]✅ All tests completed![/bold green]") except Exception as e: console.print(f"\n[bold red]❌ Test failed: {e}[/bold red]") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/adaptive/test_embedding_strategy.py", "license": "Apache License 2.0", "lines": 500, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/async_assistant/test_extract_pipeline.py
""" Test implementation of AI Assistant extract pipeline using only Crawl4AI capabilities. This follows the exact flow discussed: query enhancement, classification, HTML skimming, parent extraction, schema generation, and extraction. """ import asyncio import json import os from typing import List, Dict, Any, Optional, Union from lxml import html as lxml_html import re from crawl4ai import AsyncWebCrawler, CrawlerRunConfig from crawl4ai.async_configs import LLMConfig from crawl4ai import JsonCssExtractionStrategy, LLMExtractionStrategy from crawl4ai.utils import perform_completion_with_backoff async def extract_pipeline( base_url: str, urls: Union[str, List[str], None], query: str, target_json_example: Optional[str] = None, force_llm: bool = False, verbose: bool = True ) -> Union[Dict, List[Dict]]: """ Full implementation of the AI-powered extraction pipeline using only Crawl4AI. Pipeline: 1. Quick crawl & HTML skimming 2. Classification (structural vs semantic) using LLM 3. Parent element extraction using LLM (for structural) 4. Schema generation using Crawl4AI's generate_schema 5. Extraction execution using Crawl4AI strategies """ # Normalize URLs if urls is None: urls = base_url target_urls = [urls] if isinstance(urls, str) else urls single_result = isinstance(urls, str) or urls is None # LLM configs for different tasks llm_small = LLMConfig( provider="openai/gpt-4o-mini", api_token=os.getenv("OPENAI_API_KEY") ) llm_small.temperature = 0.3 llm_strong = LLMConfig( provider="openai/gpt-4o", api_token=os.getenv("OPENAI_API_KEY") ) llm_strong.temperature = 0.5 def vprint(msg: str): if verbose: print(f"🔍 {msg}") # Step 1: Starting vprint(f"Query: '{query}'") # Step 2: Quick crawl for analysis async with AsyncWebCrawler(verbose=False) as crawler: vprint(f"Quick crawl: {base_url}") quick_result = await crawler.arun( url=base_url, config=CrawlerRunConfig( cache_mode="bypass", delay_before_return_html=2.0 ) ) if not quick_result.success: raise Exception(f"Failed to crawl {base_url}") # Step 3: HTML Skimming using lxml def skim_html(html: str) -> str: """Remove non-structural elements using lxml.""" parser = lxml_html.HTMLParser(remove_comments=True) tree = lxml_html.fromstring(html, parser=parser) # Remove head section entirely for head in tree.xpath('//head'): head.getparent().remove(head) # Remove non-structural elements including SVGs for element in tree.xpath('//script | //style | //noscript | //meta | //link | //svg'): parent = element.getparent() if parent is not None: parent.remove(element) # Remove base64 images for img in tree.xpath('//img[@src]'): src = img.get('src', '') if 'base64' in src: img.set('src', 'BASE64_IMAGE') # Remove long class/id attributes for element in tree.xpath('//*[@class or @id]'): if element.get('class') and len(element.get('class')) > 100: element.set('class', 'LONG_CLASS') if element.get('id') and len(element.get('id')) > 50: element.set('id', 'LONG_ID') # Truncate text nodes for text_node in tree.xpath('//text()'): if text_node.strip() and len(text_node) > 100: parent = text_node.getparent() if parent is not None: new_text = text_node[:50] + "..." + text_node[-20:] if text_node.is_text: parent.text = new_text elif text_node.is_tail: parent.tail = new_text return lxml_html.tostring(tree, encoding='unicode') skimmed_html = skim_html(quick_result.html) vprint(f"Skimmed HTML from {len(quick_result.html)} to {len(skimmed_html)} chars") # Step 4: Classification using LLM classification = 'semantic' # Default if not force_llm: classification_prompt = f""" Analyze this HTML to determine extraction strategy. Query: "{query}" HTML sample: <<<<HTML>>> {skimmed_html} <<<<END HTML>>> Determine if this can be extracted using CSS/XPath patterns (structural) or requires semantic understanding (semantic). Look for: - Repeating patterns (lists, cards, tables) → structural - Consistent HTML structure → structural - Need for inference or understanding → semantic Return JSON: {{ "strategy": "structural" or "semantic", "confidence": 0.0-1.0, "reasoning": "..." }} """ response = perform_completion_with_backoff( provider=llm_small.provider, prompt_with_variables=classification_prompt, api_token=llm_small.api_token, json_response=True, temperature=llm_small.temperature ) classification_result = json.loads(response.choices[0].message.content) classification = classification_result['strategy'] vprint(f"Classification: {classification} (confidence: {classification_result['confidence']})") vprint(f"Reasoning: {classification_result['reasoning']}") if force_llm: classification = 'semantic' vprint("Forced LLM extraction") # Step 5 & 6: Execute appropriate extraction strategy if classification == 'structural': # Extract parent element using LLM with proper explanation parent_prompt = f""" Identify the CSS selector for the BASE ELEMENT TEMPLATE containing the data to extract. IMPORTANT: The base element template is a repeating pattern in the HTML where each instance contains one item of data (like a product card, article card, issue card, etc.). The selector should: - Not be too specific (avoid selecting just one item) - Not be too general (avoid selecting unrelated elements) - Select ALL instances of the repeating pattern - Point to the container that holds ONE complete data item For example: - On Amazon: div.s-result-item (each product card) - On GitHub issues: div[id^="issue_"] (each issue card) - On a blog: article.post-card (each article) User query: "{query}" """ if target_json_example: parent_prompt += f""" The user expects to extract data in this format: {target_json_example} Find the base element that contains all these fields. """ else: parent_prompt += """ Also provide a JSON example of what data can be extracted from one instance of this base element. """ parent_prompt += f""" HTML (first 8000 chars): <<<<HTML>>> {skimmed_html} <<<<END HTML>>> Return JSON: {{ "parent_selector": "css_selector_here", "explanation": "why this selector is appropriate",""" if not target_json_example: parent_prompt += """ "suggested_json_example": { "field1": "example value", "field2": "example value" }""" parent_prompt += """ }} """ response = perform_completion_with_backoff( provider=llm_small.provider, prompt_with_variables=parent_prompt, api_token=llm_small.api_token, json_response=True, temperature=llm_small.temperature ) parent_data = json.loads(response.choices[0].message.content) parent_selector = parent_data['parent_selector'] vprint(f"Parent selector: {parent_selector}") vprint(f"Explanation: {parent_data['explanation']}") # Use suggested JSON example if no target provided if not target_json_example and 'suggested_json_example' in parent_data: target_json_example = json.dumps(parent_data['suggested_json_example']) vprint(f"Using LLM suggested example: {target_json_example}") # Get the actual parent HTML for schema generation tree = lxml_html.fromstring(quick_result.html) parent_elements = tree.cssselect(parent_selector) if not parent_elements: vprint("Parent selector not found, falling back to semantic") classification = 'semantic' else: # Use the first instance as sample sample_html = lxml_html.tostring(parent_elements[0], encoding='unicode') vprint(f"Generating schema from sample HTML ({len(sample_html)} chars)") # Generate schema using Crawl4AI schema_params = { "html": sample_html, "query": query, "llm_config": llm_strong } if target_json_example: schema_params["target_json_example"] = target_json_example schema = JsonCssExtractionStrategy.generate_schema(**schema_params) vprint(f"Generated schema with {len(schema.get('fields', []))} fields") # Extract from all URLs extraction_strategy = JsonCssExtractionStrategy(schema) results = [] for url in target_urls: vprint(f"Extracting from: {url}") result = await crawler.arun( url=url, config=CrawlerRunConfig( extraction_strategy=extraction_strategy, cache_mode="bypass" ) ) if result.success and result.extracted_content: data = json.loads(result.extracted_content) results.append({ 'url': url, 'data': data, 'count': len(data) if isinstance(data, list) else 1, 'method': 'JsonCssExtraction', 'schema': schema }) return results[0] if single_result else results # Semantic extraction (LLM) if classification == 'semantic': vprint("Using LLM extraction") # Build instruction from query instruction = f""" {query} Return structured JSON data. """ extraction_strategy = LLMExtractionStrategy( llm_config=llm_strong, instruction=instruction ) results = [] for url in target_urls: vprint(f"LLM extracting from: {url}") result = await crawler.arun( url=url, config=CrawlerRunConfig( extraction_strategy=extraction_strategy, cache_mode="bypass" ) ) if result.success and result.extracted_content: data = json.loads(result.extracted_content) results.append({ 'url': url, 'data': data, 'count': len(data) if isinstance(data, list) else 1, 'method': 'LLMExtraction' }) return results[0] if single_result else results async def main(): """Test the extraction pipeline.""" print("\n🚀 CRAWL4AI EXTRACTION PIPELINE TEST") print("="*50) # Test structural extraction try: result = await extract_pipeline( base_url="https://github.com/unclecode/crawl4ai/issues", urls=None, query="I want to extract all issue titles, numbers, and who opened them", verbose=True ) print(f"\n✅ Success! Extracted {result.get('count', 0)} items") print(f"Method used: {result.get('method')}") if result.get('data'): print("\nFirst few items:") data = result['data'] items_to_show = data[:3] if isinstance(data, list) else data print(json.dumps(items_to_show, indent=2)) if result.get('schema'): print(f"\nGenerated schema fields: {[f['name'] for f in result['schema'].get('fields', [])]}") except Exception as e: print(f"\n❌ Error: {e}") import traceback traceback.print_exc() if __name__ == "__main__": # Check for API key if not os.getenv("OPENAI_API_KEY"): print("⚠️ Error: OPENAI_API_KEY environment variable not set") exit(1) asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/async_assistant/test_extract_pipeline.py", "license": "Apache License 2.0", "lines": 304, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/async_assistant/test_extract_pipeline_v2.py
""" Test implementation v2: Combined classification and preparation in one LLM call. More efficient approach that reduces token usage and LLM calls. """ import asyncio import json import os from typing import List, Dict, Any, Optional, Union from lxml import html as lxml_html import re from crawl4ai import AsyncWebCrawler, CrawlerRunConfig from crawl4ai.async_configs import LLMConfig from crawl4ai import JsonCssExtractionStrategy, LLMExtractionStrategy from crawl4ai.utils import perform_completion_with_backoff async def extract_pipeline_v2( base_url: str, urls: Union[str, List[str], None], query: str, target_json_example: Optional[str] = None, force_llm: bool = False, verbose: bool = True ) -> Union[Dict, List[Dict]]: """ Improved extraction pipeline with combined classification and preparation. Pipeline: 1. Quick crawl & HTML skimming 2. Combined LLM call for classification + preparation 3. Execute appropriate extraction strategy """ # Normalize URLs if urls is None: urls = base_url target_urls = [urls] if isinstance(urls, str) else urls single_result = isinstance(urls, str) or urls is None # LLM configs llm_small = LLMConfig( provider="openai/gpt-4o-mini", api_token=os.getenv("OPENAI_API_KEY") ) llm_small.temperature = 0.3 llm_strong = LLMConfig( provider="openai/gpt-4o", api_token=os.getenv("OPENAI_API_KEY") ) llm_strong.temperature = 0.5 def vprint(msg: str): if verbose: print(f"🔍 {msg}") vprint(f"Query: '{query}'") if target_json_example: vprint(f"Target format provided: {target_json_example[:100]}...") # Step 1: Quick crawl for analysis async with AsyncWebCrawler(verbose=False) as crawler: vprint(f"Quick crawl: {base_url}") quick_result = await crawler.arun( url=base_url, config=CrawlerRunConfig( cache_mode="bypass", delay_before_return_html=2.0 ) ) if not quick_result.success: raise Exception(f"Failed to crawl {base_url}") # HTML Skimming def skim_html(html: str) -> str: """Remove non-structural elements using lxml.""" parser = lxml_html.HTMLParser(remove_comments=True) tree = lxml_html.fromstring(html, parser=parser) # Remove head section entirely for head in tree.xpath('//head'): head.getparent().remove(head) # Remove non-structural elements including SVGs for element in tree.xpath('//script | //style | //noscript | //meta | //link | //svg'): parent = element.getparent() if parent is not None: parent.remove(element) # Remove base64 images for img in tree.xpath('//img[@src]'): src = img.get('src', '') if 'base64' in src: img.set('src', 'BASE64_IMAGE') # Remove long class/id attributes for element in tree.xpath('//*[@class or @id]'): if element.get('class') and len(element.get('class')) > 100: element.set('class', 'LONG_CLASS') if element.get('id') and len(element.get('id')) > 50: element.set('id', 'LONG_ID') # Truncate text nodes for text_node in tree.xpath('//text()'): if text_node.strip() and len(text_node) > 100: parent = text_node.getparent() if parent is not None: new_text = text_node[:50] + "..." + text_node[-20:] if text_node.is_text: parent.text = new_text elif text_node.is_tail: parent.tail = new_text return lxml_html.tostring(tree, encoding='unicode') skimmed_html = skim_html(quick_result.html) vprint(f"Skimmed HTML from {len(quick_result.html)} to {len(skimmed_html)} chars") # Step 2: Combined classification and preparation if force_llm: classification_data = {"classification": "semantic"} vprint("Forced LLM extraction") else: combined_prompt = f""" Analyze this HTML and prepare for data extraction. User query: "{query}" """ if target_json_example: combined_prompt += f""" Target format: {target_json_example} """ combined_prompt += f""" HTML: <<<<HTML>>>> {skimmed_html} <<<<END HTML>>>> STEP 1: Determine extraction strategy - If data follows repeating HTML patterns (lists, tables, cards) → "structural" - If data requires understanding/inference → "semantic" STEP 2A: If STRUCTURAL extraction is appropriate: - Find the CSS selector for the BASE ELEMENT (repeating pattern) - Base element = container holding ONE data item (e.g., product card, table row) - Selector should select ALL instances, not too specific, not too general - Count approximate number of these elements """ if not target_json_example: combined_prompt += """ - Suggest what JSON structure can be extracted from one element """ combined_prompt += """ STEP 2B: If SEMANTIC extraction is needed: - Write a detailed instruction for what to extract - Be specific about the data needed """ if not target_json_example: combined_prompt += """ - Suggest expected JSON output structure """ combined_prompt += """ Return JSON with ONLY the relevant fields based on classification: { "classification": "structural" or "semantic", "confidence": 0.0-1.0, "reasoning": "brief explanation", // Include ONLY if classification is "structural": "base_selector": "css selector", "element_count": approximate number, // Include ONLY if classification is "semantic": "extraction_instruction": "detailed instruction", // Include if no target_json_example was provided: "suggested_json_example": { ... } } """ response = perform_completion_with_backoff( provider=llm_small.provider, prompt_with_variables=combined_prompt, api_token=llm_small.api_token, json_response=True, temperature=llm_small.temperature ) classification_data = json.loads(response.choices[0].message.content) vprint(f"Classification: {classification_data['classification']} (confidence: {classification_data['confidence']})") vprint(f"Reasoning: {classification_data['reasoning']}") # Use suggested JSON example if needed if not target_json_example and 'suggested_json_example' in classification_data: target_json_example = json.dumps(classification_data['suggested_json_example']) vprint(f"Using suggested example: {target_json_example}") # Step 3: Execute extraction based on classification if classification_data['classification'] == 'structural': vprint(f"Base selector: {classification_data['base_selector']}") vprint(f"Found ~{classification_data['element_count']} elements") # Get sample HTML for schema generation tree = lxml_html.fromstring(quick_result.html) parent_elements = tree.cssselect(classification_data['base_selector']) if not parent_elements: vprint("Base selector not found, falling back to semantic") classification_data['classification'] = 'semantic' else: # Use first element as sample sample_html = lxml_html.tostring(parent_elements[0], encoding='unicode') vprint(f"Generating schema from sample ({len(sample_html)} chars)") # Generate schema schema_params = { "html": sample_html, "query": query, "llm_config": llm_strong } if target_json_example: schema_params["target_json_example"] = target_json_example schema = JsonCssExtractionStrategy.generate_schema(**schema_params) vprint(f"Generated schema with {len(schema.get('fields', []))} fields") # Extract from all URLs extraction_strategy = JsonCssExtractionStrategy(schema) results = [] for idx, url in enumerate(target_urls): vprint(f"Extracting from: {url}") # Use already crawled HTML for base_url, crawl others if idx == 0 and url == base_url: # We already have this HTML, use raw:// to avoid re-crawling raw_url = f"raw://{quick_result.html}" vprint("Using cached HTML with raw:// scheme") else: # Need to crawl this URL raw_url = url result = await crawler.arun( url=raw_url, config=CrawlerRunConfig( extraction_strategy=extraction_strategy, cache_mode="bypass" ) ) if result.success and result.extracted_content: data = json.loads(result.extracted_content) results.append({ 'url': url, # Keep original URL for reference 'data': data, 'count': len(data) if isinstance(data, list) else 1, 'method': 'JsonCssExtraction', 'schema': schema }) return results[0] if single_result else results # Semantic extraction if classification_data['classification'] == 'semantic': vprint("Using LLM extraction") # Use generated instruction or create simple one if 'extraction_instruction' in classification_data: instruction = classification_data['extraction_instruction'] vprint(f"Generated instruction: {instruction[:100]}...") else: instruction = f"{query}\n\nReturn structured JSON data." extraction_strategy = LLMExtractionStrategy( llm_config=llm_strong, instruction=instruction ) results = [] for idx, url in enumerate(target_urls): vprint(f"LLM extracting from: {url}") # Use already crawled HTML for base_url, crawl others if idx == 0 and url == base_url: # We already have this HTML, use raw:// to avoid re-crawling raw_url = f"raw://{quick_result.html}" vprint("Using cached HTML with raw:// scheme") else: # Need to crawl this URL raw_url = url result = await crawler.arun( url=raw_url, config=CrawlerRunConfig( extraction_strategy=extraction_strategy, cache_mode="bypass" ) ) if result.success and result.extracted_content: data = json.loads(result.extracted_content) results.append({ 'url': url, # Keep original URL for reference 'data': data, 'count': len(data) if isinstance(data, list) else 1, 'method': 'LLMExtraction' }) return results[0] if single_result else results async def main(): """Test the improved extraction pipeline.""" print("\n🚀 CRAWL4AI EXTRACTION PIPELINE V2 TEST") print("="*50) try: # Test 1: Structural extraction (GitHub issues) print("\nTest 1: GitHub Issues (should use structural)") result = await extract_pipeline_v2( base_url="https://github.com/unclecode/crawl4ai/issues", urls=None, query="Extract all issue titles, numbers, and authors", verbose=True ) print(f"\n✅ Extracted {result.get('count', 0)} items using {result.get('method')}") if result.get('data'): print("Sample:", json.dumps(result['data'][:2] if isinstance(result['data'], list) else result['data'], indent=2)) # Test 2: With target JSON example print("\n\nTest 2: With target JSON example") target_example = json.dumps({ "title": "Issue title here", "number": "#123", "author": "username" }) result2 = await extract_pipeline_v2( base_url="https://github.com/unclecode/crawl4ai/issues", urls=None, query="Extract GitHub issues", target_json_example=target_example, verbose=True ) print(f"\n✅ Extracted {result2.get('count', 0)} items") # Test 3: Semantic extraction (force LLM) print("\n\nTest 3: Force semantic extraction") result3 = await extract_pipeline_v2( base_url="https://en.wikipedia.org/wiki/Artificial_intelligence", urls=None, query="Extract key concepts and their relationships in AI field", force_llm=True, verbose=True ) print(f"\n✅ Extracted using {result3.get('method')}") except Exception as e: print(f"\n❌ Error: {e}") import traceback traceback.print_exc() if __name__ == "__main__": if not os.getenv("OPENAI_API_KEY"): print("⚠️ Error: OPENAI_API_KEY environment variable not set") exit(1) asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/async_assistant/test_extract_pipeline_v2.py", "license": "Apache License 2.0", "lines": 313, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/deep_crwaling/test_filter.py
# // File: tests/deep_crawling/test_filters.py import pytest from urllib.parse import urlparse from crawl4ai import ContentTypeFilter, URLFilter # Minimal URLFilter base class stub if not already importable directly for tests # In a real scenario, this would be imported from the library if not hasattr(URLFilter, '_update_stats'): # Check if it's a basic stub class URLFilter: # Basic stub for testing if needed def __init__(self, name=None): self.name = name def apply(self, url: str) -> bool: raise NotImplementedError def _update_stats(self, passed: bool): pass # Mock implementation # Assume ContentTypeFilter is structured as discussed. If its definition is not fully # available for direct import in the test environment, a more elaborate stub or direct # instantiation of the real class (if possible) would be needed. # For this example, we assume ContentTypeFilter can be imported and used. class TestContentTypeFilter: @pytest.mark.parametrize( "url, allowed_types, expected", [ # Existing tests (examples) ("http://example.com/page.html", ["text/html"], True), ("http://example.com/page.json", ["application/json"], True), ("http://example.com/image.png", ["text/html"], False), ("http://example.com/document.pdf", ["application/pdf"], True), ("http://example.com/page", ["text/html"], True), # No extension, allowed ("http://example.com/page", ["text/html"], False), # No extension, disallowed ("http://example.com/page.unknown", ["text/html"], False), # Unknown extension # Tests for PHP extensions ("http://example.com/index.php", ["application/x-httpd-php"], True), ("http://example.com/script.php3", ["application/x-httpd-php"], True), ("http://example.com/legacy.php4", ["application/x-httpd-php"], True), ("http://example.com/main.php5", ["application/x-httpd-php"], True), ("http://example.com/api.php7", ["application/x-httpd-php"], True), ("http://example.com/index.phtml", ["application/x-httpd-php"], True), ("http://example.com/source.phps", ["application/x-httpd-php-source"], True), # Test rejection of PHP extensions ("http://example.com/index.php", ["text/html"], False), ("http://example.com/script.php3", ["text/plain"], False), ("http://example.com/source.phps", ["application/x-httpd-php"], False), # Mismatch MIME ("http://example.com/source.php", ["application/x-httpd-php-source"], False), # Mismatch MIME for .php # Test case-insensitivity of extensions in URL ("http://example.com/PAGE.HTML", ["text/html"], True), ("http://example.com/INDEX.PHP", ["application/x-httpd-php"], True), ("http://example.com/SOURCE.PHPS", ["application/x-httpd-php-source"], True), # Test case-insensitivity of allowed_types ("http://example.com/index.php", ["APPLICATION/X-HTTPD-PHP"], True), ], ) def test_apply(self, url, allowed_types, expected): content_filter = ContentTypeFilter( allowed_types=allowed_types ) assert content_filter.apply(url) == expected @pytest.mark.parametrize( "url, expected_extension", [ ("http://example.com/file.html", "html"), ("http://example.com/file.tar.gz", "gz"), ("http://example.com/path/", ""), ("http://example.com/nodot", ""), ("http://example.com/.config", "config"), # hidden file with extension ("http://example.com/path/to/archive.BIG.zip", "zip"), # Case test ] ) def test_extract_extension(self, url, expected_extension): # Test the static method directly assert ContentTypeFilter._extract_extension(url) == expected_extension
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/deep_crwaling/test_filter.py", "license": "Apache License 2.0", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/docker/simple_api_test.py
#!/usr/bin/env python3 """ Simple API Test for Crawl4AI Docker Server v0.7.0 Uses only built-in Python modules to test all endpoints. """ import urllib.request import urllib.parse import json import time import sys from typing import Dict, List, Optional # Configuration BASE_URL = "http://localhost:11234" # Change to your server URL TEST_TIMEOUT = 30 class SimpleApiTester: def __init__(self, base_url: str = BASE_URL): self.base_url = base_url self.token = None self.results = [] def log(self, message: str): print(f"[INFO] {message}") def test_get_endpoint(self, endpoint: str) -> Dict: """Test a GET endpoint""" url = f"{self.base_url}{endpoint}" start_time = time.time() try: req = urllib.request.Request(url) if self.token: req.add_header('Authorization', f'Bearer {self.token}') with urllib.request.urlopen(req, timeout=TEST_TIMEOUT) as response: response_time = time.time() - start_time status_code = response.getcode() content = response.read().decode('utf-8') # Try to parse JSON try: data = json.loads(content) except: data = {"raw_response": content[:200]} return { "endpoint": endpoint, "method": "GET", "status": "PASS" if status_code < 400 else "FAIL", "status_code": status_code, "response_time": response_time, "data": data } except Exception as e: response_time = time.time() - start_time return { "endpoint": endpoint, "method": "GET", "status": "FAIL", "status_code": None, "response_time": response_time, "error": str(e) } def test_post_endpoint(self, endpoint: str, payload: Dict) -> Dict: """Test a POST endpoint""" url = f"{self.base_url}{endpoint}" start_time = time.time() try: data = json.dumps(payload).encode('utf-8') req = urllib.request.Request(url, data=data, method='POST') req.add_header('Content-Type', 'application/json') if self.token: req.add_header('Authorization', f'Bearer {self.token}') with urllib.request.urlopen(req, timeout=TEST_TIMEOUT) as response: response_time = time.time() - start_time status_code = response.getcode() content = response.read().decode('utf-8') # Try to parse JSON try: data = json.loads(content) except: data = {"raw_response": content[:200]} return { "endpoint": endpoint, "method": "POST", "status": "PASS" if status_code < 400 else "FAIL", "status_code": status_code, "response_time": response_time, "data": data } except Exception as e: response_time = time.time() - start_time return { "endpoint": endpoint, "method": "POST", "status": "FAIL", "status_code": None, "response_time": response_time, "error": str(e) } def print_result(self, result: Dict): """Print a formatted test result""" status_color = { "PASS": "✅", "FAIL": "❌", "SKIP": "⏭️" } print(f"{status_color[result['status']]} {result['method']} {result['endpoint']} " f"| {result['response_time']:.3f}s | Status: {result['status_code'] or 'N/A'}") if result['status'] == 'FAIL' and 'error' in result: print(f" Error: {result['error']}") self.results.append(result) def run_all_tests(self): """Run all API tests""" print("🚀 Starting Crawl4AI v0.7.0 API Test Suite") print(f"📡 Testing server at: {self.base_url}") print("=" * 60) # # Test basic endpoints # print("\n=== BASIC ENDPOINTS ===") # # Health check # result = self.test_get_endpoint("/health") # self.print_result(result) # # Schema endpoint # result = self.test_get_endpoint("/schema") # self.print_result(result) # # Metrics endpoint # result = self.test_get_endpoint("/metrics") # self.print_result(result) # # Root redirect # result = self.test_get_endpoint("/") # self.print_result(result) # # Test authentication # print("\n=== AUTHENTICATION ===") # # Get token # token_payload = {"email": "test@example.com"} # result = self.test_post_endpoint("/token", token_payload) # self.print_result(result) # # Extract token if successful # if result['status'] == 'PASS' and 'data' in result: # token = result['data'].get('access_token') # if token: # self.token = token # self.log(f"Successfully obtained auth token: {token[:20]}...") # Test core APIs print("\n=== CORE APIs ===") test_url = "https://example.com" test_raw_html_url = "raw://<html><body><h1>Hello, World!</h1></body></html>" # Test markdown endpoint md_payload = { "url": test_url, "f": "fit", "q": "test query", "c": "0" } result = self.test_post_endpoint("/md", md_payload) # print(result['data'].get('markdown', '')) self.print_result(result) # Test markdown endpoint with raw HTML raw_md_payload = { "url": test_raw_html_url, "f": "fit", "q": "test query", "c": "0" } result = self.test_post_endpoint("/md", raw_md_payload) self.print_result(result) # Test HTML endpoint html_payload = {"url": test_url} result = self.test_post_endpoint("/html", html_payload) self.print_result(result) # Test screenshot endpoint screenshot_payload = { "url": test_url, "screenshot_wait_for": 2 } result = self.test_post_endpoint("/screenshot", screenshot_payload) self.print_result(result) # Test PDF endpoint pdf_payload = {"url": test_url} result = self.test_post_endpoint("/pdf", pdf_payload) self.print_result(result) # Test JavaScript execution js_payload = { "url": test_url, "scripts": ["(() => document.title)()"] } result = self.test_post_endpoint("/execute_js", js_payload) self.print_result(result) # Test crawl endpoint crawl_payload = { "urls": [test_url], "browser_config": {}, "crawler_config": {} } result = self.test_post_endpoint("/crawl", crawl_payload) self.print_result(result) # Test crawl endpoint with raw HTML crawl_payload = { "urls": [test_raw_html_url], "browser_config": {}, "crawler_config": {} } result = self.test_post_endpoint("/crawl", crawl_payload) self.print_result(result) # Test config dump config_payload = {"code": "CrawlerRunConfig()"} result = self.test_post_endpoint("/config/dump", config_payload) self.print_result(result) # Test LLM endpoint llm_endpoint = f"/llm/{test_url}?q=Extract%20main%20content" result = self.test_get_endpoint(llm_endpoint) self.print_result(result) # Test ask endpoint ask_endpoint = "/ask?context_type=all&query=crawl4ai&max_results=5" result = self.test_get_endpoint(ask_endpoint) print(result) self.print_result(result) # Test job APIs print("\n=== JOB APIs ===") # Test LLM job llm_job_payload = { "url": test_url, "q": "Extract main content", "cache": False } result = self.test_post_endpoint("/llm/job", llm_job_payload) self.print_result(result) # Test crawl job crawl_job_payload = { "urls": [test_url], "browser_config": {}, "crawler_config": {} } result = self.test_post_endpoint("/crawl/job", crawl_job_payload) self.print_result(result) # Test MCP print("\n=== MCP APIs ===") # Test MCP schema result = self.test_get_endpoint("/mcp/schema") self.print_result(result) # Test error handling print("\n=== ERROR HANDLING ===") # Test invalid URL invalid_payload = {"url": "invalid-url", "f": "fit"} result = self.test_post_endpoint("/md", invalid_payload) self.print_result(result) # Test invalid endpoint result = self.test_get_endpoint("/nonexistent") self.print_result(result) # Print summary self.print_summary() def print_summary(self): """Print test results summary""" print("\n" + "=" * 60) print("📊 TEST RESULTS SUMMARY") print("=" * 60) total = len(self.results) passed = sum(1 for r in self.results if r['status'] == 'PASS') failed = sum(1 for r in self.results if r['status'] == 'FAIL') print(f"Total Tests: {total}") print(f"✅ Passed: {passed}") print(f"❌ Failed: {failed}") print(f"📈 Success Rate: {(passed/total)*100:.1f}%") if failed > 0: print("\n❌ FAILED TESTS:") for result in self.results: if result['status'] == 'FAIL': print(f" • {result['method']} {result['endpoint']}") if 'error' in result: print(f" Error: {result['error']}") # Performance statistics response_times = [r['response_time'] for r in self.results if r['response_time'] > 0] if response_times: avg_time = sum(response_times) / len(response_times) max_time = max(response_times) print(f"\n⏱️ Average Response Time: {avg_time:.3f}s") print(f"⏱️ Max Response Time: {max_time:.3f}s") # Save detailed report report_file = f"crawl4ai_test_report_{int(time.time())}.json" with open(report_file, 'w') as f: json.dump({ "timestamp": time.time(), "server_url": self.base_url, "version": "0.7.0", "summary": { "total": total, "passed": passed, "failed": failed }, "results": self.results }, f, indent=2) print(f"\n📄 Detailed report saved to: {report_file}") def main(): """Main test runner""" import argparse parser = argparse.ArgumentParser(description='Crawl4AI v0.7.0 API Test Suite') parser.add_argument('--url', default=BASE_URL, help='Base URL of the server') args = parser.parse_args() tester = SimpleApiTester(args.url) try: tester.run_all_tests() except KeyboardInterrupt: print("\n🛑 Test suite interrupted by user") except Exception as e: print(f"\n💥 Test suite failed with error: {e}") sys.exit(1) if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/docker/simple_api_test.py", "license": "Apache License 2.0", "lines": 301, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/general/test_async_url_seeder_bm25.py
""" Comprehensive test cases for AsyncUrlSeeder with BM25 scoring functionality. Tests cover all features including query-based scoring, metadata extraction, edge cases, and integration scenarios. """ import asyncio import pytest from typing import List, Dict, Any from crawl4ai import AsyncUrlSeeder, SeedingConfig, AsyncLogger import json from datetime import datetime # Test domain - using docs.crawl4ai.com as it has the actual documentation TEST_DOMAIN = "kidocode.com" TEST_DOMAIN = "docs.crawl4ai.com" TEST_DOMAIN = "www.bbc.com/sport" class TestAsyncUrlSeederBM25: """Comprehensive test suite for AsyncUrlSeeder with BM25 scoring.""" async def create_seeder(self): """Create an AsyncUrlSeeder instance for testing.""" logger = AsyncLogger() return AsyncUrlSeeder(logger=logger) # ============================================ # Basic BM25 Scoring Tests # ============================================ @pytest.mark.asyncio async def test_basic_bm25_scoring(self, seeder): """Test basic BM25 scoring with a simple query.""" config = SeedingConfig( source="sitemap", extract_head=True, query="premier league highlights", scoring_method="bm25", max_urls=200, verbose=True, force=True # Force fresh fetch ) results = await seeder.urls(TEST_DOMAIN, config) # Verify results have relevance scores assert all("relevance_score" in r for r in results) # Verify scores are normalized between 0 and 1 scores = [r["relevance_score"] for r in results] assert all(0.0 <= s <= 1.0 for s in scores) # Verify results are sorted by relevance (descending) assert scores == sorted(scores, reverse=True) # Print top 5 results for manual verification print("\nTop 5 results for 'web crawling tutorial':") for i, r in enumerate(results[:5]): print(f"{i+1}. Score: {r['relevance_score']:.3f} - {r['url']}") @pytest.mark.asyncio async def test_query_variations(self, seeder): """Test BM25 scoring with different query variations.""" queries = [ "VAR controversy", "player ratings", "live score update", "transfer rumours", "post match analysis", "injury news" ] for query in queries: config = SeedingConfig( source="sitemap", extract_head=True, query=query, scoring_method="bm25", max_urls=100, # force=True ) results = await seeder.urls(TEST_DOMAIN, config) # Verify each query produces scored results assert len(results) > 0 assert all("relevance_score" in r for r in results) print(f"\nTop result for '{query}':") if results: top = results[0] print(f" Score: {top['relevance_score']:.3f} - {top['url']}") # ============================================ # Score Threshold Tests # ============================================ @pytest.mark.asyncio async def test_score_threshold_filtering(self, seeder): """Test filtering results by minimum relevance score.""" thresholds = [0.1, 0.3, 0.5, 0.7] for threshold in thresholds: config = SeedingConfig( source="sitemap", extract_head=True, query="league standings", score_threshold=threshold, scoring_method="bm25", max_urls=50 ) results = await seeder.urls(TEST_DOMAIN, config) # Verify all results meet threshold if results: assert all(r["relevance_score"] >= threshold for r in results) print(f"\nThreshold {threshold}: {len(results)} URLs passed") @pytest.mark.asyncio async def test_extreme_thresholds(self, seeder): """Test edge cases with extreme threshold values.""" # Very low threshold - should return many results config_low = SeedingConfig( source="sitemap", extract_head=True, query="match", score_threshold=0.001, scoring_method="bm25" ) results_low = await seeder.urls(TEST_DOMAIN, config_low) # Very high threshold - might return few or no results config_high = SeedingConfig( source="sitemap", extract_head=True, query="match", score_threshold=0.99, scoring_method="bm25" ) results_high = await seeder.urls(TEST_DOMAIN, config_high) # Low threshold should return more results than high assert len(results_low) >= len(results_high) print(f"\nLow threshold (0.001): {len(results_low)} results") print(f"High threshold (0.99): {len(results_high)} results") # ============================================ # Metadata Extraction Tests # ============================================ @pytest.mark.asyncio async def test_comprehensive_metadata_extraction(self, seeder): """Test extraction of all metadata types including JSON-LD.""" config = SeedingConfig( source="sitemap", extract_head=True, query="match report", scoring_method="bm25", max_urls=5, verbose=True ) results = await seeder.urls(TEST_DOMAIN, config) for result in results: head_data = result.get("head_data", {}) # Check for various metadata fields print(f"\nMetadata for {result['url']}:") print(f" Title: {head_data.get('title', 'N/A')}") print(f" Charset: {head_data.get('charset', 'N/A')}") print(f" Lang: {head_data.get('lang', 'N/A')}") # Check meta tags meta = head_data.get("meta", {}) if meta: print(" Meta tags found:") for key in ["description", "keywords", "author", "viewport"]: if key in meta: print(f" {key}: {meta[key][:50]}...") # Check for Open Graph tags og_tags = {k: v for k, v in meta.items() if k.startswith("og:")} if og_tags: print(" Open Graph tags found:") for k, v in list(og_tags.items())[:3]: print(f" {k}: {v[:50]}...") # Check JSON-LD if head_data.get("jsonld"): print(f" JSON-LD schemas found: {len(head_data['jsonld'])}") @pytest.mark.asyncio async def test_jsonld_extraction_scoring(self, seeder): """Test that JSON-LD data contributes to BM25 scoring.""" config = SeedingConfig( source="sitemap", extract_head=True, query="Premier League match report highlights", scoring_method="bm25", max_urls=20 ) results = await seeder.urls(TEST_DOMAIN, config) # Find results with JSON-LD data jsonld_results = [r for r in results if r.get("head_data", {}).get("jsonld")] if jsonld_results: print(f"\nFound {len(jsonld_results)} URLs with JSON-LD data") for r in jsonld_results[:3]: print(f" Score: {r['relevance_score']:.3f} - {r['url']}") jsonld_data = r["head_data"]["jsonld"] print(f" JSON-LD types: {[item.get('@type', 'Unknown') for item in jsonld_data if isinstance(item, dict)]}") # ============================================ # Edge Cases and Error Handling # ============================================ @pytest.mark.asyncio async def test_empty_query(self, seeder): """Test behavior with empty query string.""" config = SeedingConfig( source="sitemap", extract_head=True, query="", scoring_method="bm25", max_urls=10 ) results = await seeder.urls(TEST_DOMAIN, config) # Should return results but all with zero scores assert len(results) > 0 assert all(r.get("relevance_score", 0) == 0 for r in results) @pytest.mark.asyncio async def test_query_without_extract_head(self, seeder): """Test query scoring when extract_head is False.""" config = SeedingConfig( source="sitemap", extract_head=False, # This should trigger a warning query="Premier League match report highlights", scoring_method="bm25", max_urls=10 ) results = await seeder.urls(TEST_DOMAIN, config) # Results should not have relevance scores assert all("relevance_score" not in r for r in results) print("\nVerified: No scores added when extract_head=False") @pytest.mark.asyncio async def test_special_characters_in_query(self, seeder): """Test queries with special characters and symbols.""" special_queries = [ "premier league + analytics", "injury/rehab routines", "AI-powered scouting", "match stats & xG", "tactical@breakdown", "transfer-window.yml" ] for query in special_queries: config = SeedingConfig( source="sitemap", extract_head=True, query=query, scoring_method="bm25", max_urls=5 ) try: results = await seeder.urls(TEST_DOMAIN, config) assert isinstance(results, list) print(f"\n✓ Query '{query}' processed successfully") except Exception as e: pytest.fail(f"Failed on query '{query}': {str(e)}") @pytest.mark.asyncio async def test_unicode_query(self, seeder): """Test queries with Unicode characters.""" unicode_queries = [ "网页爬虫", # Chinese "веб-краулер", # Russian "🚀 crawl4ai", # Emoji "naïve implementation", # Accented characters ] for query in unicode_queries: config = SeedingConfig( source="sitemap", extract_head=True, query=query, scoring_method="bm25", max_urls=5 ) try: results = await seeder.urls(TEST_DOMAIN, config) assert isinstance(results, list) print(f"\n✓ Unicode query '{query}' processed successfully") except Exception as e: print(f"\n✗ Unicode query '{query}' failed: {str(e)}") # ============================================ # Performance and Scalability Tests # ============================================ @pytest.mark.asyncio async def test_large_scale_scoring(self, seeder): """Test BM25 scoring with many URLs.""" config = SeedingConfig( source="cc+sitemap", # Use both sources for more URLs extract_head=True, query="world cup group standings", scoring_method="bm25", max_urls=100, concurrency=20, hits_per_sec=10 ) start_time = asyncio.get_event_loop().time() results = await seeder.urls(TEST_DOMAIN, config) elapsed = asyncio.get_event_loop().time() - start_time print(f"\nProcessed {len(results)} URLs in {elapsed:.2f} seconds") print(f"Average time per URL: {elapsed/len(results)*1000:.1f}ms") # Verify scoring worked at scale assert all("relevance_score" in r for r in results) # Check score distribution scores = [r["relevance_score"] for r in results] print(f"Score distribution:") print(f" Min: {min(scores):.3f}") print(f" Max: {max(scores):.3f}") print(f" Avg: {sum(scores)/len(scores):.3f}") @pytest.mark.asyncio async def test_concurrent_scoring_consistency(self, seeder): """Test that concurrent requests produce consistent scores.""" config = SeedingConfig( source="sitemap", extract_head=True, query="live score update", scoring_method="bm25", max_urls=20, concurrency=10 ) # Run the same query multiple times results_list = [] for _ in range(3): results = await seeder.urls(TEST_DOMAIN, config) results_list.append(results) # Compare scores across runs (they should be identical for same URLs) url_scores = {} for results in results_list: for r in results: url = r["url"] score = r["relevance_score"] if url in url_scores: # Scores should be very close (allowing for tiny float differences) assert abs(url_scores[url] - score) < 0.001 else: url_scores[url] = score print(f"\n✓ Consistent scores across {len(results_list)} runs") # ============================================ # Multi-Domain Tests # ============================================ @pytest.mark.asyncio async def test_many_urls_with_scoring(self, seeder): """Test many_urls method with BM25 scoring.""" domains = [TEST_DOMAIN, "docs.crawl4ai.com", "example.com"] config = SeedingConfig( source="sitemap", extract_head=True, # live_check=True, query="fixture list", scoring_method="bm25", score_threshold=0.2, max_urls=10, force=True, # Force fresh fetch ) results_dict = await seeder.many_urls(domains, config) for domain, results in results_dict.items(): print(f"\nDomain: {domain}") print(f" Found {len(results)} URLs above threshold") if results: top = results[0] print(f" Top result: {top['relevance_score']:.3f} - {top['url']}") # ============================================ # Complex Query Tests # ============================================ @pytest.mark.asyncio async def test_multi_word_complex_queries(self, seeder): """Test complex multi-word queries.""" complex_queries = [ "how to follow live match commentary", "extract expected goals stats from match data", "premier league match report analysis", "transfer rumours and confirmed signings tracker", "tactical breakdown of high press strategy" ] for query in complex_queries: config = SeedingConfig( source="sitemap", extract_head=True, query=query, scoring_method="bm25", max_urls=5 ) results = await seeder.urls(TEST_DOMAIN, config) if results: print(f"\nQuery: '{query}'") print(f"Top match: {results[0]['relevance_score']:.3f} - {results[0]['url']}") # Extract matched terms from metadata head_data = results[0].get("head_data", {}) title = head_data.get("title", "") description = head_data.get("meta", {}).get("description", "") # Simple term matching for verification query_terms = set(query.lower().split()) title_terms = set(title.lower().split()) desc_terms = set(description.lower().split()) matched_terms = query_terms & (title_terms | desc_terms) if matched_terms: print(f"Matched terms: {', '.join(matched_terms)}") # ============================================ # Cache and Force Tests # ============================================ @pytest.mark.asyncio async def test_scoring_with_cache(self, seeder): """Test that scoring works correctly with cached results.""" config = SeedingConfig( source="sitemap", extract_head=True, query="injury update timeline", scoring_method="bm25", max_urls=10, force=False # Use cache ) # First run - populate cache results1 = await seeder.urls(TEST_DOMAIN, config) # Second run - should use cache results2 = await seeder.urls(TEST_DOMAIN, config) # Results should be identical assert len(results1) == len(results2) for r1, r2 in zip(results1, results2): assert r1["url"] == r2["url"] assert abs(r1["relevance_score"] - r2["relevance_score"]) < 0.001 print("\n✓ Cache produces consistent scores") @pytest.mark.asyncio async def test_force_refresh_scoring(self, seeder): """Test force=True bypasses cache for fresh scoring.""" config_cached = SeedingConfig( source="sitemap", extract_head=True, query="transfer window", scoring_method="bm25", max_urls=5, force=False ) config_forced = SeedingConfig( source="sitemap", extract_head=True, query="transfer window", scoring_method="bm25", max_urls=5, force=True ) # Run with cache start1 = asyncio.get_event_loop().time() results1 = await seeder.urls(TEST_DOMAIN, config_cached) time1 = asyncio.get_event_loop().time() - start1 # Run with force (should be slower due to fresh fetch) start2 = asyncio.get_event_loop().time() results2 = await seeder.urls(TEST_DOMAIN, config_forced) time2 = asyncio.get_event_loop().time() - start2 print(f"\nCached run: {time1:.2f}s") print(f"Forced run: {time2:.2f}s") # Both should produce scored results assert all("relevance_score" in r for r in results1) assert all("relevance_score" in r for r in results2) # ============================================ # Source Combination Tests # ============================================ @pytest.mark.asyncio async def test_scoring_with_multiple_sources(self, seeder): """Test BM25 scoring with combined sources (cc+sitemap).""" config = SeedingConfig( source="cc+sitemap", extract_head=True, query="match highlights video", scoring_method="bm25", score_threshold=0.3, max_urls=30, concurrency=15 ) results = await seeder.urls(TEST_DOMAIN, config) # Verify we got results from both sources print(f"\nCombined sources returned {len(results)} URLs above threshold") # Check URL diversity unique_paths = set() for r in results: path = r["url"].replace("https://", "").replace("http://", "").split("/", 1)[-1] unique_paths.add(path.split("?")[0]) # Remove query params print(f"Unique paths found: {len(unique_paths)}") # All should be scored and above threshold assert all(r["relevance_score"] >= 0.3 for r in results) # ============================================ # Integration Tests # ============================================ @pytest.mark.asyncio async def test_full_workflow_integration(self, seeder): """Test complete workflow: discover -> score -> filter -> use.""" # Step 1: Discover and score URLs config = SeedingConfig( source="sitemap", extract_head=True, query="premier league opening fixtures", scoring_method="bm25", score_threshold=0.4, max_urls=10, verbose=True ) results = await seeder.urls(TEST_DOMAIN, config) print(f"\nStep 1: Found {len(results)} relevant URLs") # Step 2: Analyze top results if results: top_urls = results[:3] print("\nStep 2: Top 3 URLs for crawling:") for i, r in enumerate(top_urls): print(f"{i+1}. Score: {r['relevance_score']:.3f}") print(f" URL: {r['url']}") print(f" Title: {r['head_data'].get('title', 'N/A')}") # Check metadata quality meta = r['head_data'].get('meta', {}) if 'description' in meta: print(f" Description: {meta['description'][:80]}...") # Step 3: Verify these URLs would be good for actual crawling assert all(r["status"] == "valid" for r in results[:3]) print("\nStep 3: All top URLs are valid for crawling ✓") # ============================================ # Report Generation # ============================================ @pytest.mark.asyncio async def test_generate_scoring_report(self, seeder): """Generate a comprehensive report of BM25 scoring effectiveness.""" queries = { "beginner": "match schedule", "advanced": "tactical analysis pressing", "api": "VAR decision explanation", "deployment": "fixture changes due to weather", "extraction": "expected goals statistics" } report = { "timestamp": datetime.now().isoformat(), "domain": TEST_DOMAIN, "results": {} } for category, query in queries.items(): config = SeedingConfig( source="sitemap", extract_head=True, query=query, scoring_method="bm25", max_urls=10 ) results = await seeder.urls(TEST_DOMAIN, config) report["results"][category] = { "query": query, "total_results": len(results), "top_results": [ { "url": r["url"], "score": r["relevance_score"], "title": r["head_data"].get("title", "") } for r in results[:3] ], "score_distribution": { "min": min(r["relevance_score"] for r in results) if results else 0, "max": max(r["relevance_score"] for r in results) if results else 0, "avg": sum(r["relevance_score"] for r in results) / len(results) if results else 0 } } # Print report print("\n" + "="*60) print("BM25 SCORING EFFECTIVENESS REPORT") print("="*60) print(f"Domain: {report['domain']}") print(f"Timestamp: {report['timestamp']}") print("\nResults by Category:") for category, data in report["results"].items(): print(f"\n{category.upper()}: '{data['query']}'") print(f" Total results: {data['total_results']}") print(f" Score range: {data['score_distribution']['min']:.3f} - {data['score_distribution']['max']:.3f}") print(f" Average score: {data['score_distribution']['avg']:.3f}") print(" Top matches:") for i, result in enumerate(data['top_results']): print(f" {i+1}. [{result['score']:.3f}] {result['title']}") # ============================================ # Standalone test runner # ============================================ async def run_all_tests(): """Run all tests standalone (without pytest).""" print("Running AsyncUrlSeeder BM25 Tests...") print("="*60) test_instance = TestAsyncUrlSeederBM25() seeder = await test_instance.create_seeder() # Run each test method test_methods = [ # test_instance.test_basic_bm25_scoring, # test_instance.test_query_variations, # test_instance.test_score_threshold_filtering, # test_instance.test_extreme_thresholds, # test_instance.test_comprehensive_metadata_extraction, # test_instance.test_jsonld_extraction_scoring, # test_instance.test_empty_query, # test_instance.test_query_without_extract_head, # test_instance.test_special_characters_in_query, # test_instance.test_unicode_query, # test_instance.test_large_scale_scoring, # test_instance.test_concurrent_scoring_consistency, # test_instance.test_many_urls_with_scoring, test_instance.test_multi_word_complex_queries, test_instance.test_scoring_with_cache, test_instance.test_force_refresh_scoring, test_instance.test_scoring_with_multiple_sources, test_instance.test_full_workflow_integration, test_instance.test_generate_scoring_report ] for test_method in test_methods: try: print(f"\nRunning {test_method.__name__}...") await test_method(seeder) print(f"✓ {test_method.__name__} passed") except Exception as e: import traceback print(f"✗ {test_method.__name__} failed: {str(e)}") print(f" Error type: {type(e).__name__}") traceback.print_exc() print("\n" + "="*60) print("Test suite completed!") if __name__ == "__main__": # Run tests directly asyncio.run(run_all_tests())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/general/test_async_url_seeder_bm25.py", "license": "Apache License 2.0", "lines": 594, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/general/test_download_file.py
import asyncio from crawl4ai import CrawlerRunConfig, AsyncWebCrawler, BrowserConfig from pathlib import Path import os async def test_basic_download(): # Custom folder (otherwise defaults to ~/.crawl4ai/downloads) downloads_path = os.path.join(Path.home(), ".crawl4ai", "downloads") os.makedirs(downloads_path, exist_ok=True) browser_config = BrowserConfig( accept_downloads=True, downloads_path=downloads_path ) async with AsyncWebCrawler(config=browser_config) as crawler: run_config = CrawlerRunConfig( js_code=""" const link = document.querySelector('a[href$=".exe"]'); if (link) { link.click(); } """, delay_before_return_html=5 ) result = await crawler.arun("https://www.python.org/downloads/", config=run_config) if result.downloaded_files: print("Downloaded files:") for file_path in result.downloaded_files: print("•", file_path) else: print("No files downloaded.") if __name__ == "__main__": asyncio.run(test_basic_download())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/general/test_download_file.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/general/test_max_scroll.py
""" Sample script to test the max_scroll_steps parameter implementation """ import asyncio import os import sys # Get the grandparent directory grandparent_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(grandparent_dir) __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) from crawl4ai import AsyncWebCrawler from crawl4ai.async_configs import CrawlerRunConfig async def test_max_scroll_steps(): """ Test the max_scroll_steps parameter with different configurations """ print("🚀 Testing max_scroll_steps parameter implementation") print("=" * 60) async with AsyncWebCrawler(verbose=True) as crawler: # Test 1: Without max_scroll_steps (unlimited scrolling) print("\\n📋 Test 1: Unlimited scrolling (max_scroll_steps=None)") config1 = CrawlerRunConfig( scan_full_page=True, scroll_delay=0.1, max_scroll_steps=None, # Default behavior verbose=True ) print(f"Config: scan_full_page={config1.scan_full_page}, max_scroll_steps={config1.max_scroll_steps}") try: result1 = await crawler.arun( url="https://example.com", # Simple page for testing config=config1 ) print(f"✅ Test 1 Success: Crawled {len(result1.markdown)} characters") except Exception as e: print(f"❌ Test 1 Failed: {e}") # Test 2: With limited scroll steps print("\\n📋 Test 2: Limited scrolling (max_scroll_steps=3)") config2 = CrawlerRunConfig( scan_full_page=True, scroll_delay=0.1, max_scroll_steps=3, # Limit to 3 scroll steps verbose=True ) print(f"Config: scan_full_page={config2.scan_full_page}, max_scroll_steps={config2.max_scroll_steps}") try: result2 = await crawler.arun( url="https://techcrunch.com/", # Another test page config=config2 ) print(f"✅ Test 2 Success: Crawled {len(result2.markdown)} characters") except Exception as e: print(f"❌ Test 2 Failed: {e}") # Test 3: Test serialization/deserialization print("\\n📋 Test 3: Configuration serialization test") config3 = CrawlerRunConfig( scan_full_page=True, max_scroll_steps=5, scroll_delay=0.2 ) # Test to_dict config_dict = config3.to_dict() print(f"Serialized max_scroll_steps: {config_dict.get('max_scroll_steps')}") # Test from_kwargs config4 = CrawlerRunConfig.from_kwargs({ 'scan_full_page': True, 'max_scroll_steps': 7, 'scroll_delay': 0.3 }) print(f"Deserialized max_scroll_steps: {config4.max_scroll_steps}") print("✅ Test 3 Success: Serialization works correctly") # Test 4: Edge case - max_scroll_steps = 0 print("\\n📋 Test 4: Edge case (max_scroll_steps=0)") config5 = CrawlerRunConfig( scan_full_page=True, max_scroll_steps=0, # Should not scroll at all verbose=True ) try: result5 = await crawler.arun( url="https://techcrunch.com/", config=config5 ) print(f"✅ Test 4 Success: No scrolling performed, crawled {len(result5.markdown)} characters") except Exception as e: print(f"❌ Test 4 Failed: {e}") print("\\n" + "=" * 60) print("🎉 All tests completed!") print("\\nThe max_scroll_steps parameter is working correctly:") print("- None: Unlimited scrolling (default behavior)") print("- Positive integer: Limits scroll steps to that number") print("- 0: No scrolling performed") print("- Properly serializes/deserializes in config") if __name__ == "__main__": print("Starting max_scroll_steps test...") asyncio.run(test_max_scroll_steps())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/general/test_max_scroll.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/general/test_url_pattern.py
import sys import os # Get the grandparent directory grandparent_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(grandparent_dir) __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) import asyncio from crawl4ai.deep_crawling.filters import URLPatternFilter def test_prefix_boundary_matching(): """Test that prefix patterns respect path boundaries""" print("=== Testing URLPatternFilter Prefix Boundary Fix ===") filter_obj = URLPatternFilter(patterns=['https://langchain-ai.github.io/langgraph/*']) test_cases = [ ('https://langchain-ai.github.io/langgraph/', True), ('https://langchain-ai.github.io/langgraph/concepts/', True), ('https://langchain-ai.github.io/langgraph/tutorials/', True), ('https://langchain-ai.github.io/langgraph?param=1', True), ('https://langchain-ai.github.io/langgraph#section', True), ('https://langchain-ai.github.io/langgraphjs/', False), ('https://langchain-ai.github.io/langgraphjs/concepts/', False), ('https://other-site.com/langgraph/', False), ] all_passed = True for url, expected in test_cases: result = filter_obj.apply(url) status = "PASS" if result == expected else "FAIL" if result != expected: all_passed = False print(f"{status:4} | Expected: {expected:5} | Got: {result:5} | {url}") return all_passed def test_edge_cases(): """Test edge cases for path boundary matching""" print("\n=== Testing Edge Cases ===") test_patterns = [ ('/api/*', [ ('/api/', True), ('/api/v1', True), ('/api?param=1', True), ('/apiv2/', False), ('/api_old/', False), ]), ('*/docs/*', [ ('example.com/docs/', True), ('example.com/docs/guide', True), ('example.com/documentation/', False), ('example.com/docs_old/', False), ]), ] all_passed = True for pattern, test_cases in test_patterns: print(f"\nPattern: {pattern}") filter_obj = URLPatternFilter(patterns=[pattern]) for url, expected in test_cases: result = filter_obj.apply(url) status = "PASS" if result == expected else "FAIL" if result != expected: all_passed = False print(f" {status:4} | Expected: {expected:5} | Got: {result:5} | {url}") return all_passed if __name__ == "__main__": test1_passed = test_prefix_boundary_matching() test2_passed = test_edge_cases() if test1_passed and test2_passed: print("\n✅ All tests passed!") sys.exit(0) else: print("\n❌ Some tests failed!") sys.exit(1)
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/general/test_url_pattern.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/releases/test_release_0.6.4.py
import pytest import asyncio import time from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, BrowserConfig, CacheMode @pytest.mark.asyncio async def test_wait_for_timeout_separate_from_page_timeout(): """Test that wait_for has its own timeout separate from page_timeout""" browser_config = BrowserConfig(headless=True) # Test with short wait_for_timeout but longer page_timeout config = CrawlerRunConfig( wait_for="css:.nonexistent-element", wait_for_timeout=2000, # 2 seconds page_timeout=10000, # 10 seconds cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler(config=browser_config) as crawler: start_time = time.time() result = await crawler.arun("https://example.com", config=config) elapsed = time.time() - start_time # Should timeout after ~2 seconds (wait_for_timeout), not 10 seconds assert elapsed < 5, f"Expected timeout around 2s, but took {elapsed:.2f}s" assert result.success, "Crawl should still succeed even if wait_for times out" @pytest.mark.asyncio async def test_wait_for_timeout_with_existing_element(): """Test that wait_for_timeout works correctly when element exists""" browser_config = BrowserConfig(headless=True) config = CrawlerRunConfig( wait_for="css:body", # This should exist quickly wait_for_timeout=5000, cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler(config=browser_config) as crawler: start_time = time.time() result = await crawler.arun("https://example.com", config=config) elapsed = time.time() - start_time # Should complete quickly since body element exists assert elapsed < 3, f"Expected quick completion, but took {elapsed:.2f}s" assert result.success assert "<body" in result.html @pytest.mark.asyncio async def test_javascript_wait_for_timeout(): """Test wait_for_timeout with JavaScript condition""" browser_config = BrowserConfig(headless=True) config = CrawlerRunConfig( wait_for="js:() => window.nonExistentVariable === true", wait_for_timeout=2000, cache_mode=CacheMode.BYPASS ) async with AsyncWebCrawler(config=browser_config) as crawler: start_time = time.time() result = await crawler.arun("https://example.com", config=config) elapsed = time.time() - start_time # Should timeout after ~2 seconds assert elapsed < 4, f"Expected timeout around 2s, but took {elapsed:.2f}s" assert result.success @pytest.mark.asyncio async def test_google_analytics_integration(): """Test that Google Analytics scripts are properly integrated""" browser_config = BrowserConfig(headless=True) config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS) # Test with a simple HTML page that we can control html_content = """ <!DOCTYPE html> <html> <head> <title>Test GA Integration</title> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('config', 'GA_MEASUREMENT_ID'); </script> </head> <body> <h1>Test Page</h1> <p>Testing Google Analytics integration</p> </body> </html> """ async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(f"raw://{html_content}", config=config) assert result.success # Check that GA scripts are preserved in the HTML assert "googletagmanager.com/gtag/js" in result.html assert "dataLayer" in result.html assert "gtag('config'" in result.html @pytest.mark.asyncio async def test_mkdocs_no_duplicate_gtag(): """Test that there are no duplicate gtag.js entries in documentation""" browser_config = BrowserConfig(headless=True) config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS) # Simulate MkDocs-like HTML structure html_content = """ <!DOCTYPE html> <html> <head> <title>Crawl4AI Documentation</title> <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('config', 'G-XXXXXXXXXX'); </script> </head> <body> <h1>Crawl4AI Documentation</h1> <p>Welcome to the documentation</p> </body> </html> """ async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun(f"raw://{html_content}", config=config) assert result.success # Count occurrences of gtag.js to ensure no duplicates gtag_count = result.html.count("googletagmanager.com/gtag/js") assert gtag_count <= 1, f"Found {gtag_count} gtag.js scripts, expected at most 1" # Ensure the analytics functionality is still there if gtag_count == 1: assert "dataLayer" in result.html assert "gtag('config'" in result.html if __name__ == "__main__": pytest.main([__file__, "-v"])
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/releases/test_release_0.6.4.py", "license": "Apache License 2.0", "lines": 123, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/releases/test_release_0.7.0.py
#!/usr/bin/env python3 import asyncio import pytest import os import json import tempfile from pathlib import Path from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode from crawl4ai import JsonCssExtractionStrategy, LLMExtractionStrategy, LLMConfig from crawl4ai.content_filter_strategy import BM25ContentFilter from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator from crawl4ai.async_url_seeder import AsyncUrlSeeder from crawl4ai.utils import RobotsParser class TestCrawl4AIv070: """Test suite for Crawl4AI v0.7.0 changes""" @pytest.mark.asyncio async def test_raw_url_parsing(self): """Test raw:// URL parsing logic fix""" html_content = "<html><body><h1>Test Content</h1><p>This is a test paragraph.</p></body></html>" async with AsyncWebCrawler() as crawler: # Test raw:// prefix result1 = await crawler.arun(f"raw://{html_content}") assert result1.success assert "Test Content" in result1.markdown # Test raw: prefix result2 = await crawler.arun(f"raw:{html_content}") assert result2.success assert "Test Content" in result2.markdown @pytest.mark.asyncio async def test_max_pages_limit_batch_processing(self): """Test max_pages limit is respected during batch processing""" urls = [ "https://httpbin.org/html", "https://httpbin.org/json", "https://httpbin.org/xml" ] config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, max_pages=2 ) async with AsyncWebCrawler() as crawler: results = await crawler.arun_many(urls, config=config) # Should only process 2 pages due to max_pages limit successful_results = [r for r in results if r.success] assert len(successful_results) <= 2 @pytest.mark.asyncio async def test_navigation_abort_handling(self): """Test handling of navigation aborts during file downloads""" async with AsyncWebCrawler() as crawler: # Test with a URL that might cause navigation issues result = await crawler.arun( "https://httpbin.org/status/404", config=CrawlerRunConfig(cache_mode=CacheMode.BYPASS) ) # Should not crash even with navigation issues assert result is not None @pytest.mark.asyncio async def test_screenshot_capture_fix(self): """Test screenshot capture improvements""" config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, screenshot=True ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success assert result.screenshot is not None assert len(result.screenshot) > 0 @pytest.mark.asyncio async def test_redirect_status_codes(self): """Test that real redirect status codes are surfaced""" async with AsyncWebCrawler() as crawler: # Test with a redirect URL result = await crawler.arun( "https://httpbin.org/redirect/1", config=CrawlerRunConfig(cache_mode=CacheMode.BYPASS) ) assert result.success # Should have redirect information assert result.status_code in [200, 301, 302, 303, 307, 308] @pytest.mark.asyncio async def test_local_file_processing(self): """Test local file processing with captured_console initialization""" with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f: f.write("<html><body><h1>Local File Test</h1></body></html>") temp_file = f.name try: async with AsyncWebCrawler() as crawler: result = await crawler.arun(f"file://{temp_file}") assert result.success assert "Local File Test" in result.markdown finally: os.unlink(temp_file) @pytest.mark.asyncio async def test_robots_txt_wildcard_support(self): """Test robots.txt wildcard rules support""" parser = RobotsParser() # Test wildcard patterns robots_content = "User-agent: *\nDisallow: /admin/*\nDisallow: *.pdf" # This should work without throwing exceptions assert parser is not None @pytest.mark.asyncio async def test_exclude_external_images(self): """Test exclude_external_images flag""" html_with_images = ''' <html><body> <img src="/local-image.jpg" alt="Local"> <img src="https://external.com/image.jpg" alt="External"> </body></html> ''' config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, exclude_external_images=True ) async with AsyncWebCrawler() as crawler: result = await crawler.arun(f"raw://{html_with_images}", config=config) assert result.success # External images should be excluded assert "external.com" not in result.cleaned_html @pytest.mark.asyncio async def test_llm_extraction_strategy_fix(self): """Test LLM extraction strategy choices error fix""" if not os.getenv("OPENAI_API_KEY"): pytest.skip("OpenAI API key not available") llm_config = LLMConfig( provider="openai/gpt-4o-mini", api_token=os.getenv("OPENAI_API_KEY") ) strategy = LLMExtractionStrategy( llm_config=llm_config, instruction="Extract the main heading", extraction_type="block" ) config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, extraction_strategy=strategy ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success # Should not throw 'str' object has no attribute 'choices' error assert result.extracted_content is not None @pytest.mark.asyncio async def test_wait_for_timeout(self): """Test separate timeout for wait_for condition""" config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, wait_for="css:non-existent-element", wait_for_timeout=1000 # 1 second timeout ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) # Should timeout gracefully and still return result assert result is not None @pytest.mark.asyncio async def test_bm25_content_filter_language_parameter(self): """Test BM25 filter with language parameter for stemming""" content_filter = BM25ContentFilter( user_query="test content", language="english", use_stemming=True ) markdown_generator = DefaultMarkdownGenerator( content_filter=content_filter ) config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, markdown_generator=markdown_generator ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success assert result.markdown is not None @pytest.mark.asyncio async def test_url_normalization(self): """Test URL normalization for invalid schemes and trailing slashes""" async with AsyncWebCrawler() as crawler: # Test with trailing slash result = await crawler.arun( "https://httpbin.org/html/", config=CrawlerRunConfig(cache_mode=CacheMode.BYPASS) ) assert result.success @pytest.mark.asyncio async def test_max_scroll_steps(self): """Test max_scroll_steps parameter for full page scanning""" config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, scan_full_page=True, max_scroll_steps=3 ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success @pytest.mark.asyncio async def test_async_url_seeder(self): """Test AsyncUrlSeeder functionality""" seeder = AsyncUrlSeeder( base_url="https://httpbin.org", max_depth=1, max_urls=5 ) async with AsyncWebCrawler() as crawler: urls = await seeder.seed(crawler) assert isinstance(urls, list) assert len(urls) <= 5 @pytest.mark.asyncio async def test_pdf_processing_timeout(self): """Test PDF processing with timeout""" config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, pdf=True, pdf_timeout=10000 # 10 seconds ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success # PDF might be None for HTML pages, but should not hang assert result.pdf is not None or result.pdf is None @pytest.mark.asyncio async def test_browser_session_management(self): """Test improved browser session management""" browser_config = BrowserConfig( headless=True, use_persistent_context=True ) async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( "https://httpbin.org/html", config=CrawlerRunConfig(cache_mode=CacheMode.BYPASS) ) assert result.success @pytest.mark.asyncio async def test_memory_management(self): """Test memory management features""" config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, memory_threshold_percent=80.0, check_interval=1.0, memory_wait_timeout=600 # 10 minutes default ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success @pytest.mark.asyncio async def test_virtual_scroll_support(self): """Test virtual scroll support for modern web scraping""" config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, scan_full_page=True, virtual_scroll=True ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success @pytest.mark.asyncio async def test_adaptive_crawling(self): """Test adaptive crawling feature""" config = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, adaptive_crawling=True ) async with AsyncWebCrawler() as crawler: result = await crawler.arun("https://httpbin.org/html", config=config) assert result.success if __name__ == "__main__": # Run the tests pytest.main([__file__, "-v"])
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/releases/test_release_0.7.0.py", "license": "Apache License 2.0", "lines": 268, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_link_extractor.py
#!/usr/bin/env python3 """ Test script for Link Extractor functionality """ from crawl4ai.models import Link from crawl4ai import AsyncWebCrawler, CrawlerRunConfig from crawl4ai import LinkPreviewConfig import asyncio import sys import os # Add the crawl4ai directory to the path sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'crawl4ai')) async def test_link_extractor(): """Test the link extractor functionality""" print("🔗 Testing Link Extractor Functionality") print("=" * 50) # Test configuration with link extraction AND scoring enabled config = CrawlerRunConfig( link_preview_config=LinkPreviewConfig( include_internal=True, include_external=False, # Only internal links for this test # No include/exclude patterns for first test - let's see what we get query="API documentation reference guide", score_threshold=0.3, concurrency=5, timeout=10, max_links=5, # Just test with 5 links first verbose=True # Show detailed progress ), score_links=True, # Enable intrinsic link scoring only_text=True, verbose=True ) # Test URLs test_urls = [ "https://docs.python.org/3/", # Python docs - should have many internal links "https://httpbin.org/", # Simple site for testing ] async with AsyncWebCrawler() as crawler: for url in test_urls: print(f"\n🌐 Testing URL: {url}") print("-" * 40) try: result = await crawler.arun(url, config=config) # Debug: Check if link extraction config is being passed print(f"🔍 Debug - Link extraction config: {config.link_preview_config.to_dict() if config.link_preview_config else None}") print(f"🔍 Debug - Score links: {config.score_links}") if result.success: print(f"✅ Crawl successful!") print( f"📄 Page title: {result.metadata.get('title', 'No title')}") # Check links - handle both dict and Links object structure if isinstance(result.links, dict): internal_links = [ Link(**link) for link in result.links.get('internal', [])] external_links = [ Link(**link) for link in result.links.get('external', [])] else: internal_links = result.links.internal external_links = result.links.external print(f"🔗 Found {len(internal_links)} internal links") print(f"🌍 Found {len(external_links)} external links") # Show links with head data links_with_head = [link for link in internal_links + external_links if hasattr(link, 'head_data') and link.head_data] print( f"🧠 Links with head data extracted: {len(links_with_head)}") # Show all score types for all links (first 3) all_links = internal_links + external_links if all_links: print(f"\n🔢 Sample link scores (first 3 links):") for i, link in enumerate(all_links[:3]): print(f"\n {i+1}. {link.href}") # Show intrinsic score if hasattr(link, 'intrinsic_score') and link.intrinsic_score is not None: if link.intrinsic_score == float('inf'): print(f" Intrinsic Score: ∞ (scoring disabled)") else: print(f" Intrinsic Score: {link.intrinsic_score:.2f}/10.0") else: print(f" Intrinsic Score: Not available") # Show contextual score (BM25) if hasattr(link, 'contextual_score') and link.contextual_score is not None: print(f" Contextual Score: {link.contextual_score:.3f}") else: print(f" Contextual Score: Not available") # Show total score if hasattr(link, 'total_score') and link.total_score is not None: print(f" Total Score: {link.total_score:.3f}") else: print(f" Total Score: Not available") print(f" Text: '{link.text[:50]}...' " if link.text else " Text: (no text)") if links_with_head: print("\n📊 Sample links with head data:") # Show top 3 for i, link in enumerate(links_with_head[:3]): print(f"\n {i+1}. {link.href}") print( f" Status: {link.head_extraction_status}") # Show all three score types print(f" 📊 Scoring Summary:") if hasattr(link, 'intrinsic_score') and link.intrinsic_score is not None: if link.intrinsic_score == float('inf'): print(f" • Intrinsic Score: ∞ (scoring disabled)") else: print(f" • Intrinsic Score: {link.intrinsic_score:.2f}/10.0") else: print(f" • Intrinsic Score: Not available") if hasattr(link, 'contextual_score') and link.contextual_score is not None: print(f" • Contextual Score: {link.contextual_score:.3f}") else: print(f" • Contextual Score: Not available") if hasattr(link, 'total_score') and link.total_score is not None: print(f" • Total Score: {link.total_score:.3f}") else: print(f" • Total Score: Not available") if link.head_data: title = link.head_data.get('title', 'No title') if title: print(f" Title: {title[:60]}...") meta = link.head_data.get('meta', {}) if 'description' in meta and meta['description']: desc = meta['description'] print(f" Description: {desc[:80]}...") # Show link metadata keys (should now be properly formatted) link_data = link.head_data.get('link', {}) if link_data: keys = list(link_data.keys())[:3] print(f" Link types: {keys}") # Show failed extractions failed_links = [link for link in internal_links + external_links if hasattr(link, 'head_extraction_status') and link.head_extraction_status == 'failed'] if failed_links: print( f"\n❌ Failed head extractions: {len(failed_links)}") for link in failed_links[:2]: # Show first 2 failures print(f" - {link.href}") if hasattr(link, 'head_extraction_error') and link.head_extraction_error: print( f" Error: {link.head_extraction_error}") else: print(f"❌ Crawl failed: {result.error_message}") except Exception as e: print(f"💥 Error testing {url}: {str(e)}") import traceback traceback.print_exc() def test_config_examples(): """Show example configurations""" print("\n📚 Example Configurations") print("=" * 50) examples = [ { "name": "BM25 Scored Documentation Links", "config": LinkPreviewConfig( include_internal=True, include_external=False, include_patterns=["*/docs/*", "*/api/*", "*/reference/*"], query="API documentation reference guide", score_threshold=0.3, max_links=30, verbose=True ) }, { "name": "Internal Links Only", "config": LinkPreviewConfig( include_internal=True, include_external=False, max_links=50, verbose=True ) }, { "name": "External Links with Patterns", "config": LinkPreviewConfig( include_internal=False, include_external=True, include_patterns=["*github.com*", "*stackoverflow.com*"], max_links=20, concurrency=10 ) }, { "name": "High-Performance Mode", "config": LinkPreviewConfig( include_internal=True, include_external=False, concurrency=20, timeout=3, max_links=100, verbose=False ) } ] for example in examples: print(f"\n📝 {example['name']}:") print(" Configuration:") config_dict = example['config'].to_dict() for key, value in config_dict.items(): print(f" {key}: {value}") print(" Usage:") print(" from crawl4ai import LinkPreviewConfig") print(" config = CrawlerRunConfig(") print(" link_preview_config=LinkPreviewConfig(") for key, value in config_dict.items(): if isinstance(value, str): print(f" {key}='{value}',") elif isinstance(value, list) and value: print(f" {key}={value},") elif value is not None: print(f" {key}={value},") print(" )") print(" )") if __name__ == "__main__": # Show configuration examples first test_config_examples() # Run the actual test print("\n🚀 Running Link Extractor Tests...") asyncio.run(test_link_extractor()) print("\n✨ Test completed!")
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_link_extractor.py", "license": "Apache License 2.0", "lines": 221, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_normalize_url.py
import unittest from crawl4ai.utils import normalize_url class TestNormalizeUrl(unittest.TestCase): def test_basic_relative_path(self): self.assertEqual(normalize_url("path/to/page.html", "http://example.com/base/"), "http://example.com/base/path/to/page.html") def test_base_url_with_trailing_slash(self): self.assertEqual(normalize_url("page.html", "http://example.com/base/"), "http://example.com/base/page.html") def test_base_url_without_trailing_slash(self): # If normalize_url correctly uses urljoin, "base" is treated as a file. self.assertEqual(normalize_url("page.html", "http://example.com/base"), "http://example.com/page.html") def test_absolute_url_as_href(self): self.assertEqual(normalize_url("http://another.com/page.html", "http://example.com/"), "http://another.com/page.html") def test_href_with_leading_trailing_spaces(self): self.assertEqual(normalize_url(" page.html ", "http://example.com/"), "http://example.com/page.html") def test_empty_href(self): # urljoin with an empty href and base ending in '/' returns the base. self.assertEqual(normalize_url("", "http://example.com/base/"), "http://example.com/base/") # urljoin with an empty href and base not ending in '/' also returns base. self.assertEqual(normalize_url("", "http://example.com/base"), "http://example.com/base") def test_href_with_query_parameters(self): self.assertEqual(normalize_url("page.html?query=test", "http://example.com/"), "http://example.com/page.html?query=test") def test_href_with_fragment(self): self.assertEqual(normalize_url("page.html#section", "http://example.com/"), "http://example.com/page.html#section") def test_different_scheme_in_href(self): self.assertEqual(normalize_url("https://secure.example.com/page.html", "http://example.com/"), "https://secure.example.com/page.html") def test_parent_directory_in_href(self): self.assertEqual(normalize_url("../otherpage.html", "http://example.com/base/current/"), "http://example.com/base/otherpage.html") def test_root_relative_href(self): self.assertEqual(normalize_url("/otherpage.html", "http://example.com/base/current/"), "http://example.com/otherpage.html") def test_base_url_with_path_and_no_trailing_slash(self): # If normalize_url correctly uses urljoin, "path" is treated as a file. self.assertEqual(normalize_url("file.html", "http://example.com/path"), "http://example.com/file.html") def test_base_url_is_just_domain(self): self.assertEqual(normalize_url("page.html", "http://example.com"), "http://example.com/page.html") def test_href_is_only_query(self): self.assertEqual(normalize_url("?query=true", "http://example.com/page.html"), "http://example.com/page.html?query=true") def test_href_is_only_fragment(self): self.assertEqual(normalize_url("#fragment", "http://example.com/page.html"), "http://example.com/page.html#fragment") def test_relative_link_from_base_file_url(self): """ Tests the specific bug report: relative links from a base URL that is a file. Example: Page URL: http://example.com/path/to/document.html Link on page: <a href="./file.xlsx"> Expected: http://example.com/path/to/file.xlsx """ base_url_file = "http://example.com/zwgk/fdzdgk/zdxx/spaq/t19360680.shtml" href_relative_current_dir = "./P020241203375994691134.xlsx" expected_url1 = "http://example.com/zwgk/fdzdgk/zdxx/spaq/P020241203375994691134.xlsx" self.assertEqual(normalize_url(href_relative_current_dir, base_url_file), expected_url1) # Test with a relative link that doesn't start with "./" href_relative_no_dot_slash = "another.doc" expected_url2 = "http://example.com/zwgk/fdzdgk/zdxx/spaq/another.doc" self.assertEqual(normalize_url(href_relative_no_dot_slash, base_url_file), expected_url2) def test_invalid_base_url_scheme(self): with self.assertRaises(ValueError) as context: normalize_url("page.html", "ftp://example.com/") self.assertIn("Invalid base URL format", str(context.exception)) def test_invalid_base_url_netloc(self): with self.assertRaises(ValueError) as context: normalize_url("page.html", "http:///path/") self.assertIn("Invalid base URL format", str(context.exception)) def test_base_url_with_port(self): self.assertEqual(normalize_url("path/file.html", "http://example.com:8080/base/"), "http://example.com:8080/base/path/file.html") def test_href_with_special_characters(self): self.assertEqual(normalize_url("path%20with%20spaces/file.html", "http://example.com/"), "http://example.com/path%20with%20spaces/file.html") if __name__ == '__main__': unittest.main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_normalize_url.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:tests/test_virtual_scroll.py
""" Test virtual scroll implementation according to the design: - Create a page with virtual scroll that replaces content - Verify all 1000 items are captured """ import asyncio import os from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, VirtualScrollConfig, CacheMode, BrowserConfig async def test_virtual_scroll(): """Test virtual scroll with content replacement (true virtual scroll)""" # Create test HTML with true virtual scroll that replaces content test_html = ''' <html> <head> <style> #container { height: 500px; overflow-y: auto; border: 1px solid #ccc; } .item { height: 50px; padding: 10px; border-bottom: 1px solid #eee; } </style> </head> <body> <h1>Virtual Scroll Test - 1000 Items</h1> <div id="container"></div> <script> // True virtual scroll that REPLACES content const container = document.getElementById('container'); const totalItems = 1000; const itemsPerPage = 10; // Only show 10 items at a time let currentStartIndex = 0; // All our data const allData = []; for (let i = 0; i < totalItems; i++) { allData.push({ id: i, text: `Item ${i + 1} of ${totalItems} - Unique ID: ${i}` }); } // Function to render current page function renderPage(startIndex) { const items = []; const endIndex = Math.min(startIndex + itemsPerPage, totalItems); for (let i = startIndex; i < endIndex; i++) { const item = allData[i]; items.push(`<div class="item" data-index="${item.id}">${item.text}</div>`); } // REPLACE container content (virtual scroll) container.innerHTML = items.join(''); currentStartIndex = startIndex; } // Initial render renderPage(0); // Handle scroll container.addEventListener('scroll', () => { const scrollTop = container.scrollTop; const scrollHeight = container.scrollHeight; const clientHeight = container.clientHeight; // Calculate which page we should show based on scroll position // This creates a virtual scroll effect if (scrollTop + clientHeight >= scrollHeight - 50) { // Load next page const nextIndex = currentStartIndex + itemsPerPage; if (nextIndex < totalItems) { renderPage(nextIndex); // Reset scroll to top to continue scrolling container.scrollTop = 10; } } }); </script> </body> </html> ''' # Save test HTML to a file import tempfile with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f: f.write(test_html) test_file_path = f.name httpd = None old_cwd = os.getcwd() try: # Start a simple HTTP server import http.server import socketserver import threading import random # Find available port for _ in range(10): PORT = random.randint(8000, 9999) try: Handler = http.server.SimpleHTTPRequestHandler os.chdir(os.path.dirname(test_file_path)) httpd = socketserver.TCPServer(("", PORT), Handler) break except OSError: continue if httpd is None: raise RuntimeError("Could not find available port") server_thread = threading.Thread(target=httpd.serve_forever) server_thread.daemon = True server_thread.start() # Give server time to start await asyncio.sleep(0.5) # Configure virtual scroll # With 10 items per page and 1000 total, we need 100 pages # Let's do 120 scrolls to ensure we get everything virtual_config = VirtualScrollConfig( container_selector="#container", scroll_count=120, scroll_by="container_height", # Scroll by container height wait_after_scroll=0.1 # Quick wait for test ) config = CrawlerRunConfig( virtual_scroll_config=virtual_config, cache_mode=CacheMode.BYPASS, verbose=True ) browserConfig = BrowserConfig( headless= False ) async with AsyncWebCrawler(verbose=True, config=browserConfig) as crawler: result = await crawler.arun( url=f"http://localhost:{PORT}/{os.path.basename(test_file_path)}", config=config ) # Count all items in the result import re items = re.findall(r'data-index="(\d+)"', result.html) unique_indices = sorted(set(int(idx) for idx in items)) print(f"\n{'='*60}") print(f"TEST RESULTS:") print(f"HTML Length: {len(result.html)}") print(f"Total items found: {len(items)}") print(f"Unique items: {len(unique_indices)}") if unique_indices: print(f"Item indices: {min(unique_indices)} to {max(unique_indices)}") print(f"Expected: 0 to 999") # Check for gaps expected = set(range(1000)) actual = set(unique_indices) missing = expected - actual if missing: print(f"\n❌ FAILED! Missing {len(missing)} items") print(f"Missing indices: {sorted(missing)[:10]}{'...' if len(missing) > 10 else ''}") else: print(f"\n✅ SUCCESS! All 1000 items captured!") # Show some sample items print(f"\nSample items from result:") sample_items = re.findall(r'<div class="item"[^>]*>([^<]+)</div>', result.html)[:5] for item in sample_items: print(f" - {item}") print(f"{'='*60}\n") finally: # Clean up if httpd: httpd.shutdown() os.chdir(old_cwd) os.unlink(test_file_path) if __name__ == "__main__": asyncio.run(test_virtual_scroll())
{ "repo_id": "unclecode/crawl4ai", "file_path": "tests/test_virtual_scroll.py", "license": "Apache License 2.0", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unclecode/crawl4ai:deploy/docker/job.py
""" Job endpoints (enqueue + poll) for long-running LL​M extraction and raw crawl. Relies on the existing Redis task helpers in api.py """ from typing import Dict, Optional, Callable from fastapi import APIRouter, BackgroundTasks, Depends, Request from pydantic import BaseModel, HttpUrl from api import ( handle_llm_request, handle_crawl_job, handle_task_status, ) from schemas import WebhookConfig # ------------- dependency placeholders ------------- _redis = None # will be injected from server.py _config = None _token_dep: Callable = lambda: None # dummy until injected # public router router = APIRouter() # === init hook called by server.py ========================================= def init_job_router(redis, config, token_dep) -> APIRouter: """Inject shared singletons and return the router for mounting.""" global _redis, _config, _token_dep _redis, _config, _token_dep = redis, config, token_dep return router # ---------- payload models -------------------------------------------------- class LlmJobPayload(BaseModel): url: HttpUrl q: str schema: Optional[str] = None cache: bool = False provider: Optional[str] = None webhook_config: Optional[WebhookConfig] = None temperature: Optional[float] = None base_url: Optional[str] = None class CrawlJobPayload(BaseModel): urls: list[HttpUrl] browser_config: Dict = {} crawler_config: Dict = {} webhook_config: Optional[WebhookConfig] = None # ---------- LL​M job --------------------------------------------------------- @router.post("/llm/job", status_code=202) async def llm_job_enqueue( payload: LlmJobPayload, background_tasks: BackgroundTasks, request: Request, _td: Dict = Depends(lambda: _token_dep()), # late-bound dep ): webhook_config = None if payload.webhook_config: webhook_config = payload.webhook_config.model_dump(mode='json') return await handle_llm_request( _redis, background_tasks, request, str(payload.url), query=payload.q, schema=payload.schema, cache=payload.cache, config=_config, provider=payload.provider, webhook_config=webhook_config, temperature=payload.temperature, api_base_url=payload.base_url, ) @router.get("/llm/job/{task_id}") async def llm_job_status( request: Request, task_id: str, _td: Dict = Depends(lambda: _token_dep()) ): return await handle_task_status(_redis, task_id, base_url=str(request.base_url)) # ---------- CRAWL job ------------------------------------------------------- @router.post("/crawl/job", status_code=202) async def crawl_job_enqueue( payload: CrawlJobPayload, background_tasks: BackgroundTasks, _td: Dict = Depends(lambda: _token_dep()), ): webhook_config = None if payload.webhook_config: webhook_config = payload.webhook_config.model_dump(mode='json') return await handle_crawl_job( _redis, background_tasks, [str(u) for u in payload.urls], payload.browser_config, payload.crawler_config, config=_config, webhook_config=webhook_config, ) @router.get("/crawl/job/{task_id}") async def crawl_job_status( request: Request, task_id: str, _td: Dict = Depends(lambda: _token_dep()) ): return await handle_task_status(_redis, task_id, base_url=str(request.base_url))
{ "repo_id": "unclecode/crawl4ai", "file_path": "deploy/docker/job.py", "license": "Apache License 2.0", "lines": 98, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:deploy/docker/schemas.py
from typing import List, Optional, Dict from enum import Enum from pydantic import BaseModel, Field, HttpUrl from utils import FilterType class CrawlRequest(BaseModel): urls: List[str] = Field(min_length=1, max_length=100) browser_config: Optional[Dict] = Field(default_factory=dict) crawler_config: Optional[Dict] = Field(default_factory=dict) class HookConfig(BaseModel): """Configuration for user-provided hooks""" code: Dict[str, str] = Field( default_factory=dict, description="Map of hook points to Python code strings" ) timeout: int = Field( default=30, ge=1, le=120, description="Timeout in seconds for each hook execution" ) class Config: schema_extra = { "example": { "code": { "on_page_context_created": """ async def hook(page, context, **kwargs): # Block images to speed up crawling await context.route("**/*.{png,jpg,jpeg,gif}", lambda route: route.abort()) return page """, "before_retrieve_html": """ async def hook(page, context, **kwargs): # Scroll to load lazy content await page.evaluate("window.scrollTo(0, document.body.scrollHeight)") await page.wait_for_timeout(2000) return page """ }, "timeout": 30 } } class CrawlRequestWithHooks(CrawlRequest): """Extended crawl request with hooks support""" hooks: Optional[HookConfig] = Field( default=None, description="Optional user-provided hook functions" ) class MarkdownRequest(BaseModel): """Request body for the /md endpoint.""" url: str = Field(..., description="Absolute http/https URL to fetch") f: FilterType = Field(FilterType.FIT, description="Content‑filter strategy: fit, raw, bm25, or llm") q: Optional[str] = Field(None, description="Query string used by BM25/LLM filters") c: Optional[str] = Field("0", description="Cache‑bust / revision counter") provider: Optional[str] = Field(None, description="LLM provider override (e.g., 'anthropic/claude-3-opus')") temperature: Optional[float] = Field(None, description="LLM temperature override (0.0-2.0)") base_url: Optional[str] = Field(None, description="LLM API base URL override") class RawCode(BaseModel): code: str class HTMLRequest(BaseModel): url: str class ScreenshotRequest(BaseModel): url: str screenshot_wait_for: Optional[float] = 2 output_path: Optional[str] = None class PDFRequest(BaseModel): url: str output_path: Optional[str] = None class JSEndpointRequest(BaseModel): url: str scripts: List[str] = Field( ..., description="List of separated JavaScript snippets to execute" ) class WebhookConfig(BaseModel): """Configuration for webhook notifications.""" webhook_url: HttpUrl webhook_data_in_payload: bool = False webhook_headers: Optional[Dict[str, str]] = None class WebhookPayload(BaseModel): """Payload sent to webhook endpoints.""" task_id: str task_type: str # "crawl", "llm_extraction", etc. status: str # "completed" or "failed" timestamp: str # ISO 8601 format urls: List[str] error: Optional[str] = None data: Optional[Dict] = None # Included only if webhook_data_in_payload=True
{ "repo_id": "unclecode/crawl4ai", "file_path": "deploy/docker/schemas.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unclecode/crawl4ai:docs/apps/linkdin/c4ai_discover.py
#!/usr/bin/env python3 """ c4ai-discover — Stage‑1 Discovery CLI Scrapes LinkedIn company search + their people pages and dumps two newline‑delimited JSON files: companies.jsonl and people.jsonl. Key design rules ---------------- * No BeautifulSoup — Crawl4AI only for network + HTML fetch. * JsonCssExtractionStrategy for structured scraping; schema auto‑generated once from sample HTML provided by user and then cached under ./schemas/. * Defaults are embedded so the file runs inside VS Code debugger without CLI args. * If executed as a console script (argv > 1), CLI flags win. * Lightweight deps: argparse + Crawl4AI stack. Author: Tom @ Kidocode 2025‑04‑26 """ from __future__ import annotations import warnings, re warnings.filterwarnings( "ignore", message=r"The pseudo class ':contains' is deprecated, ':-soup-contains' should be used.*", category=FutureWarning, module=r"soupsieve" ) # ─────────────────────────────────────────────────────────────────────────────── # Imports # ─────────────────────────────────────────────────────────────────────────────── import argparse import random import asyncio import json import logging import os import pathlib import sys # 3rd-party rich for pretty logging from rich.console import Console from rich.logging import RichHandler from datetime import datetime, UTC from textwrap import dedent from types import SimpleNamespace from typing import Dict, List, Optional from urllib.parse import quote from pathlib import Path from glob import glob from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CacheMode, CrawlerRunConfig, JsonCssExtractionStrategy, BrowserProfiler, LLMConfig, ) # ─────────────────────────────────────────────────────────────────────────────── # Constants / paths # ─────────────────────────────────────────────────────────────────────────────── BASE_DIR = pathlib.Path(__file__).resolve().parent SCHEMA_DIR = BASE_DIR / "schemas" SCHEMA_DIR.mkdir(parents=True, exist_ok=True) COMPANY_SCHEMA_PATH = SCHEMA_DIR / "company_card.json" PEOPLE_SCHEMA_PATH = SCHEMA_DIR / "people_card.json" # ---------- deterministic target JSON examples ---------- _COMPANY_SCHEMA_EXAMPLE = { "handle": "/company/posify/", "profile_image": "https://media.licdn.com/dms/image/v2/.../logo.jpg", "name": "Management Research Services, Inc. (MRS, Inc)", "descriptor": "Insurance • Milwaukee, Wisconsin", "about": "Insurance • Milwaukee, Wisconsin", "followers": 1000 } _PEOPLE_SCHEMA_EXAMPLE = { "profile_url": "https://www.linkedin.com/in/lily-ng/", "name": "Lily Ng", "headline": "VP Product @ Posify", "followers": 890, "connection_degree": "2nd", "avatar_url": "https://media.licdn.com/dms/image/v2/.../lily.jpg" } # Provided sample HTML snippets (trimmed) — used exactly once to cold‑generate schema. _SAMPLE_COMPANY_HTML = (Path(__file__).resolve().parent / "snippets/company.html").read_text() _SAMPLE_PEOPLE_HTML = (Path(__file__).resolve().parent / "snippets/people.html").read_text() # --------- tighter schema prompts ---------- _COMPANY_SCHEMA_QUERY = dedent( """ Using the supplied <li> company-card HTML, build a JsonCssExtractionStrategy schema that, for every card, outputs *exactly* the keys shown in the example JSON below. JSON spec: • handle – href of the outermost <a> that wraps the logo/title, e.g. "/company/posify/" • profile_image – absolute URL of the <img> inside that link • name – text of the <a> inside the <span class*='t-16'> • descriptor – text line with industry • location • about – text of the <div class*='t-normal'> below the name (industry + geo) • followers – integer parsed from the <div> containing 'followers' IMPORTANT: Do not use the base64 kind of classes to target element. It's not reliable. The main div parent contains these li element is "div.search-results-container" you can use this. The <ul> parent has "role" equal to "list". Using these two should be enough to target the <li> elements. IMPORTANT: Remember there might be multiple <a> tags that start with https://www.linkedin.com/company/[NAME], so in case you refer to them for different fields, make sure to be more specific. One has the image, and one has the person's name. IMPORTANT: Be very smart in selecting the correct and unique way to address the element. You should ensure your selector points to a single element and is unique to the place that contains the information. """ ) _PEOPLE_SCHEMA_QUERY = dedent( """ Using the supplied <li> people-card HTML, build a JsonCssExtractionStrategy schema that outputs exactly the keys in the example JSON below. Fields: • profile_url – href of the outermost profile link • name – text inside artdeco-entity-lockup__title • headline – inner text of artdeco-entity-lockup__subtitle • followers – integer parsed from the span inside lt-line-clamp--multi-line • connection_degree – '1st', '2nd', etc. from artdeco-entity-lockup__badge • avatar_url – src of the <img> within artdeco-entity-lockup__image IMPORTANT: Do not use the base64 kind of classes to target element. It's not reliable. The main div parent contains these li element is a "div" has these classes "artdeco-card org-people-profile-card__card-spacing org-people__card-margin-bottom". """ ) # --------------------------------------------------------------------------- # Utility helpers # --------------------------------------------------------------------------- def _load_or_build_schema( path: pathlib.Path, sample_html: str, query: str, example_json: Dict, force = False ) -> Dict: """Load schema from path, else call generate_schema once and persist.""" if path.exists() and not force: return json.loads(path.read_text()) logging.info("[SCHEMA] Generating schema %s", path.name) schema = JsonCssExtractionStrategy.generate_schema( html=sample_html, llm_config=LLMConfig( provider=os.getenv("C4AI_SCHEMA_PROVIDER", "openai/gpt-4o"), api_token=os.getenv("OPENAI_API_KEY", "env:OPENAI_API_KEY"), ), query=query, target_json_example=json.dumps(example_json, indent=2), ) path.write_text(json.dumps(schema, indent=2)) return schema def _openai_friendly_number(text: str) -> Optional[int]: """Extract first int from text like '1K followers' (returns 1000).""" import re m = re.search(r"(\d[\d,]*)", text.replace(",", "")) if not m: return None val = int(m.group(1)) if "k" in text.lower(): val *= 1000 if "m" in text.lower(): val *= 1_000_000 return val # --------------------------------------------------------------------------- # Core async workers # --------------------------------------------------------------------------- async def crawl_company_search(crawler: AsyncWebCrawler, url: str, schema: Dict, limit: int) -> List[Dict]: """Paginate 10-item company search pages until `limit` reached.""" extraction = JsonCssExtractionStrategy(schema) cfg = CrawlerRunConfig( extraction_strategy=extraction, cache_mode=CacheMode.BYPASS, wait_for = ".search-marvel-srp", session_id="company_search", delay_before_return_html=1, magic = True, verbose= False, ) companies, page = [], 1 while len(companies) < max(limit, 10): paged_url = f"{url}&page={page}" res = await crawler.arun(paged_url, config=cfg) batch = json.loads(res[0].extracted_content) if not batch: break for item in batch: name = item.get("name", "").strip() handle = item.get("handle", "").strip() if not handle or not name: continue descriptor = item.get("descriptor") about = item.get("about") followers = _openai_friendly_number(str(item.get("followers", ""))) companies.append( { "handle": handle, "name": name, "descriptor": descriptor, "about": about, "followers": followers, "people_url": f"{handle}people/", "captured_at": datetime.now(UTC).isoformat(timespec="seconds") + "Z", } ) page += 1 logging.info( f"[dim]Page {page}[/] — running total: {len(companies)}/{limit} companies" ) return companies[:max(limit, 10)] async def crawl_people_page( crawler: AsyncWebCrawler, people_url: str, schema: Dict, limit: int, title_kw: str, ) -> List[Dict]: people_u = f"{people_url}?keywords={quote(title_kw)}" extraction = JsonCssExtractionStrategy(schema) cfg = CrawlerRunConfig( extraction_strategy=extraction, # scan_full_page=True, cache_mode=CacheMode.BYPASS, magic=True, wait_for=".org-people-profile-card__card-spacing", wait_for_images=5000, delay_before_return_html=1, session_id="people_search", ) res = await crawler.arun(people_u, config=cfg) if not res[0].success: return [] raw = json.loads(res[0].extracted_content) people = [] for p in raw[:limit]: followers = _openai_friendly_number(str(p.get("followers", ""))) people.append( { "profile_url": p.get("profile_url"), "name": p.get("name"), "headline": p.get("headline"), "followers": followers, "connection_degree": p.get("connection_degree"), "avatar_url": p.get("avatar_url"), } ) return people # --------------------------------------------------------------------------- # CLI + main # --------------------------------------------------------------------------- def build_arg_parser() -> argparse.ArgumentParser: ap = argparse.ArgumentParser("c4ai-discover — Crawl4AI LinkedIn discovery") sub = ap.add_subparsers(dest="cmd", required=False, help="run scope") def add_flags(parser: argparse.ArgumentParser): parser.add_argument("--query", required=False, help="query keyword(s)") parser.add_argument("--geo", required=False, type=int, help="LinkedIn geoUrn") parser.add_argument("--title-filters", default="Product,Engineering", help="comma list of job keywords") parser.add_argument("--max-companies", type=int, default=1000) parser.add_argument("--max-people", type=int, default=500) parser.add_argument("--profile-name", default=str(pathlib.Path.home() / ".crawl4ai/profiles/profile_linkedin_uc")) parser.add_argument("--outdir", default="./output") parser.add_argument("--concurrency", type=int, default=4) parser.add_argument("--log-level", default="info", choices=["debug", "info", "warn", "error"]) add_flags(sub.add_parser("full")) add_flags(sub.add_parser("companies")) add_flags(sub.add_parser("people")) # global flags ap.add_argument( "--debug", action="store_true", help="Use built-in demo defaults (same as C4AI_DEMO_DEBUG=1)", ) return ap def detect_debug_defaults(force = False) -> SimpleNamespace: if not force and sys.gettrace() is None and not os.getenv("C4AI_DEMO_DEBUG"): return SimpleNamespace() # ----- debug‑friendly defaults ----- return SimpleNamespace( cmd="full", query="health insurance management", geo=102713980, # title_filters="Product,Engineering", title_filters="", max_companies=10, max_people=5, profile_name="profile_linkedin_uc", outdir="./debug_out", concurrency=2, log_level="debug", ) async def async_main(opts): # ─────────── logging setup ─────────── console = Console() logging.basicConfig( level=opts.log_level.upper(), format="%(message)s", handlers=[RichHandler(console=console, markup=True, rich_tracebacks=True)], ) # ------------------------------------------------------------------- # Load or build schemas (one‑time LLM call each) # ------------------------------------------------------------------- company_schema = _load_or_build_schema( COMPANY_SCHEMA_PATH, _SAMPLE_COMPANY_HTML, _COMPANY_SCHEMA_QUERY, _COMPANY_SCHEMA_EXAMPLE, # True ) people_schema = _load_or_build_schema( PEOPLE_SCHEMA_PATH, _SAMPLE_PEOPLE_HTML, _PEOPLE_SCHEMA_QUERY, _PEOPLE_SCHEMA_EXAMPLE, # True ) outdir = BASE_DIR / pathlib.Path(opts.outdir) outdir.mkdir(parents=True, exist_ok=True) f_companies = (BASE_DIR / outdir / "companies.jsonl").open("a", encoding="utf-8") f_people = (BASE_DIR / outdir / "people.jsonl").open("a", encoding="utf-8") # ------------------------------------------------------------------- # Prepare crawler with cookie pool rotation # ------------------------------------------------------------------- profiler = BrowserProfiler() path = profiler.get_profile_path(opts.profile_name) bc = BrowserConfig( headless=False, verbose=False, user_data_dir=path, use_managed_browser=True, user_agent_mode = "random", user_agent_generator_config= { "platforms": "mobile", "os": "Android" } ) crawler = AsyncWebCrawler(config=bc) await crawler.start() # Single worker for simplicity; concurrency can be scaled by arun_many if needed. # crawler = await next_crawler().start() try: # Build LinkedIn search URL search_url = f'https://www.linkedin.com/search/results/companies/?keywords={quote(opts.query)}&companyHqGeo="{opts.geo}"' logging.info("Seed URL => %s", search_url) companies: List[Dict] = [] if opts.cmd in ("companies", "full"): companies = await crawl_company_search( crawler, search_url, company_schema, opts.max_companies ) for c in companies: f_companies.write(json.dumps(c, ensure_ascii=False) + "\n") logging.info(f"[bold green]✓[/] Companies scraped so far: {len(companies)}") if opts.cmd in ("people", "full"): if not companies: # load from previous run src = outdir / "companies.jsonl" if not src.exists(): logging.error("companies.jsonl missing — run companies/full first") return 10 companies = [json.loads(l) for l in src.read_text().splitlines()] total_people = 0 title_kw = " ".join([t.strip() for t in opts.title_filters.split(",") if t.strip()]) if opts.title_filters else "" for comp in companies: people = await crawl_people_page( crawler, comp["people_url"], people_schema, opts.max_people, title_kw, ) for p in people: rec = p | { "company_handle": comp["handle"], # "captured_at": datetime.now(UTC).isoformat(timespec="seconds") + "Z", "captured_at": datetime.now(UTC).isoformat(timespec="seconds") + "Z", } f_people.write(json.dumps(rec, ensure_ascii=False) + "\n") total_people += len(people) logging.info( f"{comp['name']} — [cyan]{len(people)}[/] people extracted" ) await asyncio.sleep(random.uniform(0.5, 1)) logging.info("Total people scraped: %d", total_people) finally: await crawler.close() f_companies.close() f_people.close() return 0 def main(): parser = build_arg_parser() cli_opts = parser.parse_args() # decide on debug defaults if cli_opts.debug: opts = detect_debug_defaults(force=True) cli_opts = opts else: env_defaults = detect_debug_defaults() opts = env_defaults if env_defaults else cli_opts if not getattr(opts, "cmd", None): opts.cmd = "full" exit_code = asyncio.run(async_main(cli_opts)) sys.exit(exit_code) if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/apps/linkdin/c4ai_discover.py", "license": "Apache License 2.0", "lines": 394, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/apps/linkdin/c4ai_insights.py
#!/usr/bin/env python3 """ Stage-2 Insights builder ------------------------ Reads companies.jsonl & people.jsonl (Stage-1 output) and produces: • company_graph.json • org_chart_<handle>.json (one per company) • decision_makers.csv • graph_view.html (interactive visualisation) Run: python c4ai_insights.py --in ./stage1_out --out ./stage2_out Author : Tom @ Kidocode, 2025-04-28 """ from __future__ import annotations # ─────────────────────────────────────────────────────────────────────────────── # Imports & Third-party # ─────────────────────────────────────────────────────────────────────────────── import argparse, asyncio, json, pathlib, random from datetime import datetime, UTC from types import SimpleNamespace from pathlib import Path from typing import List, Dict, Any # Pretty CLI UX from rich.console import Console from rich.logging import RichHandler from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeElapsedColumn # ─────────────────────────────────────────────────────────────────────────────── BASE_DIR = pathlib.Path(__file__).resolve().parent # ─────────────────────────────────────────────────────────────────────────────── # 3rd-party deps # ─────────────────────────────────────────────────────────────────────────────── import numpy as np # from sentence_transformers import SentenceTransformer # from sklearn.metrics.pairwise import cosine_similarity import pandas as pd import hashlib from litellm import completion #Support any LLM Provider # ─────────────────────────────────────────────────────────────────────────────── # Utils # ─────────────────────────────────────────────────────────────────────────────── def load_jsonl(path: Path) -> List[Dict[str, Any]]: with open(path, "r", encoding="utf-8") as f: return [json.loads(l) for l in f] def dump_json(obj, path: Path): with open(path, "w", encoding="utf-8") as f: json.dump(obj, f, ensure_ascii=False, indent=2) # ─────────────────────────────────────────────────────────────────────────────── # Constants # ─────────────────────────────────────────────────────────────────────────────── BASE_DIR = pathlib.Path(__file__).resolve().parent # ─────────────────────────────────────────────────────────────────────────────── # Debug defaults (mirrors Stage-1 trick) # ─────────────────────────────────────────────────────────────────────────────── def dev_defaults() -> SimpleNamespace: return SimpleNamespace( in_dir="./samples", out_dir="./samples/insights", embed_model="all-MiniLM-L6-v2", top_k=10, llm_provider="openai/gpt-4.1", llm_api_key=None, max_llm_tokens=8000, llm_temperature=1.0, stub=False, # Set to True to use a stub for org-chart inference llm_base_url=None, # e.g., "https://api.openai.com/v1" for OpenAI workers=4 ) # ─────────────────────────────────────────────────────────────────────────────── # Graph builders # ─────────────────────────────────────────────────────────────────────────────── def embed_descriptions(companies, model_name:str, opts) -> np.ndarray: from sentence_transformers import SentenceTransformer console = Console() console.print(f"Using embedding model: [bold cyan]{model_name}[/]") cache_path = BASE_DIR / Path(opts.out_dir) / "embeds_cache.json" cache = {} if cache_path.exists(): with open(cache_path) as f: cache = json.load(f) # flush cache if model differs if cache.get("_model") != model_name: cache = {} model = SentenceTransformer(model_name) new_texts, new_indices = [], [] vectors = np.zeros((len(companies), 384), dtype=np.float32) for idx, comp in enumerate(companies): text = comp.get("about") or comp.get("descriptor","") h = hashlib.sha1(text.encode("utf-8")).hexdigest() cached = cache.get(comp["handle"]) if cached and cached["hash"] == h: vectors[idx] = np.array(cached["vector"], dtype=np.float32) else: new_texts.append(text) new_indices.append((idx, comp["handle"], h)) if new_texts: embeds = model.encode(new_texts, show_progress_bar=False, convert_to_numpy=True) for vec, (idx, handle, h) in zip(embeds, new_indices): vectors[idx] = vec cache[handle] = {"hash": h, "vector": vec.tolist()} cache["_model"] = model_name with open(cache_path, "w") as f: json.dump(cache, f) return vectors def build_company_graph(companies, embeds:np.ndarray, top_k:int) -> Dict[str,Any]: from sklearn.metrics.pairwise import cosine_similarity sims = cosine_similarity(embeds) nodes, edges = [], [] for i,c in enumerate(companies): node = dict( id=c["handle"].strip("/"), name=c["name"], handle=c["handle"], about=c.get("about",""), people_url=c.get("people_url",""), industry=c.get("descriptor","").split("•")[0].strip(), geoUrn=c.get("geoUrn"), followers=c.get("followers",0), # desc_embed=embeds[i].tolist(), desc_embed=[], ) nodes.append(node) # pick top-k most similar except itself top_idx = np.argsort(sims[i])[::-1][1:top_k+1] for j in top_idx: tgt = companies[j] weight = float(sims[i,j]) if node["industry"] == tgt.get("descriptor","").split("•")[0].strip(): weight += 0.10 if node["geoUrn"] == tgt.get("geoUrn"): weight += 0.05 tgt['followers'] = tgt.get("followers", None) or 1 node["followers"] = node.get("followers", None) or 1 follower_ratio = min(node["followers"], tgt.get("followers",1)) / max(node["followers"] or 1, tgt.get("followers",1)) weight += 0.05 * follower_ratio edges.append(dict( source=node["id"], target=tgt["handle"].strip("/"), weight=round(weight,4), drivers=dict( embed_sim=round(float(sims[i,j]),4), industry_match=0.10 if node["industry"] == tgt.get("descriptor","").split("•")[0].strip() else 0, geo_overlap=0.05 if node["geoUrn"] == tgt.get("geoUrn") else 0, ) )) # return {"nodes":nodes,"edges":edges,"meta":{"generated_at":datetime.now(UTC).isoformat()}} return {"nodes":nodes,"edges":edges,"meta":{"generated_at":datetime.now(UTC).isoformat()}} # ─────────────────────────────────────────────────────────────────────────────── # Org-chart via LLM # ─────────────────────────────────────────────────────────────────────────────── async def infer_org_chart_llm(company, people, llm_provider:str, api_key:str, max_tokens:int, temperature:float, stub:bool=False, base_url:str=None): if stub: # Tiny fake org-chart when debugging offline chief = random.choice(people) nodes = [{ "id": chief["profile_url"], "name": chief["name"], "title": chief["headline"], "dept": chief["headline"].split()[:1][0], "yoe_total": 8, "yoe_current": 2, "seniority_score": 0.8, "decision_score": 0.9, "avatar_url": chief.get("avatar_url") }] return {"nodes":nodes,"edges":[],"meta":{"debug_stub":True,"generated_at":datetime.now(UTC).isoformat()}} prompt = [ {"role":"system","content":"You are an expert B2B org-chart reasoner."}, {"role":"user","content":f"""Here is the company description: <company> {json.dumps(company, ensure_ascii=False)} </company> Here is a JSON list of employees: <employees> {json.dumps(people, ensure_ascii=False)} </employees> 1) Build a reporting tree (manager -> direct reports) 2) For each person output a decision_score 0-1 for buying new software Return JSON: {{ "nodes":[{{id,name,title,dept,yoe_total,yoe_current,seniority_score,decision_score,avatar_url,profile_url}}], "edges":[{{source,target,type,confidence}}] }} """} ] resp = completion( model=llm_provider, messages=prompt, max_tokens=max_tokens, temperature=temperature, response_format={"type":"json_object"}, api_key=api_key, base_url=base_url ) chart = json.loads(resp.choices[0].message.content) chart["meta"] = dict( model=llm_provider, generated_at=datetime.now(UTC).isoformat() ) return chart # ─────────────────────────────────────────────────────────────────────────────── # CSV flatten # ─────────────────────────────────────────────────────────────────────────────── def export_decision_makers(charts_dir:Path, csv_path:Path, threshold:float=0.5): rows=[] for p in charts_dir.glob("org_chart_*.json"): data=json.loads(p.read_text()) comp = p.stem.split("org_chart_")[1] for n in data.get("nodes",[]): if n.get("decision_score",0)>=threshold: rows.append(dict( company=comp, person=n["name"], title=n["title"], decision_score=n["decision_score"], profile_url=n["id"] )) pd.DataFrame(rows).to_csv(csv_path,index=False) # ─────────────────────────────────────────────────────────────────────────────── # HTML rendering # ─────────────────────────────────────────────────────────────────────────────── def render_html(out:Path, template_dir:Path): # From template folder cp graph_view.html and ai.js in out folder import shutil shutil.copy(template_dir/"graph_view_template.html", out / "graph_view.html") shutil.copy(template_dir/"ai.js", out) # ─────────────────────────────────────────────────────────────────────────────── # Main async pipeline # ─────────────────────────────────────────────────────────────────────────────── async def run(opts): # ── silence SDK noise ────────────────────────────────────────────────────── # for noisy in ("openai", "httpx", "httpcore"): # lg = logging.getLogger(noisy) # lg.setLevel(logging.WARNING) # or ERROR if you want total silence # lg.propagate = False # optional: stop them reaching root # ────────────── logging bootstrap ────────────── console = Console() # logging.basicConfig( # level="INFO", # format="%(message)s", # handlers=[RichHandler(console=console, markup=True, rich_tracebacks=True)], # ) in_dir = BASE_DIR / Path(opts.in_dir) out_dir = BASE_DIR / Path(opts.out_dir) out_dir.mkdir(parents=True, exist_ok=True) companies = load_jsonl(in_dir/"companies.jsonl") people = load_jsonl(in_dir/"people.jsonl") console.print(f"[bold cyan]Loaded[/] {len(companies)} companies, {len(people)} people") console.print("[bold]⇢[/] Embedding company descriptions…") embeds = embed_descriptions(companies, opts.embed_model, opts) console.print("[bold]⇢[/] Building similarity graph") company_graph = build_company_graph(companies, embeds, opts.top_k) dump_json(company_graph, out_dir/"company_graph.json") # Filter companies that need processing to_process = [] for comp in companies: handle = comp["handle"].strip("/").replace("/","_") out_file = out_dir/f"org_chart_{handle}.json" if out_file.exists(): console.print(f"[green]✓[/] Skipping existing {comp['name']}") continue to_process.append(comp) if not to_process: console.print("[yellow]All companies already processed[/]") else: workers = getattr(opts, 'workers', 1) parallel = workers > 1 console.print(f"[bold]⇢[/] Inferring org-charts via LLM {f'(parallel={workers} workers)' if parallel else ''}") with Progress( SpinnerColumn(), BarColumn(), TextColumn("[progress.description]{task.description}"), TimeElapsedColumn(), console=console, ) as progress: task = progress.add_task("Org charts", total=len(to_process)) async def process_one(comp): handle = comp["handle"].strip("/").replace("/","_") persons = [p for p in people if p["company_handle"].strip("/") == comp["handle"].strip("/")] chart = await infer_org_chart_llm( comp, persons, llm_provider=opts.llm_provider, api_key=opts.llm_api_key or None, max_tokens=opts.max_llm_tokens, temperature=opts.llm_temperature, stub=opts.stub or False, base_url=opts.llm_base_url or None ) chart["meta"]["company"] = comp["name"] # Save the result immediately dump_json(chart, out_dir/f"org_chart_{handle}.json") progress.update(task, advance=1, description=f"{comp['name']} ({len(persons)} ppl)") # Create tasks for all companies tasks = [process_one(comp) for comp in to_process] # Process in batches based on worker count semaphore = asyncio.Semaphore(workers) async def bounded_process(coro): async with semaphore: return await coro # Run with concurrency control await asyncio.gather(*(bounded_process(task) for task in tasks)) console.print("[bold]⇢[/] Flattening decision-makers CSV") export_decision_makers(out_dir, out_dir/"decision_makers.csv") render_html(out_dir, template_dir=BASE_DIR/"templates") console.print(f"[bold green]✓[/] Stage-2 artefacts written to {out_dir}") # ─────────────────────────────────────────────────────────────────────────────── # CLI # ─────────────────────────────────────────────────────────────────────────────── def build_arg_parser(): p = argparse.ArgumentParser(description="Build graphs & visualisation from Stage-1 output") p.add_argument("--in", dest="in_dir", required=False, help="Stage-1 output dir", default=".") p.add_argument("--out", dest="out_dir", required=False, help="Destination dir", default=".") p.add_argument("--embed-model", default="all-MiniLM-L6-v2") p.add_argument("--top-k", type=int, default=10, help="Top-k neighbours per company") p.add_argument("--llm-provider", default="openai/gpt-4.1", help="LLM model to use in format 'provider/model_name' (e.g., 'anthropic/claude-3')") p.add_argument("--llm-api-key", help="API key for LLM provider (defaults to env vars)") p.add_argument("--llm-base-url", help="Base URL for LLM API endpoint") p.add_argument("--max-llm-tokens", type=int, default=8024) p.add_argument("--llm-temperature", type=float, default=1.0) p.add_argument("--stub", action="store_true", help="Skip OpenAI call and generate tiny fake org charts") p.add_argument("--workers", type=int, default=4, help="Number of parallel workers for LLM inference") return p def main(): dbg = dev_defaults() opts = dbg if True else build_arg_parser().parse_args() # opts = build_arg_parser().parse_args() asyncio.run(run(opts)) if __name__ == "__main__": main()
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/apps/linkdin/c4ai_insights.py", "license": "Apache License 2.0", "lines": 325, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/docker/demo_docker_polling.py
#!/usr/bin/env python3 """ demo_docker_polling.py Quick sanity-check for the asynchronous crawl job endpoints: • POST /crawl/job – enqueue work, get task_id • GET /crawl/job/{id} – poll status / fetch result The style matches demo_docker_api.py (console.rule banners, helper functions, coloured status lines). Adjust BASE_URL as needed. Run: python demo_docker_polling.py """ import asyncio, json, os, time, urllib.parse from typing import Dict, List import httpx from rich.console import Console from rich.panel import Panel from rich.syntax import Syntax console = Console() BASE_URL = os.getenv("BASE_URL", "http://localhost:11234") SIMPLE_URL = "https://example.org" LINKS_URL = "https://httpbin.org/links/10/1" # --- helpers -------------------------------------------------------------- def print_payload(payload: Dict): console.print(Panel(Syntax(json.dumps(payload, indent=2), "json", theme="monokai", line_numbers=False), title="Payload", border_style="cyan", expand=False)) async def check_server_health(client: httpx.AsyncClient) -> bool: try: resp = await client.get("/health") if resp.is_success: console.print("[green]Server healthy[/]") return True except Exception: pass console.print("[bold red]Server is not responding on /health[/]") return False async def poll_for_result(client: httpx.AsyncClient, task_id: str, poll_interval: float = 1.5, timeout: float = 90.0): """Hit /crawl/job/{id} until COMPLETED/FAILED or timeout.""" start = time.time() while True: resp = await client.get(f"/crawl/job/{task_id}") resp.raise_for_status() data = resp.json() status = data.get("status") if status.upper() in ("COMPLETED", "FAILED"): return data if time.time() - start > timeout: raise TimeoutError(f"Task {task_id} did not finish in {timeout}s") await asyncio.sleep(poll_interval) # --- demo functions ------------------------------------------------------- async def demo_poll_single_url(client: httpx.AsyncClient): payload = { "urls": [SIMPLE_URL], "browser_config": {"type": "BrowserConfig", "params": {"headless": True}}, "crawler_config": {"type": "CrawlerRunConfig", "params": {"cache_mode": "BYPASS"}} } console.rule("[bold blue]Demo A: /crawl/job Single URL[/]", style="blue") print_payload(payload) # enqueue resp = await client.post("/crawl/job", json=payload) console.print(f"Enqueue status: [bold]{resp.status_code}[/]") resp.raise_for_status() task_id = resp.json()["task_id"] console.print(f"Task ID: [yellow]{task_id}[/]") # poll console.print("Polling…") result = await poll_for_result(client, task_id) console.print(Panel(Syntax(json.dumps(result, indent=2), "json", theme="fruity"), title="Final result", border_style="green")) if result["status"] == "COMPLETED": console.print("[green]✅ Crawl succeeded[/]") else: console.print("[red]❌ Crawl failed[/]") async def demo_poll_multi_url(client: httpx.AsyncClient): payload = { "urls": [SIMPLE_URL, LINKS_URL], "browser_config": {"type": "BrowserConfig", "params": {"headless": True}}, "crawler_config": {"type": "CrawlerRunConfig", "params": {"cache_mode": "BYPASS"}} } console.rule("[bold magenta]Demo B: /crawl/job Multi-URL[/]", style="magenta") print_payload(payload) resp = await client.post("/crawl/job", json=payload) console.print(f"Enqueue status: [bold]{resp.status_code}[/]") resp.raise_for_status() task_id = resp.json()["task_id"] console.print(f"Task ID: [yellow]{task_id}[/]") console.print("Polling…") result = await poll_for_result(client, task_id) console.print(Panel(Syntax(json.dumps(result, indent=2), "json", theme="fruity"), title="Final result", border_style="green")) if result["status"] == "COMPLETED": console.print( f"[green]✅ {len(json.loads(result['result'])['results'])} URLs crawled[/]") else: console.print("[red]❌ Crawl failed[/]") # --- main runner ---------------------------------------------------------- async def main_demo(): async with httpx.AsyncClient(base_url=BASE_URL, timeout=300.0) as client: if not await check_server_health(client): return await demo_poll_single_url(client) await demo_poll_multi_url(client) console.rule("[bold green]Polling demos complete[/]", style="green") if __name__ == "__main__": try: asyncio.run(main_demo()) except KeyboardInterrupt: console.print("\n[yellow]Interrupted by user[/]") except Exception: console.print_exception(show_locals=False)
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/docker/demo_docker_polling.py", "license": "Apache License 2.0", "lines": 117, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/regex_extraction_quickstart.py
# == File: regex_extraction_quickstart.py == """ Mini–quick-start for RegexExtractionStrategy ──────────────────────────────────────────── 3 bite-sized demos that parallel the style of *quickstart_examples_set_1.py*: 1. **Default catalog** – scrape a page and pull out e-mails / phones / URLs, etc. 2. **Custom pattern** – add your own regex at instantiation time. 3. **LLM-assisted schema** – ask the model to write a pattern, cache it, then run extraction _without_ further LLM calls. Run the whole thing with:: python regex_extraction_quickstart.py """ import os, json, asyncio from pathlib import Path from typing import List from crawl4ai import ( AsyncWebCrawler, CrawlerRunConfig, CrawlResult, RegexExtractionStrategy, LLMConfig, ) # ──────────────────────────────────────────────────────────────────────────── # 1. Default-catalog extraction # ──────────────────────────────────────────────────────────────────────────── async def demo_regex_default() -> None: print("\n=== 1. Regex extraction – default patterns ===") url = "https://www.iana.org/domains/example" # has e-mail + URLs strategy = RegexExtractionStrategy( pattern = RegexExtractionStrategy.Url | RegexExtractionStrategy.Currency ) config = CrawlerRunConfig(extraction_strategy=strategy) async with AsyncWebCrawler() as crawler: result: CrawlResult = await crawler.arun(url, config=config) print(f"Fetched {url} - success={result.success}") if result.success: data = json.loads(result.extracted_content) for d in data[:10]: print(f" {d['label']:<12} {d['value']}") print(f"... total matches: {len(data)}") else: print(" !!! crawl failed") # ──────────────────────────────────────────────────────────────────────────── # 2. Custom pattern override / extension # ──────────────────────────────────────────────────────────────────────────── async def demo_regex_custom() -> None: print("\n=== 2. Regex extraction – custom price pattern ===") url = "https://www.apple.com/shop/buy-mac/macbook-pro" price_pattern = {"usd_price": r"\$\s?\d{1,3}(?:,\d{3})*(?:\.\d{2})?"} strategy = RegexExtractionStrategy(custom = price_pattern) config = CrawlerRunConfig(extraction_strategy=strategy) async with AsyncWebCrawler() as crawler: result: CrawlResult = await crawler.arun(url, config=config) if result.success: data = json.loads(result.extracted_content) for d in data: print(f" {d['value']}") if not data: print(" (No prices found - page layout may have changed)") else: print(" !!! crawl failed") # ──────────────────────────────────────────────────────────────────────────── # 3. One-shot LLM pattern generation, then fast extraction # ──────────────────────────────────────────────────────────────────────────── async def demo_regex_generate_pattern() -> None: print("\n=== 3. generate_pattern → regex extraction ===") cache_dir = Path(__file__).parent / "tmp" cache_dir.mkdir(exist_ok=True) pattern_file = cache_dir / "price_pattern.json" url = "https://www.lazada.sg/tag/smartphone/" # ── 3-A. build or load the cached pattern if pattern_file.exists(): pattern = json.load(pattern_file.open(encoding="utf-8")) print("Loaded cached pattern:", pattern) else: print("Generating pattern via LLM…") llm_cfg = LLMConfig( provider="openai/gpt-4o-mini", api_token="env:OPENAI_API_KEY", ) # pull one sample page as HTML context async with AsyncWebCrawler() as crawler: html = (await crawler.arun(url)).fit_html pattern = RegexExtractionStrategy.generate_pattern( label="price", html=html, query="Prices in Malaysian Ringgit (e.g. RM1,299.00 or RM200)", llm_config=llm_cfg, ) json.dump(pattern, pattern_file.open("w", encoding="utf-8"), indent=2) print("Saved pattern:", pattern_file) # ── 3-B. extraction pass – zero LLM calls strategy = RegexExtractionStrategy(custom=pattern) config = CrawlerRunConfig(extraction_strategy=strategy, delay_before_return_html=3) async with AsyncWebCrawler() as crawler: result: CrawlResult = await crawler.arun(url, config=config) if result.success: data = json.loads(result.extracted_content) for d in data[:15]: print(f" {d['value']}") print(f"... total matches: {len(data)}") else: print(" !!! crawl failed") # ──────────────────────────────────────────────────────────────────────────── # Entrypoint # ──────────────────────────────────────────────────────────────────────────── async def main() -> None: # await demo_regex_default() # await demo_regex_custom() await demo_regex_generate_pattern() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/regex_extraction_quickstart.py", "license": "Apache License 2.0", "lines": 112, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unclecode/crawl4ai:docs/examples/session_id_example.py
import asyncio from crawl4ai import ( AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, DefaultMarkdownGenerator, PruningContentFilter, CrawlResult ) async def main(): browser_config = BrowserConfig( headless=False, verbose=True, ) async with AsyncWebCrawler(config=browser_config) as crawler: crawler_config = CrawlerRunConfig( session_id= "hello_world", # This help us to use the same page ) result : CrawlResult = await crawler.arun( url="https://www.helloworld.org", config=crawler_config ) # Add a breakpoint here, then you will the page is open and browser is not closed print(result.markdown.raw_markdown[:500]) new_config = crawler_config.clone(js_code=["(() => ({'data':'hello'}))()"], js_only=True) result : CrawlResult = await crawler.arun( # This time there is no fetch and this only executes JS in the same opened page url="https://www.helloworld.org", config= new_config ) print(result.js_execution_result) # You should see {'data':'hello'} in the console # Get direct access to Playwright paege object. This works only if you use the same session_id and pass same config page, context = crawler.crawler_strategy.get_page(new_config) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "unclecode/crawl4ai", "file_path": "docs/examples/session_id_example.py", "license": "Apache License 2.0", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unslothai/unsloth:tests/utils/test_trunc_normal_patch.py
# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """Tests for trunc_normal low-precision patch compatibility.""" import importlib.util import inspect from pathlib import Path import pytest import torch _MISSING = object() def _load_import_fixes_module(): repo_root = Path(__file__).resolve().parents[2] import_fixes_path = repo_root / "unsloth" / "import_fixes.py" spec = importlib.util.spec_from_file_location( "unsloth_import_fixes_local", import_fixes_path ) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def _getattr_or_missing(obj, name): return getattr(obj, name) if hasattr(obj, name) else _MISSING def _restore_attr(obj, name, value): if value is _MISSING: if hasattr(obj, name): delattr(obj, name) return setattr(obj, name, value) def test_trunc_normal_patch_accepts_positional_generator(): import_fixes = _load_import_fixes_module() patch_fn = import_fixes.patch_trunc_normal_precision_issue init_mod = torch.nn.init old_fn = init_mod.trunc_normal_ old_patched = _getattr_or_missing(init_mod, "_unsloth_trunc_normal_patched") old_original = _getattr_or_missing(init_mod, "_unsloth_trunc_normal_original") try: # Normalize to an unpatched baseline before applying the patch. if old_original is not _MISSING: init_mod.trunc_normal_ = old_original if hasattr(init_mod, "_unsloth_trunc_normal_patched"): delattr(init_mod, "_unsloth_trunc_normal_patched") if hasattr(init_mod, "_unsloth_trunc_normal_original"): delattr(init_mod, "_unsloth_trunc_normal_original") patch_fn() sig = inspect.signature(init_mod.trunc_normal_) assert "generator" in sig.parameters assert sig.parameters["generator"].kind is not inspect.Parameter.KEYWORD_ONLY tensor = torch.empty(1024, dtype = torch.float32) gen = torch.Generator() gen.manual_seed(3407) init_mod.trunc_normal_(tensor, 0.0, 1.0, -2.0, 2.0, gen) init_mod.trunc_normal_(tensor, mean = 0.0, std = 1.0, a = -2.0, b = 2.0, generator = gen) finally: init_mod.trunc_normal_ = old_fn _restore_attr(init_mod, "_unsloth_trunc_normal_patched", old_patched) _restore_attr(init_mod, "_unsloth_trunc_normal_original", old_original) def test_trunc_normal_patch_rejects_invalid_generator(): import_fixes = _load_import_fixes_module() patch_fn = import_fixes.patch_trunc_normal_precision_issue init_mod = torch.nn.init old_fn = init_mod.trunc_normal_ old_patched = _getattr_or_missing(init_mod, "_unsloth_trunc_normal_patched") old_original = _getattr_or_missing(init_mod, "_unsloth_trunc_normal_original") try: if old_original is not _MISSING: init_mod.trunc_normal_ = old_original if hasattr(init_mod, "_unsloth_trunc_normal_patched"): delattr(init_mod, "_unsloth_trunc_normal_patched") if hasattr(init_mod, "_unsloth_trunc_normal_original"): delattr(init_mod, "_unsloth_trunc_normal_original") patch_fn() sig = inspect.signature(init_mod.trunc_normal_) if "generator" not in sig.parameters: pytest.skip("torch.nn.init.trunc_normal_ lacks a generator parameter") tensor = torch.empty(16, dtype = torch.float32) with pytest.raises(TypeError): init_mod.trunc_normal_(tensor, generator = 123) finally: init_mod.trunc_normal_ = old_fn _restore_attr(init_mod, "_unsloth_trunc_normal_patched", old_patched) _restore_attr(init_mod, "_unsloth_trunc_normal_original", old_original)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/test_trunc_normal_patch.py", "license": "Apache License 2.0", "lines": 92, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/kernels/moe/autotune_cache.py
# Unsloth # Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """ Auto-tuning cache system for MoE kernels to ensure tuning runs only once at training start. """ import hashlib import json import logging import os import time from typing import Dict, List, Optional, Tuple, Any import torch import triton logger = logging.getLogger(__name__) # Global cache for kernel configurations _kernel_config_cache: Dict[str, Any] = {} _autotune_completed: Dict[str, bool] = {} def _get_cache_key( num_experts: int, hidden_dim: int, intermediate_dim: int, top_k: int, dtype: torch.dtype, device_capability: Tuple[int, int], seq_len: int = 8192, # Default sequence length for tuning ) -> str: """Generate a unique cache key based on model configuration.""" key_data = { "num_experts": num_experts, "hidden_dim": hidden_dim, "intermediate_dim": intermediate_dim, "top_k": top_k, "dtype": str(dtype), "device_capability": device_capability, "seq_len": seq_len, } key_str = json.dumps(key_data, sort_keys = True) return hashlib.md5(key_str.encode()).hexdigest() def _get_cache_file_path(cache_key: str) -> str: """Get the file path for the cache file.""" cache_dir = os.path.expanduser("~/.cache/unsloth/moe_autotune") os.makedirs(cache_dir, exist_ok = True) return os.path.join(cache_dir, f"{cache_key}.json") def load_cached_config(cache_key: str) -> Optional[Dict[str, Any]]: """Load cached kernel configuration from disk.""" cache_file = _get_cache_file_path(cache_key) if not os.path.exists(cache_file): return None try: with open(cache_file, "r") as f: cached_data = json.load(f) # Verify cache is still valid (same device, etc.) current_device_capability = torch.cuda.get_device_capability() if cached_data.get("device_capability") != current_device_capability: logger.info("Device capability changed, invalidating cache") os.remove(cache_file) return None logger.info(f"Loaded cached MoE kernel config: {cache_key}") return cached_data except Exception as e: logger.warning(f"Failed to load cache file {cache_file}: {e}") try: os.remove(cache_file) except: pass return None def save_cached_config( cache_key: str, config_fwd: Any, config_bwd_dx: Any, config_bwd_dw: Any, metadata: Dict[str, Any] = None, ) -> None: """Save kernel configuration to disk cache.""" cache_file = _get_cache_file_path(cache_key) cache_data = { "timestamp": time.time(), "device_capability": torch.cuda.get_device_capability(), "config_fwd": config_fwd.__dict__ if hasattr(config_fwd, "__dict__") else str(config_fwd), "config_bwd_dx": config_bwd_dx.__dict__ if hasattr(config_bwd_dx, "__dict__") else str(config_bwd_dx), "config_bwd_dw": config_bwd_dw.__dict__ if hasattr(config_bwd_dw, "__dict__") else str(config_bwd_dw), "metadata": metadata or {}, } try: with open(cache_file, "w") as f: json.dump(cache_data, f, indent = 2) logger.info(f"Saved MoE kernel config cache: {cache_key}") except Exception as e: logger.warning(f"Failed to save cache file {cache_file}: {e}") def get_or_autotune_moe_kernels( num_experts: int, hidden_dim: int, intermediate_dim: int, top_k: int, dtype: torch.dtype, force_autotune: bool = False, seq_len: int = 8192, ) -> Tuple[Any, Any, Any]: """ Get cached kernel configurations or run auto-tuning. Args: num_experts: Number of experts in the MoE layer hidden_dim: Hidden dimension of the model intermediate_dim: Intermediate dimension for MoE MLP top_k: Number of experts to route to dtype: Data type for computation force_autotune: Force re-running autotuning even if cache exists seq_len: Sequence length to use for tuning benchmarks Returns: Tuple of (config_fwd, config_bwd_dx, config_bwd_dw) """ device_capability = torch.cuda.get_device_capability() cache_key = _get_cache_key( num_experts, hidden_dim, intermediate_dim, top_k, dtype, device_capability, seq_len, ) # 0. Check for environment variable override to DISABLE autotuning if os.environ.get("UNSLOTH_MOE_DISABLE_AUTOTUNE", "0") == "1": logger.info( f"UNSLOTH_MOE_DISABLE_AUTOTUNE=1: Using Heuristic (Safe) MoE kernel configs for SM{device_capability[0]}{device_capability[1]}" ) return _get_heuristic_configs() if not force_autotune and cache_key in _kernel_config_cache: logger.info(f"Using in-memory cached MoE kernel configs: {cache_key}") return _kernel_config_cache[cache_key] # Try to load from disk if not force_autotune: cached_data = load_cached_config(cache_key) if cached_data is not None: # Reconstruct config objects from cached data try: from .grouped_gemm.kernels.tuning import ( KernelConfigForward, KernelConfigBackward_dX, KernelConfigBackward_dW, ) config_fwd = KernelConfigForward(**cached_data["config_fwd"]) config_bwd_dx = KernelConfigBackward_dX(**cached_data["config_bwd_dx"]) config_bwd_dw = KernelConfigBackward_dW(**cached_data["config_bwd_dw"]) configs = (config_fwd, config_bwd_dx, config_bwd_dw) _kernel_config_cache[cache_key] = configs return configs except Exception as e: logger.warning(f"Failed to reconstruct cached configs: {e}") # Run autotuning if cache_key in _autotune_completed and not force_autotune: logger.info(f"Autotuning already completed for: {cache_key}") return _kernel_config_cache[cache_key] logger.info(f"Running MoE kernel auto-tuning for: {cache_key}") logger.info( f"Configuration: {num_experts} experts, {hidden_dim} hidden, {intermediate_dim} intermediate, top_k={top_k}" ) try: configs = _run_moe_autotuning( num_experts, hidden_dim, intermediate_dim, top_k, dtype, seq_len ) # Cache the results _kernel_config_cache[cache_key] = configs _autotune_completed[cache_key] = True # Save to disk config_fwd, config_bwd_dx, config_bwd_dw = configs save_cached_config( cache_key, config_fwd, config_bwd_dx, config_bwd_dw, { "num_experts": num_experts, "hidden_dim": hidden_dim, "intermediate_dim": intermediate_dim, }, ) logger.info(f"MoE kernel auto-tuning completed: {cache_key}") return configs except Exception as e: logger.error(f"MoE kernel auto-tuning failed: {e}") if "AttributeError" in str(e) and "_experimental_make_tensor_descriptor" in str( e ): logger.warning( "Unsloth: Your Triton version might be incompatible with TMA features. Falling back to default configs." ) logger.info("Falling back to default kernel configurations") return _get_default_configs() def _run_moe_autotuning( num_experts: int, hidden_dim: int, intermediate_dim: int, top_k: int, dtype: torch.dtype, seq_len: int, ) -> Tuple[Any, Any, Any]: """Run the actual auto-tuning for MoE kernels.""" # Create dummy inputs for tuning device = "cuda" # Use a fixed, safe number of tokens for autotuning to avoid OOMs and dependency on seq_len # 4096 is standard for finding good kernels without consuming 10GB+ VRAM # We ignore the passed seq_len for the actual allocation to satisfy user request num_tokens = 4096 total_tokens = num_tokens * top_k # Create dummy tensors hidden_states = torch.randn(num_tokens, hidden_dim, device = device, dtype = dtype) # Create dummy weights gate_up_weights = torch.randn( num_experts, 2 * intermediate_dim, hidden_dim, device = device, dtype = dtype ) down_weights = torch.randn( num_experts, hidden_dim, intermediate_dim, device = device, dtype = dtype ) # Create dummy routing data m_sizes = torch.randint( 1, total_tokens // num_experts + 1, (num_experts,), device = device ) m_sizes = m_sizes * (total_tokens // m_sizes.sum().item()) # Adjust to ensure exact total diff = total_tokens - m_sizes.sum().item() if diff != 0: m_sizes[0] += diff gather_indices = torch.arange(total_tokens, device = device) torch.randperm(total_tokens, out = gather_indices) # Autotune forward kernel - use the interface function with autotune=True # This properly invokes the kernel and lets triton handle the autotuning from .grouped_gemm.interface import ( grouped_gemm_forward, grouped_gemm_dX, grouped_gemm_dW, ) from .grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel from .grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dX_kernel, _autotuned_grouped_gemm_dW_kernel, ) from .grouped_gemm.kernels.tuning import ( KernelConfigForward, KernelConfigBackward_dX, KernelConfigBackward_dW, ) logger.info("Autotuning forward kernel (first GEMM)...") # Run with autotune=True to trigger autotuning _ = grouped_gemm_forward( X = hidden_states, W = gate_up_weights, topk = top_k, m_sizes = m_sizes, gather_indices = gather_indices, permute_x = True, permute_y = False, autotune = True, ) triton_config_fwd = _autotuned_grouped_gemm_forward_kernel.best_config # Convert triton.Config to KernelConfigForward config_fwd = KernelConfigForward( BLOCK_SIZE_M = triton_config_fwd.kwargs["BLOCK_SIZE_M"], BLOCK_SIZE_N = triton_config_fwd.kwargs["BLOCK_SIZE_N"], BLOCK_SIZE_K = triton_config_fwd.kwargs["BLOCK_SIZE_K"], num_warps = triton_config_fwd.num_warps, num_stages = triton_config_fwd.num_stages, use_tma_load_x = triton_config_fwd.kwargs.get("USE_TMA_LOAD_X", False), use_tma_load_w = triton_config_fwd.kwargs.get("USE_TMA_LOAD_W", False), use_tma_store = triton_config_fwd.kwargs.get("USE_TMA_STORE", False), ) # Autotune backward dX kernel logger.info("Autotuning backward dX kernel...") dummy_grad = torch.randn( total_tokens, 2 * intermediate_dim, device = device, dtype = dtype ) _ = grouped_gemm_dX( dY = dummy_grad, W = gate_up_weights, gather_indices = gather_indices, m_sizes = m_sizes, topk = top_k, permute_x = True, permute_y = False, autotune = True, ) triton_config_bwd_dx = _autotuned_grouped_gemm_dX_kernel.best_config # Convert triton.Config to KernelConfigBackward_dX config_bwd_dx = KernelConfigBackward_dX( BLOCK_SIZE_M = triton_config_bwd_dx.kwargs["BLOCK_SIZE_M"], BLOCK_SIZE_N = triton_config_bwd_dx.kwargs["BLOCK_SIZE_N"], BLOCK_SIZE_K = triton_config_bwd_dx.kwargs["BLOCK_SIZE_K"], num_warps = triton_config_bwd_dx.num_warps, num_stages = triton_config_bwd_dx.num_stages, use_tma_load_dy = triton_config_bwd_dx.kwargs.get("USE_TMA_LOAD_dY", False), use_tma_load_w = triton_config_bwd_dx.kwargs.get("USE_TMA_LOAD_W", False), use_tma_store = triton_config_bwd_dx.kwargs.get("USE_TMA_STORE", False), ) # Autotune backward dW kernel logger.info("Autotuning backward dW kernel...") _ = grouped_gemm_dW( X = hidden_states, dY = dummy_grad, m_sizes = m_sizes, gather_indices = gather_indices, topk = top_k, permute_x = True, permute_y = False, autotune = True, ) triton_config_bwd_dw = _autotuned_grouped_gemm_dW_kernel.best_config # Convert triton.Config to KernelConfigBackward_dW config_bwd_dw = KernelConfigBackward_dW( BLOCK_SIZE_M = triton_config_bwd_dw.kwargs["BLOCK_SIZE_M"], BLOCK_SIZE_N = triton_config_bwd_dw.kwargs["BLOCK_SIZE_N"], BLOCK_SIZE_K = triton_config_bwd_dw.kwargs["BLOCK_SIZE_K"], num_warps = triton_config_bwd_dw.num_warps, num_stages = triton_config_bwd_dw.num_stages, use_tma_load_dy = triton_config_bwd_dw.kwargs.get("USE_TMA_LOAD_dY", False), use_tma_load_x = triton_config_bwd_dw.kwargs.get("USE_TMA_LOAD_X", False), use_tma_store = triton_config_bwd_dw.kwargs.get("USE_TMA_STORE", False), ) return config_fwd, config_bwd_dx, config_bwd_dw return config_fwd, config_bwd_dx, config_bwd_dw def _get_heuristic_configs() -> Tuple[Any, Any, Any]: """ Get 'Safe Heuristic' kernel configurations. These are verified to be safe on A100 (SM80) and provide ~9x speedup on H100/B200. """ from .grouped_gemm.kernels.tuning import ( KernelConfigForward, KernelConfigBackward_dX, KernelConfigBackward_dW, ) # Safe Forward Config: 64x128x128 (Fits A100 SMEM) config_fwd = KernelConfigForward( BLOCK_SIZE_M = 64, BLOCK_SIZE_N = 128, BLOCK_SIZE_K = 128, num_warps = 8, num_stages = 3, permute_x = True, permute_y = True, use_tma_load_x = False, use_tma_load_w = False, # TMA loads might need alignment checks, safer to disable for heuristic use_tma_store = False, ) # Safe Backward Configs: 64x64x256 config_bwd_dx = KernelConfigBackward_dX( BLOCK_SIZE_M = 64, BLOCK_SIZE_N = 64, BLOCK_SIZE_K = 256, num_warps = 8, num_stages = 4, permute_x = True, permute_y = True, use_tma_load_dy = False, use_tma_load_w = False, use_tma_store = False, ) config_bwd_dw = KernelConfigBackward_dW( BLOCK_SIZE_M = 64, BLOCK_SIZE_N = 64, BLOCK_SIZE_K = 256, num_warps = 8, num_stages = 4, permute_x = True, permute_y = True, use_tma_load_dy = False, use_tma_load_x = False, use_tma_store = False, ) return config_fwd, config_bwd_dx, config_bwd_dw def _get_default_configs() -> Tuple[Any, Any, Any]: """Get default kernel configurations as fallback.""" from .grouped_gemm.kernels.tuning import ( KernelConfigForward, KernelConfigBackward_dX, KernelConfigBackward_dW, ) logger.warning("Using default MoE kernel configurations (not optimal)") config_fwd = KernelConfigForward( BLOCK_SIZE_M = 128, BLOCK_SIZE_N = 128, BLOCK_SIZE_K = 64, num_warps = 8, num_stages = 3, use_tma_load_x = False, use_tma_load_w = False, use_tma_store = False, ) config_bwd_dx = KernelConfigBackward_dX( BLOCK_SIZE_M = 128, BLOCK_SIZE_N = 128, BLOCK_SIZE_K = 64, num_warps = 8, num_stages = 3, use_tma_load_dy = False, use_tma_load_w = False, use_tma_store = False, ) config_bwd_dw = KernelConfigBackward_dW( BLOCK_SIZE_M = 128, BLOCK_SIZE_N = 128, BLOCK_SIZE_K = 64, num_warps = 8, num_stages = 3, use_tma_load_dy = False, use_tma_load_x = False, use_tma_store = False, ) return config_fwd, config_bwd_dx, config_bwd_dw def clear_cache() -> None: """Clear all cached kernel configurations.""" global _kernel_config_cache, _autotune_completed _kernel_config_cache.clear() _autotune_completed.clear() logger.info("Cleared MoE kernel cache") def is_autotuning_completed(cache_key: str) -> bool: """Check if autotuning has been completed for a given cache key.""" return cache_key in _autotune_completed
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/autotune_cache.py", "license": "Apache License 2.0", "lines": 435, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unslothai/unsloth:unsloth/models/glm4_moe.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ GLM-4.7 Flash (GLM4 MoE Lite) optimized implementation using grouped GEMM. Key architecture differences from Qwen3 MoE: - Router uses sigmoid activation (not softmax) - Has routed_scaling_factor of 1.8 - Has 1 shared expert that processes all tokens - Uses group-based selection before topk - Uses MLA (Multi-head Latent Attention) """ from .llama import * import os from ._utils import __version__ from .llama import ( LlamaRotaryEmbedding, LlamaLinearScalingRotaryEmbedding, fix_prepare_inputs_for_generation, fast_rms_layernorm_inference, fast_swiglu_inference, LlamaModel_fast_forward, LlamaModel_fast_forward_inference, CausalLM_fast_forward, PeftModel_fast_forward, ) import torch import torch.nn.functional as F from typing import Optional, Tuple from ..kernels import fast_rms_layernorm # Import the grouped gemm utilities from unsloth kernels # The grouped_gemm module expects its parent directory to be in sys.path HAS_GROUPED_GEMM = False try: import sys import os # Add the moe directory (parent of grouped_gemm) to sys.path _moe_path = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "kernels", "moe" ) if _moe_path not in sys.path: sys.path.insert(0, _moe_path) # Import grouped_gemm package first to apply TMA compatibility shim # This patches triton.language to support both old and new TMA API names import grouped_gemm # noqa: F401 - triggers TMA compatibility shim from grouped_gemm.interface import grouped_gemm from grouped_gemm.reference.moe_ops import ( get_routing_indices, permute, unpermute, ) HAS_GROUPED_GEMM = True except ImportError as e: import warnings warnings.warn( f"Grouped GEMM not available: {e}. MoE will use fallback implementation." ) # Import transformers GLM4 MoE Lite classes try: from transformers.models.glm4_moe_lite.modeling_glm4_moe_lite import ( Glm4MoeLiteAttention, Glm4MoeLiteMoE, Glm4MoeLiteMLP, Glm4MoeLiteNaiveMoe, Glm4MoeLiteTopkRouter, Glm4MoeLiteDecoderLayer, Glm4MoeLiteModel, Glm4MoeLiteForCausalLM, Glm4MoeLiteRMSNorm, ) HAS_GLM4_MOE = True except ImportError: HAS_GLM4_MOE = False # Create dummy classes for type checking class Glm4MoeLiteAttention: pass class Glm4MoeLiteMoE: pass class Glm4MoeLiteMLP: pass class Glm4MoeLiteNaiveMoe: pass class Glm4MoeLiteTopkRouter: pass class Glm4MoeLiteDecoderLayer: pass class Glm4MoeLiteModel: pass class Glm4MoeLiteForCausalLM: pass torch_nn_functional_silu = torch.nn.functional.silu def Glm4MoeLiteMoE_fast_forward(self, hidden_states): """ Optimized MoE forward pass using grouped GEMM. GLM4 MoE specifics: - Uses sigmoid router activation (not softmax) - Has routed_scaling_factor of 1.8 - Has 1 shared expert that always processes all tokens - Uses group-based selection with topk_group """ residuals = hidden_states orig_shape = hidden_states.shape batch_size, seq_len, hidden_dim = orig_shape num_tokens = batch_size * seq_len # Flatten hidden states for routing hidden_states = hidden_states.view(-1, hidden_dim) # Router computation router_logits = self.gate(hidden_states) # [num_tokens, n_routed_experts] topk_indices, topk_weights = self.route_tokens_to_experts(router_logits) # Cast routing weights to match hidden_states dtype (Qwen3 pattern) # Sigmoid router returns fp32, but hidden_states may be bf16 topk_weights = topk_weights.to(hidden_states.dtype) # Get routing indices for grouped GEMM with torch.no_grad(): token_counts_by_expert, gather_indices = get_routing_indices( topk_indices, self.n_routed_experts ) # Use grouped GEMM for expert computation if HAS_GROUPED_GEMM: # Cast hidden_states to match expert weights dtype # Under autocast, hidden_states may be fp32 while weights are bf16 hidden_states = hidden_states.to(self.experts.gate_up_proj.dtype) # First grouped GEMM: gate_up_proj with permute_x # Input: [num_tokens, hidden_dim] -> Output: [total_tokens, 2*intermediate_dim] intermediate = grouped_gemm( X = hidden_states, W = self.experts.gate_up_proj, m_sizes = token_counts_by_expert.int(), topk = self.top_k, gather_indices = gather_indices, permute_x = True, permute_y = False, autotune = True, is_first_gemm = True, ) # Activation: SiLU(gate) * up gate, up = intermediate.chunk(2, dim = -1) intermediate = torch_nn_functional_silu(gate) * up # Second grouped GEMM: down_proj with permute_y # Input: [total_tokens, intermediate_dim] -> Output: [total_tokens, hidden_dim] expert_output = grouped_gemm( X = intermediate, W = self.experts.down_proj, m_sizes = token_counts_by_expert.int(), topk = self.top_k, gather_indices = gather_indices, permute_x = False, permute_y = True, autotune = True, is_first_gemm = False, ) # Merge topk weights: [num_tokens, top_k, hidden_dim] -> [num_tokens, hidden_dim] hidden_states = ( expert_output.view(num_tokens, self.top_k, hidden_dim) * topk_weights.unsqueeze(-1) ).sum(dim = 1) else: # Fallback to naive implementation hidden_states = self.experts(hidden_states, topk_indices, topk_weights) # Add shared expert output hidden_states = hidden_states + self.shared_experts(residuals.view(-1, hidden_dim)) return hidden_states.view(*orig_shape) def Glm4MoeLiteNaiveMoe_fast_forward( self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor, ) -> torch.Tensor: """ Optimized expert forward using grouped GEMM. Args: hidden_states: [num_tokens, hidden_dim] top_k_index: [num_tokens, top_k] indices of selected experts top_k_weights: [num_tokens, top_k] weights for selected experts Returns: [num_tokens, hidden_dim] output after weighted sum of expert outputs """ num_tokens, hidden_dim = hidden_states.shape top_k = top_k_index.shape[1] # Cast routing weights to match hidden_states dtype (Qwen3 pattern) top_k_weights = top_k_weights.to(hidden_states.dtype) if not HAS_GROUPED_GEMM: # Fallback to original naive implementation final_hidden_states = torch.zeros_like(hidden_states) with torch.no_grad(): expert_mask = torch.nn.functional.one_hot( top_k_index, num_classes = self.num_experts ) expert_mask = expert_mask.permute(2, 1, 0) expert_hit = torch.greater(expert_mask.sum(dim = (-1, -2)), 0).nonzero() for expert_idx in expert_hit: expert_idx = expert_idx[0] if expert_idx == self.num_experts: continue top_k_pos, token_idx = torch.where(expert_mask[expert_idx]) current_state = hidden_states[token_idx] gate, up = torch.nn.functional.linear( current_state, self.gate_up_proj[expert_idx] ).chunk(2, dim = -1) current_hidden_states = self.act_fn(gate) * up current_hidden_states = torch.nn.functional.linear( current_hidden_states, self.down_proj[expert_idx] ) current_hidden_states = ( current_hidden_states * top_k_weights[token_idx, top_k_pos, None] ) final_hidden_states.index_add_( 0, token_idx, current_hidden_states.to(final_hidden_states.dtype) ) return final_hidden_states # Get routing indices for grouped GEMM with torch.no_grad(): token_counts_by_expert, gather_indices = get_routing_indices( top_k_index, self.num_experts ) # Cast hidden_states to match expert weights dtype # Under autocast, hidden_states may be fp32 while weights are bf16 hidden_states = hidden_states.to(self.gate_up_proj.dtype) # First grouped GEMM: gate_up_proj intermediate = grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert.int(), topk = top_k, gather_indices = gather_indices, permute_x = True, permute_y = False, autotune = True, is_first_gemm = True, ) # Activation: SiLU(gate) * up gate, up = intermediate.chunk(2, dim = -1) intermediate = self.act_fn(gate) * up # Second grouped GEMM: down_proj expert_output = grouped_gemm( X = intermediate, W = self.down_proj, m_sizes = token_counts_by_expert.int(), topk = top_k, gather_indices = gather_indices, permute_x = False, permute_y = True, autotune = True, is_first_gemm = False, ) # Merge topk weights final_hidden_states = ( expert_output.view(num_tokens, top_k, hidden_dim) * top_k_weights.unsqueeze(-1) ).sum(dim = 1) return final_hidden_states def Glm4MoeLiteDecoderLayer_fast_forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values = None, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, **kwargs, ) -> torch.Tensor: """ Optimized decoder layer forward with fast RMS layernorm. """ # Check if we're in inference mode is_inference = use_cache and hasattr(self, "_flag_for_generation") if is_inference: # Self-attention with fast inference path residual = hidden_states hidden_states = fast_rms_layernorm_inference( self.input_layernorm, hidden_states ) hidden_states, _ = self.self_attn( hidden_states = hidden_states, attention_mask = attention_mask, position_ids = position_ids, past_key_values = past_key_values, use_cache = use_cache, cache_position = cache_position, position_embeddings = position_embeddings, **kwargs, ) hidden_states = residual + hidden_states # MLP/MoE residual = hidden_states hidden_states = fast_rms_layernorm_inference( self.post_attention_layernorm, hidden_states ) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states else: # Training path residual = hidden_states hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states) hidden_states, _ = self.self_attn( hidden_states = hidden_states, attention_mask = attention_mask, position_ids = position_ids, past_key_values = past_key_values, use_cache = use_cache, cache_position = cache_position, position_embeddings = position_embeddings, **kwargs, ) hidden_states = residual + hidden_states # MLP/MoE residual = hidden_states hidden_states = fast_rms_layernorm(self.post_attention_layernorm, hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states return hidden_states def Glm4MoeLiteMLP_fast_forward(self, x): """ Optimized MLP forward using fused SwiGLU. """ return fast_swiglu_inference(self, x) class FastGLM47Model(FastLlamaModel): """ Fast GLM-4.7 Flash (GLM4 MoE Lite) model with grouped GEMM optimization. This provides 2-3x throughput improvement for MoE layers by: - Replacing sequential expert loops with grouped GEMM operations - Fusing permutation operations into the GEMM kernels - Using optimized RMS LayerNorm and SwiGLU implementations """ @staticmethod def pre_patch(): if not HAS_GLM4_MOE: raise ImportError( "Unsloth: GLM4 MoE Lite support requires transformers >= 5.0.0. " "Please upgrade with: pip install --upgrade transformers" ) # Patch MoE forward with grouped GEMM optimization # TMA compatibility is handled by grouped_gemm/__init__.py which patches # triton.language to support both old (_experimental_make_tensor_descriptor) # and new (make_tensor_descriptor) API names if HAS_GROUPED_GEMM: Glm4MoeLiteNaiveMoe.forward = Glm4MoeLiteNaiveMoe_fast_forward Glm4MoeLiteMoE.forward = Glm4MoeLiteMoE_fast_forward # Note: We don't patch the following for GLM4 MoE because: # - GLM4 uses MLA (Multi-head Latent Attention) which has different projection names # - Glm4MoeLiteRotaryEmbedding doesn't have extend_rope_embedding method # - The decoder layer and model forward functions assume Llama-compatible infrastructure return @staticmethod def from_pretrained( model_name = "unsloth/GLM-4.7-Flash", max_seq_length = 4096, dtype = None, load_in_4bit = True, token = None, device_map = "sequential", rope_scaling = None, fix_tokenizer = True, model_patcher = None, tokenizer_name = None, trust_remote_code = False, **kwargs, ): # Pop kwargs that are used by loader but not passed to model kwargs.pop("unsloth_force_compile", None) return FastLlamaModel.from_pretrained( model_name = model_name, max_seq_length = max_seq_length, dtype = dtype, load_in_4bit = load_in_4bit, token = token, device_map = device_map, rope_scaling = rope_scaling, fix_tokenizer = fix_tokenizer, model_patcher = FastGLM47Model, tokenizer_name = tokenizer_name, trust_remote_code = trust_remote_code, **kwargs, )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/models/glm4_moe.py", "license": "Apache License 2.0", "lines": 384, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/models/sentence_transformer.py
# Copyright 2025 electroglyph. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from .loader import FastModel, DISABLE_SDPA_MODEL_NAMES from ._utils import SUPPORTS_BFLOAT16 import inspect import json import os import types from huggingface_hub import hf_hub_download from typing import Optional import torch from transformers.modeling_outputs import BaseModelOutput from collections import OrderedDict from transformers.models.distilbert import modeling_distilbert from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa import transformers from packaging.version import Version import re from transformers import AutoModel, AutoConfig from transformers.models.auto.auto_factory import _get_model_class import tempfile from huggingface_hub import HfApi, get_token from ..save import unsloth_save_pretrained_torchao, unsloth_save_pretrained_gguf import contextlib import shutil def _save_pretrained_torchao( self, save_directory, tokenizer = None, torchao_config = None, push_to_hub = False, token = None, ): self.save_pretrained(save_directory) # grab inner model inner_model = self[0].auto_model if hasattr(inner_model, "_orig_mod"): inner_model = inner_model._orig_mod # merge LoRA first if hasattr(inner_model, "merge_and_unload"): inner_model = inner_model.merge_and_unload() # confirm Transformer path transformer_path = "0_Transformer" modules_path = os.path.join(save_directory, "modules.json") if os.path.exists(modules_path): try: with open(modules_path, "r") as f: modules = json.load(f) for m in modules: if m.get("type", "").endswith("Transformer"): transformer_path = m.get("path", "") break except: pass transformer_dir = os.path.join(save_directory, transformer_path) transformer_dir = os.path.abspath(transformer_dir) if tokenizer is None: tokenizer = self.tokenizer @contextlib.contextmanager def patch_unsloth_save(): original_causal = transformers.AutoModelForCausalLM original_rmtree = shutil.rmtree # unsloth_save_pretrained_torchao expects AutoModelForCausalLM transformers.AutoModelForCausalLM = transformers.AutoModel # prevent unsloth from deleting the unquantized model directory shutil.rmtree = lambda *args, **kwargs: None try: yield finally: # unpatch transformers.AutoModelForCausalLM = original_causal shutil.rmtree = original_rmtree with patch_unsloth_save(): unsloth_save_pretrained_torchao( inner_model, transformer_dir, tokenizer = tokenizer, torchao_config = torchao_config, push_to_hub = push_to_hub, token = token, ) # avoid `0_Transformer-torchao`, it was either this or fix modules.json torchao_dir = transformer_dir + "-torchao" if os.path.exists(torchao_dir): if not os.path.exists(transformer_dir): os.makedirs(transformer_dir, exist_ok = True) # move contents for item in os.listdir(torchao_dir): s = os.path.join(torchao_dir, item) d = os.path.join(transformer_dir, item) if os.path.isdir(s): shutil.copytree(s, d, dirs_exist_ok = True) else: shutil.copy2(s, d) # remove torchao dir shutil.rmtree(torchao_dir) # remove conflicting safetensors if we brought in bin if os.path.exists(os.path.join(transformer_dir, "pytorch_model.bin")): safetensors_path = os.path.join(transformer_dir, "model.safetensors") if os.path.exists(safetensors_path): try: os.remove(safetensors_path) except: pass try: FastSentenceTransformer._add_unsloth_branding(save_directory) except: pass # Thanks Etherl: def _save_pretrained_gguf( self, save_directory, tokenizer = None, quantization_method = "fast_quantized", first_conversion = None, push_to_hub = False, token = None, max_shard_size = "5GB", temporary_location = "_unsloth_temporary_saved_buffers", maximum_memory_usage = 0.85, **kwargs, ): """ Saves the SentenceTransformer model to GGUF format by saving the inner transformer model, converting it, and placing the resulting GGUF files in the save directory. """ # 1. Save standard SentenceTransformer structure (configs, modules.json, etc.) self.save_pretrained(save_directory) # 2. Extract inner transformer model inner_model = self[0].auto_model if hasattr(inner_model, "_orig_mod"): inner_model = inner_model._orig_mod # If it's a PEFT model, unsloth_save_pretrained_gguf handles merging, # but we pass the inner model wrapper. # 3. Identify where the transformer weights are stored transformer_path = "0_Transformer" modules_path = os.path.join(save_directory, "modules.json") if os.path.exists(modules_path): try: with open(modules_path, "r") as f: modules = json.load(f) for m in modules: if m.get("type", "").endswith("Transformer"): transformer_path = m.get("path", "") break except: pass # This is where Unsloth will perform the save + conversion operations transformer_dir = os.path.join(save_directory, transformer_path) # Ensure this path is absolute for consistent comparison later transformer_dir = os.path.abspath(transformer_dir) if tokenizer is None: tokenizer = self.tokenizer # 4. Patch environment to ensure Unsloth treats this embedding model correctly @contextlib.contextmanager def patch_unsloth_gguf_save(): # Prevent deletion of the directory we just created via self.save_pretrained original_rmtree = shutil.rmtree try: yield finally: shutil.rmtree = original_rmtree # 5. Call Unsloth's GGUF saver on the inner model targeting the transformer subdirectory with patch_unsloth_gguf_save(): result = unsloth_save_pretrained_gguf( inner_model, save_directory = transformer_dir, tokenizer = tokenizer, quantization_method = quantization_method, first_conversion = first_conversion, push_to_hub = False, # Force local first to move files token = token, max_shard_size = max_shard_size, temporary_location = temporary_location, maximum_memory_usage = maximum_memory_usage, ) # 6. Move GGUF files from the subdirectory (0_Transformer) to the root save_directory gguf_files = result.get("gguf_files", []) new_gguf_locations = [] for gguf_file in gguf_files: if os.path.exists(gguf_file): filename = os.path.basename(gguf_file) dest_path = os.path.join(save_directory, filename) # Convert to absolute path to avoid mixing relative/absolute in commonpath abs_gguf_file = os.path.abspath(gguf_file) # Check if file is inside transformer_dir (subpath) try: is_subpath = ( os.path.commonpath([abs_gguf_file, transformer_dir]) == transformer_dir ) except ValueError: # Can happen on Windows with different drives, or mix of absolute/relative (handled by abspath above) is_subpath = False if is_subpath: # If the GGUF file is inside the transformer_dir, move it out to root shutil.move(gguf_file, dest_path) new_gguf_locations.append(dest_path) else: # If it's elsewhere, move it to root if not already there if os.path.abspath(dest_path) != abs_gguf_file: shutil.move(gguf_file, dest_path) new_gguf_locations.append(dest_path) # Update result with new locations result["gguf_files"] = new_gguf_locations # 7. Add branding try: FastSentenceTransformer._add_unsloth_branding(save_directory) # Add GGUF details to README readme_path = os.path.join(save_directory, "README.md") if os.path.exists(readme_path): with open(readme_path, "a", encoding = "utf-8") as f: f.write("\n## GGUF Quantization\n") f.write( f"This model contains GGUF quantized versions in: {', '.join([os.path.basename(f) for f in new_gguf_locations])}\n" ) except: pass # 8. Handle Push to Hub if requested if push_to_hub: if token is None: token = get_token() api = HfApi(token = token) repo_id = save_directory # Assuming save_directory is the repo name if pushing print(f"Unsloth: Uploading to {repo_id}...") try: api.create_repo( repo_id = repo_id, exist_ok = True, private = kwargs.get("private", False) ) api.upload_folder( folder_path = save_directory, repo_id = repo_id, commit_message = "Upload GGUF and SentenceTransformer model", ) print(f"Unsloth: Uploaded to https://huggingface.co/{repo_id}") except Exception as e: print(f"Unsloth: Upload failed: {e}") return result def _push_to_hub_gguf( self, repo_id, tokenizer = None, quantization_method = "fast_quantized", first_conversion = None, token = None, private = None, commit_message = "Upload GGUF SentenceTransformer model trained with Unsloth", commit_description = "Upload GGUF model trained with Unsloth 2x faster", max_shard_size = "5GB", temporary_location = "_unsloth_temporary_saved_buffers", maximum_memory_usage = 0.85, create_pr = False, revision = None, tags = None, **kwargs, ): """ Converts the SentenceTransformer model to GGUF format and pushes to the Hugging Face Hub. This method: 1. Saves the model locally to a temporary directory in GGUF format. 2. Uploads the GGUF files, config, Ollama Modelfile, and README to the Hub. 3. Cleans up the temporary directory. Args: repo_id (str): The Hugging Face Hub repo ID (e.g., "username/model-name"). tokenizer: The tokenizer to save. Defaults to `self.tokenizer`. quantization_method (str or list): GGUF quantization method(s). Can be a string or list of strings. Choose from the following options: * "not_quantized" : Recommended. Fast conversion. Slow inference, big files. * "fast_quantized" : Recommended. Fast conversion. OK inference, OK file size. * "quantized" : Recommended. Slow conversion. Fast inference, small files. * "f32" : Not recommended. Retains 100% accuracy, but super slow and memory hungry. * "f16" : Fastest conversion + retains 100% accuracy. Slow and memory hungry. * "q8_0" : Fast conversion. High resource use, but generally acceptable. * "q4_k_m" : Recommended. Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q4_K * "q5_k_m" : Recommended. Uses Q6_K for half of the attention.wv and feed_forward.w2 tensors, else Q5_K * "q2_k" : Uses Q4_K for the attention.vw and feed_forward.w2 tensors, Q2_K for the other tensors. * "q3_k_l" : Uses Q5_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K * "q3_k_m" : Uses Q4_K for the attention.wv, attention.wo, and feed_forward.w2 tensors, else Q3_K * "q3_k_s" : Uses Q3_K for all tensors * "q4_0" : Original quant method, 4-bit. * "q4_1" : Higher accuracy than q4_0 but not as high as q5_0. However has quicker inference than q5 models. * "q4_k_s" : Uses Q4_K for all tensors * "q5_0" : Higher accuracy, higher resource usage and slower inference. * "q5_1" : Even higher accuracy, resource usage and slower inference. * "q5_k_s" : Uses Q5_K for all tensors * "q6_k" : Uses Q8_K for all tensors first_conversion (str, optional): The initial conversion format before quantization. token (str, optional): Hugging Face token. Uses cached token if not provided. private (bool, optional): Whether the repo should be private. commit_message (str): Commit message for the upload. commit_description (str): Commit description for the upload. max_shard_size (str): Maximum shard size for saving. temporary_location (str): Temp directory for intermediate files. maximum_memory_usage (float): Max fraction of memory to use. create_pr (bool): Whether to create a pull request instead of pushing directly. revision (str, optional): Branch/revision to push to. tags (list, optional): Additional tags for the repo. Returns: str: The full repo ID on Hugging Face Hub. """ if token is None: token = get_token() if token is None: raise ValueError( "No HF token provided. Please provide a token or login with `huggingface-cli login`" ) api = HfApi(token = token) # Determine full repo_id if "/" not in repo_id: username = api.whoami()["name"] full_repo_id = f"{username}/{repo_id}" else: full_repo_id = repo_id model_name = full_repo_id.split("/")[-1] # Create repo try: api.create_repo( repo_id = full_repo_id, private = private, exist_ok = True, repo_type = "model", ) except Exception as e: print(f"Unsloth Warning: Could not create repo: {e}") # Save to temporary directory first with tempfile.TemporaryDirectory(prefix = "unsloth_st_gguf_") as temp_dir: print(f"Unsloth: Converting SentenceTransformer to GGUF format...") # Call save_pretrained_gguf to do the local conversion result = _save_pretrained_gguf( self, save_directory = temp_dir, tokenizer = tokenizer, quantization_method = quantization_method, first_conversion = first_conversion, push_to_hub = False, # We handle upload ourselves token = token, max_shard_size = max_shard_size, temporary_location = temporary_location, maximum_memory_usage = maximum_memory_usage, ) gguf_files = result.get("gguf_files", []) modelfile_location = result.get("modelfile_location", None) is_vlm = result.get("is_vlm", False) fix_bos_token = result.get("fix_bos_token", False) print(f"Unsloth: Uploading GGUF to https://huggingface.co/{full_repo_id}...") # Upload GGUF files for file_location in gguf_files: if os.path.exists(file_location): filename = os.path.basename(file_location) print(f" Uploading {filename}...") api.upload_file( path_or_fileobj = file_location, path_in_repo = filename, repo_id = full_repo_id, repo_type = "model", commit_message = commit_message, commit_description = commit_description, create_pr = create_pr, revision = revision, ) # Upload Modelfile if exists if modelfile_location and os.path.exists(modelfile_location): print(" Uploading Ollama Modelfile...") api.upload_file( path_or_fileobj = modelfile_location, path_in_repo = "Modelfile", repo_id = full_repo_id, repo_type = "model", commit_message = f"{commit_message} - Ollama Modelfile", create_pr = create_pr, revision = revision, ) # Upload config.json if exists config_path = os.path.join(temp_dir, "config.json") if os.path.exists(config_path): print(" Uploading config.json...") api.upload_file( path_or_fileobj = config_path, path_in_repo = "config.json", repo_id = full_repo_id, repo_type = "model", commit_message = f"{commit_message} - config", create_pr = create_pr, revision = revision, ) # Create and upload README gguf_basenames = [os.path.basename(f) for f in gguf_files if os.path.exists(f)] readme_content = f"""--- tags: - gguf - llama.cpp - unsloth - sentence-transformers {"- vision-language-model" if is_vlm else ""} --- # {model_name} - GGUF This sentence-transformers model was finetuned and converted to GGUF format using [Unsloth](https://github.com/unslothai/unsloth). ## Available Model files: """ for fname in gguf_basenames: readme_content += f"- `{fname}`\n" if modelfile_location and os.path.exists(modelfile_location): readme_content += "\n## Ollama\n" readme_content += "An Ollama Modelfile is included for easy deployment.\n" if fix_bos_token: readme_content += "\n## Note\n" readme_content += ( "The model's BOS token behavior was adjusted for GGUF compatibility.\n" ) readme_content += ( "\nThis was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth)\n" '[<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)\n' ) readme_path = os.path.join(temp_dir, "README.md") with open(readme_path, "w", encoding = "utf-8") as f: f.write(readme_content) api.upload_file( path_or_fileobj = readme_path, path_in_repo = "README.md", repo_id = full_repo_id, repo_type = "model", commit_message = "Add README", create_pr = create_pr, revision = revision, ) # Add tags all_tags = ["gguf", "llama-cpp", "unsloth", "sentence-transformers"] if is_vlm: all_tags.append("vision-language-model") if tags is not None: if isinstance(tags, (list, tuple)): all_tags.extend(tags) else: all_tags.append(tags) try: api.add_tags(repo_id = full_repo_id, tags = all_tags, repo_type = "model") except: pass print( f"Unsloth: Successfully uploaded GGUF to https://huggingface.co/{full_repo_id}" ) return full_repo_id class FastSentenceTransformer(FastModel): @staticmethod def _read_pooling_mode(model_name, token): """ Read the pooling mode from the modules.json file if it exists, otherwise return "mean". """ try: if os.path.exists(model_name) and os.path.exists( os.path.join(model_name, "modules.json") ): modules_json_path = os.path.join(model_name, "modules.json") else: modules_json_path = hf_hub_download( model_name, "modules.json", token = token ) with open(modules_json_path, "r") as f: modules_config = json.load(f) pooling_config_path = None for module in modules_config: if module.get("type", "") == "sentence_transformers.models.Pooling": pooling_path = module.get("path", "") if pooling_path: # try to find config.json for pooling module if os.path.exists(model_name) and os.path.exists( os.path.join(model_name, pooling_path, "config.json") ): pooling_config_path = os.path.join( model_name, pooling_path, "config.json" ) else: pooling_config_path = hf_hub_download( model_name, os.path.join(pooling_path, "config.json"), token = token, ) break if pooling_config_path: with open(pooling_config_path, "r") as f: pooling_config = json.load(f) # from here: # https://github.com/huggingface/sentence-transformers/blob/main/sentence_transformers/models/Pooling.py#L43 pooling_map = { "pooling_mode_cls_token": "cls", "pooling_mode_mean_tokens": "mean", "pooling_mode_max_tokens": "max", "pooling_mode_mean_sqrt_len_tokens": "mean_sqrt_len", "pooling_mode_weightedmean_tokens": "weightedmean", "pooling_mode_lasttoken": "lasttoken", } for config_key, mode in pooling_map.items(): if pooling_config.get(config_key): if mode != "mean": print(f"Pooling mode detected as {mode}, updating...") return mode except Exception as e: print( f"Failed to detect pooling mode, not a sentence-transformers model. Using default pooling mode 'mean', this may or may not work." ) return "mean" # should prolly be done upstream instead of this hackfest here @staticmethod def _patch_mpnet_v4(): """ Patch the MPNetModel to support gradient checkpointing. Supports transformers 4. """ from transformers.models.mpnet import modeling_mpnet # add supports_gradient_checkpointing flag modeling_mpnet.MPNetModel.supports_gradient_checkpointing = True # add _set_gradient_checkpointing method def _set_gradient_checkpointing(self, module = None, value = True): if module is None: module = self.encoder if isinstance(module, modeling_mpnet.MPNetEncoder): module.gradient_checkpointing = value modeling_mpnet.MPNetModel._set_gradient_checkpointing = ( _set_gradient_checkpointing ) # patch MPNetEncoder.forward to support checkpointing # based on: # https://github.com/huggingface/transformers/blob/v4.57.3/src/transformers/models/mpnet/modeling_mpnet.py#L321 def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, output_hidden_states: bool = False, return_dict: bool = False, **kwargs, ): position_bias = self.compute_position_bias(hidden_states) all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) # do gradient checkpointing if enabled and training if getattr(self, "gradient_checkpointing", False) and self.training: def create_custom_forward(module): # bog standard checkpoint def custom_forward(*inputs): return module(*inputs, output_attentions = output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, head_mask[i] if head_mask is not None else None, position_bias, use_reentrant = True, # fix for torch 2.9 ) else: # original code from here on layer_outputs = layer_module( hidden_states, attention_mask, head_mask[i] if head_mask is not None else None, position_bias, output_attentions = output_attentions, **kwargs, ) hidden_states = layer_outputs[0] if output_attentions: all_attentions = all_attentions + (layer_outputs[1],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None ) return BaseModelOutput( last_hidden_state = hidden_states, hidden_states = all_hidden_states, attentions = all_attentions, ) # assign the patched forward modeling_mpnet.MPNetEncoder.forward = forward @staticmethod def _patch_mpnet_v5(): """ Patch the MPNetModel to support gradient checkpointing. Supports transformers 5. """ from transformers.models.mpnet import modeling_mpnet # add supports_gradient_checkpointing flag modeling_mpnet.MPNetModel.supports_gradient_checkpointing = True # add _set_gradient_checkpointing method def _set_gradient_checkpointing(self, module = None, value = True): if module is None: module = self.encoder if isinstance(module, modeling_mpnet.MPNetEncoder): module.gradient_checkpointing = value modeling_mpnet.MPNetModel._set_gradient_checkpointing = ( _set_gradient_checkpointing ) # patch MPNetEncoder.forward to support checkpointing # based on: # https://github.com/huggingface/transformers/blob/v5.0.0rc1/src/transformers/models/mpnet/modeling_mpnet.py#L284 def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, output_hidden_states: bool = False, return_dict: bool = False, **kwargs, ): position_bias = self.compute_position_bias(hidden_states) all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) # do gradient checkpointing if enabled and training if getattr(self, "gradient_checkpointing", False) and self.training: def create_custom_forward(module): # checkpoint def custom_forward(*inputs): return module(*inputs, output_attentions = output_attentions) return custom_forward layer_outputs = torch.utils.checkpoint.checkpoint( create_custom_forward(layer_module), hidden_states, attention_mask, position_bias, use_reentrant = True, # required for torch >= 2.9 ) else: # original code from here on layer_outputs = layer_module( hidden_states, attention_mask, position_bias, output_attentions, **kwargs, ) hidden_states = layer_outputs[0] if output_attentions: all_attentions = all_attentions + (layer_outputs[1],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None ) return BaseModelOutput( last_hidden_state = hidden_states, hidden_states = all_hidden_states, attentions = all_attentions, ) modeling_mpnet.MPNetEncoder.forward = forward @staticmethod def _patch_distilbert_v4(): # change kwargs to positional args to be compatible with peft_utils """ Patch the forward method of the DistilBertModel to use positional arguments instead of keyword arguments. Transformers 4 version. """ # based on: # https://github.com/huggingface/transformers/blob/v4.57.3/src/transformers/models/distilbert/modeling_distilbert.py#L666 # original code from here on: def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, head_mask: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ): output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask) input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError( "You have to specify either input_ids or inputs_embeds" ) device = input_ids.device if input_ids is not None else inputs_embeds.device head_mask_is_none = head_mask is None # Prepare head mask if needed head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) embeddings = self.embeddings( input_ids, inputs_embeds ) # (bs, seq_length, dim) if self.config._attn_implementation == "flash_attention_2": attention_mask = ( attention_mask if (attention_mask is not None and 0 in attention_mask) else None ) else: if attention_mask is None: attention_mask = torch.ones( input_shape, device = device ) # (bs, seq_length) if ( self.config._attn_implementation == "sdpa" and head_mask_is_none and not output_attentions ): attention_mask = _prepare_4d_attention_mask_for_sdpa( attention_mask, embeddings.dtype, tgt_len = input_shape[1] ) # patch here, change kwargs to positional args: return self.transformer( embeddings, attention_mask, head_mask, output_attentions, output_hidden_states, return_dict, ) modeling_distilbert.DistilBertModel.forward = forward @staticmethod def _has_add_pooling_layer(config, auto_model_class = None): """ Checks if the model class supports the `add_pooling_layer` argument """ try: if auto_model_class is None: auto_model_class = AutoModel # try to resolve the class model_class = _get_model_class(config, auto_model_class._model_mapping) if model_class: sig = inspect.signature(model_class.__init__) return "add_pooling_layer" in sig.parameters except: pass return False @staticmethod def _patch_distilbert_v5(): """ Patch the forward method of the DistilBertModel to use positional arguments instead of keyword arguments. Transformers 5 version. """ # based on: # https://github.com/huggingface/transformers/blob/v5.0.0rc1/src/transformers/models/distilbert/modeling_distilbert.py#L386 # original code from here on: from transformers.masking_utils import create_bidirectional_mask def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, **kwargs, ): if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError( "You must specify exactly one of input_ids or inputs_embeds" ) embeddings = self.embeddings(input_ids, inputs_embeds, position_ids) attention_mask = create_bidirectional_mask( config = self.config, input_embeds = embeddings, attention_mask = attention_mask, ) # patch here: unsloth gradient checkpointing hook needs positional arguments return self.transformer( embeddings, attention_mask, **kwargs, ) modeling_distilbert.DistilBertModel.forward = forward @staticmethod def _add_unsloth_tags(repo_id, token, tags = None): """ Add Unsloth and sentence-transformers tags to the Hugging Face Hub repository. """ from huggingface_hub import HfApi api = HfApi(token = token) if tags is None: tags = [] tags.extend(["unsloth", "sentence-transformers"]) try: api.add_tags( repo_id = repo_id, tags = tags, repo_type = "model", ) except: pass @staticmethod def _add_unsloth_branding(save_directory): """ Add Unsloth branding to the README.md file generated by sentence-transformers. """ readme_path = os.path.join(save_directory, "README.md") if not os.path.exists(readme_path): return with open(readme_path, "r", encoding = "utf-8") as f: content = f.read() # add unsloth tag to frontmatter if "---\ntags:\n" in content: content = content.replace("---\ntags:\n", "---\ntags:\n- unsloth\n") else: # if tags exist but not right at start, use regex to append pattern = r"(^tags:\s*\n)" if re.search(pattern, content, re.MULTILINE): content = re.sub( pattern, r"\1- unsloth\n", content, count = 1, flags = re.MULTILINE ) # add branding badge and text branding = ( "\n\nThis model was finetuned with [Unsloth](https://github.com/unslothai/unsloth).\n\n" '[<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)\n' ) # add to description if "# SentenceTransformer" in content: parts = content.split("# SentenceTransformer", 1) content = parts[0] + "# SentenceTransformer" + branding + parts[1] else: content += branding with open(readme_path, "w", encoding = "utf-8") as f: f.write(content) @staticmethod def _module_path(model_name, token = None): """ Returns the path to the modules.json file or None """ try: if os.path.exists(model_name) and os.path.isdir(model_name): path = os.path.join(model_name, "modules.json") return path if os.path.exists(path) else None else: try: return hf_hub_download(model_name, "modules.json", token = token) except: return None except: return None @staticmethod def _create_transformer_module( model_name, model, tokenizer, max_seq_length, trust_remote_code, ): """Helper to create and configure a Transformer module.""" from sentence_transformers.models import Transformer # prevents sentence-transformers from loading the model a second time, thanks Etherl original_from_pretrained = AutoModel.from_pretrained def return_existing_model(*args, **kwargs): return model try: # Temporarily redirect AutoModel loading to return our pre-loaded model AutoModel.from_pretrained = return_existing_model # Initialize Transformer transformer_module = Transformer( model_name, max_seq_length = max_seq_length, model_args = {"trust_remote_code": trust_remote_code}, config_args = {"trust_remote_code": trust_remote_code}, ) finally: # Restore original functionality immediately AutoModel.from_pretrained = original_from_pretrained transformer_module.tokenizer = tokenizer transformer_module.do_lower_case = getattr(tokenizer, "do_lower_case", False) # sentence-transformers only passes along known keys to model.forward model_forward_params = list(inspect.signature(model.forward).parameters) transformer_module.model_forward_params = set(model_forward_params) | { "input_ids", "attention_mask", "token_type_ids", "inputs_embeds", } # determine max_seq_length if not provided if max_seq_length is None: if hasattr(model, "config") and hasattr( model.config, "max_position_embeddings" ): max_seq_length = model.config.max_position_embeddings elif hasattr(tokenizer, "model_max_length"): max_seq_length = tokenizer.model_max_length else: max_seq_length = 512 transformer_module.max_seq_length = max_seq_length transformer_module.config_keys = ["max_seq_length", "do_lower_case"] transformer_module.save_in_root = True if hasattr(model, "config"): model.config.tokenizer_class = tokenizer.__class__.__name__ return transformer_module @staticmethod def _load_modules( model_name, token, model, tokenizer, max_seq_length, pooling_mode, trust_remote_code = False, ) -> tuple[OrderedDict, bool]: """ Load modules from modules.json if available, otherwise fallback to hard-coded modules. Returns: tuple[OrderedDict, bool]: (modules, no_modules_json) """ from sentence_transformers.util import import_from_string, load_dir_path from sentence_transformers.models import Pooling, Normalize modules = OrderedDict() modules_json_path = FastSentenceTransformer._module_path(model_name, token) if modules_json_path: with open(modules_json_path, encoding = "utf8") as f: modules_config = json.load(f) for module_config in modules_config: class_ref = module_config["type"] name = module_config.get( "name", str(module_config.get("idx", len(modules))) ) if class_ref == "sentence_transformers.models.Transformer": transformer_module = ( FastSentenceTransformer._create_transformer_module( model_name, model, tokenizer, max_seq_length, trust_remote_code, ) ) modules[name] = transformer_module else: # load other modules (Pooling, Normalize, etc.) module_path = module_config["path"] if os.path.isdir(model_name): load_path = os.path.join(model_name, module_path) else: try: load_path = load_dir_path( model_name, module_path, token = token ) except Exception as e: print( f"Unsloth Warning: Could not download module {module_path}: {e}" ) continue module_class = import_from_string(class_ref) try: module = module_class.load(load_path) modules[name] = module except Exception as e: print( f"Unsloth Warning: Failed to load module {name} ({class_ref}): {e}" ) return modules, False # fallback if no modules.json (non sentence-transformers models) print( "Unsloth: No modules.json found, falling back to [Transformer, Pooling, Normalize]. This may or may not work." ) transformer_module = FastSentenceTransformer._create_transformer_module( model_name, model, tokenizer, max_seq_length, trust_remote_code ) modules["0"] = transformer_module hidden_size = getattr(model.config, "hidden_size", 768) if pooling_mode == "mean": pooling_mode = FastSentenceTransformer._read_pooling_mode(model_name, token) modules["1"] = Pooling( word_embedding_dimension = hidden_size, pooling_mode = pooling_mode ) modules["2"] = Normalize() return modules, True # Encoder model types that benefit from native torch.compile instead of Unsloth patching ENCODER_MODEL_TYPES = { "mpnet", "bert", "distilbert", "modernbert", "roberta", "xlm-roberta", "albert", "electra", } @staticmethod def _estimate_compile_threshold( model, batch_size = None, grad_accum = None, max_seq_length = None, ): """ Estimate the minimum training steps needed for torch.compile to be beneficial. Returns the threshold with a 1.2x safety margin built in. Based on empirical benchmarks: - Larger models have lower breakeven (more time saved per step) - Warmup time scales with model size but speedup also increases Optional inputs (batch_size, grad_accum, max_seq_length) allow a coarse pre-run adjustment. These are intentionally conservative and avoid any runtime measurements. """ # Get parameter count from inner model if hasattr(model, "__getitem__"): try: inner = model[0].auto_model params = sum(p.numel() for p in inner.parameters()) except: params = 100_000_000 # Default to 100M if can't determine else: params = sum(p.numel() for p in model.parameters()) model_type = None try: if "inner" in locals(): model_type = getattr(getattr(inner, "config", None), "model_type", None) except Exception: model_type = None if isinstance(model_type, str): model_type = model_type.lower() params_m = params / 1e6 # Empirical formula based on benchmarks with batch_size=2, grad_accum=4 # Small models: high fixed overhead, lower speedup # Large models: warmup scales but speedup is significant if params_m < 50: estimated_warmup = 35 + params_m * 0.3 base_speedup = 1.35 elif params_m < 200: estimated_warmup = 12 + params_m * 0.03 base_speedup = 1.75 else: estimated_warmup = 15 + params_m * 0.04 base_speedup = 1.60 # Estimate time per step (ms) and time saved naive_ms = 50 + params_m * 1.0 compiled_ms = naive_ms / base_speedup time_saved_per_step_s = (naive_ms - compiled_ms) / 1000 if time_saved_per_step_s > 0: breakeven = estimated_warmup / time_saved_per_step_s else: breakeven = float("inf") # Return threshold with 1.2x safety margin threshold = breakeven * 1.2 # Optional adjustment based on expected work per step. # This uses only pre-run information (batch size, grad accum, seq length). generic_scale = 1.0 fast_scale = 1.0 if ( batch_size is not None or grad_accum is not None or max_seq_length is not None ): try: bs = int(batch_size) if batch_size is not None else 2 ga = int(grad_accum) if grad_accum is not None else 4 seq = int(max_seq_length) if max_seq_length is not None else 512 except Exception: bs, ga, seq = 2, 4, 512 bs = max(1, bs) ga = max(1, ga) # Guard against unbounded tokenizer.model_max_length seq = max(64, min(seq, 8192)) ref_bs, ref_ga, ref_seq = 2, 4, 512 # Generic path: lighter scaling, less conservative than params-only. ga_scale = (ref_ga / ga) ** 1.0 bs_seq_scale = ((ref_bs * ref_seq) / (bs * seq)) ** 0.15 generic_scale = 0.35 * ga_scale * bs_seq_scale generic_scale = max(0.05, min(generic_scale, 5.0)) # Fast encoder path: stronger scaling based on observed behavior. fast_ga_scale = (ref_ga / ga) ** 1.5 fast_bs_seq_scale = ((ref_bs * ref_seq) / (bs * seq)) ** 0.25 fast_scale = 0.2 * fast_ga_scale * fast_bs_seq_scale fast_scale = max(0.05, min(fast_scale, 5.0)) # Conservative safety factors: generic is less conservative than fast. generic_threshold = threshold * generic_scale * 1.25 is_fast_type = ( isinstance(model_type, str) and model_type in FastSentenceTransformer.ENCODER_MODEL_TYPES ) if is_fast_type: fast_threshold = threshold * fast_scale * 1.5 # Prefer the smaller (less conservative) of the two estimates. final_threshold = min(generic_threshold, fast_threshold) else: final_threshold = generic_threshold # Reduce mpnet overestimation slightly. if model_type == "mpnet": final_threshold *= 0.7 # Lower bound to avoid compiling on extremely short runs. return int(max(20, final_threshold)) @staticmethod def _apply_torch_compile(model, mode = "default"): """ Apply torch.compile to a SentenceTransformer model. Includes workaround for accelerate's unwrap_model bug. """ if hasattr(model, "__getitem__"): inner_model = model[0].auto_model compiled = torch.compile(inner_model, mode = mode) model[0].auto_model = compiled # Fix for accelerate unwrap_model bug: # When SentenceTransformer contains a compiled inner model, # accelerate checks has_compiled_regions() which returns True, # then tries to access model.__dict__["_orig_mod"] which fails. # This workaround sets _orig_mod to satisfy accelerate. model.__dict__["_orig_mod"] = model else: model = torch.compile(model, mode = mode) return model @staticmethod def from_pretrained( model_name, max_seq_length = None, dtype = None, load_in_4bit = False, # Changed default: 4-bit is slow for encoders load_in_8bit = False, load_in_16bit = True, # Changed default: 16-bit is optimal for encoders full_finetuning = False, token = None, device_map = "sequential", rope_scaling = None, fix_tokenizer = True, trust_remote_code = False, use_gradient_checkpointing = False, # Changed default: conflicts with torch.compile resize_model_vocab = None, revision = None, use_exact_model_name = False, offload_embedding = False, random_state = 3407, max_lora_rank = 64, disable_log_stats = True, qat_scheme = None, unsloth_tiled_mlp = False, pooling_mode = "mean", for_inference = False, **kwargs, ): try: from sentence_transformers import SentenceTransformer from sentence_transformers.models import Transformer, Pooling, Normalize except ImportError: raise ImportError( "Unsloth: To use `FastSentenceTransformer`, you must install `sentence-transformers`.\n" "Run `pip install sentence-transformers` to install it." ) # if for_inference == True, skip Unsloth optimizations to avoid torch compile issues if for_inference: st_device = device_map if isinstance(st_device, dict) or ( isinstance(st_device, str) and st_device in ["auto", "sequential"] ): st_device = None # this was added because when loading for inference it was defaulting to float32 # propagate dtype to model_kwargs, default to "auto" model_kwargs = kwargs.get("model_kwargs", {}) model_kwargs["dtype"] = dtype if dtype is not None else "auto" # filter kwargs for SentenceTransformer st_kwargs = { "device": st_device, "trust_remote_code": trust_remote_code, "token": token, "revision": revision, "model_kwargs": model_kwargs, } # add other known kwargs if present known_keys = [ "cache_folder", "truncate_dim", "tokenizer_kwargs", "config_kwargs", ] for k in known_keys: if k in kwargs: st_kwargs[k] = kwargs[k] st_model = SentenceTransformer(model_name, **st_kwargs) return st_model # sanity check, thanks Etherl: if full_finetuning and (load_in_4bit or load_in_8bit): print( "Unsloth: You selected full finetuning support, but 4bit / 8bit is enabled - disabling LoRA / QLoRA." ) load_in_4bit = False load_in_8bit = False load_in_fp8 = False load_in_16bit = False if int(load_in_4bit) + int(load_in_8bit) + int(load_in_16bit) >= 2: raise RuntimeError( "Unsloth: Can only load in 4bit or 8bit or 16bit, not a combination!\n" "Also, we by default set `load_in_16bit = True`.\n" "If you want 4bit LoRA finetuning, set `load_in_16bit = False` and `load_in_4bit = True`\n" "If you want 8bit finetuning, set both `load_in_16bit = False` and `load_in_8bit = True`" ) if "auto_model" not in kwargs: kwargs["auto_model"] = AutoModel transformers4 = Version(transformers.__version__).major < 5 model_type = "" config = None try: config = AutoConfig.from_pretrained( model_name, token = token, trust_remote_code = trust_remote_code ) model_type = getattr(config, "model_type", "") except: pass # Fast encoder path: Use native torch.compile for encoder models (6x speedup) # This bypasses Unsloth's auto-compiler which adds @torch.compiler.disable decorators # that interfere with torch.compile and cause runtime errors for encoder models. # NOTE: The old Unsloth path is BROKEN for encoder models with torch 2.9+ due to # conflicting @torch.compile and @torch.compiler.disable decorators. # Set UNSLOTH_COMPILE_DISABLE=1 to disable torch.compile and use the old path. is_encoder_model = ( model_type.lower() in FastSentenceTransformer.ENCODER_MODEL_TYPES ) use_fast_encoder = os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") != "1" if use_fast_encoder and is_encoder_model: # torch.compile mode: "default" is safest for PEFT/LoRA training # Note: "reduce-overhead" uses CUDA Graphs which is incompatible with PEFT compile_mode = "default" # Determine dtype - handle float16 machines that don't support bfloat16 if dtype is None: if load_in_16bit: dtype = torch.float16 if not SUPPORTS_BFLOAT16 else torch.bfloat16 else: dtype = torch.float32 elif dtype == torch.bfloat16 and not SUPPORTS_BFLOAT16: print( "Unsloth: Device does not support bfloat16. Using float16 instead." ) dtype = torch.float16 # Determine device st_device = device_map if isinstance(st_device, dict) or ( isinstance(st_device, str) and st_device in ["auto", "sequential"] ): st_device = "cuda" # Check if model supports SDPA (Scaled Dot Product Attention) for extra speedup supports_sdpa = False if config is not None: try: model_class = _get_model_class( config, kwargs.get("auto_model", AutoModel)._model_mapping ) supports_sdpa = getattr(model_class, "_supports_sdpa", False) except: pass # Build model_kwargs for SentenceTransformer model_kwargs = {"torch_dtype": dtype} # Enable SDPA if supported (1.2x extra speedup on top of torch.compile) # But disable for models with known SDPA + torch.compile backward issues _force_eager = False for _sdpa_model in DISABLE_SDPA_MODEL_NAMES: if _sdpa_model in model_type.lower(): supports_sdpa = False _force_eager = True break if supports_sdpa: model_kwargs["attn_implementation"] = "sdpa" elif _force_eager: model_kwargs["attn_implementation"] = "eager" # Print optimization status sdpa_str = " + SDPA" if supports_sdpa else "" if load_in_4bit: print( f"Unsloth: Using fast encoder path for {model_type} with 4-bit quantization{sdpa_str}" ) else: print( f"Unsloth: Using fast encoder path for {model_type} (torch.compile{sdpa_str})" ) # Handle 4-bit quantization via BitsAndBytesConfig if load_in_4bit: from transformers import BitsAndBytesConfig bnb_config = BitsAndBytesConfig( load_in_4bit = True, bnb_4bit_compute_dtype = dtype, bnb_4bit_quant_type = "nf4", bnb_4bit_use_double_quant = True, ) model_kwargs["quantization_config"] = bnb_config # When using quantization, device must be handled by accelerate st_device = None # Handle gradient checkpointing - warn user it conflicts with torch.compile _use_gc = use_gradient_checkpointing if _use_gc and _use_gc != False: print( "Unsloth Warning: Gradient checkpointing is incompatible with torch.compile." ) print("Disabling torch.compile to enable gradient checkpointing.") compile_mode = None # Disable compilation is_mpnet = "mpnet" == model_type.lower() if is_mpnet and transformers4: FastSentenceTransformer._patch_mpnet_v4() elif is_mpnet: FastSentenceTransformer._patch_mpnet_v5() # Load via native SentenceTransformer (bypasses Unsloth patching) st_model = SentenceTransformer( model_name, device = st_device, trust_remote_code = trust_remote_code, token = token, revision = revision, model_kwargs = model_kwargs, ) # Store metadata for get_peft_model st_model._unsloth_fast_encoder = True st_model._compile_mode = compile_mode st_model._dtype = dtype st_model._load_in_4bit = load_in_4bit st_model.no_modules = False # Add save methods def _save_pretrained_merged(self, save_directory, **save_kwargs): self.save_pretrained(save_directory) tokenizer = save_kwargs.pop("tokenizer", self.tokenizer) if hasattr(self[0], "auto_model"): inner = self[0].auto_model # Handle compiled model if hasattr(inner, "_orig_mod"): inner = inner._orig_mod if hasattr(inner, "merge_and_unload"): merged = inner.merge_and_unload() merged.save_pretrained(save_directory) elif hasattr(inner, "save_pretrained"): inner.save_pretrained(save_directory) if tokenizer is not None: tokenizer.save_pretrained(save_directory) FastSentenceTransformer._add_unsloth_branding(save_directory) st_model.save_pretrained_merged = types.MethodType( _save_pretrained_merged, st_model ) st_model.save_pretrained_torchao = types.MethodType( _save_pretrained_torchao, st_model ) st_model.save_pretrained_gguf = types.MethodType( _save_pretrained_gguf, st_model ) st_model.push_to_hub_gguf = types.MethodType(_push_to_hub_gguf, st_model) def _push_to_hub_merged(self, repo_id, **push_kwargs): hub_token = push_kwargs.get("token", None) or get_token() if hub_token is None: raise ValueError("No HF token provided") api = HfApi(token = hub_token) try: api.create_repo( repo_id = repo_id, private = push_kwargs.get("private"), exist_ok = True, repo_type = "model", ) except: pass FastSentenceTransformer._add_unsloth_tags(repo_id, hub_token) with tempfile.TemporaryDirectory() as temp_dir: self.save_pretrained_merged(temp_dir, **push_kwargs) api.upload_folder( folder_path = temp_dir, repo_id = repo_id, commit_message = push_kwargs.get( "commit_message", "Upload model" ), ) print(f"Unsloth: Pushed to https://huggingface.co/{repo_id}") st_model.push_to_hub_merged = types.MethodType( _push_to_hub_merged, st_model ) return st_model # Warn if using 4-bit with encoder (slow due to dequantization overhead) if is_encoder_model and load_in_4bit: print( "Unsloth Warning: 4-bit quantization adds ~2.3x overhead for encoder models." ) print("Consider using load_in_16bit=True for better performance.") # check if the model supports add_pooling_layer if "add_pooling_layer" not in kwargs: supported = FastSentenceTransformer._has_add_pooling_layer( config, kwargs.get("auto_model", AutoModel) ) if supported: kwargs["add_pooling_layer"] = False # forces fp8 to be False since it's not supported fp8 = kwargs.pop("load_in_fp8", None) if fp8: logging.info("Unsloth: Disabling fp8 for model") load_in_fp8 = False # this is a fix for Snowflake/snowflake-arctic-embed-l-v2.0 # it has pooler weights which we don't care about for training, # however unsloth throws an exception if "UNSLOTH_WARN_UNINITIALIZED" == 1 and it sees unused weights old_environ = os.environ.get("UNSLOTH_WARN_UNINITIALIZED", "1") os.environ["UNSLOTH_WARN_UNINITIALIZED"] = "0" is_distilbert = "distilbert" == model_type.lower() is_mpnet = "mpnet" == model_type.lower() if is_distilbert and transformers4: FastSentenceTransformer._patch_distilbert_v4() elif is_distilbert: FastSentenceTransformer._patch_distilbert_v5() elif is_mpnet and transformers4: FastSentenceTransformer._patch_mpnet_v4() elif is_mpnet: FastSentenceTransformer._patch_mpnet_v5() # check if modules.json exists - if not, force 16-bit training # why? because i have to implement saving myself for these models, and i don't feel like adding dequantization # to the save_pretrained_merged for a model that really should be trained in 16-bit anyway has_modules_json = ( FastSentenceTransformer._module_path(model_name, token) is not None ) if not has_modules_json and load_in_4bit: print( "Unsloth: No modules.json found. This is not a sentence-transformers model.\n" "Forcing 16-bit loading to simplify merged model saving." ) load_in_4bit = False load_in_16bit = True try: model, tokenizer = FastModel.from_pretrained( model_name = model_name, max_seq_length = max_seq_length, dtype = dtype, load_in_4bit = load_in_4bit, load_in_8bit = load_in_8bit, load_in_16bit = load_in_16bit, full_finetuning = full_finetuning, token = token, device_map = device_map, rope_scaling = rope_scaling, fix_tokenizer = fix_tokenizer, trust_remote_code = trust_remote_code, use_gradient_checkpointing = use_gradient_checkpointing, resize_model_vocab = resize_model_vocab, revision = revision, return_logits = False, use_exact_model_name = use_exact_model_name, offload_embedding = offload_embedding, random_state = random_state, max_lora_rank = max_lora_rank, disable_log_stats = disable_log_stats, qat_scheme = qat_scheme, load_in_fp8 = load_in_fp8, unsloth_tiled_mlp = unsloth_tiled_mlp, **kwargs, ) finally: os.environ["UNSLOTH_WARN_UNINITIALIZED"] = old_environ # try to load modules, otherwise fallback to old hard-coded modules from sentence_transformers import SentenceTransformer modules, no_modules = FastSentenceTransformer._load_modules( model_name, token, model, tokenizer, max_seq_length, pooling_mode, trust_remote_code = trust_remote_code, ) st_device = device_map if isinstance(st_device, dict) or ( isinstance(st_device, str) and st_device in ["auto", "sequential"] ): st_device = None st_model = SentenceTransformer(modules = modules, device = st_device) st_model.no_modules = no_modules def _save_pretrained_merged(self, save_directory, **kwargs): # check which adapter files exist before save_pretrained adapter_files = ["adapter_model.safetensors", "adapter_config.json"] existing_before = { f for f in adapter_files if os.path.exists(os.path.join(save_directory, f)) } # sentence-transformers config and modules only get saved if we call save_pretrained self.save_pretrained(save_directory) # remove LoRA adapters only if they were created by save_pretrained (not pre-existing) for file in adapter_files: if file not in existing_before: try: os.remove(os.path.join(save_directory, file)) except: pass tokenizer = kwargs.pop("tokenizer", self.tokenizer) if self.no_modules: # fallback for non-sentence-transformers models print( "Unsloth: No modules detected. Using standard merge_and_unload for saving..." ) safe_kwargs = kwargs.copy() # filter out Unsloth-specific args that are not in huggingface's save_pretrained unsloth_args = [ "save_method", "temporary_location", "maximum_memory_usage", ] for k in unsloth_args: safe_kwargs.pop(k, None) merged_model = self[0].auto_model.merge_and_unload() merged_model.save_pretrained(save_directory, **safe_kwargs) if tokenizer is not None: tokenizer.save_pretrained(save_directory) else: self[0].auto_model.save_pretrained_merged( save_directory, tokenizer = tokenizer, **kwargs ) # add Unsloth branding to the generated README try: FastSentenceTransformer._add_unsloth_branding(save_directory) except Exception as e: print(f"Unsloth Warning: Failed to add branding to README: {e}") st_model.save_pretrained_merged = types.MethodType( _save_pretrained_merged, st_model ) st_model.save_pretrained_torchao = types.MethodType( _save_pretrained_torchao, st_model ) st_model.save_pretrained_gguf = types.MethodType( _save_pretrained_gguf, st_model ) st_model.push_to_hub_gguf = types.MethodType(_push_to_hub_gguf, st_model) def _push_to_hub_merged(self, repo_id, **kwargs): token = kwargs.get("token", None) or get_token() if token is None: raise ValueError( "No HF token provided. Please provide a token or login with `hf auth login`" ) private = kwargs.get("private", None) commit_message = kwargs.get("commit_message", "Upload model") from huggingface_hub import HfApi api = HfApi(token = token) try: api.create_repo( repo_id = repo_id, private = private, exist_ok = True, repo_type = "model", ) except: pass # order doesn't seem to matter for this after repo creation... FastSentenceTransformer._add_unsloth_tags(repo_id, token) with tempfile.TemporaryDirectory() as temp_dir: self.save_pretrained_merged(temp_dir, **kwargs) api.upload_folder( folder_path = temp_dir, repo_id = repo_id, commit_message = commit_message, ) print( f"Unsloth: Successfully pushed merged model to https://huggingface.co/{repo_id}" ) st_model.push_to_hub_merged = types.MethodType(_push_to_hub_merged, st_model) return st_model @staticmethod def get_peft_model( model, r = 16, target_modules = [ "query", "key", "value", "dense", ], lora_alpha = 16, lora_dropout = 0.0, bias = "none", layers_to_transform = None, layers_pattern = None, use_gradient_checkpointing = False, # Changed default: conflicts with torch.compile random_state = 3407, max_seq_length = 2048, use_rslora = False, modules_to_save = None, init_lora_weights = True, loftq_config = {}, **kwargs, ): from sentence_transformers import SentenceTransformer from peft import LoraConfig, get_peft_model as peft_get_peft_model if "task_type" not in kwargs: kwargs["task_type"] = "FEATURE_EXTRACTION" print("Setting task_type to FEATURE_EXTRACTION") if isinstance(model, SentenceTransformer): # Check if this is a fast encoder model (uses torch.compile instead of Unsloth patching) is_fast_encoder = getattr(model, "_unsloth_fast_encoder", False) if is_fast_encoder: # Fast encoder path: Use native PEFT + torch.compile (6x speedup) transformer_module = model[0] inner_model = transformer_module.auto_model # Check if model is quantized (4-bit/8-bit) is_quantized = ( getattr(inner_model, "is_quantized", False) or getattr(inner_model.config, "quantization_config", None) is not None ) # Track if gradient checkpointing was actually enabled gc_enabled = False # this is needed when from_pretrained was called without gradient # checkpointing but get_peft_model requests it if use_gradient_checkpointing and use_gradient_checkpointing != False: import transformers from packaging.version import Version transformers4 = Version(transformers.__version__).major < 5 model_type = getattr(inner_model.config, "model_type", "").lower() if model_type == "mpnet" and transformers4: FastSentenceTransformer._patch_mpnet_v4() elif model_type == "mpnet": FastSentenceTransformer._patch_mpnet_v5() # Prepare for k-bit training if quantized if is_quantized: from ._utils import prepare_model_for_kbit_training _gc_for_kbit = ( use_gradient_checkpointing if use_gradient_checkpointing else False ) try: inner_model = prepare_model_for_kbit_training( inner_model, use_gradient_checkpointing = _gc_for_kbit, ) print("Unsloth: Prepared quantized model for k-bit training") gc_enabled = bool(_gc_for_kbit) except ValueError as e: if "does not support gradient checkpointing" in str(e): # Model doesn't support gradient checkpointing, disable it print( f"Unsloth Warning: {inner_model.__class__.__name__} does not support gradient checkpointing. Skipping." ) inner_model = prepare_model_for_kbit_training( inner_model, use_gradient_checkpointing = False, ) print( "Unsloth: Prepared quantized model for k-bit training (without gradient checkpointing)" ) else: raise # Enable gradient checkpointing if requested (only for non-quantized, since prepare_model handles it) elif use_gradient_checkpointing and use_gradient_checkpointing != False: if hasattr(inner_model, "gradient_checkpointing_enable"): try: inner_model.gradient_checkpointing_enable() print("Unsloth: Enabled gradient checkpointing") gc_enabled = True except ValueError as e: if "does not support gradient checkpointing" in str(e): print( f"Unsloth Warning: {inner_model.__class__.__name__} does not support gradient checkpointing. Skipping." ) # Create LoRA config lora_config = LoraConfig( r = r, lora_alpha = lora_alpha, target_modules = target_modules, lora_dropout = lora_dropout, bias = bias, task_type = kwargs.get("task_type", "FEATURE_EXTRACTION"), ) # Apply PEFT directly (not through FastModel) peft_model = peft_get_peft_model(inner_model, lora_config) # Apply QAT if specified qat_scheme = kwargs.get("qat_scheme", None) if qat_scheme is not None: from ._utils import _prepare_model_for_qat peft_model = _prepare_model_for_qat(peft_model, qat_scheme) # Determine compile mode (only if not using gradient checkpointing) compile_mode = getattr(model, "_compile_mode", "default") # Re-enable torch.compile if gradient checkpointing was requested but couldn't be enabled if compile_mode is None and not gc_enabled: compile_mode = "default" print( "Unsloth: Re-enabling torch.compile since gradient checkpointing is not supported" ) # Re-assign the peft model back to the transformer module transformer_module.auto_model = peft_model # Store compile info for auto-compile at trainer time # torch.compile is deferred until training starts so we can check max_steps if compile_mode is not None: model._compile_mode = compile_mode model._compile_threshold = ( FastSentenceTransformer._estimate_compile_threshold(model) ) # Flag to indicate compile has not been applied yet model._compile_pending = True print( f"Unsloth: torch.compile will be applied automatically if max_steps > {model._compile_threshold}" ) else: model._compile_mode = None model._compile_pending = False print( "Unsloth: torch.compile disabled (gradient checkpointing enabled)" ) return model # Original path for non-fast-encoder models transformer_module = model[0] inner_model = transformer_module.auto_model peft_model = FastModel.get_peft_model( model = inner_model, r = r, target_modules = target_modules, lora_alpha = lora_alpha, lora_dropout = lora_dropout, bias = bias, layers_to_transform = layers_to_transform, layers_pattern = layers_pattern, use_gradient_checkpointing = use_gradient_checkpointing, random_state = random_state, max_seq_length = max_seq_length, use_rslora = use_rslora, modules_to_save = modules_to_save, init_lora_weights = init_lora_weights, loftq_config = loftq_config, **kwargs, ) # re-assign the peft model back to the transformer module transformer_module.auto_model = peft_model return model else: return FastModel.get_peft_model( model = model, r = r, target_modules = target_modules, lora_alpha = lora_alpha, lora_dropout = lora_dropout, bias = bias, layers_to_transform = layers_to_transform, layers_pattern = layers_pattern, use_gradient_checkpointing = use_gradient_checkpointing, random_state = random_state, max_seq_length = max_seq_length, use_rslora = use_rslora, modules_to_save = modules_to_save, init_lora_weights = init_lora_weights, loftq_config = loftq_config, **kwargs, ) def _patch_sentence_transformer_trainer(): """ Patch SentenceTransformerTrainer to automatically apply torch.compile when training steps exceed the breakeven threshold. This is called automatically when this module is imported. """ try: from sentence_transformers import SentenceTransformerTrainer except ImportError: return # sentence_transformers not installed if getattr(SentenceTransformerTrainer, "_unsloth_auto_compile_patched", False): return # Already patched from functools import wraps _original_init = SentenceTransformerTrainer.__init__ @wraps(_original_init) def _patched_init(self, *args, **kwargs): # Extract model and training_args model = kwargs.get("model") or (args[0] if args else None) training_args = kwargs.get("args") or (args[1] if len(args) > 1 else None) # Check if model has pending compile if ( model is not None and training_args is not None and getattr(model, "_compile_pending", False) ): max_steps = getattr(training_args, "max_steps", -1) compile_mode = getattr(model, "_compile_mode", "default") # Re-estimate threshold now that training args are available batch_size = getattr(training_args, "per_device_train_batch_size", None) grad_accum = getattr(training_args, "gradient_accumulation_steps", None) max_seq_length = getattr(model, "max_seq_length", None) if max_seq_length is None and hasattr(model, "__getitem__"): try: max_seq_length = getattr(model[0], "max_seq_length", None) except Exception: max_seq_length = None if max_seq_length is None: tokenizer = getattr(model, "tokenizer", None) max_seq_length = ( getattr(tokenizer, "model_max_length", None) if tokenizer is not None else None ) threshold = FastSentenceTransformer._estimate_compile_threshold( model, batch_size = batch_size, grad_accum = grad_accum, max_seq_length = max_seq_length, ) model._compile_threshold = threshold if max_steps > 0 and max_steps >= threshold: print( f"Unsloth: Auto-compiling model ({max_steps} steps >= {threshold} threshold)" ) FastSentenceTransformer._apply_torch_compile(model, mode = compile_mode) model._compile_pending = False elif max_steps > 0: print( f"Unsloth: Skipping torch.compile ({max_steps} steps < {threshold} threshold)" ) model._compile_pending = False # Call original __init__ _original_init(self, *args, **kwargs) # Disable mixed precision when FORCE_FLOAT32 is active (matches rl.py behavior) if os.environ.get("UNSLOTH_FORCE_FLOAT32", "0") == "1": if hasattr(self, "args") and self.args is not None: if self.args.fp16 or self.args.bf16: print( "Unsloth: Switching to float32 training since model cannot work with float16" ) self.args.fp16 = False self.args.bf16 = False if hasattr(self.args, "bf16_full_eval"): self.args.bf16_full_eval = False if hasattr(self.args, "fp16_full_eval"): self.args.fp16_full_eval = False SentenceTransformerTrainer.__init__ = _patched_init SentenceTransformerTrainer._unsloth_auto_compile_patched = True # Auto-patch trainer on module import _patch_sentence_transformer_trainer()
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/models/sentence_transformer.py", "license": "Apache License 2.0", "lines": 1838, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:tests/test_raw_text.py
#!/usr/bin/env python3 """ Minimal test for raw text training implementation. Tests basic functionality without heavy dependencies. """ import sys import os import tempfile from pathlib import Path import importlib.util # Mock the datasets module since it's not installed class MockDataset: def __init__(self, data_dict): self.data = data_dict self.column_names = list(data_dict.keys()) def __len__(self): return len(next(iter(self.data.values()))) def __getitem__(self, idx): if isinstance(idx, str): # Allow accessing columns by name like dataset['text'] return self.data[idx] elif isinstance(idx, int): # Allow accessing individual rows by index return {key: values[idx] for key, values in self.data.items()} else: raise TypeError(f"Invalid index type: {type(idx)}") @classmethod def from_dict(cls, data_dict): return cls(data_dict) # Mock datasets module datasets_mock = type(sys)("datasets") datasets_mock.Dataset = MockDataset sys.modules["datasets"] = datasets_mock # Import the raw_text module directly to avoid unsloth/__init__.py dependencies current_dir = os.path.dirname(__file__) raw_text_path = os.path.join( os.path.dirname(current_dir), "unsloth", "dataprep", "raw_text.py" ) spec = importlib.util.spec_from_file_location("raw_text", raw_text_path) raw_text_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(raw_text_module) RawTextDataLoader = raw_text_module.RawTextDataLoader TextPreprocessor = raw_text_module.TextPreprocessor def test_raw_text_loader(): """Test basic RawTextDataLoader functionality.""" # Mock tokenizer for testing class MockTokenizer: def __init__(self): self.eos_token = "</s>" self.eos_token_id = 2 # Mock EOS token ID def __call__(self, text, return_tensors = None, add_special_tokens = False): words = text.split() token_ids = list(range(len(words))) if return_tensors == "pt": # Mock tensor-like object class MockTensor: def __init__(self, data): self.data = data def __getitem__(self, idx): return self.data def __len__(self): return len(self.data) def tolist(self): return self.data return {"input_ids": [MockTensor(token_ids)]} return {"input_ids": token_ids} def decode(self, token_ids, skip_special_tokens = False): return " ".join([f"word_{i}" for i in token_ids]) # Create test file test_content = "This is a test file for raw text training. " * 10 with tempfile.NamedTemporaryFile(mode = "w", suffix = ".txt", delete = False) as f: f.write(test_content) test_file = f.name try: # Test loader tokenizer = MockTokenizer() loader = RawTextDataLoader(tokenizer, chunk_size = 5, stride = 2) # Test loading with text output (legacy mode) text_dataset = loader.load_from_file(test_file, return_tokenized = False) assert len(text_dataset) > 0, "Should create at least one chunk" assert "text" in text_dataset.column_names, "Dataset should have 'text' column" # Test loading with tokenized output (new efficient mode) tokenized_dataset = loader.load_from_file(test_file, return_tokenized = True) assert len(tokenized_dataset) > 0, "Should create at least one tokenized chunk" assert ( "input_ids" in tokenized_dataset.column_names ), "Dataset should have 'input_ids' column" assert ( "attention_mask" in tokenized_dataset.column_names ), "Dataset should have 'attention_mask' column" # Verify tokenized data structure first_sample = tokenized_dataset[0] assert isinstance(first_sample["input_ids"], list), "input_ids should be a list" assert isinstance( first_sample["attention_mask"], list ), "attention_mask should be a list" assert len(first_sample["input_ids"]) == len( first_sample["attention_mask"] ), "input_ids and attention_mask should have same length" # Verify labels field exists (for causal LM training) assert ( "labels" in tokenized_dataset.column_names ), "Dataset should have 'labels' column" assert ( first_sample["labels"] == first_sample["input_ids"] ), "labels should match input_ids" # Test constructor validation try: bad_loader = RawTextDataLoader(tokenizer, chunk_size = 0, stride = 2) assert False, "Should raise ValueError for chunk_size=0" except ValueError as e: assert "chunk_size must be positive" in str(e) try: bad_loader = RawTextDataLoader(tokenizer, chunk_size = 5, stride = 10) assert False, "Should raise ValueError for stride >= chunk_size" except ValueError as e: assert "stride" in str(e) and "chunk_size" in str(e) # Test preprocessor preprocessor = TextPreprocessor() clean_text = preprocessor.clean_text(" messy text \n\n\n ") assert "messy text" in clean_text, "Should clean text properly" # Test validation stats = preprocessor.validate_dataset(text_dataset) assert stats["total_samples"] > 0, "Should count samples" assert "warnings" in stats, "Should include warnings" print("✅ All tests passed!") return True except Exception as e: print(f"❌ Test failed: {e}") return False finally: # Cleanup os.unlink(test_file) if __name__ == "__main__": success = test_raw_text_loader() sys.exit(0 if success else 1)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/test_raw_text.py", "license": "Apache License 2.0", "lines": 136, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/utils/test_attention_masks.py
# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """Unit tests for packed-attention mask helpers with sliding-window logic.""" import math import torch from unsloth.utils import attention_dispatch from unsloth.utils import packing as packing_utils def _make_seq_info(lengths): lengths = torch.tensor(lengths, dtype = torch.int32) cu = torch.cat( [ torch.zeros(1, dtype = torch.int32), torch.cumsum(lengths, dim = 0, dtype = torch.int32), ] ) max_len = int(lengths.max().item()) return lengths, cu, max_len def test_sdpa_packed_attention_mask_sliding_window(): seq_info = _make_seq_info([5, 3]) mask = packing_utils.build_sdpa_packed_attention_mask( seq_info, dtype = torch.float32, device = torch.device("cpu"), sliding_window = 3, ) assert mask.shape == (1, 1, 8, 8) block_first = mask[0, 0, :5, :5] upper = torch.triu(torch.ones_like(block_first), diagonal = 1).bool() assert torch.all(block_first[upper] == float("-inf")) assert block_first[3, 0].item() == float("-inf") assert block_first[4, 1].item() == float("-inf") assert block_first[4, 2].item() > -math.inf assert mask[0, 0, 0, 6].item() == float("-inf") def test_xformers_block_mask_sliding_window(monkeypatch): class _FakeMask: def __init__(self, lengths, window = None): self.lengths = lengths self.window = window @classmethod def from_seqlens(cls, lengths): return cls(tuple(lengths)) def make_local_attention(self, window_size): return _FakeMask(self.lengths, window = window_size) monkeypatch.setattr(packing_utils, "_XFormersBlockMask", _FakeMask, raising = False) seq_info = _make_seq_info([4, 4]) mask = packing_utils.build_xformers_block_causal_mask( seq_info, sliding_window = 2, ) assert isinstance(mask, _FakeMask) assert mask.window == 2 def test_run_attention_sdpa_passes_sliding_window(monkeypatch): seq_info = _make_seq_info([3, 2]) sliding_window = 2 original_builder = attention_dispatch.build_sdpa_packed_attention_mask captured = {} def _capture_builder(seq_info_arg, *, dtype, device, sliding_window = None): captured["window"] = sliding_window return original_builder( seq_info_arg, dtype = dtype, device = device, sliding_window = sliding_window, ) monkeypatch.setattr( attention_dispatch, "build_sdpa_packed_attention_mask", _capture_builder, ) def _fake_sdpa(Q, K, V, **kwargs): captured["mask"] = kwargs.get("attn_mask") return torch.zeros_like(Q) monkeypatch.setattr(attention_dispatch, "scaled_dot_product_attention", _fake_sdpa) config = attention_dispatch.AttentionConfig( backend = attention_dispatch.SDPA, n_kv_heads = 1, n_groups = 1, ) context = attention_dispatch.AttentionContext( bsz = 1, q_len = 5, kv_seq_len = 5, n_heads = 1, head_dim = 1, requires_grad = False, seq_info = seq_info, attention_mask = None, causal_mask = None, sliding_window = sliding_window, ) Q = torch.zeros(1, 1, 5, 1) K = torch.zeros_like(Q) V = torch.zeros_like(Q) attention_dispatch.run_attention( config = config, context = context, Q = Q, K = K, V = V, ) assert captured["window"] == sliding_window mask = captured["mask"] assert mask is not None and mask.shape == (1, 1, 5, 5) assert mask[0, 0, 4, 1].item() == float("-inf") def test_run_attention_xformers_passes_sliding_window(monkeypatch): seq_info = _make_seq_info([4]) sliding_window = 3 class _FakeBias: pass captured = {} def _fake_builder(seq_info_arg, *, sliding_window = None, base_mask = None): captured["window"] = sliding_window captured["base"] = base_mask return _FakeBias() def _fake_attention(Q, K, V, attn_bias = None, **_): captured["bias"] = attn_bias return torch.zeros_like(Q) monkeypatch.setattr( attention_dispatch, "build_xformers_block_causal_mask", _fake_builder ) monkeypatch.setattr( attention_dispatch, "xformers_attention", _fake_attention, raising = False ) monkeypatch.setattr( attention_dispatch, "XFORMERS_BLOCK_DIAG_CLS", _FakeBias, raising = False ) config = attention_dispatch.AttentionConfig( backend = attention_dispatch.XFORMERS, n_kv_heads = 1, n_groups = 1, ) context = attention_dispatch.AttentionContext( bsz = 1, q_len = 4, kv_seq_len = 4, n_heads = 1, head_dim = 1, requires_grad = False, seq_info = seq_info, attention_mask = None, causal_mask = None, sliding_window = sliding_window, ) Q = torch.zeros(1, 1, 4, 1) K = torch.zeros_like(Q) V = torch.zeros_like(Q) attention_dispatch.run_attention( config = config, context = context, Q = Q, K = K, V = V, ) assert captured["window"] == sliding_window assert isinstance(captured["bias"], _FakeBias) def test_run_attention_flash_varlen_receives_window_and_softcap(monkeypatch): seq_info = _make_seq_info([4]) sliding_window = 3 softcap = 0.5 window_tuple = (sliding_window, sliding_window) captured = {} def _fake_flash_varlen(Q, K, V, cu_q, cu_k, max_q, max_k, **kwargs): captured["kwargs"] = kwargs return torch.zeros_like(Q) monkeypatch.setattr( attention_dispatch, "flash_attn_varlen_func", _fake_flash_varlen, ) monkeypatch.setattr(attention_dispatch, "HAS_FLASH_ATTENTION", True) config = attention_dispatch.AttentionConfig( backend = attention_dispatch.FLASH_VARLEN, n_kv_heads = 1, n_groups = 1, flash_varlen_kwargs = { "dropout_p": 0.0, "softmax_scale": 1.0, "causal": True, "softcap": softcap, "window_size": window_tuple, }, ) context = attention_dispatch.AttentionContext( bsz = 1, q_len = 4, kv_seq_len = 4, n_heads = 1, head_dim = 2, requires_grad = False, seq_info = seq_info, attention_mask = None, causal_mask = None, sliding_window = sliding_window, ) Q = torch.zeros(1, 1, 4, 2) K = torch.zeros_like(Q) V = torch.zeros_like(Q) attention_dispatch.run_attention( config = config, context = context, Q = Q, K = K, V = V, ) assert captured["kwargs"]["softcap"] == softcap assert captured["kwargs"]["window_size"] == window_tuple """Unit tests for packed-attention mask helpers with sliding-window logic."""
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/test_attention_masks.py", "license": "Apache License 2.0", "lines": 219, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/utils/test_packing.py
# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. from unsloth import FastLanguageModel from unsloth.utils import attention_dispatch as attention_dispatch_utils from unsloth.utils.packing import ( configure_padding_free, configure_sample_packing, enable_padding_free_metadata, enable_sample_packing, mask_packed_sequence_boundaries, ) from contextlib import ExitStack from types import SimpleNamespace from unittest.mock import patch import pytest import torch from datasets import Dataset from trl import SFTConfig, SFTTrainer from trl.trainer.sft_trainer import DataCollatorForLanguageModeling def _build_packed_training_setup(tmp_path, device): dtype = None if device.type == "cuda": if torch.cuda.is_bf16_supported(): dtype = torch.bfloat16 else: dtype = torch.float16 try: model, tokenizer = FastLanguageModel.from_pretrained( model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM", max_seq_length = 64, load_in_4bit = False, dtype = dtype, ) except OSError as exc: # pragma: no cover - offline CI pytest.skip(f"Requires access to tiny llama checkpoint: {exc}") model.to(device) dataset = Dataset.from_dict( { "text": [ "Hello world!", "Short sample.", "This is a slightly longer packed example to test batching.", "Another response to include in the batch.", ] } ) training_args = SFTConfig( per_device_train_batch_size = 1, per_device_eval_batch_size = 1, gradient_accumulation_steps = 1, dataset_text_field = "text", max_length = 64, logging_steps = 1, max_steps = 1, fp16 = device.type == "cuda" and not torch.cuda.is_bf16_supported(), bf16 = device.type == "cuda" and torch.cuda.is_bf16_supported(), dataset_num_proc = 1, output_dir = str(tmp_path), packing = True, ) trainer = SFTTrainer( model = model, processing_class = tokenizer, train_dataset = dataset, args = training_args, ) enable_sample_packing(model, trainer) dataloader = trainer.get_train_dataloader() batch = next(iter(dataloader)) model_device = next(model.parameters()).device for key, value in list(batch.items()): if torch.is_tensor(value): batch[key] = value.to(model_device) from unsloth.models import llama as llama_mod return model, batch, trainer, llama_mod def _trim_batch_to_total_tokens(data, total_tokens): def _trim_tensor(t: torch.Tensor): if t.ndim >= 2 and t.size(1) > total_tokens: return t[:, :total_tokens].contiguous() return t trimmed = {} for key, value in data.items(): if torch.is_tensor(value): trimmed[key] = _trim_tensor(value) else: trimmed[key] = value return trimmed def test_mask_packed_sequence_boundaries_marks_single_row(): shift_labels = torch.arange(6, dtype = torch.long).view(1, 6) changed = mask_packed_sequence_boundaries( shift_labels, torch.tensor([2, 1, 3], dtype = torch.int32), ) assert changed is True flat = shift_labels.view(-1) assert flat[1].item() == -100 assert flat[2].item() == -100 assert flat[5].item() == -100 assert flat[0].item() != -100 def test_mask_packed_sequence_boundaries_across_multiple_rows(): shift_labels = torch.arange(10, dtype = torch.long).view(2, 5) lengths = torch.tensor([3, 2, 4, 1], dtype = torch.int32) changed = mask_packed_sequence_boundaries(shift_labels, lengths) assert changed is True flat = shift_labels.view(-1) for idx in (2, 4, 8, 9): assert flat[idx].item() == -100 assert torch.any(flat != -100) def test_configure_sample_packing(): config = SimpleNamespace() configure_sample_packing(config) assert config.packing is True assert config.padding_free is True assert config.remove_unused_columns is False def test_configure_padding_free(): config = SimpleNamespace(remove_unused_columns = True) configure_padding_free(config) assert config.padding_free is True assert config.remove_unused_columns is False class _DummyChild(torch.nn.Module): def __init__(self): super().__init__() self.max_seq_length = 8 class _DummyModel(torch.nn.Module): def __init__(self): super().__init__() self.max_seq_length = 16 self.child = _DummyChild() self.config = SimpleNamespace(_attn_implementation = "sdpa") self.generation_config = SimpleNamespace(attn_implementation = "sdpa") class _DummyTrainer: def __init__(self): self.args = SimpleNamespace(remove_unused_columns = True) collator_args = { "pad_token_id": 0, "completion_only_loss": False, "return_tensors": "pt", } optional_flags = [ {"padding_free": True, "return_position_ids": False}, {"padding_free": True}, {}, ] for extra in optional_flags: try: self.data_collator = DataCollatorForLanguageModeling( **collator_args, **extra ) break except TypeError: continue # Ensure attributes exist even if the constructor did not accept them if not hasattr(self.data_collator, "padding_free"): self.data_collator.padding_free = True if not hasattr(self.data_collator, "return_position_ids"): self.data_collator.return_position_ids = False class _PaddingFreeCollator: def __init__(self): self.padding_free = True self.return_position_ids = False self.calls = 0 def torch_call(self, examples): self.calls += 1 return { "input_ids": torch.tensor([[0]], dtype = torch.long), "examples_seen": self.calls, } def test_enable_sample_packing(): model = _DummyModel() trainer = _DummyTrainer() enable_sample_packing(model, trainer) # model hierarchy should now allow packed overlength inputs assert getattr(model, "_unsloth_allow_packed_overlength") is True assert getattr(model.child, "_unsloth_allow_packed_overlength") is True collator = trainer.data_collator assert collator.return_position_ids is True assert getattr(collator, "_unsloth_packing_wrapped") is True examples = [ { "input_ids": [0, 1, 2], "labels": [0, 1, 2], "seq_lengths": [2, 1], }, { "input_ids": [3, 4, 5], "labels": [3, 4, 5], "seq_lengths": [3], }, ] batch = collator.torch_call(examples) # packed lengths are aggregated into a single tensor assert "packed_seq_lengths" in batch assert torch.equal( batch["packed_seq_lengths"], torch.tensor([2, 1, 3], dtype = torch.int32), ) assert batch["input_ids"].shape == (1, 6) expected_positions = torch.tensor([0, 1, 0, 0, 1, 2], dtype = torch.long) assert torch.equal(batch["position_ids"].view(-1)[:6], expected_positions) def test_enable_sample_packing_trl_collator(tmp_path): device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") model, _, trainer, _ = _build_packed_training_setup(tmp_path, device) enable_sample_packing(model, trainer) examples = [ { "input_ids": [0, 1, 2], "labels": [0, 1, 2], "seq_lengths": [2, 1], }, { "input_ids": [3, 4, 5], "labels": [3, 4, 5], "seq_lengths": [3], }, ] batch = trainer.data_collator.torch_call(examples) assert batch["input_ids"].shape == (1, 6) assert torch.equal( batch["packed_seq_lengths"], torch.tensor([2, 1, 3], dtype = torch.int32), ) expected_positions = torch.tensor([0, 1, 0, 0, 1, 2], dtype = torch.long) assert torch.equal(batch["position_ids"].view(-1)[:6], expected_positions) if hasattr(trainer, "accelerator"): trainer.accelerator.free_memory() def test_enable_padding_free_metadata(): model = _DummyModel() trainer = SimpleNamespace( args = SimpleNamespace(remove_unused_columns = True), data_collator = _PaddingFreeCollator(), ) enable_padding_free_metadata(model, trainer) assert getattr(model, "_unsloth_allow_packed_overlength") is True assert getattr(model.child, "_unsloth_allow_packed_overlength") is True collator = trainer.data_collator assert collator.return_position_ids is True assert getattr(collator, "_unsloth_padding_free_lengths_wrapped") is True examples = [ {"input_ids": [0, 1, 2]}, {"input_ids": [3, 4]}, ] batch = collator.torch_call(examples) assert torch.equal( batch["packed_seq_lengths"], torch.tensor([3, 2], dtype = torch.int32), ) assert trainer.args.remove_unused_columns is False def test_packing_sdpa(tmp_path): device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") model, batch, trainer, llama_mod = _build_packed_training_setup(tmp_path, device) assert "packed_seq_lengths" in batch assert "attention_mask" not in batch assert batch["packed_seq_lengths"].dtype == torch.int32 total_tokens = batch["input_ids"].size(-1) assert int(batch["packed_seq_lengths"].sum().item()) == total_tokens packed_tokens = int(batch["packed_seq_lengths"].sum().item()) assert "position_ids" in batch flat_positions = batch["position_ids"].reshape(-1)[:packed_tokens] expected_positions = torch.cat( [ torch.arange(length, dtype = torch.long) for length in batch["packed_seq_lengths"].tolist() ] ) assert torch.equal(flat_positions.cpu(), expected_positions) inputs = _trim_batch_to_total_tokens(batch, packed_tokens) seq_info = llama_mod.get_packed_info_from_kwargs( {"packed_seq_lengths": batch["packed_seq_lengths"]}, inputs["input_ids"].device, ) assert seq_info is not None original_mask = attention_dispatch_utils.build_sdpa_packed_attention_mask mask_calls = [] captured_loss_labels = {} def _capture_mask(seq_info, dtype, device, *, sliding_window = None): mask_calls.append(tuple(seq_info[0].tolist())) return original_mask( seq_info, dtype = dtype, device = device, sliding_window = sliding_window, ) def _capture_loss(*, logits, labels, **loss_kwargs): captured_loss_labels["labels"] = labels.detach().to("cpu") return torch.zeros((), device = logits.device, dtype = logits.dtype) with ExitStack() as stack: stack.enter_context( patch.object(attention_dispatch_utils, "HAS_FLASH_ATTENTION", False) ) stack.enter_context( patch.object(attention_dispatch_utils, "HAS_XFORMERS", False) ) stack.enter_context( patch.object( attention_dispatch_utils, "build_sdpa_packed_attention_mask", side_effect = _capture_mask, ) ) stack.enter_context( patch.object( llama_mod, "fast_cross_entropy_loss", side_effect = _capture_loss, ) ) with torch.no_grad(): outputs = model(**inputs) assert mask_calls, "SDPA packed mask was not constructed" assert outputs.loss is not None assert "labels" in captured_loss_labels flat_loss_labels = captured_loss_labels["labels"].reshape(-1) boundaries = ( torch.cumsum( batch["packed_seq_lengths"].to(device = "cpu", dtype = torch.long), dim = 0 ) - 1 ) for idx in boundaries.tolist(): assert flat_loss_labels[idx].item() == -100 assert torch.any(flat_loss_labels != -100) if hasattr(trainer, "accelerator"): trainer.accelerator.free_memory()
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/test_packing.py", "license": "Apache License 2.0", "lines": 335, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/utils/attention_dispatch.py
# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """Shared helpers for attention backend selection and execution.""" from __future__ import annotations from dataclasses import dataclass from typing import Any, Optional, Tuple import torch from torch import Tensor from torch.nn.functional import scaled_dot_product_attention from ..models._utils import * from ..utils.packing import ( build_sdpa_packed_attention_mask, build_xformers_block_causal_mask, ) if HAS_FLASH_ATTENTION: from flash_attn import flash_attn_func, flash_attn_varlen_func HAS_XFORMERS = xformers is not None SDPA_HAS_GQA = "enable_gqa" in (scaled_dot_product_attention.__doc__ or "") FLASH_VARLEN = "flash_varlen" FLASH_DENSE = "flash_dense" XFORMERS = "xformers" SDPA = "sdpa" XFORMERS_BLOCK_DIAG_CLS = ( xformers.attn_bias.BlockDiagonalCausalMask if HAS_XFORMERS else None ) @dataclass class AttentionConfig: """ Per-layer attention metadata. NOTE(djsaunde): I had originally intended this to be populated once per layer, but we're currently constructing it on every forward pass since it can possibly be invalid from one forward pass to the next (e.g., switching from training to inference). For now, I'm keeping separate from AttentionContext for the sake of better grouping of params. """ backend: str n_kv_heads: int n_groups: int flash_dense_kwargs: Optional[dict[str, Any]] = None flash_varlen_kwargs: Optional[dict[str, Any]] = None sdpa_kwargs: Optional[dict[str, Any]] = None xformers_kwargs: Optional[dict[str, Any]] = None @dataclass class AttentionContext: """Per-call info required to run attention.""" bsz: int q_len: int kv_seq_len: int n_heads: int head_dim: int requires_grad: bool seq_info: Optional[Tuple[Tensor, Tensor, int]] attention_mask: Optional[Tensor] causal_mask: Optional[Any] sliding_window: Optional[int] = None def select_attention_backend(use_varlen: bool = False) -> str: """Return attention backend based on availability / priority order.""" if HAS_FLASH_ATTENTION: if use_varlen: return FLASH_VARLEN else: return FLASH_DENSE if HAS_XFORMERS: return XFORMERS return SDPA def run_attention( *, config: AttentionConfig, context: AttentionContext, Q: Tensor, K: Tensor, V: Tensor, ) -> Tensor: """ Run attention using config / context info. Backend choice is prioritized for speed: FlashAttention when installed (`flash_varlen` for packed/variable-length inputs with `seq_info`, otherwise dense flash), then xFormers if flash is unavailable, with PyTorch SDPA as the final fallback (e.g., CPU or no fused kernels). Varlen flash is preferred when packing metadata is present because it avoids padding and keeps peak memory low. xFormers and SDPA can also handle packed batches (we pass a block-diagonal mask into each). """ backend = config.backend if backend == FLASH_VARLEN and context.seq_info is None: backend = FLASH_DENSE if HAS_FLASH_ATTENTION else SDPA # [TODO] Flash attention does not support arbitrary attention masks (only # causal via flag). When a padding mask is present (e.g. left-padded # batched generation), fall back to SDPA which consumes attn_mask. # xFormers also does not thread context.attention_mask through, so the # same fallback applies. if context.attention_mask is not None and backend in ( FLASH_DENSE, FLASH_VARLEN, XFORMERS, ): backend = SDPA flash_dense_kwargs = config.flash_dense_kwargs or {} flash_varlen_kwargs = config.flash_varlen_kwargs or {} sdpa_kwargs = config.sdpa_kwargs or {} xformers_kwargs = config.xformers_kwargs or {} bsz = context.bsz n_heads = context.n_heads q_len = context.q_len head_dim = context.head_dim kv_seq_len = context.kv_seq_len requires_grad = context.requires_grad sliding_window = context.sliding_window if backend == FLASH_VARLEN: Q_f = Q.transpose(1, 2).reshape(bsz * q_len, n_heads, head_dim) K_f = K.transpose(1, 2).reshape(bsz * q_len, config.n_kv_heads, head_dim) V_f = V.transpose(1, 2).reshape(bsz * q_len, config.n_kv_heads, head_dim) _, cu_seqlens, max_seqlen = context.seq_info return flash_attn_varlen_func( Q_f, K_f, V_f, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **flash_varlen_kwargs, ).view(bsz, q_len, n_heads, head_dim) elif backend == FLASH_DENSE: Q_t = Q.transpose(1, 2) K_t = K.transpose(1, 2) V_t = V.transpose(1, 2) return flash_attn_func(Q_t, K_t, V_t, **flash_dense_kwargs).reshape( bsz, q_len, n_heads, head_dim ) elif backend == XFORMERS: attn_bias = build_xformers_block_causal_mask( context.seq_info, sliding_window = sliding_window, base_mask = context.causal_mask, ) Q_t = Q.transpose(1, 2) K_t = K.transpose(1, 2) V_t = V.transpose(1, 2) K_mod = K_t V_mod = V_t Q_mod = Q_t if config.n_groups != 1: K_mod = K_t.view(bsz, kv_seq_len, config.n_kv_heads, 1, head_dim) V_mod = V_t.view(bsz, kv_seq_len, config.n_kv_heads, 1, head_dim) K_mod = K_mod.expand( bsz, kv_seq_len, config.n_kv_heads, config.n_groups, head_dim ) V_mod = V_mod.expand( bsz, kv_seq_len, config.n_kv_heads, config.n_groups, head_dim ) if requires_grad: K_mod = K_mod.reshape(bsz, kv_seq_len, n_heads, head_dim) V_mod = V_mod.reshape(bsz, kv_seq_len, n_heads, head_dim) else: Q_mod = Q_t.view( bsz, q_len, config.n_kv_heads, config.n_groups, head_dim ) has_block = XFORMERS_BLOCK_DIAG_CLS is not None and isinstance( attn_bias, XFORMERS_BLOCK_DIAG_CLS ) if config.n_groups != 1 and has_block: if not requires_grad: Q_mod = Q_mod.view( 1, bsz * q_len, config.n_kv_heads, config.n_groups, head_dim ) K_mod = K_mod.view( 1, bsz * kv_seq_len, config.n_kv_heads, config.n_groups, head_dim ) V_mod = V_mod.view( 1, bsz * kv_seq_len, config.n_kv_heads, config.n_groups, head_dim ) else: Q_mod = Q_mod.view(1, bsz * q_len, n_heads, head_dim) K_mod = K_mod.view(1, bsz * kv_seq_len, n_heads, head_dim) V_mod = V_mod.view(1, bsz * kv_seq_len, n_heads, head_dim) out = xformers_attention( Q_mod, K_mod, V_mod, attn_bias = attn_bias, **xformers_kwargs, ) if config.n_groups != 1 and not requires_grad: out = out.view(bsz, q_len, config.n_kv_heads, config.n_groups, head_dim) out = out.reshape(bsz, q_len, n_heads, head_dim) else: out = out.view(bsz, q_len, n_heads, head_dim) return out else: local_mask = context.attention_mask is_causal_local = False if context.seq_info is not None and local_mask is None: local_mask = build_sdpa_packed_attention_mask( context.seq_info, dtype = Q.dtype, device = Q.device, sliding_window = sliding_window, ) else: q_len_local = Q.shape[-2] k_len_local = K.shape[-2] # ---- SDPA mask normalization for left padding / 2D masks ---- if local_mask is not None and isinstance(local_mask, torch.Tensor): local_mask = local_mask.to(device = Q.device) if local_mask.dim() == 2: # key padding keep mask: (bsz, k_len), 1/True = real token if local_mask.dtype == torch.bool: key_keep = local_mask else: # tokenizer attention_mask is typically int 0/1 key_keep = local_mask != 0 past_len = ( k_len_local - q_len_local ) # works for prefill (0) and decode q_pos = torch.arange( past_len, past_len + q_len_local, device = Q.device ) k_pos = torch.arange(k_len_local, device = Q.device) causal_keep = ( k_pos[None, :] <= q_pos[:, None] ) # True = allowed (SDPA) if sliding_window is not None: causal_keep &= k_pos[None, :] >= ( q_pos[:, None] - (sliding_window - 1) ) # (bsz, 1, q_len, k_len) boolean keep mask local_mask = ( causal_keep[None, None, :, :] & key_keep[:, None, None, :] ) elif local_mask.dim() == 3: # (bsz, q_len, k_len) -> (bsz, 1, q_len, k_len) local_mask = local_mask[:, None, :, :] elif local_mask.dim() == 4: if local_mask.dtype != torch.bool: # Use boolean keep masks for better SDPA stability. local_mask = local_mask.eq(0) else: raise ValueError( f"Unsupported SDPA attention_mask rank: {local_mask.dim()}" ) # Avoid NaNs from fully-masked rows (common with left padding). if local_mask.dtype == torch.bool: no_allowed = ~local_mask.any( dim = -1, keepdim = True ) # (bsz,1,q_len,1) local_mask = local_mask | no_allowed is_causal_local = local_mask is None and q_len_local == k_len_local kwargs = dict(sdpa_kwargs) kwargs.setdefault("attn_mask", local_mask) kwargs.setdefault("is_causal", is_causal_local) use_sdpa_gqa = SDPA_HAS_GQA and config.n_groups != 1 if ( use_sdpa_gqa and (not requires_grad) and isinstance(local_mask, torch.Tensor) and local_mask.dim() >= 3 and local_mask.shape[0] > 1 ): # Batched masked inference has shown row-coupled drift with SDPA GQA. # Fall back to explicit KV expansion for deterministic row-wise behavior. use_sdpa_gqa = False if use_sdpa_gqa: kwargs.setdefault("enable_gqa", True) out = scaled_dot_product_attention(Q, K, V, **kwargs) return out.transpose(1, 2) K_mod = K V_mod = V if config.n_groups != 1: K_mod = K[:, :, None, :, :].expand( bsz, config.n_kv_heads, config.n_groups, kv_seq_len, head_dim ) V_mod = V[:, :, None, :, :].expand( bsz, config.n_kv_heads, config.n_groups, kv_seq_len, head_dim ) K_mod = K_mod.reshape(bsz, n_heads, kv_seq_len, head_dim) V_mod = V_mod.reshape(bsz, n_heads, kv_seq_len, head_dim) out = scaled_dot_product_attention( Q.contiguous(), K_mod.contiguous(), V_mod.contiguous(), **kwargs, ) return out.transpose(1, 2).contiguous() __all__ = [ "AttentionConfig", "AttentionContext", "select_attention_backend", "run_attention", ]
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/utils/attention_dispatch.py", "license": "Apache License 2.0", "lines": 302, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unslothai/unsloth:scripts/enforce_kwargs_spacing.py
#!/usr/bin/env python3 """Ensure keyword arguments use spaces around '=', prune redundant pass statements.""" from __future__ import annotations import ast import argparse import io import sys import tokenize from collections import defaultdict from pathlib import Path def enforce_spacing(text: str) -> tuple[str, bool]: """Return updated text with keyword '=' padded by spaces, plus change flag.""" lines = text.splitlines(keepends=True) if not lines: return text, False offsets: dict[int, int] = defaultdict(int) changed = False reader = io.StringIO(text).readline for token in tokenize.generate_tokens(reader): if token.type != tokenize.OP or token.string != "=": continue line_index = token.start[0] - 1 col = token.start[1] + offsets[line_index] if line_index < 0 or line_index >= len(lines): continue line = lines[line_index] if col >= len(line) or line[col] != "=": continue line_changed = False # Insert a space before '=' when missing and not preceded by whitespace. if col > 0 and line[col - 1] not in {" ", "\t"}: line = f"{line[:col]} {line[col:]}" offsets[line_index] += 1 col += 1 line_changed = True changed = True # Insert a space after '=' when missing and not followed by whitespace or newline. next_index = col + 1 if next_index < len(line) and line[next_index] not in {" ", "\t", "\n", "\r"}: line = f"{line[:next_index]} {line[next_index:]}" offsets[line_index] += 1 line_changed = True changed = True if line_changed: lines[line_index] = line if not changed: return text, False return "".join(lines), True def remove_redundant_passes(text: str) -> tuple[str, bool]: """Drop pass statements that share a block with other executable code.""" try: tree = ast.parse(text) except SyntaxError: return text, False redundant: list[ast.Pass] = [] def visit(node: ast.AST) -> None: for attr in ("body", "orelse", "finalbody"): value = getattr(node, attr, None) if not isinstance(value, list) or len(value) <= 1: continue for stmt in value: if isinstance(stmt, ast.Pass): redundant.append(stmt) for stmt in value: if isinstance(stmt, ast.AST): visit(stmt) handlers = getattr(node, "handlers", None) if handlers: for handler in handlers: visit(handler) visit(tree) if not redundant: return text, False lines = text.splitlines(keepends=True) changed = False for node in sorted( redundant, key=lambda item: (item.lineno, item.col_offset), reverse=True ): start = node.lineno - 1 end = (node.end_lineno or node.lineno) - 1 if start >= len(lines): continue changed = True if start == end: line = lines[start] col_start = node.col_offset col_end = node.end_col_offset or (col_start + 4) segment = line[:col_start] + line[col_end:] lines[start] = segment if segment.strip() else "" continue # Defensive fall-back for unexpected multi-line 'pass'. prefix = lines[start][: node.col_offset] lines[start] = prefix if prefix.strip() else "" for idx in range(start + 1, end): lines[idx] = "" suffix = lines[end][(node.end_col_offset or 0) :] lines[end] = suffix # Normalise to ensure lines end with newlines except at EOF. result_lines: list[str] = [] for index, line in enumerate(lines): if not line: continue if index < len(lines) - 1 and not line.endswith("\n"): result_lines.append(f"{line}\n") else: result_lines.append(line) return "".join(result_lines), changed def process_file(path: Path) -> bool: try: with tokenize.open(path) as handle: original = handle.read() encoding = handle.encoding except (OSError, SyntaxError) as exc: # SyntaxError from tokenize on invalid python print(f"Failed to read {path}: {exc}", file=sys.stderr) return False updated, changed = enforce_spacing(original) updated, removed = remove_redundant_passes(updated) if changed or removed: path.write_text(updated, encoding=encoding) return True return False def main(argv: list[str]) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("files", nargs="+", help="Python files to fix") args = parser.parse_args(argv) touched: list[Path] = [] self_path = Path(__file__).resolve() for entry in args.files: path = Path(entry) # Skip modifying this script to avoid self-edit loops. if path.resolve() == self_path: continue if not path.exists() or path.is_dir(): continue if process_file(path): touched.append(path) if touched: for path in touched: print(f"Adjusted kwarg spacing in {path}") return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))
{ "repo_id": "unslothai/unsloth", "file_path": "scripts/enforce_kwargs_spacing.py", "license": "Apache License 2.0", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unslothai/unsloth:scripts/run_ruff_format.py
#!/usr/bin/env python3 """Run `ruff format` followed by kwarg spacing enforcement.""" from __future__ import annotations import subprocess import sys from pathlib import Path HERE = Path(__file__).resolve().parent def main(argv: list[str]) -> int: files = [arg for arg in argv if Path(arg).exists()] if not files: return 0 ruff_cmd = [sys.executable, "-m", "ruff", "format", *files] ruff_proc = subprocess.run(ruff_cmd) if ruff_proc.returncode != 0: return ruff_proc.returncode spacing_script = HERE / "enforce_kwargs_spacing.py" spacing_cmd = [sys.executable, str(spacing_script), *files] spacing_proc = subprocess.run(spacing_cmd) return spacing_proc.returncode if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))
{ "repo_id": "unslothai/unsloth", "file_path": "scripts/run_ruff_format.py", "license": "Apache License 2.0", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
unslothai/unsloth:unsloth/device_type.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = [ "is_hip", "get_device_type", "DEVICE_TYPE", "DEVICE_TYPE_TORCH", "DEVICE_COUNT", "ALLOW_PREQUANTIZED_MODELS", "ALLOW_BITSANDBYTES", ] import torch import functools import inspect from unsloth_zoo.utils import Version @functools.cache def is_hip(): return bool(getattr(getattr(torch, "version", None), "hip", None)) @functools.cache def get_device_type(): if hasattr(torch, "cuda") and torch.cuda.is_available(): if is_hip(): return "hip" return "cuda" elif hasattr(torch, "xpu") and torch.xpu.is_available(): return "xpu" # Check torch.accelerator if hasattr(torch, "accelerator"): if not torch.accelerator.is_available(): raise NotImplementedError( "Unsloth cannot find any torch accelerator? You need a GPU." ) accelerator = str(torch.accelerator.current_accelerator()) if accelerator in ("cuda", "xpu", "hip"): raise RuntimeError( f"Unsloth: Weirdly `torch.cuda.is_available()`, `torch.xpu.is_available()` and `is_hip` all failed.\n" f"But `torch.accelerator.current_accelerator()` works with it being = `{accelerator}`\n" f"Please reinstall torch - it's most likely broken :(" ) raise NotImplementedError( "Unsloth currently only works on NVIDIA, AMD and Intel GPUs." ) DEVICE_TYPE: str = get_device_type() # HIP fails for autocast and other torch functions. Use CUDA instead DEVICE_TYPE_TORCH = DEVICE_TYPE if DEVICE_TYPE_TORCH == "hip": DEVICE_TYPE_TORCH = "cuda" @functools.cache def get_device_count(): if DEVICE_TYPE in ("cuda", "hip"): return torch.cuda.device_count() elif DEVICE_TYPE == "xpu": return torch.xpu.device_count() else: return 1 DEVICE_COUNT: int = get_device_count() # 4-bit quantization requires a block size of 64 # this is not supported on AMD Instinct GPUs currently # | Device Type | Warp Size | Block Size | # |-----------------|-----------|------------| # | CUDA | 32 | 64 | # | Radeon (Navi) | 32 | 64 | # | Instinct (MI) | 64 | 128 | # # Since bitsandbytes 0.49.0, pre-quantized models with 64 blockwise now works # on Radeon GPUs, but not Instinct MI300x for eg [WIP] # See https://github.com/bitsandbytes-foundation/bitsandbytes/pull/1748 ALLOW_PREQUANTIZED_MODELS: bool = True # HSA_STATUS_ERROR_EXCEPTION checks - sometimes AMD fails for BnB ALLOW_BITSANDBYTES: bool = True if DEVICE_TYPE == "hip": try: import bitsandbytes except: print( "Unsloth: `bitsandbytes` is not installed - 4bit QLoRA unallowed, but 16bit and full finetuning works." ) ALLOW_PREQUANTIZED_MODELS = False ALLOW_BITSANDBYTES = False if ALLOW_BITSANDBYTES: ALLOW_BITSANDBYTES = Version(bitsandbytes.__version__) > Version("0.48.2.dev0") if Version(bitsandbytes.__version__) > Version("0.49.0"): try: # Pre-quantized bitsandbytes models use blocksize 64, so we need to check the GPU from bitsandbytes.cextension import ROCM_WARP_SIZE_64 ALLOW_PREQUANTIZED_MODELS = not ROCM_WARP_SIZE_64 except Exception as e: print( "Unsloth: Checking `from bitsandbytes.cextension import ROCM_WARP_SIZE_64` had error = \n" f"{str(e)}\n" "4bit QLoRA disabled for now, but 16bit and full finetuning works." ) ALLOW_PREQUANTIZED_MODELS = False ALLOW_BITSANDBYTES = False elif ALLOW_BITSANDBYTES: from bitsandbytes.nn.modules import Params4bit if "blocksize = 64 if not HIP_ENVIRONMENT else 128" in inspect.getsource( Params4bit ): ALLOW_PREQUANTIZED_MODELS = False
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/device_type.py", "license": "Apache License 2.0", "lines": 111, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/ollama_template_mappers.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = [ "OLLAMA_TEMPLATES", "OLLAMA_TEMPLATE_TO_MODEL_MAPPER", "MODEL_TO_OLLAMA_TEMPLATE_MAPPER", ] OLLAMA_TEMPLATES = {} # =========================================== Unsloth unsloth_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}{{ .System }} {{ end }}{{ if .Prompt }}>>> User: {{ .Prompt }} {{ end }}>>> Assistant: {{ .Response }}{__EOS_TOKEN__} """ PARAMETER stop "{__EOS_TOKEN__}" PARAMETER temperature 1.5 PARAMETER min_p 0.1 SYSTEM """You are a helpful assistant to the user""" ''' OLLAMA_TEMPLATES["unsloth"] = unsloth_ollama # =========================================== Zephyr zephyr_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}<|system|> {{ .System }}{__EOS_TOKEN__} {{ end }}{{ if .Prompt }}<|user|> {{ .Prompt }}{__EOS_TOKEN__} {{ end }}<|assistant|> {{ .Response }}{__EOS_TOKEN__} """ PARAMETER stop "{__EOS_TOKEN__}" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["zephyr"] = zephyr_ollama # =========================================== ChatML chatml_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}{{ if .Prompt }}<|im_start|>user {{ .Prompt }}<|im_end|> {{ end }}<|im_start|>assistant {{ .Response }}<|im_end|> """ PARAMETER stop "<|im_start|>" PARAMETER stop "<|im_end|>" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["chatml"] = chatml_ollama # =========================================== Mistral-1 # Ollama from https://www.ollama.com/library/mistral # Mistral v0.1 https://ollama.com/library/mistral:v0.1/blobs/22e1b2e8dc2f # Mistral v0.2 https://ollama.com/library/mistral:v0.2/blobs/e6836092461f mistral_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """[INST] {{ if .System }}{{ .System }} {{ end }}{{ .Prompt }} [/INST]""" PARAMETER stop "[INST]" PARAMETER stop "[/INST]" ''' # mistral:v0.3 https://ollama.com/library/mistral:v0.3/blobs/1ff5b64b61b9 # mistral-large https://ollama.com/library/mistral-large:latest/blobs/96adabcf2c08 mistral_v03_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- if .Messages }} {{- range $index, $_ := .Messages }} {{- if eq .Role "user" }} {{- if and (eq (len (slice $.Messages $index)) 1) $.Tools }}[AVAILABLE_TOOLS] {{ $.Tools }}[/AVAILABLE_TOOLS] {{- end }}[INST] {{ if and $.System (eq (len (slice $.Messages $index)) 1) }}{{ $.System }} {{ end }}{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{- if .Content }}{{ .Content }} {{- else if .ToolCalls }}[TOOL_CALLS] [ {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{- end }}] {{- end }}</s> {{- else if eq .Role "tool" }}[TOOL_RESULTS] {"content": {{ .Content }}} [/TOOL_RESULTS] {{- end }} {{- end }} {{- else }}[INST] {{ if .System }}{{ .System }} {{ end }}{{ .Prompt }}[/INST] {{- end }}{{ .Response }} {{- if .Response }}</s> {{- end }}""" PARAMETER stop "[INST]" PARAMETER stop "[/INST]" PARAMETER stop "</s>" ''' # Mistral-small https://ollama.com/library/mistral-small:latest/blobs/6db27cd4e277 mistral_small_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- range $index, $_ := .Messages }} {{- if eq .Role "system" }}[SYSTEM_PROMPT]{{ .Content }}[/SYSTEM_PROMPT] {{- else if eq .Role "user" }} {{- if and (le (len (slice $.Messages $index)) 2) $.Tools }}[AVAILABLE_TOOLS]{{ $.Tools }}[/AVAILABLE_TOOLS] {{- end }}[INST]{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{- if .Content }}{{ .Content }} {{- if not (eq (len (slice $.Messages $index)) 1) }}</s> {{- end }} {{- else if .ToolCalls }}[TOOL_CALLS][ {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{- end }}]</s> {{- end }} {{- else if eq .Role "tool" }}[TOOL_RESULTS]{"content": {{ .Content }}}[/TOOL_RESULTS] {{- end }} {{- end }}""" PARAMETER temperature 0.15 SYSTEM """You are Mistral Small 3, a Large Language Model (LLM) created by Mistral AI, a French startup headquartered in Paris. Your knowledge base was last updated on 2023-10-01. When you're not sure about some information, you say that you don't have the information and don't make up anything. If the user's question is not clear, ambiguous, or does not provide enough context for you to accurately answer the question, you do not try to answer it right away and you rather ask the user to clarify their request (e.g. "What are some good restaurants around me?" => "Where are you?" or "When is the next flight to Tokyo" => "Where do you travel from?")""" ''' # mistral-small-3.1 https://ollama.com/library/mistral-small3.1:latest/blobs/6db27cd4e277 mistral_small_31_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- range $index, $_ := .Messages }} {{- if eq .Role "system" }}[SYSTEM_PROMPT]{{ .Content }}[/SYSTEM_PROMPT] {{- else if eq .Role "user" }} {{- if and (le (len (slice $.Messages $index)) 2) $.Tools }}[AVAILABLE_TOOLS]{{ $.Tools }}[/AVAILABLE_TOOLS] {{- end }}[INST]{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{- if .Content }}{{ .Content }} {{- if not (eq (len (slice $.Messages $index)) 1) }}</s> {{- end }} {{- else if .ToolCalls }}[TOOL_CALLS][ {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{- end }}]</s> {{- end }} {{- else if eq .Role "tool" }}[TOOL_RESULTS]{"content": {{ .Content }}}[/TOOL_RESULTS] {{- end }} {{- end }}""" PARAMETER num_ctx 4096 SYSTEM """You are Mistral Small 3.1, a Large Language Model (LLM) created by Mistral AI, a French startup headquartered in Paris. You power an AI assistant called Le Chat. Your knowledge base was last updated on 2023-10-01. When you're not sure about some information, you say that you don't have the information and don't make up anything. If the user's question is not clear, ambiguous, or does not provide enough context for you to accurately answer the question, you do not try to answer it right away and you rather ask the user to clarify their request (e.g. "What are some good restaurants around me?" => "Where are you?" or "When is the next flight to Tokyo" => "Where do you travel from?"). You are always very attentive to dates, in particular you try to resolve dates (e.g. "yesterday" is {yesterday}) and when asked about information at specific dates, you discard information that is at another date. You follow these instructions in all languages, and always respond to the user in the language they use or request. Next sections describe the capabilities that you have. # WEB BROWSING INSTRUCTIONS You cannot perform any web search or access internet to open URLs, links etc. If it seems like the user is expecting you to do so, you clarify the situation and ask the user to copy paste the text directly in the chat. # MULTI-MODAL INSTRUCTIONS You have the ability to read images, but you cannot generate images. You also cannot transcribe audio files or videos. You cannot read nor transcribe audio files or videos.""" ''' # mistral-small-3.2 https://ollama.com/library/mistral-small3.2:latest/blobs/706c4d1164f7 mistral_small_32_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- range $index, $_ := .Messages }} {{- if eq .Role "system" }}[SYSTEM_PROMPT]{{ .Content }}[/SYSTEM_PROMPT] {{- else if eq .Role "user" }} {{- if and (le (len (slice $.Messages $index)) 2) $.Tools }}[AVAILABLE_TOOLS]{{ $.Tools }}[/AVAILABLE_TOOLS] {{- end }}[INST]{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{- if .Content }}{{ .Content }} {{- if not (eq (len (slice $.Messages $index)) 1) }}</s> {{- end }} {{- else if .ToolCalls }} {{- range $i, $_ := .ToolCalls }}[TOOL_CALLS]{{ .Function.Name }}[CALL_ID]{{ $i }}[ARGS]{{ .Function.Arguments }} {{- end }}</s> {{- end }} {{- else if eq .Role "tool" }}[TOOL_RESULTS]{"content": {{ .Content }}}[/TOOL_RESULTS] {{- end }} {{- end }}""" PARAMETER temperature 0.15 SYSTEM """You are Mistral Small 3.2, a Large Language Model (LLM) created by Mistral AI, a French startup headquartered in Paris. You power an AI assistant called Le Chat. Your knowledge base was last updated on 2023-10-01. When you're not sure about some information or when the user's request requires up-to-date or specific data, you must use the available tools to fetch the information. Do not hesitate to use tools whenever they can provide a more accurate or complete response. If no relevant tools are available, then clearly state that you don't have the information and avoid making up anything. If the user's question is not clear, ambiguous, or does not provide enough context for you to accurately answer the question, you do not try to answer it right away and you rather ask the user to clarify their request (e.g. "What are some good restaurants around me?" => "Where are you?" or "When is the next flight to Tokyo" => "Where do you travel from?"). You are always very attentive to dates, in particular you try to resolve dates and when asked about information at specific dates, you discard information that is at another date. You follow these instructions in all languages, and always respond to the user in the language they use or request. Next sections describe the capabilities that you have. # WEB BROWSING INSTRUCTIONS You cannot perform any web search or access internet to open URLs, links etc. If it seems like the user is expecting you to do so, you clarify the situation and ask the user to copy paste the text directly in the chat. # MULTI-MODAL INSTRUCTIONS You have the ability to read images, but you cannot generate images. You also cannot transcribe audio files or videos. You cannot read nor transcribe audio files or videos. TOOL CALLING INSTRUCTIONS You may have access to tools that you can use to fetch information or perform actions. You must use these tools in the following situations: 1. When the request requires up-to-date information. 2. When the request requires specific data that you do not have in your knowledge base. 3. When the request involves actions that you cannot perform without tools. Always prioritize using tools to provide the most accurate and helpful response. If tools are not available, inform the user that you cannot perform the requested action at the moment.""" ''' # https://ollama.com/library/mixtral:latest/blobs/53d74de0d84c mixtral_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """[INST] {{ if .System }}{{ .System }} {{ end }}{{ .Prompt }} [/INST] {{ .Response }}""" PARAMETER stop "[INST]" PARAMETER stop "[/INST]" ''' # https://registry.ollama.ai/library/mistral-nemo:latest/blobs/438402ddac75 mistral_nemo_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """ {{- range $i, $_ := .Messages }} {{- if eq .Role "user" }} {{- if and $.Tools (le (len (slice $.Messages $i)) 2) }}[AVAILABLE_TOOLS]{{ $.Tools }}[/AVAILABLE_TOOLS] {{- end }}[INST]{{ if and $.System (eq (len (slice $.Messages $i)) 1) }}{{ $.System }} {{ end }}{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{- if .Content }} {{ .Content }}{{ if not (eq (len (slice $.Messages $i)) 1) }}</s>{{ end }} {{- else if .ToolCalls }}[TOOL_CALLS][ {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{- end }}]</s> {{- end }} {{- else if eq .Role "tool" }}[TOOL_RESULTS]{"content": {{ .Content }}}[/TOOL_RESULTS] {{- end }} {{- end }}""" PARAMETER stop "[INST]" PARAMETER stop "[/INST]" ''' # https://ollama.com/library/codestral:latest/blobs/51707752a87c codestral_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """ {{- if .Suffix }}[SUFFIX]{{ .Suffix }}[PREFIX] {{ .Prompt }} {{- else if .Messages }} {{- range $index, $_ := .Messages }} {{- if eq .Role "user" }}[INST] {{ if and $.System (eq (len (slice $.Messages $index)) 1) }}{{ $.System }} {{ end }}{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{ .Content }}</s> {{- end }} {{- end }} {{- else }}[INST] {{ if .System }}{{ .System }} {{ end }}{{ .Prompt }} [/INST] {{- end }} {{ .Response }} {{- if .Response }}</s> {{- end }} """ PARAMETER stop "[INST]" PARAMETER stop "[/INST]" PARAMETER stop "[PREFIX]" PARAMETER stop "[MIDDLE]" PARAMETER stop "[SUFFIX]" ''' # https://ollama.com/library/devstral:latest/blobs/ea9ec42474e0 devstral_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- $lastUserIndex := -1 }} {{- range $index, $_ := .Messages }} {{- if eq .Role "user" }}{{ $lastUserIndex = $index }}{{ end }} {{- end }} {{- range $index, $_ := .Messages }} {{- if eq .Role "system" }}[SYSTEM_PROMPT]{{ .Content }}[/SYSTEM_PROMPT] {{- else if eq .Role "user" }} {{- if and (eq $lastUserIndex $index) $.Tools }}[AVAILABLE_TOOLS]{{ $.Tools }}[/AVAILABLE_TOOLS] {{- end }}[INST]{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{- if .Content }}{{ .Content }} {{- if not (eq (len (slice $.Messages $index)) 1) }}</s> {{- end }} {{- else if .ToolCalls }}[TOOL_CALLS][ {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{- end }}]</s> {{- end }} {{- else if eq .Role "tool" }}[TOOL_RESULTS]{"content": {{ .Content }}}[/TOOL_RESULTS] {{- end }} {{- end }}""" SYSTEM """You are Devstral, a helpful agentic model trained by Mistral AI and using the OpenHands scaffold. You can interact with a computer to solve tasks. <ROLE> Your primary role is to assist users by executing commands, modifying code, and solving technical problems effectively. You should be thorough, methodical, and prioritize quality over speed. * If the user asks a question, like "why is X happening", don't try to fix the problem. Just give an answer to the question. </ROLE> <EFFICIENCY> * Each action you take is somewhat expensive. Wherever possible, combine multiple actions into a single action, e.g. combine multiple bash commands into one, using sed and grep to edit/view multiple files at once. * When exploring the codebase, use efficient tools like find, grep, and git commands with appropriate filters to minimize unnecessary operations. </EFFICIENCY> <FILE_SYSTEM_GUIDELINES> * When a user provides a file path, do NOT assume it's relative to the current working directory. First explore the file system to locate the file before working on it. * If asked to edit a file, edit the file directly, rather than creating a new file with a different filename. * For global search-and-replace operations, consider using `sed` instead of opening file editors multiple times. </FILE_SYSTEM_GUIDELINES> <CODE_QUALITY> * Write clean, efficient code with minimal comments. Avoid redundancy in comments: Do not repeat information that can be easily inferred from the code itself. * When implementing solutions, focus on making the minimal changes needed to solve the problem. * Before implementing any changes, first thoroughly understand the codebase through exploration. * If you are adding a lot of code to a function or file, consider splitting the function or file into smaller pieces when appropriate. </CODE_QUALITY> <VERSION_CONTROL> * When configuring git credentials, use "openhands" as the user.name and "openhands@all-hands.dev" as the user.email by default, unless explicitly instructed otherwise. * Exercise caution with git operations. Do NOT make potentially dangerous changes (e.g., pushing to main, deleting repositories) unless explicitly asked to do so. * When committing changes, use `git status` to see all modified files, and stage all files necessary for the commit. Use `git commit -a` whenever possible. * Do NOT commit files that typically shouldn't go into version control (e.g., node_modules/, .env files, build directories, cache files, large binaries) unless explicitly instructed by the user. * If unsure about committing certain files, check for the presence of .gitignore files or ask the user for clarification. </VERSION_CONTROL> <PULL_REQUESTS> * When creating pull requests, create only ONE per session/issue unless explicitly instructed otherwise. * When working with an existing PR, update it with new commits rather than creating additional PRs for the same issue. * When updating a PR, preserve the original PR title and purpose, updating description only when necessary. </PULL_REQUESTS> <PROBLEM_SOLVING_WORKFLOW> 1. EXPLORATION: Thoroughly explore relevant files and understand the context before proposing solutions 2. ANALYSIS: Consider multiple approaches and select the most promising one 3. TESTING: * For bug fixes: Create tests to verify issues before implementing fixes * For new features: Consider test-driven development when appropriate * If the repository lacks testing infrastructure and implementing tests would require extensive setup, consult with the user before investing time in building testing infrastructure * If the environment is not set up to run tests, consult with the user first before investing time to install all dependencies 4. IMPLEMENTATION: Make focused, minimal changes to address the problem 5. VERIFICATION: If the environment is set up to run tests, test your implementation thoroughly, including edge cases. If the environment is not set up to run tests, consult with the user first before investing time to run tests. </PROBLEM_SOLVING_WORKFLOW> <SECURITY> * Only use GITHUB_TOKEN and other credentials in ways the user has explicitly requested and would expect. * Use APIs to work with GitHub or other platforms, unless the user asks otherwise or your task requires browsing. </SECURITY> <ENVIRONMENT_SETUP> * When user asks you to run an application, don't stop if the application is not installed. Instead, please install the application and run the command again. * If you encounter missing dependencies: 1. First, look around in the repository for existing dependency files (requirements.txt, pyproject.toml, package.json, Gemfile, etc.) 2. If dependency files exist, use them to install all dependencies at once (e.g., `pip install -r requirements.txt`, `npm install`, etc.) 3. Only install individual packages directly if no dependency files are found or if only specific packages are needed * Similarly, if you encounter missing dependencies for essential tools requested by the user, install them when possible. </ENVIRONMENT_SETUP> <TROUBLESHOOTING> * If you've made repeated attempts to solve a problem but tests still fail or the user reports it's still broken: 1. Step back and reflect on 5-7 different possible sources of the problem 2. Assess the likelihood of each possible cause 3. Methodically address the most likely causes, starting with the highest probability 4. Document your reasoning process * When you run into any major issue while executing a plan from the user, please don't try to directly work around it. Instead, propose a new plan and confirm with the user before proceeding. </TROUBLESHOOTING>""" ''' # https://ollama.com/library/magistral:latest/blobs/35f7a1efc383 magistral_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """ {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1}} {{- if eq .Role "system" }}[SYSTEM_PROMPT]{{ .Content }}[/SYSTEM_PROMPT] {{- else if eq .Role "user" }} {{- if and (le (len (slice $.Messages $i)) 2) $.Tools }}[AVAILABLE_TOOLS]{{ $.Tools }}[/AVAILABLE_TOOLS] {{- end }}[INST]{{ .Content }}[/INST] {{- else if eq .Role "assistant" }} {{- if and $.IsThinkSet (and $last .Thinking) -}} <think> {{ .Thinking }} </think> {{ end }} {{- if .Content }}{{ .Content }} {{- end }} {{- if .ToolCalls }}{{ range $i, $_ := .ToolCalls }}[TOOL_CALLS]{{ .Function.Name }}[CALL_ID]{{ $i }}[ARGS]{{ .Function.Arguments }}{{ end }} {{- end }} {{- if not (eq (len (slice $.Messages $i)) 1) }}</s> {{- end }} {{- else if eq .Role "tool" }}[TOOL_RESULTS]0[TOOL_CONTENT]{{ .Content }}[/TOOL_RESULTS] {{- end }} {{- if and $last (ne .Role "assistant") }}{{ if and $.IsThinkSet (not $.Think) -}}<think> </think> {{ end }} {{- end }} {{- end }}""" PARAMETER temperature 0.7 PARAMETER top_p 0.95 SYSTEM """A user will ask you to solve a task. You should first draft your thinking process (inner monologue) until you have derived the final answer. Afterwards, write a self-contained summary of your thoughts (i.e. your summary should be succinct but contain all the critical steps you needed to reach the conclusion). You should use Markdown and Latex to format your response. Write both your thoughts and summary in the same language as the task posed by the user. Your thinking process must follow the template below: <think> Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct answer. </think> Here, provide a concise summary that reflects your reasoning and presents a clear final answer to the user. Problem:""" ''' OLLAMA_TEMPLATES["mistral"] = mistral_ollama OLLAMA_TEMPLATES["mistral-v03"] = mistral_v03_ollama OLLAMA_TEMPLATES["mistral-small"] = mistral_small_ollama OLLAMA_TEMPLATES["mistral-small-31"] = mistral_small_31_ollama OLLAMA_TEMPLATES["mistral-small-32"] = mistral_small_32_ollama OLLAMA_TEMPLATES["mixtral"] = mixtral_ollama OLLAMA_TEMPLATES["mistral-nemo"] = mistral_nemo_ollama OLLAMA_TEMPLATES["devstral"] = devstral_ollama OLLAMA_TEMPLATES["magistral"] = magistral_ollama OLLAMA_TEMPLATES["codestral"] = codestral_ollama # =========================================== Llama-2 # Ollama from https://www.ollama.com/library/llama3 llama_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """[INST] <<SYS>>{{ .System }}<</SYS>> {{ .Prompt }} [/INST]""" PARAMETER stop "{__EOS_TOKEN__}" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["llama"] = llama_ollama # =========================================== Vicuna # Ollama from https://www.ollama.com/library/vicuna vicuna_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}{{ .System }} {{ end }}{{ if .Prompt }}USER: {{ .Prompt }} {{ end }}ASSISTANT: {{ .Response }} {__EOS_TOKEN__}""" PARAMETER stop "{__EOS_TOKEN__}" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["vicuna"] = vicuna_ollama # =========================================== Vicuna Old vicuna_old_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}{{ .System }} {{ end }}{{ if .Prompt }}### Human: {{ .Prompt }} {{ end }}### Assistant: {{ .Response }}{__EOS_TOKEN__} """ PARAMETER stop "{__EOS_TOKEN__}" PARAMETER temperature 1.5 PARAMETER min_p 0.1 SYSTEM """A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.""" ''' OLLAMA_TEMPLATES["vicuna_old"] = vicuna_old_ollama OLLAMA_TEMPLATES["vicuna old"] = OLLAMA_TEMPLATES["vicuna_old"] # =========================================== Alpaca multi turn alpaca_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}{{ .System }} {{ end }}{{ if .Prompt }}### Instruction: {{ .Prompt }}{{ end }} ### Response: {{ .Response }}{__EOS_TOKEN__} """ PARAMETER stop "{__EOS_TOKEN__}" PARAMETER temperature 1.5 PARAMETER min_p 0.1 SYSTEM """Below are some instructions that describe some tasks. Write responses that appropriately complete each request.""" ''' OLLAMA_TEMPLATES["alpaca"] = alpaca_ollama # =========================================== Gemma # Ollama from https://www.ollama.com/library/gemma gemma_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """<start_of_turn>user {{ if .System }}{{ .System }} {{ end }}{{ .Prompt }}<end_of_turn> <start_of_turn>model {{ .Response }}<end_of_turn> """ PARAMETER repeat_penalty 1 PARAMETER stop "<start_of_turn>" PARAMETER stop "<end_of_turn>" PARAMETER penalize_newline false PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["gemma"] = gemma_ollama # =========================================== Gemma with ChatML instead gemma_chatml_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}{{ if .Prompt }}<|im_start|>user {{ .Prompt }}<|im_end|> {{ end }}<|im_start|>assistant {{ .Response }}<|im_end|> """ PARAMETER repeat_penalty 1 PARAMETER stop "<|im_start|>" PARAMETER stop "<|im_end|>" PARAMETER penalize_newline false PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["gemma_chatml"] = gemma_chatml_ollama # =========================================== Gemma 2 # Same as Gemma 1, but with sliding window attention! # https://ollama.com/library/gemma2/blobs/6522ca797f47 gemma2_ollama = gemma_ollama + "PARAMETER num_ctx 4096\n" OLLAMA_TEMPLATES["gemma2"] = gemma2_ollama # =========================================== Gemma 2 with ChatML instead gemma2_chatml_ollama = gemma_chatml_ollama + "PARAMETER num_ctx 4096\n" OLLAMA_TEMPLATES["gemma2_chatml"] = gemma2_chatml_ollama # =========================================== Llama-3 # Ollama from https://www.ollama.com/library/llama3 llama3_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}<|start_header_id|>system<|end_header_id|> {{ .System }}<|eot_id|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> {{ .Prompt }}<|eot_id|>{{ end }}<|start_header_id|>assistant<|end_header_id|> {{ .Response }}<|eot_id|>""" PARAMETER num_keep 24 PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" PARAMETER stop "<|eot_id|>" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["llama-3"] = llama3_ollama OLLAMA_TEMPLATES["llama3"] = llama3_ollama # =========================================== Phi-3 # Ollama from https://www.ollama.com/library/phi3 phi3_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}<|system|> {{ .System }}<|end|> {{ end }}{{ if .Prompt }}<|user|> {{ .Prompt }}<|end|> {{ end }}<|assistant|> {{ .Response }}<|end|> """ PARAMETER stop "<|end|>" PARAMETER stop "<|user|>" PARAMETER stop "<|assistant|>" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["phi-3"] = phi3_ollama OLLAMA_TEMPLATES["phi-35"] = OLLAMA_TEMPLATES["phi-3"] OLLAMA_TEMPLATES["phi-3.5"] = OLLAMA_TEMPLATES["phi-3"] # =========================================== Llama-3.1 """ No trimming in Llama 3.1 Instruct! Also an extra newline for Cutting Knowledge Date See https://colab.research.google.com/drive/1Xpqq5xpIgO-B00MQ-UccYMwN2J8QFgBM?usp=sharing Also should be import datetime tokenizer.apply_chat_template( messages, add_generation_prompt = True, tokenize = False, date_string = datetime.today().strftime("%d %B %Y")), ) """ # Ollama from https://ollama.com/library/llama3.1 (needs updating!) llama31_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .Messages }} {{- if or .System .Tools }}<|start_header_id|>system<|end_header_id|> {{- if .System }} {{ .System }} {{- end }} {{- if .Tools }} You are a helpful assistant with tool calling capabilities. When you receive a tool call response, use the output to format an answer to the original use question. {{- end }} {{- end }}<|eot_id|> {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 }} {{- if eq .Role "user" }}<|start_header_id|>user<|end_header_id|> {{- if and $.Tools $last }} Given the following functions, please respond with a JSON for a function call with its proper arguments that best answers the given prompt. Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. Do not use variables. {{ $.Tools }} {{- end }} {{ .Content }}<|eot_id|>{{ if $last }}<|start_header_id|>assistant<|end_header_id|> {{ end }} {{- else if eq .Role "assistant" }}<|start_header_id|>assistant<|end_header_id|> {{- if .ToolCalls }} {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "parameters": {{ .Function.Arguments }}}{{ end }} {{- else }} {{ .Content }}{{ if not $last }}<|eot_id|>{{ end }} {{- end }} {{- else if eq .Role "tool" }}<|start_header_id|>ipython<|end_header_id|> {{ .Content }}<|eot_id|>{{ if $last }}<|start_header_id|>assistant<|end_header_id|> {{ end }} {{- end }} {{- end }} {{- else }} {{- if .System }}<|start_header_id|>system<|end_header_id|> {{ .System }}<|eot_id|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> {{ .Prompt }}<|eot_id|>{{ end }}<|start_header_id|>assistant<|end_header_id|> {{ end }}{{ .Response }}{{ if .Response }}<|eot_id|>{{ end }}""" PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" PARAMETER stop "<|eot_id|>" PARAMETER stop "<|eom_id|>" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' # https://ollama.com/ajindal/llama3.1-storm:8b/blobs/1970553b62f4 llama_31_storm_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """ {{ if .Messages }} {{- if or .System .Tools }}<|start_header_id|>system<|end_header_id|> {{- if .System }} {{ .System }} {{- end }} {{- if .Tools }} You are a function calling AI model. You may call one or more functions to assist with the user query. Don't make assumptions about what values to plug into function. The user may use the terms function calling or tool use interchangeably. Here are the available functions: <tools>{{ json .Tools }}</tools> For each function call return a json object with function name and arguments within <tool_call></tool_call> XML tags in the format: <tool_call>{"tool_name": <function-name>, "tool_arguments": <args-dict>}</tool_call> {{- end }} {{- end }}<|eot_id|> {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 }} {{- if eq .Role "user" }}<|start_header_id|>user<|end_header_id|> {{ .Content }}<|eot_id|>{{ if $last }}<|start_header_id|>assistant<|end_header_id|> {{ end }} {{- else if eq .Role "assistant" }}<|start_header_id|>assistant<|end_header_id|> {{- if .ToolCalls }} {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "parameters": {{ .Function.Arguments }}}{{ end }} {{- else }} {{ .Content }}{{ if not $last }}<|eot_id|>{{ end }} {{- end }} {{- else if eq .Role "tool" }}<|start_header_id|>ipython<|end_header_id|> {{ .Content }}<|eot_id|>{{ if $last }}<|start_header_id|>assistant<|end_header_id|> {{ end }} {{- end }} {{- end }} {{- else }} {{- if .System }}<|start_header_id|>system<|end_header_id|> {{ .System }}<|eot_id|>{{ end }}{{ if .Prompt }}<|start_header_id|>user<|end_header_id|> {{ .Prompt }}<|eot_id|>{{ end }}<|start_header_id|>assistant<|end_header_id|> {{ end }}{{ .Response }}{{ if .Response }}<|eot_id|>{{ end }} """ PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" PARAMETER stop "<|eot_id|>" ''' # https://ollama.com/library/nemotron:latest/blobs/4863fe3335f3 llama_31_nemotron_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """<|start_header_id|>system<|end_header_id|> {{ if .Tools }}You have access to the following functions. To call a function, please respond with JSON for a function call. Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}. Do not use variables. {{ range .Tools }}{{ . }} {{ end }} {{- end }}{{ .System }}<|eot_id|> {{- range $i, $_ := .Messages }} {{- $isLastMessage := eq (len (slice $.Messages $i)) 1 -}} {{- if eq .Role "system" }} {{- else if eq .Role "assistant" }}<|start_header_id|>assistant<|end_header_id|> {{ if .Content }}{{ .Content }} {{- else if .ToolCalls }} {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "parameters": {{ .Function.Arguments }} } {{- end }} {{- end }} {{- if not $isLastMessage }}<|eot_id|> {{- end }} {{- else if eq .Role "tool" }}<|start_header_id|>ipython<|end_header_id|> {{ .Content }}<|eot_id|> {{- if $isLastMessage }}<|start_header_id|>assistant<|end_header_id|> {{ end }} {{- else }}<|start_header_id|>{{ .Role }}<|end_header_id|> {{ .Content }}<|eot_id|> {{- if $isLastMessage }}<|start_header_id|>assistant<|end_header_id|> {{ end }} {{- end }} {{- end }} """ PARAMETER stop "<|start_header_id|>" PARAMETER stop "<|end_header_id|>" PARAMETER stop "<|eot_id|>" ''' # https://ollama.com/library/llama3.2-vision:latest/blobs/715415638c895a1f8e8c6 llama_32_vision_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- range $index, $_ := .Messages }}<|start_header_id|>{{ .Role }}<|end_header_id|> {{ .Content }} {{- if gt (len (slice $.Messages $index)) 1 }}<|eot_id|> {{- else if ne .Role "assistant" }}<|eot_id|><|start_header_id|>assistant<|end_header_id|> {{ end }} {{- end }}""" PARAMETER temperature 0.6 PARAMETER top_p 0.9 ''' OLLAMA_TEMPLATES["llama-3.1"] = llama31_ollama OLLAMA_TEMPLATES["llama-31"] = llama31_ollama OLLAMA_TEMPLATES["llama-31-nemotron"] = llama_31_nemotron_ollama OLLAMA_TEMPLATES["llama-31-storm"] = llama_31_storm_ollama OLLAMA_TEMPLATES["llama-32-vision"] = llama_32_vision_ollama for version in ("llama-3.2", "llama-3.3", "llama-32", "llama-33"): OLLAMA_TEMPLATES[version] = OLLAMA_TEMPLATES["llama-3.1"] # =========================================== tinyllama # tinyllama-chat https://ollama.com/library/tinyllama:latest/blobs/af0ddbdaaa26 tinyllama_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """<|system|> {{ .System }}</s> <|user|> {{ .Prompt }}</s> <|assistant|>""" PARAMETER stop "<|system|>" PARAMETER stop "<|user|>" PARAMETER stop "<|assistant|>" PARAMETER stop "</s>" SYSTEM """You are a helpful AI assistant.""" ''' OLLAMA_TEMPLATES["tinyllama"] = tinyllama_ollama # =========================================== Qwen 2/2.5 # Qwen2 https://ollama.com/library/qwen2:latest/blobs/77c91b422cc9 # Qwen2.5 from https://ollama.com/library/qwen2.5/blobs/eb4402837c78 qwen25_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- if .Messages }} {{- if or .System .Tools }}<|im_start|>system {{- if .System }} {{ .System }} {{- end }} {{- if .Tools }} # Tools You may call one or more functions to assist with the user query. You are provided with function signatures within <tools></tools> XML tags: <tools> {{- range .Tools }} {"type": "function", "function": {{ .Function }}} {{- end }} </tools> For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags: <tool_call> {"name": <function-name>, "arguments": <args-json-object>} </tool_call> {{- end }}<|im_end|> {{ end }} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if eq .Role "user" }}<|im_start|>user {{ .Content }}<|im_end|> {{ else if eq .Role "assistant" }}<|im_start|>assistant {{ if .Content }}{{ .Content }} {{- else if .ToolCalls }}<tool_call> {{ range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{ end }}</tool_call> {{- end }}{{ if not $last }}<|im_end|> {{ end }} {{- else if eq .Role "tool" }}<|im_start|>user <tool_response> {{ .Content }} </tool_response><|im_end|> {{ end }} {{- if and (ne .Role "assistant") $last }}<|im_start|>assistant {{ end }} {{- end }} {{- else }} {{- if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}{{ if .Prompt }}<|im_start|>user {{ .Prompt }}<|im_end|> {{ end }}<|im_start|>assistant {{ end }}{{ .Response }}{{ if .Response }}<|im_end|>{{ end }}""" PARAMETER stop "<|im_end|>" PARAMETER stop "<|endoftext|>" PARAMETER temperature 1.5 PARAMETER min_p 0.1 SYSTEM """You are Qwen, created by Alibaba Cloud. You are a helpful assistant.""" ''' # https://ollama.com/library/qwen2.5-coder:latest/blobs/1e65450c3067 qwen_25_coder_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- if .Suffix }}<|fim_prefix|>{{ .Prompt }}<|fim_suffix|>{{ .Suffix }}<|fim_middle|> {{- else if .Messages }} {{- if or .System .Tools }}<|im_start|>system {{- if .System }} {{ .System }} {{- end }} {{- if .Tools }} # Tools You may call one or more functions to assist with the user query. You are provided with function signatures within <tools></tools>: <tools> {{- range .Tools }} {"type": "function", "function": {{ .Function }}} {{- end }} </tools> For each function call, return a json object with function name and arguments within <tool_call></tool_call> with NO other text. Do not include any backticks or ```json. <tool_call> {"name": <function-name>, "arguments": <args-json-object>} </tool_call> {{- end }}<|im_end|> {{ end }} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if eq .Role "user" }}<|im_start|>user {{ .Content }}<|im_end|> {{ else if eq .Role "assistant" }}<|im_start|>assistant {{ if .Content }}{{ .Content }} {{- else if .ToolCalls }}<tool_call> {{ range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{ end }}</tool_call> {{- end }}{{ if not $last }}<|im_end|> {{ end }} {{- else if eq .Role "tool" }}<|im_start|>user <tool_response> {{ .Content }} </tool_response><|im_end|> {{ end }} {{- if and (ne .Role "assistant") $last }}<|im_start|>assistant {{ end }} {{- end }} {{- else }} {{- if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}{{ if .Prompt }}<|im_start|>user {{ .Prompt }}<|im_end|> {{ end }}<|im_start|>assistant {{ end }}{{ .Response }}{{ if .Response }}<|im_end|>{{ end }}""" SYSTEM """You are Qwen, created by Alibaba Cloud. You are a helpful assistant.""" ''' # https://ollama.com/library/qwen2.5vl:latest/blobs/a242d8dfdc8f qwen_25_vl_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- if .System -}} <|im_start|>system {{ .System }}<|im_end|> {{- end -}} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if eq .Role "user" }} <|im_start|>user {{ .Content }}<|im_end|> {{- else if eq .Role "assistant" }} <|im_start|>assistant {{ if .Content }}{{ .Content }}{{ if not $last }}<|im_end|> {{- else -}}<|im_end|>{{- end -}} {{- end -}} {{- end -}} {{- if and (ne .Role "assistant") $last }} <|im_start|>assistant {{ end -}} {{- end }}""" PARAMETER temperature 0.0001 SYSTEM """You are a helpful assistant.""" ''' # https://ollama.com/library/openthinker:latest/blobs/32695b892af8 openthinker_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} <|im_start|>{{ .Role }}<|im_sep|> {{ .Content }}{{ if not $last }}<|im_end|> {{ end }} {{- if and (ne .Role "assistant") $last }}<|im_end|> <|im_start|>assistant<|im_sep|> {{ end }} {{- end }}""" ''' OLLAMA_TEMPLATES["qwen-25"] = qwen25_ollama OLLAMA_TEMPLATES["qwen-2.5"] = qwen25_ollama OLLAMA_TEMPLATES["qwen-25-coder"] = qwen_25_coder_ollama OLLAMA_TEMPLATES["qwen-25-vl"] = qwen_25_vl_ollama OLLAMA_TEMPLATES["openthinker"] = openthinker_ollama OLLAMA_TEMPLATES["qwen-2"] = qwen25_ollama # =========================================== Phi-4 _phi4_ollama_template = ( "{{ if .System }}<|im_start|><|system|><|im_sep|>{{ .System }}<|im_end|>{{ end }}" "{{ if .Prompt }}<|im_start|><|user|><|im_sep|>{{ .Prompt }}<|im_end|>{{ end }}" "<|im_start|><|assistant|><|im_sep|>{{ .Response }}<|im_end|>" ) # Ollama from https://www.ollama.com/library/phi4 is different phi_4_ollama = f''' FROM {{__FILE_LOCATION__}} TEMPLATE """{_phi4_ollama_template}""" PARAMETER stop "<|im_end|>" PARAMETER stop "<|im_start|>" PARAMETER stop "<|im_sep|>" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' # https://ollama.com/library/phi4-reasoning:latest/blobs/32695b892af8 phi_4_reasoning_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """ {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} <|im_start|>{{ .Role }}<|im_sep|> {{ .Content }}{{ if not $last }}<|im_end|> {{ end }} {{- if and (ne .Role "assistant") $last }}<|im_end|> <|im_start|>assistant<|im_sep|> {{ end }} {{- end }}""" PARAMETER stop "<|im_start|>" PARAMETER stop "<|im_end|>" PARAMETER stop "<|im_sep|>" ''' # https://ollama.com/library/phi4-mini:latest/blobs/813f53fdc6e5 phi_4_mini_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- if or .System .Tools }}<|system|>{{ if .System }}{{ .System }}{{ end }} {{- if .Tools }}{{ if not .System }}You are a helpful assistant with some tools.{{ end }}<|tool|>{{ .Tools }}<|/tool|><|end|> {{- end }} {{- end }} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if ne .Role "system" }}<|{{ .Role }}|>{{ .Content }} {{- if .ToolCalls }}<|tool_call|>[{{ range .ToolCalls }}{"name":"{{ .Function.Name }}","arguments":{{ .Function.Arguments }}{{ end }}]<|/tool_call|> {{- end }} {{- if not $last }}<|end|> {{- end }} {{- if and (ne .Role "assistant") $last }}<|end|><|assistant|>{{ end }} {{- end }} {{- end }}""" ''' # https://ollama.com/library/phi4-mini-reasoning:latest/blobs/c895a1f8e8c6 phi_4_mini_reasoning_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """ {{- if .System }}<|system|>{{ .System }} {{- end }} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if ne .Role "system" }}<|{{ .Role }}|>{{ .Content }} {{- if not $last }}<|end|> {{- end }} {{- if and (ne .Role "assistant") $last }}<|end|><|assistant|>{{ end }} {{- end }} {{- end }}""" SYSTEM """Your name is Phi, an AI math expert developed by Microsoft.""" ''' OLLAMA_TEMPLATES["phi-4"] = phi_4_ollama OLLAMA_TEMPLATES["phi-4-reasoning"] = phi_4_reasoning_ollama OLLAMA_TEMPLATES["phi-4-mini"] = phi_4_mini_ollama OLLAMA_TEMPLATES["phi-4-mini-reasoning"] = phi_4_mini_reasoning_ollama # =========================================== Gemma-3 # Ollama from https://ollama.com/library/gemma3/blobs/e0a42594d802 gemma3_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 }} {{- if or (eq .Role "user") (eq .Role "system") }}<start_of_turn>user {{ .Content }}<end_of_turn> {{ if $last }}<start_of_turn>model {{ end }} {{- else if eq .Role "assistant" }}<start_of_turn>model {{ .Content }}{{ if not $last }}<end_of_turn> {{ end }} {{- end }} {{- end }}""" PARAMETER stop "<end_of_turn>" PARAMETER stop "<eos>" PARAMETER temperature 1.0 PARAMETER min_p 0.0 PARAMETER top_k 64 PARAMETER top_p 0.95 PARAMETER num_predict 32768 ''' # https://ollama.com/library/gemma3:270m/blobs/4b19ac7dd2fb gemma3_270m_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- $systemPromptAdded := false }} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 }} {{- if eq .Role "user" }}<start_of_turn>user {{- if (and (not $systemPromptAdded) $.System) }} {{- $systemPromptAdded = true }} {{ $.System }} {{ end }} {{ .Content }}<end_of_turn> {{ if $last }}<start_of_turn>model {{ end }} {{- else if eq .Role "assistant" }}<start_of_turn>model {{ .Content }}{{ if not $last }}<end_of_turn> {{ end }} {{- end }} {{- end }} """ PARAMETER stop "<end_of_turn>" PARAMETER top_k 64 PARAMETER top_p 0.95 ''' OLLAMA_TEMPLATES["gemma-3"] = gemma3_ollama OLLAMA_TEMPLATES["gemma3"] = gemma3_ollama OLLAMA_TEMPLATES["gemma3-270m"] = gemma3_270m_ollama # =========================================== Qwen-3 # Ollama template for Qwen-3 (see https://ollama.com/library/qwen3/blobs/eb4402837c78) qwen3_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- if .Messages }} {{- if or .System .Tools }}<|im_start|>system {{- if .System }} {{ .System }} {{- end }} {{- if .Tools }} # Tools You may call one or more functions to assist with the user query. You are provided with function signatures within <tools></tools> XML tags: <tools> {{- range .Tools }} {"type": "function", "function": {{ .Function }}} {{- end }} </tools> For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags: <tool_call> {"name": <function-name>, "arguments": <args-json-object>} </tool_call> {{- end }}<|im_end|> {{ end }} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if eq .Role "user" }}<|im_start|>user {{ .Content }}<|im_end|> {{ else if eq .Role "assistant" }}<|im_start|>assistant {{ if .Content }}{{ .Content }} {{- else if .ToolCalls }}<tool_call> {{ range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{ end }}</tool_call> {{- end }}{{ if not $last }}<|im_end|> {{ end }} {{- else if eq .Role "tool" }}<|im_start|>user <tool_response> {{ .Content }} </tool_response><|im_end|> {{ end }} {{- if and (ne .Role "assistant") $last }}<|im_start|>assistant {{ end }} {{- end }} {{- else }} {{- if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}{{ if .Prompt }}<|im_start|>user {{ .Prompt }}<|im_end|> {{ end }}<|im_start|>assistant {{ end }}{{ .Response }}{{ if .Response }}<|im_end|>{{ end }}""" PARAMETER stop "<|im_end|>" PARAMETER stop "<|im_start|>" PARAMETER temperature 0.6 PARAMETER min_p 0.0 PARAMETER top_k 20 PARAMETER top_p 0.95 PARAMETER repeat_penalty 1 ''' qwen3_template_eos_token = "<|im_end|>" OLLAMA_TEMPLATES["qwen-3"] = qwen3_ollama OLLAMA_TEMPLATES["qwen3"] = qwen3_ollama # =========================================== Gemma-3n # Ollama from https://ollama.com/library/gemma3n/blobs/e0a42594d802 gemma3n_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 }} {{- if or (eq .Role "user") (eq .Role "system") }}<start_of_turn>user {{ .Content }}<end_of_turn> {{ if $last }}<start_of_turn>model {{ end }} {{- else if eq .Role "assistant" }}<start_of_turn>model {{ .Content }}{{ if not $last }}<end_of_turn> {{ end }} {{- end }} {{- end }}""" ''' OLLAMA_TEMPLATES["gemma-3n"] = gemma3n_ollama OLLAMA_TEMPLATES["gemma3n"] = gemma3n_ollama # =========================================== GPT-OSS # Ollama from https://ollama.com/library/gpt-oss:latest/blobs/fa6710a93d78 gptoss_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI. Knowledge cutoff: 2024-06 Current date: {{ currentDate }} {{- if and .IsThinkSet .Think (ne .ThinkLevel "") }} Reasoning: {{ .ThinkLevel }} {{- else if or (not .IsThinkSet) (and .IsThinkSet .Think) }} Reasoning: medium {{- end }} {{- $hasNonBuiltinTools := false }} {{- if .Tools -}} {{- $hasBrowserSearch := false }} {{- $hasBrowserOpen := false }} {{- $hasBrowserFind := false }} {{- $hasPython := false }} {{- range .Tools }} {{- if eq .Function.Name "browser.search" -}}{{- $hasBrowserSearch = true -}} {{- else if eq .Function.Name "browser.open" -}}{{- $hasBrowserOpen = true -}} {{- else if eq .Function.Name "browser.find" -}}{{- $hasBrowserFind = true -}} {{- else if eq .Function.Name "python" -}}{{- $hasPython = true -}} {{- else }}{{ $hasNonBuiltinTools = true -}} {{- end }} {{- end }} {{- if or $hasBrowserSearch $hasBrowserOpen $hasBrowserFind $hasPython }} # Tools {{- if or $hasBrowserSearch $hasBrowserOpen $hasBrowserFind }} ## browser // Tool for browsing. // The `cursor` appears in brackets before each browsing display: `[{cursor}]`. // Cite information from the tool using the following format: // `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`. // Do not quote more than 10 words directly from the tool output. // sources=web (default: web) namespace browser { {{- if $hasBrowserSearch }} // Searches for information related to `query` and displays `topn` results. type search = (_: { query: string, topn?: number, // default: 10 source?: string, }) => any; {{- end }} {{- if $hasBrowserOpen }} // Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines. // Valid link ids are displayed with the formatting: `【{id}†.*】`. // If `cursor` is not provided, the most recent page is implied. // If `id` is a string, it is treated as a fully qualified URL associated with `source`. // If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available. // Use this function without `id` to scroll to a new location of an opened page. type open = (_: { id?: number | string, // default: -1 cursor?: number, // default: -1 loc?: number, // default: -1 num_lines?: number, // default: -1 view_source?: boolean, // default: false source?: string, }) => any; {{- end }} {{- if $hasBrowserFind }} // Finds exact matches of `pattern` in the current page, or the page given by `cursor`. type find = (_: { pattern: string, cursor?: number, // default: -1 }) => any; {{- end }} } // namespace browser {{- end }}{{/* end if has browser tools */}} {{- if $hasPython }} ## python Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files). When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster. {{- end }}{{/* end if hasPython */}} {{- end }}{{/* end if has any built-in tools */}} {{- end }}{{/* end if .Tools */}} # Valid channels: analysis, commentary, final. Channel must be included for every message.{{ if $hasNonBuiltinTools }} Calls to these tools must go to the commentary channel: 'functions'. {{- end -}}<|end|>{{/* end of system */ -}} {{- if or $hasNonBuiltinTools .System -}} <|start|>developer<|message|>{{- if $hasNonBuiltinTools }}# Tools ## functions namespace functions { {{- range .Tools }} {{- if not (or (eq .Function.Name "browser.search") (eq .Function.Name "browser.open") (eq .Function.Name "browser.find") (eq .Function.Name "python")) }} {{if .Function.Description }} // {{ .Function.Description }} {{- end }} {{- if and .Function.Parameters.Properties (gt (len .Function.Parameters.Properties) 0) }} type {{ .Function.Name }} = (_: { {{- range $name, $prop := .Function.Parameters.Properties }} {{- if $prop.Description }} // {{ $prop.Description }} {{- end }} {{ $name }}: {{ if gt (len $prop.Type) 1 }}{{ range $i, $t := $prop.Type }}{{ if $i }} | {{ end }}{{ $t }}{{ end }}{{ else }}{{ index $prop.Type 0 }}{{ end }}, {{- end }} }) => any; {{- else }} type {{ .Function.Name }} = () => any; {{- end }} {{- end }}{{/* end if not browser tool */}} {{- end }}{{/* end of range .Tools */}} } // namespace functions {{- end }}{{/* end if hasNonBuiltinTools */}} {{- if .System}} # Instructions {{ .System }} {{- end -}} <|end|> {{- end -}} {{- /* Find the index of the last user message */ -}} {{- $lastUserIdx := -1 }} {{- $prefillingContent := false }} {{- $prefillingThinkingOnly := false }} {{- range $i, $msg := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if eq $msg.Role "user" }} {{- $lastUserIdx = $i }} {{- end -}} {{- if and $last (eq $msg.Role "assistant") (gt (len $msg.Content) 0) }} {{- $prefillingContent = true }} {{- else if and $last (eq $msg.Role "assistant") (gt (len $msg.Thinking) 0) }} {{- $prefillingThinkingOnly = true }} {{- end }} {{- end -}} {{- /* Now render messages */ -}} {{- range $i, $msg := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if (ne $msg.Role "system") -}} {{- if eq $msg.Role "tool" -}} {{- if or (eq $msg.ToolName "python") (eq $msg.ToolName "browser.search") (eq $msg.ToolName "browser.open") (eq $msg.ToolName "browser.find") -}} <|start|>{{ $msg.ToolName }} to=assistant<|message|>{{ $msg.Content }}<|end|> {{- else -}} <|start|>functions.{{ $msg.ToolName }} to=assistant<|message|>{{ $msg.Content }}<|end|> {{- end -}} {{- else if eq $msg.Role "assistant" -}} {{- if and $msg.Thinking (gt $i $lastUserIdx) -}}{{- /* Show thinking only after last user message */ -}} <|start|>assistant<|channel|>analysis<|message|>{{ $msg.Thinking }}{{- if not $prefillingThinkingOnly -}}<|end|>{{- end -}} {{- end -}} {{- if gt (len $msg.Content) 0 -}} <|start|>assistant<|channel|>final<|message|>{{ $msg.Content }}{{- if not $prefillingContent -}}<|end|>{{- end -}} {{- end -}} {{- if gt (len $msg.ToolCalls) 0 -}} {{- range $j, $toolCall := $msg.ToolCalls -}} {{- $isBuiltin := or (eq $toolCall.Function.Name "python") (eq $toolCall.Function.Name "browser.search") (eq $toolCall.Function.Name "browser.open") (eq $toolCall.Function.Name "browser.find") -}} <|start|>assistant<|channel|>{{ if $isBuiltin }}analysis{{ else }}commentary{{ end }} to={{ if not $isBuiltin}}functions.{{end}}{{ $toolCall.Function.Name }} <|constrain|>json<|message|>{{ $toolCall.Function.Arguments }}<|call|> {{- end -}} {{- end -}} {{- else if eq $msg.Role "user" -}} <|start|>{{ $msg.Role }}<|message|>{{ $msg.Content }}<|end|> {{- end }} {{- else }} {{- end }} {{- end -}} {{- if not (or $prefillingContent $prefillingThinkingOnly) -}} <|start|>assistant {{- end -}}""" PARAMETER temperature 1.0 PARAMETER top_k 0 PARAMETER top_p 1.0 ''' OLLAMA_TEMPLATES["gpt-oss"] = gptoss_ollama OLLAMA_TEMPLATES["gptoss"] = gptoss_ollama # =========================================== Qwen3 # Ollama from https://ollama.com/library/qwen3/blobs/53e4ea15e8f5 qwen3_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """ {{- $lastUserIdx := -1 -}} {{- range $idx, $msg := .Messages -}} {{- if eq $msg.Role "user" }}{{ $lastUserIdx = $idx }}{{ end -}} {{- end }} {{- if or .System .Tools }}<|im_start|>system {{ if .System }} {{ .System }} {{- end }} {{- if .Tools }} # Tools You may call one or more functions to assist with the user query. You are provided with function signatures within <tools></tools> XML tags: <tools> {{- range .Tools }} {"type": "function", "function": {{ .Function }}} {{- end }} </tools> For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags: <tool_call> {"name": <function-name>, "arguments": <args-json-object>} </tool_call> {{- end -}} <|im_end|> {{ end }} {{- range $i, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $i)) 1 -}} {{- if eq .Role "user" }}<|im_start|>user {{ .Content }}<|im_end|> {{ else if eq .Role "assistant" }}<|im_start|>assistant {{ if (and $.IsThinkSet (and .Thinking (or $last (gt $i $lastUserIdx)))) -}} <think>{{ .Thinking }}</think> {{ end -}} {{ if .Content }}{{ .Content }} {{- else if .ToolCalls }}<tool_call> {{ range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{ end }}</tool_call> {{- end }}{{ if not $last }}<|im_end|> {{ end }} {{- else if eq .Role "tool" }}<|im_start|>user <tool_response> {{ .Content }} </tool_response><|im_end|> {{ end }} {{- if and (ne .Role "assistant") $last }}<|im_start|>assistant {{ end }} {{- end }} """ ''' OLLAMA_TEMPLATES["qwen3-instruct"] = qwen3_ollama OLLAMA_TEMPLATES["qwen3-thinking"] = qwen3_ollama # =========================================== Starling-LM # Ollama from https://ollama.com/library/starling-lm:7b/blobs/4b21bfc435b4 starling_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}GPT4 Correct System: {{ .System }}<|end_of_turn|> {{ end }}{{ if .Prompt }}GPT4 Correct User: {{ .Prompt }}<|end_of_turn|> {{ end }}GPT4 Correct Assistant: {{ .Response }}<|end_of_turn|>""" PARAMETER stop "<|end_of_turn|>" PARAMETER stop "GPT4 Correct User:" PARAMETER stop "GPT4 Correct Assistant:" PARAMETER stop "GPT4 Correct System:" PARAMETER temperature 1.5 PARAMETER min_p 0.1 ''' OLLAMA_TEMPLATES["starling"] = starling_ollama # =========================================== Yi-chat # Ollama from https://ollama.com/library/yi:34b-chat/blobs/62fbfd9ed093 yi_chat_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{ if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}{{ if .Prompt }}<|im_start|>user {{ .Prompt }}<|im_end|> {{ end }}<|im_start|>assistant {{ .Response }}<|im_end|>""" ''' OLLAMA_TEMPLATES["yi-chat"] = yi_chat_ollama # =========================================== Granite # Ollama from https://ollama.com/library/granite3.2:latest/blobs/3e7ca51acd6e granite_32_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- /* ------ MESSAGE PARSING ------ */}} {{- /* Declare the prompt structure variables to be filled in from messages */}} {{- $system := "" }} {{- $documents := "" }} {{- $documentCounter := 0 }} {{- $thinking := false }} {{- $citations := false }} {{- $hallucinations := false }} {{- $length := "" }} {{- /* Loop over messages and look for a user-provided system message and documents */ -}} {{- range .Messages }} {{- /* User defined system prompt(s) */}} {{- if (eq .Role "system")}} {{- if (ne $system "") }} {{- $system = print $system " " }} {{- end}} {{- $system = print $system .Content }} {{- end}} {{- /* NOTE: Since Ollama collates consecutive roles, for control and documents, we work around this by allowing the role to contain a qualifier after the role string. */ -}} {{- /* Role specified thinking */ -}} {{- if (and (ge (len .Role) 7) (eq (slice .Role 0 7) "control")) }} {{- if (eq .Content "thinking")}}{{- $thinking = true }}{{- end}} {{- if (eq .Content "citations")}}{{- $citations = true }}{{- end}} {{- if (eq .Content "hallucinations")}}{{- $hallucinations = true }}{{- end}} {{- if (and (ge (len .Content) 7) (eq (slice .Content 0 7) "length "))}} {{- $length = print ` {"length": "` (slice .Content 7) `"}` }} {{- end}} {{- end}} {{- /* Role specified document */ -}} {{- if (and (ge (len .Role) 8) (eq (slice .Role 0 8) "document")) }} {{- if (ne $documentCounter 0)}} {{- $documents = print $documents " "}} {{- end}} {{- $identifier := $documentCounter}} {{- if (ge (len .Role) 9) }} {{- $identifier = (slice .Role 8)}} {{- end}} {{- $documents = print $documents "Document " $identifier "" .Content}} {{- $documentCounter = len (printf "a%*s" $documentCounter "")}} {{- end}} {{- end}} {{- /* If no user message provided, build the default system message */ -}} {{- if eq $system "" }} {{- $system = "Knowledge Cutoff Date: April 2024.You are Granite, developed by IBM."}} {{- /* Add Tools prompt */}} {{- if .Tools }} {{- $system = print $system " You are a helpful AI assistant with access to the following tools. When a tool is required to answer the user's query, respond with <|tool_call|> followed by a JSON list of tools used. If a tool does not exist in the provided list of tools, notify the user that you do not have the ability to fulfill the request." }} {{- end}} {{- /* Add documents prompt */}} {{- if $documents }} {{- if .Tools }} {{- $system = print $system " "}} {{- else }} {{- $system = print $system " "}} {{- end}} {{- $system = print $system "Write the response to the user's input by strictly aligning with the facts in the provided documents. If the information needed to answer the question is not available in the documents, inform the user that the question cannot be answered based on the available data." }} {{- if $citations}} {{- $system = print $system " In your response, use the symbols <co> and </co> to indicate when a fact comes from a document in the search result, e.g <co>0</co> for a fact from document 0. Afterwards, list all the citations with their corresponding documents in an ordered list."}} {{- end}} {{- if $hallucinations}} {{- $system = print $system "Finally, after the response is written, include a numbered list of sentences from the response that are potentially hallucinated and not based in the documents."}} {{- end}} {{- end}} {{- /* Prompt without tools or documents */}} {{- if (and (not .Tools) (not $documents)) }} {{- $system = print $system " You are a helpful AI assistant."}} {{- if $thinking}} {{- $system = print $system "Respond to every user query in a comprehensive and detailed way. You can write down your thought process before responding. Write your thoughts after 'Here is my thought process:' and write your response after 'Here is my response:' for each user query."}} {{- end}} {{- end}} {{- /* Add thinking prompt if no tools or documents */}} {{- if (and $thinking (not .Tools) (not $documents)) }} {{- $system = print $system " You are a helpful AI assistant.Respond to every user query in a comprehensive and detailed way. You can write down your thought process before responding. Write your thoughts after 'Here is my thought process:' and write your response after 'Here is my response:' for each user query."}} {{- end}} {{- end}} {{- /* ------ TEMPLATE EXPANSION ------ */}} {{- /* System Prompt */ -}} <|start_of_role|>system<|end_of_role|>{{- $system }}<|end_of_text|> {{- /* Tools */ -}} {{- if .Tools }} <|start_of_role|>tools<|end_of_role|>[ {{- range $index, $_ := .Tools }} {{ . }} {{- if and (ne (len (slice $.Tools $index)) 1) (gt (len $.Tools) 1) }}, {{- end}} {{- end }} ] {{- end}} {{- /* Documents */ -}} {{- if $documents }} <|start_of_role|>documents<|end_of_role|> {{ $documents }}<|end_of_text|> {{- end}} {{- /* Standard Messages */}} {{- range $index, $_ := .Messages }} {{- if (and (ne .Role "system") (or (lt (len .Role) 7) (ne (slice .Role 0 7) "control")) (or (lt (len .Role) 8) (ne (slice .Role 0 8) "document")) )}} <|start_of_role|> {{- if eq .Role "tool" }}tool_response {{- else }}{{ .Role }} {{- end }}<|end_of_role|> {{- if .Content }}{{ .Content }} {{- else if .ToolCalls }}<|tool_call|> {{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}} {{- end }} {{- end }} {{- if eq (len (slice $.Messages $index)) 1 }} {{- if eq .Role "assistant" }} {{- else }}<|end_of_text|> <|start_of_role|>assistant<|end_of_role|> {{- end -}} {{- else }}<|end_of_text|> {{- end }} {{- end }} {{- end }} """ ''' # granite-3.2-vision https://ollama.com/library/granite3.2-vision:latest/blobs/579046ba1157 granite_32_vision_ollama = ''' FROM {__FILE_LOCATION__} TEMPLATE """{{- /* Tools */ -}} {{- if .Tools -}} <|start_of_role|>available_tools<|end_of_role|> {{- range $index, $_ := .Tools }} {{- $last := eq (len (slice $.Tools $index)) 1 }} {{ . }} {{- if not $last }} {{ end}} {{- end -}} <|end_of_text|> {{ end }} {{- /* System Prompt */ -}} {{- if and (gt (len .Messages) 0) (eq (index .Messages 0).Role "system") -}} <|system|> {{(index .Messages 0).Content}} {{- else -}} <|system|> A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. {{- end }} {{- /*Main message loop*/ -}} {{- range $index, $_ := .Messages }} {{- $last := eq (len (slice $.Messages $index)) 1 }} {{- if eq .Role "system" }} {{- else if eq .Role "user" }} <|user|> {{.Content}} {{- else if eq .Role "assistant" }} <|assistant|> {{- if .Content }} {{.Content}} <|end_of_text|> {{ end }} {{- else if eq .Role "assistant_tool_call" }} <|start_of_role|>assistant<|end_of_role|><|tool_call|>{{.Content}}<|end_of_text|> {{- else if eq .Role "tool_response" }} <|start_of_role|>tool_response<|end_of_role|>{{.Content}}<|end_of_text|> {{- end }} {{- /* Add generation prompt */ -}} {{ if $last }} {{- if eq .Role "assistant" }} {{- else }} <|assistant|> {{- end }} {{- end }} {{- end }}""" PARAMETER num_ctx 16384 PARAMETER temperature 0 SYSTEM """A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.""" ''' OLLAMA_TEMPLATES["granite-32"] = granite_32_ollama OLLAMA_TEMPLATES["granite-32-vision"] = granite_32_vision_ollama OLLAMA_TEMPLATE_TO_MODEL_MAPPER = { "phi-3.5": ( "unsloth/Phi-3.5-mini-instruct-bnb-4bit", "unsloth/Phi-3.5-mini-instruct", "microsoft/Phi-3.5-mini-instruct", ), "phi-3": ( "unsloth/Phi-3-mini-4k-instruct-bnb-4bit", "unsloth/Phi-3-mini-4k-instruct", "microsoft/Phi-3-mini-4k-instruct", "unsloth/Phi-3-medium-4k-instruct-bnb-4bit", "unsloth/Phi-3-medium-4k-instruct", "microsoft/Phi-3-medium-4k-instruct", "unsloth/Phi-3-mini-4k-instruct-v0-bnb-4bit", "unsloth/Phi-3-mini-4k-instruct-v0", ), "phi-4": ( "unsloth/phi-4-unsloth-bnb-4bit", "unsloth/phi-4", "microsoft/phi-4", "unsloth/phi-4-bnb-4bit", ), "phi-4-reasoning": ( "unsloth/phi-4-reasoning-unsloth-bnb-4bit", "unsloth/phi-4-reasoning", "microsoft/Phi-4-reasoning", "unsloth/phi-4-reasoning-bnb-4bit", "unsloth/phi-4-reasoning-plus-unsloth-bnb-4bit", "unsloth/phi-4-reasoning-plus", "microsoft/Phi-4-reasoning-plus", "unsloth/phi-4-reasoning-plus-bnb-4bit", ), "phi-4-mini": ( "unsloth/Phi-4-mini-instruct-unsloth-bnb-4bit", "unsloth/Phi-4-mini-instruct", "microsoft/Phi-4-mini-instruct", "unsloth/Phi-4-mini-instruct-bnb-4bit", ), "phi-4-mini-reasoning": ( "unsloth/phi-4-mini-reasoning-unsloth-bnb-4bit", "unsloth/phi-4-mini-reasoning", "microsoft/Phi-4-mini-reasoning", "unsloth/phi-4-mini-reasoning-bnb-4bit", ), "mistral": ( "unsloth/mistral-7b-instruct-v0.1-bnb-4bit", "unsloth/mistral-7b-instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", "unsloth/mistral-7b-instruct-v0.2-bnb-4bit", "unsloth/mistral-7b-instruct-v0.2", "mistralai/Mistral-7B-Instruct-v0.2", ), "mistral-v03": ( "unsloth/mistral-7b-instruct-v0.3-bnb-4bit", "unsloth/mistral-7b-instruct-v0.3", "mistralai/Mistral-7B-Instruct-v0.3", "unsloth/Mistral-Large-Instruct-2407-bnb-4bit", "mistralai/Mistral-Large-Instruct-2407", ), "mistral-small": ( "unsloth/Mistral-Small-Instruct-2409-bnb-4bit", "unsloth/Mistral-Small-Instruct-2409", "mistralai/Mistral-Small-Instruct-2409", "unsloth/Mistral-Small-24B-Instruct-2501-unsloth-bnb-4bit", "unsloth/Mistral-Small-24B-Instruct-2501", "mistralai/Mistral-Small-24B-Instruct-2501", "unsloth/Mistral-Small-24B-Instruct-2501-bnb-4bit", ), "mistral-small-31": ( "unsloth/Mistral-Small-3.1-24B-Instruct-2503-unsloth-bnb-4bit", "unsloth/Mistral-Small-3.1-24B-Instruct-2503", "mistralai/Mistral-Small-3.1-24B-Instruct-2503", "unsloth/Mistral-Small-3.1-24B-Instruct-2503-bnb-4bit", ), "mistral-small-32": ( "unsloth/Mistral-Small-3.2-24B-Instruct-2506-unsloth-bnb-4bit", "unsloth/Mistral-Small-3.2-24B-Instruct-2506", "mistralai/Mistral-Small-3.2-24B-Instruct-2506", "unsloth/Mistral-Small-3.2-24B-Instruct-2506-bnb-4bit", ), "mixtral": ( "unsloth/Mixtral-8x7B-Instruct-v0.1-unsloth-bnb-4bit", "unsloth/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mixtral-8x7B-Instruct-v0.1", "unsloth/Mixtral-8x7B-Instruct-v0.1-bnb-4bit", ), "mistral-nemo": ( "unsloth/Mistral-Nemo-Instruct-2407-bnb-4bit", "unsloth/Mistral-Nemo-Instruct-2407", "mistralai/Mistral-Nemo-Instruct-2407", ), "codestral": ( "mistralai/Codestral-22B-v0.1", "mistral-community/Codestral-22B-v0.1", ), "devstral": ( "unsloth/Devstral-Small-2505-unsloth-bnb-4bit", "unsloth/Devstral-Small-2505", "mistralai/Devstral-Small-2505", "unsloth/Devstral-Small-2505-bnb-4bit", "unsloth/Devstral-Small-2507-unsloth-bnb-4bit", "unsloth/Devstral-Small-2507", "mistralai/Devstral-Small-2507", "unsloth/Devstral-Small-2507-bnb-4bit", ), "magistral": ( "unsloth/Magistral-Small-2506-unsloth-bnb-4bit", "unsloth/Magistral-Small-2506", "mistralai/Magistral-Small-2506", "unsloth/Magistral-Small-2506-bnb-4bit", "unsloth/Magistral-Small-2507-unsloth-bnb-4bit", "unsloth/Magistral-Small-2507", "mistralai/Magistral-Small-2507", "unsloth/Magistral-Small-2507-bnb-4bit", "unsloth/Magistral-Small-2509-unsloth-bnb-4bit", "unsloth/Magistral-Small-2509", "mistralai/Magistral-Small-2509", "unsloth/Magistral-Small-2509-bnb-4bit", ), "tinyllama": ( "unsloth/tinyllama-chat-bnb-4bit", "unsloth/tinyllama-chat", "TinyLlama/TinyLlama-1.1B-Chat-v1.0", ), "llama": ( "unsloth/llama-2-7b-bnb-4bit", "unsloth/llama-2-7b", "meta-llama/Llama-2-7b-hf", "unsloth/llama-2-13b-bnb-4bit", "unsloth/llama-2-13b", "meta-llama/Llama-2-13b-hf", "unsloth/llama-2-7b-chat-bnb-4bit", "unsloth/llama-2-7b-chat", "meta-llama/Llama-2-7b-chat-hf", ), "llama3": ( "unsloth/llama-3-8b-Instruct-bnb-4bit", "unsloth/llama-3-8b-Instruct", "meta-llama/Meta-Llama-3-8B-Instruct", "unsloth/llama-3-70b-Instruct-bnb-4bit", "meta-llama/Meta-Llama-3-70B-Instruct", ), "llama-3.1": ( "unsloth/Meta-Llama-3.1-8B-Instruct-unsloth-bnb-4bit", "unsloth/Meta-Llama-3.1-8B-Instruct", "meta-llama/Meta-Llama-3.1-8B-Instruct", "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit", "unsloth/Llama-3.1-8B-Instruct-unsloth-bnb-4bit", "unsloth/Llama-3.1-8B-Instruct", "meta-llama/Llama-3.1-8B-Instruct", "unsloth/Llama-3.1-8B-Instruct-bnb-4bit", "unsloth/Meta-Llama-3.1-405B-Instruct-bnb-4bit", "meta-llama/Meta-Llama-3.1-405B-Instruct", "unsloth/Meta-Llama-3.1-70B-Instruct-bnb-4bit", "unsloth/Meta-Llama-3.1-70B-Instruct", "meta-llama/Meta-Llama-3.1-70B-Instruct", "unsloth/Hermes-3-Llama-3.1-8B-bnb-4bit", "unsloth/Hermes-3-Llama-3.1-8B", "NousResearch/Hermes-3-Llama-3.1-8B", "unsloth/Hermes-3-Llama-3.1-70B-bnb-4bit", "unsloth/Hermes-3-Llama-3.1-70B", "NousResearch/Hermes-3-Llama-3.1-70B", "unsloth/Hermes-3-Llama-3.1-405B-bnb-4bit", "NousResearch/Hermes-3-Llama-3.1-405B", "unsloth/Llama-3.1-Tulu-3-8B-bnb-4bit", "unsloth/Llama-3.1-Tulu-3-8B", "allenai/Llama-3.1-Tulu-3-8B", "unsloth/Llama-3.1-Tulu-3-70B-bnb-4bit", "unsloth/Llama-3.1-Tulu-3-70B", "allenai/Llama-3.1-Tulu-3-70B", ), "llama-31-storm": ( "unsloth/Llama-3.1-Storm-8B-bnb-4bit", "unsloth/Llama-3.1-Storm-8B", "akjindal53244/Llama-3.1-Storm-8B", ), "llama-31-nemotron": ( "unsloth/Llama-3.1-Nemotron-70B-Instruct-bnb-4bit", "unsloth/Llama-3.1-Nemotron-70B-Instruct", "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF", ), "llama-3.2": ( "unsloth/Llama-3.2-1B-Instruct-unsloth-bnb-4bit", "unsloth/Llama-3.2-1B-Instruct", "meta-llama/Llama-3.2-1B-Instruct", "unsloth/Llama-3.2-1B-Instruct-bnb-4bit", "unsloth/Llama-3.2-3B-Instruct-unsloth-bnb-4bit", "unsloth/Llama-3.2-3B-Instruct", "meta-llama/Llama-3.2-3B-Instruct", "unsloth/Llama-3.2-3B-Instruct-bnb-4bit", ), "llama-32-vision": ( "unsloth/Llama-3.2-11B-Vision-Instruct-unsloth-bnb-4bit", "unsloth/Llama-3.2-11B-Vision-Instruct", "meta-llama/Llama-3.2-11B-Vision-Instruct", "unsloth/Llama-3.2-11B-Vision-Instruct-bnb-4bit", "unsloth/Llama-3.2-90B-Vision-Instruct-bnb-4bit", "unsloth/Llama-3.2-90B-Vision-Instruct", "meta-llama/Llama-3.2-90B-Vision-Instruct", ), "llama-3.3": ( "unsloth/Llama-3.3-70B-Instruct-bnb-4bit", "unsloth/Llama-3.3-70B-Instruct", "meta-llama/Llama-3.3-70B-Instruct", ), "gemma": ( "unsloth/gemma-7b-it-bnb-4bit", "unsloth/gemma-7b-it", "google/gemma-7b-it", "google/gemma-2b-it", "unsloth/gemma-1.1-2b-it-bnb-4bit", "unsloth/gemma-1.1-2b-it", "google/gemma-1.1-2b-it", "unsloth/gemma-1.1-7b-it-bnb-4bit", "unsloth/gemma-1.1-7b-it", "google/gemma-1.1-7b-it", ), "gemma2": ( "unsloth/gemma-2-9b-it-bnb-4bit", "unsloth/gemma-2-9b-it", "google/gemma-2-9b-it", "unsloth/gemma-2-27b-it-bnb-4bit", "unsloth/gemma-2-27b-it", "google/gemma-2-27b-it", "unsloth/gemma-2-2b-it-bnb-4bit", "unsloth/gemma-2-2b-it", "google/gemma-2-2b-it", ), "gemma-3": ( "unsloth/gemma-3-1b-it-unsloth-bnb-4bit", "unsloth/gemma-3-1b-it", "google/gemma-3-1b-it", "unsloth/gemma-3-1b-it-bnb-4bit", "unsloth/gemma-3-4b-it-unsloth-bnb-4bit", "unsloth/gemma-3-4b-it", "google/gemma-3-4b-it", "unsloth/gemma-3-4b-it-bnb-4bit", "unsloth/gemma-3-12b-it-unsloth-bnb-4bit", "unsloth/gemma-3-12b-it", "google/gemma-3-12b-it", "unsloth/gemma-3-12b-it-bnb-4bit", "unsloth/gemma-3-27b-it-unsloth-bnb-4bit", "unsloth/gemma-3-27b-it", "google/gemma-3-27b-it", "unsloth/gemma-3-27b-it-bnb-4bit", "unsloth/medgemma-4b-it-unsloth-bnb-4bit", "unsloth/medgemma-4b-it", "google/medgemma-4b-it", "unsloth/medgemma-4b-it-bnb-4bit", "unsloth/medgemma-27b-text-it-unsloth-bnb-4bit", "unsloth/medgemma-27b-text-it", "google/medgemma-27b-text-it", "unsloth/medgemma-27b-text-it-bnb-4bit", ), "gemma3n": ( "unsloth/gemma-3n-E4B-it-unsloth-bnb-4bit", "unsloth/gemma-3n-E4B-it", "google/gemma-3n-E4B-it", "unsloth/gemma-3n-E4B-it-unsloth-bnb-4bit", "unsloth/gemma-3n-E2B-it-unsloth-bnb-4bit", "unsloth/gemma-3n-E2B-it", "google/gemma-3n-E2B-it", "unsloth/gemma-3n-E2B-it-unsloth-bnb-4bit", ), "gemma3-270m": ( "unsloth/gemma-3-270m-it-unsloth-bnb-4bit", "unsloth/gemma-3-270m-it", "google/gemma-3-270m-it", "unsloth/gemma-3-270m-it-bnb-4bit", ), "qwen-25": ( "unsloth/Qwen2.5-0.5B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-0.5B-Instruct", "Qwen/Qwen2.5-0.5B-Instruct", "unsloth/Qwen2.5-0.5B-Instruct-bnb-4bit", "unsloth/Qwen2.5-1.5B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-1.5B-Instruct", "Qwen/Qwen2.5-1.5B-Instruct", "unsloth/Qwen2.5-1.5B-Instruct-bnb-4bit", "unsloth/Qwen2.5-3B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-3B-Instruct", "Qwen/Qwen2.5-3B-Instruct", "unsloth/Qwen2.5-3B-Instruct-bnb-4bit", "unsloth/Qwen2.5-7B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-7B-Instruct", "Qwen/Qwen2.5-7B-Instruct", "unsloth/Qwen2.5-7B-Instruct-bnb-4bit", "unsloth/Qwen2.5-14B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-14B-Instruct", "Qwen/Qwen2.5-14B-Instruct", "unsloth/Qwen2.5-14B-Instruct-bnb-4bit", "unsloth/Qwen2.5-32B-Instruct-bnb-4bit", "unsloth/Qwen2.5-32B-Instruct", "Qwen/Qwen2.5-32B-Instruct", "unsloth/Qwen2.5-72B-Instruct-bnb-4bit", "unsloth/Qwen2.5-72B-Instruct", "Qwen/Qwen2.5-72B-Instruct", "unsloth/Qwen2.5-Math-1.5B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Math-1.5B-Instruct", "Qwen/Qwen2.5-Math-1.5B-Instruct", "unsloth/Qwen2.5-Math-7B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Math-7B-Instruct", "Qwen/Qwen2.5-Math-7B-Instruct", "unsloth/Qwen2.5-Math-72B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Math-72B-Instruct", "Qwen/Qwen2.5-Math-72B-Instruct", ), "qwen-25-coder": ( "unsloth/Qwen2.5-Coder-0.5B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Coder-0.5B-Instruct", "Qwen/Qwen2.5-Coder-0.5B-Instruct", "unsloth/Qwen2.5-Coder-1.5B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Coder-1.5B-Instruct", "Qwen/Qwen2.5-Coder-1.5B-Instruct", "unsloth/Qwen2.5-Coder-3B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Coder-3B-Instruct", "Qwen/Qwen2.5-Coder-3B-Instruct", "unsloth/Qwen2.5-Coder-7B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Coder-7B-Instruct", "Qwen/Qwen2.5-Coder-7B-Instruct", "unsloth/Qwen2.5-Coder-14B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Coder-14B-Instruct", "Qwen/Qwen2.5-Coder-14B-Instruct", "unsloth/Qwen2.5-Coder-32B-Instruct-bnb-4bit", "unsloth/Qwen2.5-Coder-32B-Instruct", "Qwen/Qwen2.5-Coder-32B-Instruct", ), "qwen-25-vl": ( "unsloth/Qwen2.5-VL-3B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-VL-3B-Instruct", "Qwen/Qwen2.5-VL-3B-Instruct", "unsloth/Qwen2.5-VL-3B-Instruct-bnb-4bit", "unsloth/Qwen2.5-VL-7B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-VL-7B-Instruct", "Qwen/Qwen2.5-VL-7B-Instruct", "unsloth/Qwen2.5-VL-7B-Instruct-bnb-4bit", "unsloth/Qwen2.5-VL-32B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-VL-32B-Instruct", "Qwen/Qwen2.5-VL-32B-Instruct", "unsloth/Qwen2.5-VL-32B-Instruct-bnb-4bit", "unsloth/Qwen2.5-VL-72B-Instruct-unsloth-bnb-4bit", "unsloth/Qwen2.5-VL-72B-Instruct", "Qwen/Qwen2.5-VL-72B-Instruct", "unsloth/Qwen2.5-VL-72B-Instruct-bnb-4bit", ), "openthinker": ( "unsloth/OpenThinker-7B-unsloth-bnb-4bit", "unsloth/OpenThinker-7B", "open-thoughts/OpenThinker-7B", "unsloth/OpenThinker-7B-bnb-4bit", ), "qwen-2": ( "unsloth/Qwen2-0.5B-Instruct-bnb-4bit", "unsloth/Qwen2-0.5B-Instruct", "Qwen/Qwen2-0.5B-Instruct", "unsloth/Qwen2-1.5B-Instruct-bnb-4bit", "unsloth/Qwen2-1.5B-Instruct", "Qwen/Qwen2-1.5B-Instruct", "unsloth/Qwen2-7B-Instruct-bnb-4bit", "unsloth/Qwen2-7B-Instruct", "Qwen/Qwen2-7B-Instruct", "unsloth/Qwen2-70B-Instruct-bnb-4bit", "Qwen/Qwen2-70B-Instruct", ), "qwen3": ( "unsloth/Qwen3-0.6B-unsloth-bnb-4bit", "unsloth/Qwen3-0.6B", "Qwen/Qwen3-0.6B", "unsloth/Qwen3-0.6B-bnb-4bit", "unsloth/Qwen3-1.7B-unsloth-bnb-4bit", "unsloth/Qwen3-1.7B", "Qwen/Qwen3-1.7B", "unsloth/Qwen3-1.7B-bnb-4bit", "unsloth/Qwen3-4B-unsloth-bnb-4bit", "unsloth/Qwen3-4B", "Qwen/Qwen3-4B", "unsloth/Qwen3-4B-bnb-4bit", "unsloth/Qwen3-8B-unsloth-bnb-4bit", "unsloth/Qwen3-8B", "Qwen/Qwen3-8B", "unsloth/Qwen3-8B-bnb-4bit", "unsloth/Qwen3-14B-unsloth-bnb-4bit", "unsloth/Qwen3-14B", "Qwen/Qwen3-14B", "unsloth/Qwen3-14B-bnb-4bit", "unsloth/Qwen3-32B-unsloth-bnb-4bit", "unsloth/Qwen3-32B", "Qwen/Qwen3-32B", "unsloth/Qwen3-32B-bnb-4bit", "unsloth/Qwen3-30B-A3B-unsloth-bnb-4bit", "unsloth/Qwen3-30B-A3B", "Qwen/Qwen3-30B-A3B", "unsloth/Qwen3-30B-A3B-bnb-4bit", ), "qwen3-instruct": ( "unsloth/Qwen3-4B-Instruct-2507-unsloth-bnb-4bit", "unsloth/Qwen3-4B-Instruct-2507", "Qwen/Qwen3-4B-Instruct-2507", "unsloth/Qwen3-4B-Instruct-2507-bnb-4bit", "unsloth/Qwen3-30B-A3B-Instruct-2507", "Qwen/Qwen3-30B-A3B-Instruct-2507", "unsloth/Qwen3-Coder-30B-A3B-Instruct", "Qwen/Qwen3-Coder-30B-A3B-Instruct", "unsloth/Qwen3-4B-Instruct-2507-unsloth-bnb-4bit", "unsloth/Qwen3-4B-Instruct-2507", "Qwen/Qwen3-4B-Instruct-2507", "unsloth/Qwen3-4B-Instruct-2507-bnb-4bit", ), "qwen3-thinking": ( "unsloth/QwQ-32B-Preview-bnb-4bit", "unsloth/QwQ-32B-Preview", "Qwen/QwQ-32B-Preview", "unsloth/QwQ-32B-unsloth-bnb-4bit", "unsloth/QwQ-32B", "Qwen/QwQ-32B", "unsloth/QwQ-32B-bnb-4bit", "unsloth/Qwen3-4B-Thinking-2507-unsloth-bnb-4bit", "unsloth/Qwen3-4B-Thinking-2507", "Qwen/Qwen3-4B-Thinking-2507", "unsloth/Qwen3-4B-Thinking-2507-bnb-4bit", "unsloth/Qwen3-30B-A3B-Thinking-2507", "Qwen/Qwen3-30B-A3B-Thinking-2507", ), "zephyr": ( "unsloth/zephyr-sft-bnb-4bit", "unsloth/zephyr-sft", "HuggingFaceH4/mistral-7b-sft-beta", ), "chatml": ( "unsloth/Hermes-2-Pro-Mistral-7B-bnb-4bit", "unsloth/Hermes-2-Pro-Mistral-7B", "NousResearch/Hermes-2-Pro-Mistral-7B", "unsloth/OpenHermes-2.5-Mistral-7B-bnb-4bit", "unsloth/OpenHermes-2.5-Mistral-7B", "teknium/OpenHermes-2.5-Mistral-7B", ), "gpt-oss": ( "unsloth/gpt-oss-20b-unsloth-bnb-4bit", "unsloth/gpt-oss-20b", "openai/gpt-oss-20b", "unsloth/gpt-oss-20b-unsloth-bnb-4bit", "unsloth/gpt-oss-120b-unsloth-bnb-4bit", "unsloth/gpt-oss-120b", "openai/gpt-oss-120b", "unsloth/gpt-oss-120b-unsloth-bnb-4bit", ), "starling": ( "unsloth/Starling-LM-7B-beta-bnb-4bit", "unsloth/Starling-LM-7B-beta", "Nexusflow/Starling-LM-7B-beta", ), "yi-chat": ( "unsloth/yi-34b-chat-bnb-4bit", "01-ai/Yi-6B-Chat", "01-ai/Yi-34B-Chat", ), "granite-32": ( "unsloth/granite-3.2-2b-instruct-unsloth-bnb-4bit", "unsloth/granite-3.2-2b-instruct", "ibm-granite/granite-3.2-2b-instruct", "unsloth/granite-3.2-2b-instruct-bnb-4bit", "unsloth/granite-3.2-8b-instruct-unsloth-bnb-4bit", "unsloth/granite-3.2-8b-instruct", "ibm-granite/granite-3.2-8b-instruct", "unsloth/granite-3.2-8b-instruct-bnb-4bit", ), "granite-32-vision": ( "unsloth/granite-vision-3.2-2b-unsloth-bnb-4bit", "unsloth/granite-vision-3.2-2b", "ibm-granite/granite-vision-3.2-2b", "unsloth/granite-vision-3.2-2b-bnb-4bit", ), } MODEL_TO_OLLAMA_TEMPLATE_MAPPER = {} for key, values in OLLAMA_TEMPLATE_TO_MODEL_MAPPER.items(): for value in values: MODEL_TO_OLLAMA_TEMPLATE_MAPPER[value] = key # Get lowercased lowered_key = key.lower() for value in values: MODEL_TO_OLLAMA_TEMPLATE_MAPPER[value.lower()] = lowered_key
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/ollama_template_mappers.py", "license": "Apache License 2.0", "lines": 1958, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:tests/utils/test_qat.py
from unsloth import FastLanguageModel from typing import Dict import pytest import torch try: from torchao.quantization.qat import FakeQuantizedLinear from torchao.quantization.qat.fake_quantizer import ( FakeQuantizerBase, Float8FakeQuantizer, Int4WeightFakeQuantizer, IntxFakeQuantizer, ) except ImportError: print( "Missing torchao import, please install or upgrade torchao with: pip install 'torchao>=0.15.0'" ) class _CountingFakeQuantizer(torch.nn.Module): """ Dummy fake quantizer that counts the number of times it has been called. """ def __init__(self): super().__init__() self.count = 0 def forward(self, x: torch.Tensor) -> torch.Tensor: self.count += 1 return x def _get_model(qat_scheme: str, full_finetuning: bool): """ Return a 2-tuple of (model, tokenizer), where the model has been configured to use QAT. If `full_finetuning` is False, return the PEFT (LoRA) model. """ model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Qwen3-1.7B", load_in_4bit = False, full_finetuning = full_finetuning, qat_scheme = qat_scheme if full_finetuning else None, ) if not full_finetuning: model = FastLanguageModel.get_peft_model( model, qat_scheme = qat_scheme, ) return model, tokenizer def _test_linear_is_fake_quantized(linear: torch.nn.Linear, qat_scheme: str): """ Verify that the given linear contains fake quantizers according to the `qat_scheme`. """ weight_only = False if qat_scheme == "fp8-int4": act_fq_class = Float8FakeQuantizer weight_fq_class = Int4WeightFakeQuantizer min_in_features = 128 elif qat_scheme == "fp8-fp8": act_fq_class = Float8FakeQuantizer weight_fq_class = Float8FakeQuantizer min_in_features = -1 elif qat_scheme == "int8": act_fq_class = None weight_fq_class = IntxFakeQuantizer min_in_features = 128 weight_only = True else: raise ValueError(f"Unknown qat_scheme: {qat_scheme}") # Check base layer activations and weights base_layer = getattr(linear, "base_layer", linear) if base_layer.in_features >= min_in_features: assert isinstance(base_layer, FakeQuantizedLinear) if not weight_only: assert isinstance(base_layer.activation_fake_quantizer, act_fq_class) assert isinstance(base_layer.weight_fake_quantizer, weight_fq_class) # Check lora A and B (only for full_finetuning=False) if hasattr(linear, "lora_A") and hasattr(linear, "lora_B"): lora_A = linear.lora_A.default lora_B = linear.lora_B.default if lora_A.in_features >= min_in_features: assert isinstance(lora_A, FakeQuantizedLinear) if not weight_only: assert isinstance(lora_A.activation_fake_quantizer, act_fq_class) assert isinstance(lora_A.weight_fake_quantizer, weight_fq_class) if lora_B.in_features >= min_in_features: assert isinstance(lora_B, FakeQuantizedLinear) if not weight_only: assert isinstance(lora_B.activation_fake_quantizer, act_fq_class) assert isinstance(lora_B.weight_fake_quantizer, weight_fq_class) def _test_fake_quantizers_are_called( model: torch.nn.Module, example_inputs: Dict, full_finetuning: bool, qat_scheme: str, ): """ Verify that the fake quantizers are actually called when the model is called. """ weight_only = qat_scheme == "int8" def _swap_fake_quantizers(model: torch.nn.Module): for name, child in model.named_children(): if isinstance(child, FakeQuantizerBase): setattr(model, name, _CountingFakeQuantizer()) def _assert_fake_quantizers_are_called(model: torch.nn.Module): for name, child in model.named_children(): if full_finetuning: if isinstance(child, FakeQuantizedLinear): if not weight_only: assert child.activation_fake_quantizer.count == 1 assert child.weight_fake_quantizer.count == 1 else: # For LoRA, we only fake quantize the input activations once per block: # For self_attn, we only fake quantize the q_proj's input activations # For mlp, we only fake quantize the gate_proj's input activations if name == "self_attn": base_layer = child.q_proj.base_layer if not weight_only: assert hasattr(base_layer, "activation_fake_quantizer") assert base_layer.activation_fake_quantizer.count == 1 elif name == "mlp": base_layer = child.gate_proj.base_layer if not weight_only: assert hasattr(base_layer, "activation_fake_quantizer") assert base_layer.activation_fake_quantizer.count == 1 elif isinstance(child, FakeQuantizedLinear): # Weight fake quantizers should always be called assert child.weight_fake_quantizer.count == 1 for k, v in example_inputs.items(): example_inputs[k] = v.cuda() model.apply(_swap_fake_quantizers) model(**example_inputs) model.apply(_assert_fake_quantizers_are_called) def _test_model_fake_quantize(qat_scheme: str, full_finetuning: bool): """ Test that all linear layers in the model are fake quantized according to the `qat_scheme`. """ model, tokenizer = _get_model(qat_scheme, full_finetuning) if full_finetuning: model = model.model else: model = model.base_model.model.model for layer in model.layers: _test_linear_is_fake_quantized(layer.self_attn.q_proj, qat_scheme) _test_linear_is_fake_quantized(layer.self_attn.k_proj, qat_scheme) _test_linear_is_fake_quantized(layer.self_attn.v_proj, qat_scheme) _test_linear_is_fake_quantized(layer.mlp.gate_proj, qat_scheme) _test_linear_is_fake_quantized(layer.mlp.up_proj, qat_scheme) _test_linear_is_fake_quantized(layer.mlp.down_proj, qat_scheme) inputs = tokenizer("How are you?", return_tensors = "pt") _test_fake_quantizers_are_called(model, inputs, full_finetuning, qat_scheme) # TODO: there are bad interactions across tests right now, need to figure out # how to disable model caching before re-enabling this test @pytest.mark.parametrize("qat_scheme", ["fp8-int4", "fp8-fp8", "int8"]) def _test_full_model_fake_quantize(qat_scheme: str): _test_model_fake_quantize(qat_scheme, full_finetuning = True) @pytest.mark.parametrize("qat_scheme", ["fp8-int4", "fp8-fp8", "int8"]) def test_lora_model_fake_quantize(qat_scheme: str): _test_model_fake_quantize(qat_scheme, full_finetuning = False)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/test_qat.py", "license": "Apache License 2.0", "lines": 153, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/gpt-oss-merge/test_merged_model.py
# inference_on_merged.py from unsloth import FastLanguageModel from transformers import TextStreamer import torch import gc import os import shutil def safe_remove_directory(path): try: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) return True else: print(f"Path {path} is not a valid directory") return False except Exception as e: print(f"Failed to remove directory {path}: {e}") return False print("🔥 Loading the 16-bit merged model from disk...") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./gpt-oss-finetuned-merged", max_seq_length = 1024, load_in_4bit = True, load_in_8bit = False, ) print("✅ Merged model loaded successfully.") # --- Run Inference --- print("\n🚀 Running inference...") messages = [ {"role": "user", "content": "Solve x^5 + 3x^4 - 10 = 3."}, ] inputs = merged_tokenizer.apply_chat_template( messages, add_generation_prompt = True, return_tensors = "pt", return_dict = True, reasoning_effort = "low", # **NEW!** Set reasoning effort to low, medium or high ).to(merged_model.device) _ = merged_model.generate( **inputs, max_new_tokens = 512, streamer = TextStreamer(merged_tokenizer) ) print("\n✅ Inference complete.") # --- Final Cleanup --- print("\n🧹 Cleaning up merged model directory and cache...") del merged_model, merged_tokenizer torch.cuda.empty_cache() gc.collect() safe_remove_directory("./gpt-oss-finetuned-merged") safe_remove_directory( "./unsloth_compiled_cache" ) # Clean up cache created by this process print("✅ Final cleanup complete. Exiting inference script.")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/gpt-oss-merge/test_merged_model.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/gpt-oss-merge/train_and_merge.py
# train_and_merge.py from unsloth import FastLanguageModel from trl import SFTTrainer, SFTConfig from datasets import load_dataset import torch import gc import os import shutil def safe_remove_directory(path): try: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) return True else: print(f"Path {path} is not a valid directory") return False except Exception as e: print(f"Failed to remove directory {path}: {e}") return False # This tokenizer will be used by the mapping function tokenizer = None def formatting_prompts_func(examples): convos = examples["messages"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} # --- Load 4-bit Model and Train --- print("Loading 4-bit Mxfp4 gpt-oss model for training...") max_seq_length = 1024 model, tokenizer = FastLanguageModel.from_pretrained( "unsloth/gpt-oss-20b", max_seq_length = max_seq_length, load_in_4bit = True ) dataset = load_dataset("HuggingFaceH4/Multilingual-Thinking", split = "train[:50]").map( formatting_prompts_func, batched = True ) model = FastLanguageModel.get_peft_model( model, r = 8, target_modules = [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", ], lora_alpha = 16, use_gradient_checkpointing = "unsloth", random_state = 3407, ) trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset, args = SFTConfig( per_device_train_batch_size = 1, gradient_accumulation_steps = 4, max_steps = 10, learning_rate = 2e-4, output_dir = "outputs", report_to = "none", ), ) print("Starting fine-tuning...") trainer.train() print("Fine-tuning complete.") # --- Merge and Save --- print("\n💾 Merging and saving the 16-bit model to './gpt-oss-finetuned-merged'...") model.save_pretrained_merged( save_directory = "./gpt-oss-finetuned-merged", tokenizer = tokenizer ) print("✅ Model merged and saved.") # --- Cleanup --- print("\n🧹 Cleaning up training artifacts...") del model, trainer, tokenizer, dataset torch.cuda.empty_cache() gc.collect() safe_remove_directory("./outputs") safe_remove_directory( "./unsloth_compiled_cache" ) # Clean up the cache created by this process print("✅ Cleanup complete. Exiting training script.")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/gpt-oss-merge/train_and_merge.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_merge_4bit_validation.py
from unsloth import FastLanguageModel from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import DataCollatorForSeq2Seq, TrainingArguments from datasets import load_dataset import torch import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory def formatting_prompts_func(examples): convos = examples["messages"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} print(f"\n{'='*80}") print("🔍 PHASE 1: Loading Base Model and Initial Training") print(f"{'='*80}") if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Llama-3.1-8B-Instruct", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) tokenizer = get_chat_template( tokenizer, chat_template = "llama-3.1", ) # Load small dataset for quick training dataset_train = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "train[:100]" ) dataset_train = dataset_train.map(formatting_prompts_func, batched = True) print("✅ Base model loaded successfully!") print(f"\n{'='*80}") print("🔍 PHASE 2: First Fine-tuning") print(f"{'='*80}") model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 10, # Very short training for test learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 5, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) trainer_stats = trainer.train() print("✅ First fine-tuning completed!") print(f"\n{'='*80}") print("🔍 PHASE 3: Save with Forced 4bit Merge") print(f"{'='*80}") model.save_pretrained_merged( save_directory = "./test_4bit_model", tokenizer = tokenizer, save_method = "forced_merged_4bit", ) print("✅ Model saved with forced 4bit merge!") print(f"\n{'='*80}") print("🔍 PHASE 4: Loading 4bit Model and Second Fine-tuning") print(f"{'='*80}") # Clean up first model del model del tokenizer torch.cuda.empty_cache() # Load the 4bit merged model model_4bit, tokenizer_4bit = FastLanguageModel.from_pretrained( model_name = "./test_4bit_model", max_seq_length = 2048, load_in_4bit = True, load_in_8bit = False, ) tokenizer_4bit = get_chat_template( tokenizer_4bit, chat_template = "llama-3.1", ) print("✅ 4bit model loaded successfully!") # Add LoRA adapters to the 4bit model model_4bit = FastLanguageModel.get_peft_model( model_4bit, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) # Second fine-tuning trainer_4bit = SFTTrainer( model = model_4bit, tokenizer = tokenizer_4bit, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer_4bit), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 10, # Very short training for test learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 5, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs_4bit", report_to = "none", ), ) trainer_4bit.train() print("✅ Second fine-tuning on 4bit model completed!") print(f"\n{'='*80}") print("🔍 PHASE 5: Testing TypeError on Regular Merge (Should Fail)") print(f"{'='*80}") try: model_4bit.save_pretrained_merged( save_directory = "./test_should_fail", tokenizer = tokenizer_4bit, # No save_method specified, should default to regular merge ) assert False, "Expected TypeError but merge succeeded!" except TypeError as e: expected_error = "Base model should be a 16bits or mxfp4 base model for a 16bit model merge. Use `save_method=forced_merged_4bit` instead" assert expected_error in str(e), f"Unexpected error message: {str(e)}" print("✅ Correct TypeError raised for 4bit base model regular merge attempt!") print(f"Error message: {str(e)}") print(f"\n{'='*80}") print("🔍 PHASE 6: Successful Save with Forced 4bit Method") print(f"{'='*80}") try: model_4bit.save_pretrained_merged( save_directory = "./test_4bit_second", tokenizer = tokenizer_4bit, save_method = "forced_merged_4bit", ) print("✅ Successfully saved 4bit model with forced 4bit method!") except Exception as e: assert False, f"Phase 6 failed unexpectedly: {e}" print(f"\n{'='*80}") print("🔍 CLEANUP") print(f"{'='*80}") # Cleanup safe_remove_directory("./outputs") safe_remove_directory("./outputs_4bit") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./test_4bit_model") safe_remove_directory("./test_4bit_second") safe_remove_directory("./test_should_fail") print("✅ All tests passed successfully!")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_merge_4bit_validation.py", "license": "Apache License 2.0", "lines": 214, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/import_fixes.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import importlib.abc import importlib.machinery import importlib.util from pathlib import Path from importlib.metadata import version as importlib_version from packaging.version import Version as TrueVersion import re import logging import textwrap import warnings import sys import functools # We cannot do from unsloth_zoo.log import logger since FBGEMM might cause seg faults. UNSLOTH_ENABLE_LOGGING = os.environ.get("UNSLOTH_ENABLE_LOGGING", "0") in ( "1", "True", "true", ) logger = logging.getLogger(__name__) if UNSLOTH_ENABLE_LOGGING: logging.basicConfig( level = logging.INFO, format = "[%(name)s|%(levelname)s]%(message)s" ) logger.setLevel(logging.INFO) else: logging.basicConfig( level = logging.WARNING, format = "[%(name)s|%(levelname)s]%(message)s" ) logger.setLevel(logging.WARNING) _AMDGPU_IDS_MISSING_TEXT = "amdgpu.ids: No such file or directory" def Version(version): try: new_version = str(version) new_version = re.match(r"[0-9\.]{1,}", new_version) if new_version is None: raise Exception(str(e)) new_version = new_version.group(0).rstrip(".") if new_version != version: new_version += ".1" # Add .1 for dev / alpha / beta / rc return TrueVersion(new_version) except: from inspect import getframeinfo, stack caller = getframeinfo(stack()[1][0]) raise RuntimeError( f"Unsloth: Could not get version for `{version}`\n" f"File name = [{caller.filename}] Line number = [{caller.lineno}]" ) # Ignore logging messages class HideLoggingMessage(logging.Filter): __slots__ = ("text",) def __init__(self, text): self.text = text def filter(self, x): return not (self.text in x.getMessage()) class HidePrintMessage: def __init__(self, original_stream): self._original_stream = original_stream self._hidden_texts = [] def add_filter(self, text): self._hidden_texts.append(text) def write(self, message): if not any(text in message for text in self._hidden_texts): self._original_stream.write(message) def flush(self): self._original_stream.flush() def __getattr__(self, name): return getattr(self._original_stream, name) import contextlib import ctypes try: _libc = ctypes.CDLL(None) except Exception: _libc = None @contextlib.contextmanager def suppress_cuda_printf(): """Suppress CUDA device-side printf by redirecting stdout/stderr fds to /dev/null. CUDA device printf (eg CUTLASS "Arch conditional MMA" errors on Blackwell) writes to stdout fd 1 at the C level, bypassing Python sys.stdout entirely. The existing HidePrintMessage filter on sys.stderr cannot catch these since they go to a different fd at a different layer. This context manager redirects both fd 1 and fd 2 at the OS level, syncs CUDA, then restores them. """ sys.stdout.flush() sys.stderr.flush() saved_fds = {} try: for fd in (1, 2): saved_fds[fd] = os.dup(fd) devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, fd) os.close(devnull) yield finally: try: import torch if torch.cuda.is_available(): torch.cuda.synchronize() except Exception: pass if _libc is not None: try: _libc.fflush(None) except Exception: pass for fd, saved in saved_fds.items(): os.dup2(saved, fd) os.close(saved) if not UNSLOTH_ENABLE_LOGGING: import sys # Apply to stderr for FBGEMM and CUTLASS errors sys.stderr = HidePrintMessage(sys.stderr) # https://github.com/pytorch/FBGEMM/blob/d99cd96490ec4aabac2ee95b1e76ea4dcfcfa628/fbgemm_gpu/experimental/gemm/triton_gemm/utils.py#L43-L52 sys.stderr.add_filter("TMA benchmarks will be running") # CUTLASS/FBGEMM MMA instruction error on SM90 vs SM100 (Blackwell) GPUs # https://github.com/NVIDIA/cutlass/blob/main/include/cutlass/gemm/kernel/sm90_gemm_tma_warpspecialized.hpp sys.stderr.add_filter("Arch conditional MMA instruction used without targeting") # CUTLASS arch conditional errors for various architectures sys.stderr.add_filter("CUTE_INVALID_CONTROL_PATH") # CUTLASS TMA-related errors when not targeting correct architecture sys.stderr.add_filter("Trying to use tma without CUTE_ARCH_TMA") # Skipping import of cpp extensions due to incompatible torch version 2.9.0+cu128 for torchao version 0.15.0 logging.getLogger("torchao").setLevel(logging.ERROR) # Also filter torchao print to stderr about cpp extensions sys.stderr.add_filter("Skipping import of cpp extensions") # SyntaxWarning: invalid escape sequence '\.' warnings.filterwarnings( "ignore", message = "invalid escape sequence", category = SyntaxWarning ) # PYTORCH_CUDA_ALLOC_CONF is deprecated warning from torch warnings.filterwarnings("ignore", message = "PYTORCH_CUDA_ALLOC_CONF is deprecated") # TF32 precision deprecation warning from torch warnings.filterwarnings( "ignore", message = "Please use the new API settings to control TF32" ) # Deprecation warnings from torchao warnings.filterwarnings("ignore", message = "`int4_weight_only` is deprecated") warnings.filterwarnings("ignore", message = "`int8_weight_only` is deprecated") # TorchAO deprecated import paths (https://github.com/pytorch/ao/issues/2752) warnings.filterwarnings( "ignore", message = r"Importing.*from torchao\.dtypes.*is deprecated", category = DeprecationWarning, ) warnings.filterwarnings( "ignore", message = r"Importing BlockSparseLayout from torchao\.dtypes is deprecated", category = DeprecationWarning, ) # SWIG builtin type warnings (from bitsandbytes/triton SWIG bindings) warnings.filterwarnings( "ignore", message = r"builtin type Swig.*has no __module__ attribute", category = DeprecationWarning, ) # Triton autotuner deprecation (https://github.com/triton-lang/triton/pull/4496) warnings.filterwarnings( "ignore", message = r"warmup, rep, and use_cuda_graph parameters are deprecated", category = DeprecationWarning, ) # Python 3.12+ multiprocessing fork warning in multi-threaded processes warnings.filterwarnings( "ignore", message = r".*multi-threaded.*use of fork\(\) may lead to deadlocks", category = DeprecationWarning, ) # Resource warnings from internal socket/file operations warnings.filterwarnings( "ignore", message = r"unclosed.*socket", category = ResourceWarning ) warnings.filterwarnings( "ignore", message = r"unclosed file.*dev/null", category = ResourceWarning ) # torch 2.9+ pin_memory/is_pinned device arg deprecation warnings.filterwarnings( "ignore", message = r"The `device` argument is deprecated", category = DeprecationWarning, ) warnings.filterwarnings( "ignore", message = r".*pin_memory.*device.*deprecated", category = DeprecationWarning, ) warnings.filterwarnings( "ignore", message = r".*is_pinned.*device.*deprecated", category = DeprecationWarning, ) # vllm "Level is deprecated" stderr noise sys.stderr.add_filter("Level is deprecated") # PydanticSerializationUnexpectedValue warning warnings.filterwarnings( "ignore", message = r".*PydanticSerializationUnexpectedValue", ) warnings.filterwarnings( "ignore", message = r"Expected.*but got.*with value.*is not.*subclass", ) # Triton "df: No such file or directory" stderr noise sys.stderr.add_filter("df: No such file") # ROCm/libdrm missing ids table stderr noise on some AMD setups sys.stderr.add_filter(_AMDGPU_IDS_MISSING_TEXT) # Apex ROCm fused RoPE backend selection warning when Aiter is enabled. warnings.filterwarnings( "ignore", message = r"^Aiter backend is selected for fused RoPE\.?", category = UserWarning, module = r"^apex\.transformer\.functional\.fused_rope$", ) # Fix up AttributeError: 'MessageFactory' object has no attribute 'GetPrototype' # MUST do this at the start primarily due to tensorflow causing issues def fix_message_factory_issue(): try: import google.protobuf.message_factory class MessageFactory: def CreatePrototype(self, *args, **kwargs): return def GetMessages(self, *args, **kwargs): return def GetPrototype(self, *args, **kwargs): return if not hasattr(google.protobuf.message_factory, "MessageFactory"): logger.info("Unsloth: Patching protobuf.MessageFactory as it doesn't exist") google.protobuf.message_factory.MessageFactory = MessageFactory elif ( hasattr(google.protobuf.message_factory, "MessageFactory") and not hasattr( google.protobuf.message_factory.MessageFactory, "GetPrototype" ) and not hasattr(google.protobuf.message_factory, "GetMessageClass") ): google.protobuf.message_factory.MessageFactory = MessageFactory logger.info("Unsloth: Patching protobuf.MessageFactory as it doesn't exist") elif ( hasattr(google.protobuf.message_factory, "MessageFactory") and not hasattr( google.protobuf.message_factory.MessageFactory, "GetPrototype" ) and hasattr(google.protobuf.message_factory, "GetMessageClass") ): GetMessageClass = google.protobuf.message_factory.GetMessageClass def GetPrototype(self, descriptor): return GetMessageClass(descriptor) google.protobuf.message_factory.MessageFactory.GetPrototype = GetPrototype logger.info("Unsloth: Patching protobuf.MessageFactory.GetPrototype") pass except: pass # Fix Xformers performance issues since 0.0.25 def fix_xformers_performance_issue(): spec = importlib.util.find_spec("xformers") if spec is None: return xformers_version = importlib_version("xformers") if Version(xformers_version) < Version("0.0.29"): xformers_location = spec.origin if xformers_location is None: xformers_location = spec.submodule_search_locations[0] else: xformers_location = os.path.split(xformers_location)[0] cutlass = Path(xformers_location) / "ops" / "fmha" / "cutlass.py" try: if cutlass.exists(): with open(cutlass, "r+", encoding = "utf-8") as f: text = f.read() # See https://github.com/facebookresearch/xformers/issues/1176#issuecomment-2545829591 if "num_splits_key=-1," in text: text = text.replace( "num_splits_key=-1,", "num_splits_key=None,", ) f.seek(0) f.write(text) f.truncate() logger.info( "Unsloth: Patching Xformers to fix some performance issues." ) except Exception as e: logger.info(f"Unsloth: Failed patching Xformers with error = {str(e)}") def patch_vllm_for_notebooks(): import sys ipython = None try: from IPython import get_ipython as _get_ipython except Exception: _get_ipython = None if _get_ipython is not None: try: ipython = _get_ipython() except Exception: ipython = None if ipython is None: try: import builtins _get_ipython = getattr(builtins, "get_ipython", None) if callable(_get_ipython): ipython = _get_ipython() except Exception: ipython = None if ipython is None: return try: shell = ipython.__class__.__name__ is_notebook = shell == "ZMQInteractiveShell" or "google.colab" in str( type(ipython) ) except Exception: return if not is_notebook: return if not hasattr(sys.stdout, "fileno"): return needs_patch = False try: fd = sys.stdout.fileno() if not isinstance(fd, int) or fd < 0: needs_patch = True except Exception: needs_patch = True if not needs_patch: return logger.info( "Unsloth: Notebook detected - Patching sys.stdout.fileno for newer `vllm>=0.12.0` versions" ) sys.stdout.fileno = lambda: 1 # ValueError: 'aimv2' is already used by a Transformers config, pick another name. def fix_vllm_aimv2_issue(): spec = importlib.util.find_spec("vllm") if spec is None: return vllm_version = importlib_version("vllm") if Version(vllm_version) < Version("0.10.1"): vllm_location = spec.origin if vllm_location is None: vllm_location = spec.submodule_search_locations[0] else: vllm_location = os.path.split(vllm_location)[0] ovis_config = Path(vllm_location) / "transformers_utils" / "configs" / "ovis.py" try: if ovis_config.exists(): with open(ovis_config, "r+", encoding = "utf-8") as f: text = f.read() # See https://github.com/vllm-project/vllm-ascend/issues/2046 if 'AutoConfig.register("aimv2", AIMv2Config)' in text: text = text.replace( 'AutoConfig.register("aimv2", AIMv2Config)', "", ) text = text.replace( """backbone_config.pop('model_type') backbone_config = AutoConfig.for_model(model_type, **backbone_config)""", """if model_type != "aimv2": backbone_config.pop('model_type') backbone_config = AutoConfig.for_model(model_type, **backbone_config) else: backbone_config = AIMv2Config(**backbone_config)""", ) f.seek(0) f.write(text) f.truncate() logger.info( "Unsloth: Patching vLLM to fix `'aimv2' is already used by a Transformers config, pick another name.`" ) except Exception as e: logger.info(f"Unsloth: Failed patching vLLM with error = {str(e)}") def fix_vllm_guided_decoding_params(): def _maybe_raise_vllm_transformers_mismatch(error): error_text = str(error) if ( "ALLOWED_LAYER_TYPES" in error_text or "transformers.configuration_utils" in error_text ): try: vllm_version = importlib_version("vllm") except Exception: vllm_version = "unknown" raise RuntimeError( "Unsloth: vLLM with version " f"{vllm_version} does not yet support transformers>=5.0.0. " "Please downgrade to transformers==4.57.3 via " 'pip install --force-reinstall "transformers==4.57.3". ' f"Original error: {error}" ) from error if importlib.util.find_spec("vllm") is None: return # GuidedDecodingParmas is renamed to StructuredOutputsParams in vLLM # https://github.com/vllm-project/vllm/pull/22772/files # trl still wants to use GuidedDecodingParams. This is a temporary patch till trl updates try: import vllm except (ImportError, OSError) as e: _maybe_raise_vllm_transformers_mismatch(e) if disable_broken_vllm(e): return raise try: from vllm.sampling_params import GuidedDecodingParams except (ImportError, OSError) as e: _maybe_raise_vllm_transformers_mismatch(e) if disable_broken_vllm(e): return if not hasattr(vllm, "sampling_params") or not hasattr( vllm.sampling_params, "StructuredOutputsParams" ): raise vllm.sampling_params.GuidedDecodingParams = ( vllm.sampling_params.StructuredOutputsParams ) def ignore_logger_messages(): # Ignore Environment variable `HF_TOKEN` is set try: from huggingface_hub._login import logger as huggingface_hub_logger huggingface_hub_logger.addFilter(HideLoggingMessage("`HF_TOKEN`")) del huggingface_hub_logger except: pass def patch_ipykernel_hf_xet(): # HF-XET == 1.1.10 and ipykernel == 7.0.0 / 7.0.1 causes issues # See https://github.com/huggingface/xet-core/issues/526 # 2025-10-13T20:37:33.028737Z ERROR Python exception updating progress:, error: PyErr { type: <class 'LookupError'>, value: LookupError(<ContextVar name='shell_parent' at 0x7535b4cebd80>), traceback: Some(<traceback object at 0x753408489f40>) }, caller: "src/progress_update.rs:313" # at /home/runner/work/xet-core/xet-core/error_printer/src/lib.rs:28 if importlib.util.find_spec("hf_xet") is None: return if importlib.util.find_spec("ipykernel") is None: return if importlib.util.find_spec("huggingface_hub") is None: return ipykernel_version = Version(importlib_version("ipykernel")) if ( (Version(importlib_version("hf_xet")) == Version("1.1.10")) and ( (ipykernel_version == Version("7.0.0")) or ( ipykernel_version == Version("7.0.1") ) # 7.0.1 seems to also break with LookupError: <ContextVar name='shell_parent' at 0x7a9775143ec0> ) ): print( "#### Unsloth: `hf_xet==1.1.10` and `ipykernel==7.0.0` or `ipykernel==7.0.1` breaks progress bars. Using ASCII progress bars.\n" "#### Unsloth: To re-enable progress bars, please upgrade to `ipykernel>=7.1.0` or wait for a fix to\n" "https://github.com/huggingface/xet-core/issues/526" ) from huggingface_hub.utils import disable_progress_bars disable_progress_bars() def patch_trackio(): # Set some environment variables to customize the Trackio dashboard for experiment tracking # See https://github.com/unslothai/notebooks/pull/110 os.environ["TRACKIO_LOGO_LIGHT_URL"] = ( "https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20logo%20black%20text.png" ) os.environ["TRACKIO_LOGO_DARK_URL"] = ( "https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20logo%20white%20text.png" ) os.environ["TRACKIO_PLOT_ORDER"] = "train/reward" def patch_datasets(): # Datasets 4.4.0 and 4.4.1 weirdly have some weird `_thread.RLock_recursion_count` issues if importlib.util.find_spec("datasets") is None: return datasets_version = Version(importlib_version("datasets")) if (datasets_version <= Version("4.5.0")) and ( datasets_version >= Version("4.4.0") ): raise NotImplementedError( f"#### Unsloth: Using `datasets = {str(datasets_version)}` will cause recursion errors.\n" "Please downgrade datasets to `datasets==4.3.0" ) def check_fbgemm_gpu_version(): if importlib.util.find_spec("fbgemm_gpu") is None: return try: fbgemm_gpu_version = importlib_version("fbgemm_gpu_genai") except: return # We noticed some SegFault or bad alloc errors on lower versions of fbgemm_gpu. # Instead of raising an error, disable FBGEMM and fall back to Triton kernels. if Version(fbgemm_gpu_version) < Version("1.4.0"): os.environ["UNSLOTH_HAS_FBGEMM"] = "0" logger.info( f"Unsloth: fbgemm_gpu_genai=={fbgemm_gpu_version} is old and may cause issues. " f"Disabling FBGEMM - using Triton kernels instead." ) return logger.info(f"Unsloth: fbgemm_gpu_genai=={fbgemm_gpu_version} detected.") def patch_enable_input_require_grads(): """ Patch transformers PreTrainedModel.enable_input_require_grads to handle vision models that raise NotImplementedError from get_input_embeddings(). """ import inspect from transformers import PreTrainedModel # Check if the original function iterates over self.modules() instead of just returning the enable_input_require_grads # Ref: https://github.com/huggingface/transformers/pull/41993/files#diff-6b72b98c4c2dcfc6cc606843917733f5d858374fbc22a735ff483bbc0c1e63eaL1979-R1996 try: original_source = inspect.getsource(PreTrainedModel.enable_input_require_grads) except: return # Only patch if the new pattern exists (iterating over self.modules()) if "for module in self.modules()" not in original_source: return def _patched_enable_input_require_grads(self): def make_inputs_require_grads(module, input, output): output.requires_grad_(True) hooks = [] seen_modules = set() for module in self.modules(): if not ( isinstance(module, PreTrainedModel) and hasattr(module, "get_input_embeddings") ): continue try: input_embeddings = module.get_input_embeddings() except NotImplementedError: # Vision models may not implement get_input_embeddings - skip them # For GLM V4.6 for example, this skips only `self.visual` continue if input_embeddings is None: continue embedding_id = id(input_embeddings) if embedding_id in seen_modules: continue seen_modules.add(embedding_id) hooks.append( input_embeddings.register_forward_hook(make_inputs_require_grads) ) self._require_grads_hooks = hooks if hooks: self._require_grads_hook = hooks[0] PreTrainedModel.enable_input_require_grads = _patched_enable_input_require_grads logger.info( "Unsloth: Patched enable_input_require_grads for vision model compatibility" ) def _is_custom_torch_build(raw_version_str): """Check if a raw version string indicates a custom or source build. Must operate on the raw string from importlib_version(), not the parsed Version object, since our custom Version() strips local identifiers. Standard PyTorch releases use: +cu124, +rocm6.3, +cpu, +xpu Source/custom builds use: +gitXXXXXXX, +HEXHASH, or other suffixes. """ if "+" not in raw_version_str: return False local = raw_version_str.split("+", 1)[1] if not local: return False # Use fullmatch so the entire local identifier must match, not just a prefix. # cu/rocm require a trailing digit (e.g. cu124, rocm6.3). cpu/xpu are exact. # Case-insensitive since some builds may use uppercase. return not re.fullmatch(r"cu\d[\d.]*|rocm\d[\d.]*|cpu|xpu", local, re.IGNORECASE) def _infer_required_torchvision(torch_major, torch_minor): """Infer the minimum required torchvision minor version from torch version. The torch -> torchvision minor version mapping follows a consistent formula: torch 1.x -> torchvision 0.(x + 1) (verified: torch 1.7 through 1.13) torch 2.x -> torchvision 0.(x + 15) (verified: torch 2.0 through 2.9) Returns (tv_major, tv_minor) or None if the major version is unrecognized. """ if torch_major == 1 and torch_minor >= 7: return (0, torch_minor + 1) if torch_major == 2: return (0, torch_minor + 15) return None def torchvision_compatibility_check(): # Allow skipping via environment variable for custom environments if os.environ.get("UNSLOTH_SKIP_TORCHVISION_CHECK", "0").lower() in ("1", "true"): return if importlib.util.find_spec("torch") is None: raise ImportError("Unsloth: torch not found. Please install torch first.") if importlib.util.find_spec("torchvision") is None: return try: torch_version_raw = importlib_version("torch") torchvision_version_raw = importlib_version("torchvision") except Exception: return try: torch_v = Version(torch_version_raw) tv_v = Version(torchvision_version_raw) except Exception: return # Known compatibility table (ground truth, takes precedence over formula). # See https://pytorch.org/get-started/previous-versions/ TORCH_TORCHVISION_COMPAT = { (2, 9): (0, 24), (2, 8): (0, 23), (2, 7): (0, 22), (2, 6): (0, 21), (2, 5): (0, 20), (2, 4): (0, 19), } # Extract major.minor from the parsed version torch_release = torch_v.release if len(torch_release) < 2: return torch_major, torch_minor = torch_release[0], torch_release[1] # Try known table first, then fall back to formula for forward compatibility required = TORCH_TORCHVISION_COMPAT.get((torch_major, torch_minor)) if required is None: required = _infer_required_torchvision(torch_major, torch_minor) if required is None: return required_tv_str = f"{required[0]}.{required[1]}.0" if tv_v >= Version(required_tv_str): logger.info( f"Unsloth: torch=={torch_version_raw} and " f"torchvision=={torchvision_version_raw} are compatible." ) return # Version mismatch detected message = ( f"Unsloth: torch=={torch_version_raw} requires " f"torchvision>={required_tv_str}, " f"but found torchvision=={torchvision_version_raw}. " f'Try updating torchvision via `pip install --upgrade "torchvision>={required_tv_str}"`. ' f"Please refer to https://pytorch.org/get-started/previous-versions/ " f"for more information." ) is_custom = _is_custom_torch_build(torch_version_raw) or _is_custom_torch_build( torchvision_version_raw ) # Detect nightly/dev/alpha/beta/rc builds from the raw version string. # These often have version mismatches that are expected. _pre_tags = (".dev", "a0", "b0", "rc", "alpha", "beta", "nightly") is_prerelease = any(t in torch_version_raw for t in _pre_tags) or any( t in torchvision_version_raw for t in _pre_tags ) # Only downgrade to warning for custom/source or prerelease builds. # Stable mismatches should fail fast to prevent runtime operator errors. if is_custom or is_prerelease: reason = "custom/source build" if is_custom else "pre-release build" logger.warning( f"{message}\n" f"Detected a {reason}. " f"Continuing with a warning. " f"Set UNSLOTH_SKIP_TORCHVISION_CHECK=1 to silence this." ) return raise ImportError(message) # Fix TRL OpenEnv 0.26 NameError: name 'SamplingParams' is not defined def fix_openenv_no_vllm(): spec = importlib.util.find_spec("trl") if spec is None: return trl_location = spec.origin if trl_location is None: trl_location = spec.submodule_search_locations[0] else: trl_location = os.path.split(trl_location)[0] openenv = Path(trl_location) / "experimental" / "openenv" / "utils.py" if not openenv.exists(): return try: with open(openenv, "r+", encoding = "utf-8") as f: text = f.read() bad = ( "if is_vllm_available():\n" " from vllm import SamplingParams\n" " from vllm.sampling_params import GuidedDecodingParams\n" ) replace_with = bad + ( "else:\n" " from typing import Any\n" " SamplingParams = Any\n" " GuidedDecodingParams = Any\n" "\n" ) if bad + "\n" + "\n" in text and replace_with not in text: text = text.replace(bad + "\n" + "\n", replace_with) f.seek(0) f.write(text) f.truncate() logger.info( "Unsloth: Patching TRL OpenEnv to fix SamplingParams not defined" ) except Exception as e: logger.info(f"Unsloth: Failed patching TRL OpenEnv with error = {str(e)}") # Fix Exeuctorch needing get_mapped_key def fix_executorch(): spec = importlib.util.find_spec("executorch") if spec is None: return executorch_location = spec.origin if executorch_location is None: executorch_location = spec.submodule_search_locations[0] else: executorch_location = os.path.split(executorch_location)[0] executorch = Path(executorch_location) / "examples" / "models" / "__init__.py" if not executorch.exists(): return try: what = r""" import sys import types import re from typing import Any, Optional def get_mapped_key(key: str, mapping_dict: dict[str, str]) -> str: try: # Checks if there is a layer # in the key if any(k.isdigit() for k in key.split(".")): # Replace layer number with "{}" to create key for lookup abstract_key = re.sub(r"(\.\d+)", ".{}", key) layer_num = re.search(r"\d+", key).group(0) new_key = mapping_dict[abstract_key] new_key = new_key.format(layer_num) else: new_key = mapping_dict[key] except KeyError as e: raise Exception( f'Error converting the state dict. Found unexpected key: "{key}". ' "Please make sure you're loading a checkpoint with the right format. " ) from e return new_key torchtune = types.ModuleType("torchtune") torchtune.__path__ = [] models = types.ModuleType("torchtune.models") models.__path__ = [] convert_weights = types.ModuleType("torchtune.models.convert_weights") convert_weights.get_mapped_key = get_mapped_key torchtune.models = models models.convert_weights = convert_weights sys.modules["torchtune"] = torchtune sys.modules["torchtune.models"] = models sys.modules["torchtune.models.convert_weights"] = convert_weights """ what = textwrap.dedent(what) with open(executorch, "r+", encoding = "utf-8") as f: text = f.read() bad = "from enum import Enum\n" if bad in text and what not in text: text = text.replace(bad + "\n", bad + "\n" + what) f.seek(0) f.write(text) f.truncate() logger.info("Unsloth: Patching Executorch to fix get_mapped_key") except Exception as e: logger.info(f"Unsloth: Failed Executorch with error = {str(e)}") def fix_diffusers_warnings(): # Silence Flax classes are deprecated and will be removed in Diffusers v1.0.0. os.environ["DIFFUSERS_VERBOSITY"] = "error" def fix_huggingface_hub(): # huggingface_hub.is_offline_mode got removed, so add it back import huggingface_hub if not hasattr(huggingface_hub, "is_offline_mode"): huggingface_hub.is_offline_mode = ( lambda: huggingface_hub.constants.HF_HUB_OFFLINE ) def fix_triton_compiled_kernel_missing_attrs(): """ Triton 3.6.0+ removed direct `num_ctas` and `cluster_dims` attributes from CompiledKernel, but torch 2.9.x Inductor still expects them in torch/_inductor/runtime/triton_heuristics.py make_launcher() (line ~1757). The scope dict eagerly evaluates: binary.metadata.num_ctas, *binary.metadata.cluster_dims when hasattr(binary, "metadata") is True, but metadata lacks cluster_dims. This crashes before reaching the new launch path that doesn't need cta_args. Upstream fix: pytorch/pytorch@97bd4db added hasattr guards. We monkey-patch CompiledKernel.__init__ to inject the missing attributes so the older hasattr(binary, "num_ctas") branch succeeds instead. """ try: import torch except (ImportError, ModuleNotFoundError): return try: import triton import triton.compiler.compiler as triton_compiler except (ImportError, ModuleNotFoundError): return # Only needed when the CompiledKernel class lacks num_ctas as a direct attr # but has metadata (triton >= 3.6.0 with torch < 2.10) _ck_cls = triton_compiler.CompiledKernel if hasattr(_ck_cls, "num_ctas"): return # Old triton with direct attrs -- no patch needed _orig_init = _ck_cls.__init__ def _patched_init(self, *args, **kwargs): _orig_init(self, *args, **kwargs) if not hasattr(self, "num_ctas"): self.num_ctas = getattr(self.metadata, "num_ctas", 1) if not hasattr(self, "cluster_dims") and not hasattr(self, "clusterDims"): self.cluster_dims = (1, 1, 1) _ck_cls.__init__ = _patched_init logger.info( "Unsloth: Patched triton CompiledKernel with num_ctas/cluster_dims " "for torch.compile compatibility." ) def patch_trunc_normal_precision_issue(): """ Patch torch.nn.init.trunc_normal_ for low precision tensors to run init in fp32. torch.nn.init.trunc_normal_ can saturate at truncation bounds in fp16/bf16 on some versions/backends. This was observed in TorchTitan investigations where low-precision truncation produced boundary-heavy initialization behavior: https://github.com/pytorch/torchtitan/pull/2342 To avoid that failure mode, initialize into a temporary fp32 tensor, then copy back to the original dtype. """ try: import torch except (ImportError, ModuleNotFoundError): return if getattr(torch.nn.init, "_unsloth_trunc_normal_patched", False): return original_trunc_normal = torch.nn.init.trunc_normal_ if getattr(original_trunc_normal, "__unsloth_trunc_normal_patched__", False): torch.nn.init._unsloth_trunc_normal_patched = True return low_precision_dtypes = {torch.float16, torch.bfloat16} def _call_original(target, mean, std, a, b, generator): if generator is None: return original_trunc_normal(target, mean = mean, std = std, a = a, b = b) try: return original_trunc_normal( target, mean = mean, std = std, a = a, b = b, generator = generator ) except TypeError as exc: # Older torch versions may not accept a generator keyword argument. msg = str(exc).lower() if "unexpected keyword argument" in msg and "generator" in msg: return original_trunc_normal(target, mean = mean, std = std, a = a, b = b) raise try: from torch.distributed._tensor import DTensor except Exception: DTensor = None @torch.no_grad() def _patched_trunc_normal_( tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0, generator = None, ): if DTensor is not None and isinstance(tensor, DTensor): local_tensor = getattr(tensor, "_local_tensor", None) if local_tensor is None: return _call_original(tensor, mean, std, a, b, generator) if local_tensor.dtype in low_precision_dtypes: local_fp32 = local_tensor.float() _call_original(local_fp32, mean, std, a, b, generator) local_tensor.copy_(local_fp32.to(dtype = local_tensor.dtype)) return tensor return _call_original(tensor, mean, std, a, b, generator) if tensor.dtype in low_precision_dtypes: tensor_fp32 = tensor.float() _call_original(tensor_fp32, mean, std, a, b, generator) tensor.copy_(tensor_fp32.to(dtype = tensor.dtype)) return tensor return _call_original(tensor, mean, std, a, b, generator) _patched_trunc_normal_.__unsloth_trunc_normal_patched__ = True _patched_trunc_normal_._unsloth_original = original_trunc_normal torch.nn.init._unsloth_trunc_normal_original = original_trunc_normal torch.nn.init.trunc_normal_ = _patched_trunc_normal_ torch.nn.init._unsloth_trunc_normal_patched = True logger.info("Unsloth: Patched torch.nn.init.trunc_normal_ for fp16/bf16 stability.") def check_vllm_torch_sm100_compatibility(): """ Check for incompatible vLLM + torch < 2.9.0 + SM100 (Blackwell) combination. vLLM's distributed module (device_communicators) crashes with std::bad_alloc when imported on SM100 GPUs (B200/B100) with torch < 2.9.0. This is due to C++ code in vLLM's NCCL/distributed layer being incompatible with older torch versions on the newer Blackwell architecture. This check runs early (before vLLM import) to provide a helpful error message instead of a cryptic std::bad_alloc crash. """ # Check if vLLM is installed (without importing it) if importlib.util.find_spec("vllm") is None: return # Check torch version try: torch_version = Version(importlib_version("torch")) if torch_version >= Version("2.9.0"): return # torch >= 2.9.0 is compatible except Exception: return # Can't determine torch version, skip check # Check if any CUDA GPU is SM100 (Blackwell) try: import torch if not torch.cuda.is_available(): return has_sm100 = False sm100_gpu_name = None for i in range(torch.cuda.device_count()): major, minor = torch.cuda.get_device_capability(i) if major == 10: has_sm100 = True sm100_gpu_name = torch.cuda.get_device_name(i) break if not has_sm100: return except Exception: return # Get vLLM version for the error message try: vllm_version = importlib_version("vllm") except Exception: vllm_version = "unknown" # Incompatible combination detected - raise helpful error raise RuntimeError( f"Unsloth: Incompatible configuration detected.\n\n" f" GPU: {sm100_gpu_name} (SM100 / Blackwell architecture)\n" f" torch version: {torch_version}\n" f" vLLM version: {vllm_version}\n\n" f"vLLM's distributed module crashes with std::bad_alloc on SM100 GPUs " f"(B200/B100/Blackwell) when using torch < 2.9.0.\n\n" f"To fix this, please upgrade torch:\n" f" pip install --upgrade torch>=2.9.0\n\n" f"Alternatively, if you don't need vLLM:\n" f" pip uninstall vllm" ) def fix_vllm_pdl_blackwell(): """ Fix vLLM PDL (Programmatic Dependent Launch) bug on Blackwell GPUs (SM100). The issue: vLLM's LoRA Triton kernels use tl.extra.cuda.gdc_wait() for PDL optimization on SM90+ GPUs. This fails on SM100 (B200/B100) during CUDA graph capture because Triton's pipeliner can't handle gdc_wait in complex kernels. See: https://github.com/vllm-project/vllm/issues/30872 """ if importlib.util.find_spec("vllm") is None: return # Check if any CUDA GPU is SM100 (Blackwell) try: import torch if not torch.cuda.is_available(): return # Scan all GPUs for SM100 - fix applies globally via env var and monkey-patch has_sm100 = False sm100_gpu_name = None for i in range(torch.cuda.device_count()): major, minor = torch.cuda.get_device_capability(i) if major == 10: has_sm100 = True sm100_gpu_name = torch.cuda.get_device_name(i) break if not has_sm100: return except Exception: return # Helper to check if module spec exists def _spec_exists(name): try: return importlib.util.find_spec(name) is not None except (ImportError, OSError, ModuleNotFoundError, ValueError): return False # Check if vLLM has the PDL-related modules before doing internet check has_utils = _spec_exists("vllm.lora.ops.triton_ops.utils") has_expand_op = _spec_exists("vllm.lora.ops.triton_ops.lora_expand_op") has_shrink_op = _spec_exists("vllm.lora.ops.triton_ops.lora_shrink_op") if not has_utils and not has_expand_op and not has_shrink_op: # Old vLLM version without PDL support - nothing to patch return # Check if vLLM version includes the fix VLLM_PDL_FIX_VERSION = "0.15.0" try: vllm_version = Version(importlib_version("vllm")) if vllm_version >= Version(VLLM_PDL_FIX_VERSION): logger.info( f"Unsloth: SM100 ({sm100_gpu_name}) detected but vLLM {vllm_version} " f"should include PDL fix - skipping workaround" ) return except Exception as e: logger.debug( f"Unsloth: vLLM version check failed ({e}), applying PDL workaround." ) # Apply the PDL fix os.environ["TRITON_DISABLE_PDL"] = "1" def fake_supports_pdl(*args, **kwargs): return False patched = [] patched_names = set() def _record_patch(name): if name not in patched_names: patched.append(name) patched_names.add(name) # First, patch the source module (utils.py) where supports_pdl is defined. # This is critical because supports_pdl uses @lru_cache - we must clear the # cache to prevent stale cached results from the original function. try: utils_module = importlib.import_module("vllm.lora.ops.triton_ops.utils") if hasattr(utils_module, "supports_pdl"): original_fn = utils_module.supports_pdl if hasattr(original_fn, "cache_clear"): original_fn.cache_clear() utils_module.supports_pdl = fake_supports_pdl _record_patch("utils") except (ImportError, ModuleNotFoundError, AttributeError): pass # Also patch the consumer modules that import supports_pdl from utils. # This ensures the patched function is used even if the module was already # imported before this fix runs. consumer_modules = { "lora_expand_op": "vllm.lora.ops.triton_ops.lora_expand_op", "lora_shrink_op": "vllm.lora.ops.triton_ops.lora_shrink_op", "fused_moe_lora_op": "vllm.lora.ops.triton_ops.fused_moe_lora_op", } for name, path in consumer_modules.items(): try: module = importlib.import_module(path) if hasattr(module, "supports_pdl"): module.supports_pdl = fake_supports_pdl _record_patch(name) except (ImportError, ModuleNotFoundError, AttributeError): pass # Patch any additional already-loaded triton ops consumers that expose supports_pdl. for module_name, module in tuple(sys.modules.items()): if not module_name.startswith("vllm.lora.ops.triton_ops."): continue if module is None or not hasattr(module, "supports_pdl"): continue module.supports_pdl = fake_supports_pdl _record_patch(module_name.rsplit(".", 1)[-1]) if patched: logger.info( f"Unsloth: Applied PDL fix for SM100 ({sm100_gpu_name}) - " f"patched: {', '.join(patched)}" ) else: # Just set the env var - vLLM might be an older version without supports_pdl logger.info(f"Unsloth: Set TRITON_DISABLE_PDL=1 for SM100 ({sm100_gpu_name})") def patch_openspiel_env_async(): """Apply nest_asyncio for OpenEnv EnvClient async compatibility. OpenEnv's EnvClient uses async methods (reset/step). In Jupyter notebooks these work via top-level await, but converted scripts need asyncio.get_event_loop().run_until_complete() wrappers. Applying nest_asyncio ensures nested event loop calls work in all contexts without replacing the original async methods (which would break scripts that already have their own sync wrappers). """ try: import inspect from openenv.core.env_client import EnvClient if not inspect.iscoroutinefunction(EnvClient.reset): return # Already sync, nothing to do try: import nest_asyncio nest_asyncio.apply() logger.info( "Unsloth: Applied nest_asyncio for OpenEnv EnvClient async compatibility" ) except ImportError: logger.info( "Unsloth: nest_asyncio not installed, OpenEnv async methods may need manual wrapping" ) except (ImportError, AttributeError): pass # openenv not installed def patch_torchcodec_audio_decoder(): """Call unsloth_zoo's AudioDecoder patch.""" try: from unsloth_zoo.dataset_utils import patch_torchcodec_audio_decoder as _patch _patch() except (ImportError, AttributeError, RuntimeError): pass def disable_torchcodec_if_broken(): """Disable torchcodec in transformers if it cannot actually load. transformers checks if torchcodec is installed via importlib.util.find_spec(), but this returns True even when torchcodec cannot load its native libraries (e.g., when FFmpeg is missing). This causes runtime errors when transformers tries to use torchcodec for audio loading. This function tests if torchcodec can actually load and if not, patches transformers to think torchcodec is unavailable so it falls back to librosa. """ try: import importlib.util if importlib.util.find_spec("torchcodec") is None: return # torchcodec not installed, nothing to do # Test if torchcodec can actually load from torchcodec.decoders import AudioDecoder except (ImportError, RuntimeError, OSError): # torchcodec cannot load - disable it in transformers try: import transformers.utils.import_utils as tf_import_utils tf_import_utils._torchcodec_available = False except (ImportError, AttributeError): pass CAUSAL_CONV1D_BROKEN = False _CAUSAL_CONV1D_PREFIX = "causal_conv1d" _CAUSAL_CONV1D_BLOCKER_SENTINEL = "_unsloth_causal_conv1d_blocker" VLLM_BROKEN = False _VLLM_PREFIX = "vllm" _VLLM_BLOCKER_SENTINEL = "_unsloth_vllm_blocker" _ROCM_ENV_HINT_KEYS = ( "ROCM_PATH", "ROCM_HOME", "HIP_PATH", "HSA_PATH", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", ) _ROCM_PATH_HINTS = ( Path("/opt/rocm"), Path("/dev/kfd"), Path("/sys/module/amdgpu"), ) _AMDGPU_ASIC_ID_TABLE_PATH_ENV = "AMDGPU_ASIC_ID_TABLE_PATH" _AMDGPU_ASIC_ID_CANDIDATE_PATHS = ( Path("/usr/share/libdrm/amdgpu.ids"), Path("/usr/local/share/libdrm/amdgpu.ids"), Path("/opt/rocm/share/libdrm/amdgpu.ids"), Path("/opt/amdgpu/share/libdrm/amdgpu.ids"), ) def _log_rocm_detection(message): if UNSLOTH_ENABLE_LOGGING: logger.info(message) @functools.lru_cache(1) def _is_rocm_torch_build() -> bool: # Most official ROCm wheels include a local version suffix like +rocmX.Y. # Some custom/source builds do not, so we fall back to runtime hints. try: torch_version_raw = str(importlib_version("torch")).lower() if "rocm" in torch_version_raw: _log_rocm_detection( "Unsloth: ROCm detection matched torch version tag (+rocm)." ) return True except Exception: pass # Environment hints commonly present on ROCm runtimes. for key in _ROCM_ENV_HINT_KEYS: value = os.environ.get(key, "") if isinstance(value, str) and value.strip(): _log_rocm_detection( f"Unsloth: ROCm detection matched environment key `{key}`." ) return True # Filesystem / driver hints for ROCm stacks. for path in _ROCM_PATH_HINTS: try: if path.exists(): _log_rocm_detection( f"Unsloth: ROCm detection matched filesystem hint `{path}`." ) return True except Exception: continue _log_rocm_detection("Unsloth: ROCm detection did not match any known hints.") return False def _iter_amdgpu_asic_id_table_candidates(): # Try torch-adjacent ids table paths first without importing torch. try: torch_spec = importlib.util.find_spec("torch") except Exception: torch_spec = None roots = [] if torch_spec is not None: if torch_spec.origin: roots.append(Path(torch_spec.origin).resolve().parent) if torch_spec.submodule_search_locations: for location in torch_spec.submodule_search_locations: roots.append(Path(location).resolve()) seen = set() for root in roots: for candidate in ( root / "share" / "libdrm" / "amdgpu.ids", root.parent / "share" / "libdrm" / "amdgpu.ids", root.parent.parent / "share" / "libdrm" / "amdgpu.ids", ): candidate_str = str(candidate) if candidate_str in seen: continue seen.add(candidate_str) yield candidate for candidate in _AMDGPU_ASIC_ID_CANDIDATE_PATHS: candidate_str = str(candidate) if candidate_str in seen: continue seen.add(candidate_str) yield candidate def configure_amdgpu_asic_id_table_path(): # Honor an existing valid user-provided path. configured = os.environ.get(_AMDGPU_ASIC_ID_TABLE_PATH_ENV, "").strip() if configured: configured_path = Path(configured) try: if configured_path.is_file(): return str(configured_path) except Exception: pass # Only attempt this on ROCm-like environments. if not _is_rocm_torch_build(): return None for candidate in _iter_amdgpu_asic_id_table_candidates(): try: if candidate.is_file(): os.environ[_AMDGPU_ASIC_ID_TABLE_PATH_ENV] = str(candidate) if UNSLOTH_ENABLE_LOGGING: logger.info( f"Unsloth: Set {_AMDGPU_ASIC_ID_TABLE_PATH_ENV}={candidate}" ) return str(candidate) except Exception: continue return None def _is_causal_conv1d_name(module_name: str) -> bool: return module_name == _CAUSAL_CONV1D_PREFIX or module_name.startswith( _CAUSAL_CONV1D_PREFIX + "." ) def _is_vllm_name(module_name: str) -> bool: return module_name == _VLLM_PREFIX or module_name.startswith(_VLLM_PREFIX + ".") def _resolve_module_name(module_name, package): if not isinstance(module_name, str): return module_name if module_name.startswith("."): try: return importlib.util.resolve_name(module_name, package) except Exception: return module_name return module_name def _is_broken_causal_conv1d_error(error) -> bool: checked = set() current = error while current is not None and id(current) not in checked: checked.add(id(current)) message = str(current).lower() if ( ("causal_conv1d_cuda" in message and "undefined symbol" in message) or ("_zn3c103hip28c10_hip_check_implementation" in message) or ("causal_conv1d" in message and "undefined symbol" in message) ): return True current = getattr(current, "__cause__", None) or getattr( current, "__context__", None ) return False def _is_broken_vllm_error(error) -> bool: checked = set() current = error while current is not None and id(current) not in checked: checked.add(id(current)) message = str(current).lower() if ( ("vllm/_c" in message or "vllm._c" in message) and ( "undefined symbol" in message or "cannot open shared object file" in message or ".so:" in message ) ) or ("vllm" in message and "undefined symbol" in message): return True # Also catch CUDA shared library mismatches during vllm import # e.g. "libcudart.so.12: cannot open shared object file" if ( "libcudart" in message or "libcublas" in message or "libnvrtc" in message ) and "cannot open shared object file" in message: return True current = getattr(current, "__cause__", None) or getattr( current, "__context__", None ) return False def _get_vllm_cuda_mismatch_message(error): """If the error is a CUDA version mismatch, return a helpful install message.""" import re as _re checked = set() current = error wanted_cuda = None while current is not None and id(current) not in checked: checked.add(id(current)) message = str(current) # Extract the CUDA version vllm was built for, e.g. "libcudart.so.12" match = _re.search(r"libcudart\.so\.(\d+)", message) if match: wanted_cuda = match.group(1) break current = getattr(current, "__cause__", None) or getattr( current, "__context__", None ) if wanted_cuda is None: return None # Detect what CUDA version is actually available on the system system_cuda_display = None # Human-readable, e.g. "13.0" system_cuda_tag = None # For wheel URL, e.g. "130" try: import torch cuda_version = torch.version.cuda # e.g. "13.0" or "12.8" if cuda_version: system_cuda_display = cuda_version system_cuda_tag = cuda_version.replace(".", "")[:3] # "130" or "128" except Exception: pass if system_cuda_tag is None or system_cuda_tag.startswith(wanted_cuda): return None # Not a mismatch or can't determine try: vllm_version = importlib_version("vllm").split("+")[0] except Exception: vllm_version = "VLLM_VERSION" cpu_arch = "x86_64" try: import platform cpu_arch = platform.machine() except Exception: pass return ( f"Unsloth: vLLM was built for CUDA {wanted_cuda} but this system has " f"CUDA {system_cuda_display}. Please reinstall vLLM with the correct CUDA version:\n" f"\n" f" uv pip install https://github.com/vllm-project/vllm/releases/download/" f"v{vllm_version}/vllm-{vllm_version}+cu{system_cuda_tag}-cp38-abi3-" f"manylinux_2_35_{cpu_arch}.whl" ) class _CausalConv1dImportBlockerLoader(importlib.abc.Loader): __slots__ = ("module_name",) def __init__(self, module_name): self.module_name = module_name def create_module(self, spec): return None def exec_module(self, module): raise ModuleNotFoundError(f"No module named '{self.module_name}'") class _CausalConv1dImportBlockerFinder(importlib.abc.MetaPathFinder): __slots__ = (_CAUSAL_CONV1D_BLOCKER_SENTINEL,) def __init__(self): setattr(self, _CAUSAL_CONV1D_BLOCKER_SENTINEL, True) def find_spec(self, fullname, path = None, target = None): if not CAUSAL_CONV1D_BROKEN or not _is_causal_conv1d_name(fullname): return None return importlib.machinery.ModuleSpec( name = fullname, loader = _CausalConv1dImportBlockerLoader(fullname), is_package = fullname == _CAUSAL_CONV1D_PREFIX, ) class _VllmImportBlockerLoader(importlib.abc.Loader): __slots__ = ("module_name",) def __init__(self, module_name): self.module_name = module_name def create_module(self, spec): return None def exec_module(self, module): raise ModuleNotFoundError(f"No module named '{self.module_name}'") class _VllmImportBlockerFinder(importlib.abc.MetaPathFinder): __slots__ = (_VLLM_BLOCKER_SENTINEL,) def __init__(self): setattr(self, _VLLM_BLOCKER_SENTINEL, True) def find_spec(self, fullname, path = None, target = None): if not VLLM_BROKEN or not _is_vllm_name(fullname): return None return importlib.machinery.ModuleSpec( name = fullname, loader = _VllmImportBlockerLoader(fullname), is_package = fullname == _VLLM_PREFIX, ) def _patch_find_spec_for_causal_conv1d(): current_find_spec = importlib.util.find_spec if getattr(current_find_spec, "_unsloth_causal_conv1d_find_spec_patch", False): return def _blocked_find_spec(name, package = None): resolved_name = _resolve_module_name(name, package) if CAUSAL_CONV1D_BROKEN and isinstance(resolved_name, str): if _is_causal_conv1d_name(resolved_name): return None return current_find_spec(name, package) _blocked_find_spec._unsloth_causal_conv1d_find_spec_patch = True _blocked_find_spec._unsloth_original_find_spec = current_find_spec importlib.util.find_spec = _blocked_find_spec def _patch_find_spec_for_vllm(): current_find_spec = importlib.util.find_spec if getattr(current_find_spec, "_unsloth_vllm_find_spec_patch", False): return def _blocked_find_spec(name, package = None): resolved_name = _resolve_module_name(name, package) if VLLM_BROKEN and isinstance(resolved_name, str): if _is_vllm_name(resolved_name): return None return current_find_spec(name, package) _blocked_find_spec._unsloth_vllm_find_spec_patch = True _blocked_find_spec._unsloth_original_find_spec = current_find_spec importlib.util.find_spec = _blocked_find_spec def _install_causal_conv1d_blocker(): _patch_find_spec_for_causal_conv1d() for finder in sys.meta_path: if getattr(finder, _CAUSAL_CONV1D_BLOCKER_SENTINEL, False): return sys.meta_path.insert(0, _CausalConv1dImportBlockerFinder()) def _install_vllm_blocker(): _patch_find_spec_for_vllm() for finder in sys.meta_path: if getattr(finder, _VLLM_BLOCKER_SENTINEL, False): return sys.meta_path.insert(0, _VllmImportBlockerFinder()) def _clear_causal_conv1d_modules(): for module_name in list(sys.modules): if _is_causal_conv1d_name(module_name): sys.modules.pop(module_name, None) def _clear_vllm_modules(): for module_name in list(sys.modules): if _is_vllm_name(module_name): sys.modules.pop(module_name, None) def disable_broken_vllm(error = None): """Disable vLLM dynamically when its shared library is ABI-broken.""" global VLLM_BROKEN if VLLM_BROKEN: _install_vllm_blocker() return True failure = error if failure is None: try: if importlib.util.find_spec("vllm") is None: return False except Exception: return False try: import vllm # noqa: F401 return False except Exception as import_error: failure = import_error if not _is_broken_vllm_error(failure): return False VLLM_BROKEN = True _clear_vllm_modules() _install_vllm_blocker() cuda_msg = _get_vllm_cuda_mismatch_message(failure) if cuda_msg: logger.warning(cuda_msg) else: logger.warning( "Unsloth: Detected broken vLLM binary extension; " "disabling vLLM imports and continuing import.\n" "Please reinstall via `uv pip install unsloth vllm torchvision torchaudio " "--torch-backend=auto`." ) return True def _disable_transformers_causal_conv1d(): try: import transformers.utils.import_utils as tf_import_utils except Exception: return if hasattr(tf_import_utils, "is_causal_conv1d_available"): tf_import_utils.is_causal_conv1d_available = lambda: False for attr_name in ( "_causal_conv1d_available", "_is_causal_conv1d_available", ): if hasattr(tf_import_utils, attr_name): setattr(tf_import_utils, attr_name, False) def disable_broken_causal_conv1d(): """Disable causal_conv1d dynamically when its shared library is ABI-broken. This mirrors Unsloth's FlashAttention fallback behavior: if importing causal_conv1d fails with a known binary symbol error, we disable it at startup so model imports do not hard-fail. """ global CAUSAL_CONV1D_BROKEN if CAUSAL_CONV1D_BROKEN: _install_causal_conv1d_blocker() _disable_transformers_causal_conv1d() return try: if importlib.util.find_spec("causal_conv1d") is None: return except Exception: return try: import causal_conv1d # noqa: F401 return except Exception as error: if not _is_broken_causal_conv1d_error(error): return CAUSAL_CONV1D_BROKEN = True _clear_causal_conv1d_modules() _install_causal_conv1d_blocker() _disable_transformers_causal_conv1d() print( "Unsloth: Detected broken causal_conv1d binary; " "disabling causal_conv1d fast path and continuing import." )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/import_fixes.py", "license": "Apache License 2.0", "lines": 1476, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:tests/saving/vision_models/test_save_merge_qwen2.5vl32B_model_ocr_benchmark.py
# -*- coding: utf-8 -*- from unsloth import FastVisionModel import torch from qwen_vl_utils import process_vision_info import os from datasets import load_dataset from trl import SFTTrainer, SFTConfig import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.ocr_eval import OCRModelEvaluator ## Dataset Preparation from datasets import load_dataset dataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train") # To select the first 2000 examples train_dataset = dataset.select(range(2000)) # To select the next 200 examples for evaluation eval_dataset = dataset.select(range(2000, 2200)) # Convert dataset to OAI messages def format_data(sample): return { "messages": [ { "role": "system", "content": [{"type": "text", "text": system_message}], }, { "role": "user", "content": [ { "type": "text", "text": sample["question"], }, { "type": "image", "image": sample["image"], }, ], }, { "role": "assistant", "content": [{"type": "text", "text": sample["answer"]}], }, ], } system_message = "You are an expert french ocr system." # Convert dataset to OAI messages # need to use list comprehension to keep Pil.Image type, .mape convert image to bytes train_dataset = [format_data(sample) for sample in train_dataset] eval_dataset = [format_data(sample) for sample in eval_dataset] ## Setup OCR main evaluation function and helpers import os import torch from tqdm import tqdm import pandas as pd from jiwer import wer, cer from qwen_vl_utils import process_vision_info # ocr_evaluator = OCRModelEvaluator() model_comparison_results = {} ## Finetuning Setup and Run # Load Base Model model, tokenizer = FastVisionModel.from_pretrained( model_name = "unsloth/Qwen2.5-VL-32B-Instruct-bnb-4bit", max_seq_length = 2048, # Choose any for long context! load_in_4bit = True, # 4 bit quantization to reduce memory load_in_8bit = False, # [NEW!] A bit more accurate, uses 2x memory full_finetuning = False, # [NEW!] We have full finetuning now! ) # benchmark base model performance model_name = "Unsloth Base model" FastVisionModel.for_inference(model) avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_base_model_results" ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) ## Lora Finetuning model = FastVisionModel.get_peft_model( model, finetune_vision_layers = True, # Turn off for just text! finetune_language_layers = True, # Should leave on! finetune_attention_modules = True, # Attention good for GRPO finetune_mlp_modules = True, # SHould leave on always! r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 # target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", # "gate_proj", "up_proj", "down_proj",], lora_alpha = 32, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes! use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ ) from unsloth import is_bf16_supported from unsloth.trainer import UnslothVisionDataCollator FastVisionModel.for_training(model) # Enable for training! model.config.use_cache = False trainer = SFTTrainer( model = model, tokenizer = tokenizer, data_collator = UnslothVisionDataCollator(model, tokenizer), train_dataset = train_dataset, args = SFTConfig( # per_device_train_batch_size = 4, # gradient_accumulation_steps = 8, per_device_train_batch_size = 2, gradient_accumulation_steps = 4, gradient_checkpointing = True, gradient_checkpointing_kwargs = { "use_reentrant": False }, # use reentrant checkpointing max_grad_norm = 0.3, # max gradient norm based on QLoRA paper warmup_ratio = 0.03, # num_train_epochs = 2, # Set this instead of max_steps for full training runs max_steps = 60, learning_rate = 2e-4, fp16 = not is_bf16_supported(), bf16 = is_bf16_supported(), logging_steps = 5, save_strategy = "epoch", optim = "adamw_torch_fused", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "unsloth-qwen2.5-vl-32b-french-ocr-checkpoints", report_to = "none", # For Weights and Biases # You MUST put the below items for vision finetuning: remove_unused_columns = False, dataset_text_field = "", dataset_kwargs = {"skip_prepare_dataset": True}, dataset_num_proc = 4, max_seq_length = 2048, ), ) # run training trainer_stats = trainer.train() model.save_pretrained("unsloth-qwen2.5-vl-32b-french-ocr-adapter", tokenizer) tokenizer.save_pretrained("unsloth-qwen2.5-vl-32b-french-ocr-adapter") ## Measure Adapter Performance # benchmark lora model performance model_name = "Unsloth lora adapter model" FastVisionModel.for_inference(model) avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_lora_model_results" ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) ## Merge Model def find_lora_base_model(model_to_inspect): current = model_to_inspect if hasattr(current, "base_model"): current = current.base_model if hasattr(current, "model"): current = current.model return current base = find_lora_base_model(model) print((base.__class__.__name__)) # merge default 16 bits model.save_pretrained_merged( save_directory = "qwen2.5-ocr-merged-finetune-merge-16bit", tokenizer = tokenizer ) ## Benchmark merged model performance ### 16 bits merged model model, tokenizer = FastVisionModel.from_pretrained( "./qwen2.5-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = False ) # benchmark 4bit loaded, 16bits merged model performance model_name = "Unsloth 16bits-merged model load-16bits" model.config.use_cache = True avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_16bits_merged_model_load_16bits_results", ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # load 16bits-merged model in 4 bits model, tokenizer = FastVisionModel.from_pretrained( "./qwen2.5-ocr-merged-finetune-merge-16bit", load_in_4bit = True, load_in_8bit = False ) # benchmark 4bit loaded, 16bits merged model performance model_name = "Unsloth 16bits-merged model load-4bits" model.config.use_cache = True avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_16bits_merged_model_load_4bits_results", ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # load model in 8 bits model, tokenizer = FastVisionModel.from_pretrained( "./qwen2.5-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = True ) # benchmark 4bit loaded, 16bits merged model performance model_name = "Unsloth 16bits-merged model load-8bits" avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_16bits_merged_model_load_8bits_results", ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # """### 4 bits merged model""" # # # load 4bits-merged model in 4 bits # model, tokenizer = FastVisionModel.from_pretrained("./qwen2-ocr-merged-finetune-merge-4bit",load_in_4bit=True, load_in_8bit=False) # # # benchmark 4bit loaded, 4bits merged model performance # model_name = "Unsloth 4bits-merged model load-4bits" # # avg_wer, avg_cer = ocr_evaluator.evaluate_model(model, tokenizer, eval_dataset, output_dir="unsloth_4bits_merged_model_load_4bits_results") # ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # # # load model in 8 bits # model, tokenizer = FastVisionModel.from_pretrained("./qwen2-ocr-merged-finetune-merge-4bit",load_in_4bit=False, load_in_8bit=True) # # # benchmark 8bit loaded, 4bits merged model performance # model_name = "Unsloth 4bits-merged model load-8bits" # # avg_wer, avg_cer = ocr_evaluator.evaluate_model(model, tokenizer, eval_dataset, output_dir="unsloth_4bits_merged_model_load_8bits_results") # ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # Model comparison report # print model comparison ocr_evaluator.print_model_comparison() # Final cleanup print("\n🧹 Cleaning up temporary files...") safe_remove_directory("./unsloth-qwen2.5-vl-32b-french-ocr-adapter") safe_remove_directory("./unsloth-qwen2.5-vl-32b-french-ocr-checkpoints") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./qwen2.5-ocr-merged-finetune-merge-16bit") print("\n🎯 Pipeline completed successfully!") print("=" * 80)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/vision_models/test_save_merge_qwen2.5vl32B_model_ocr_benchmark.py", "license": "Apache License 2.0", "lines": 236, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/models/falcon_h1.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .llama import * import os from ._utils import __version__ from unsloth_zoo.utils import Version, _get_dtype from unsloth_zoo.hf_utils import dtype_from_config from ..utils.packing import get_packed_info_from_kwargs from ..utils.attention_dispatch import ( AttentionConfig, AttentionContext, run_attention, select_attention_backend, SDPA, ) from .llama import ( LlamaRotaryEmbedding, LlamaLinearScalingRotaryEmbedding, _LlamaModel_fast_forward_inference, ) try: from transformers.models.falcon_h1.modeling_falcon_h1 import ( FalconH1Attention, FalconH1DecoderLayer, FalconH1Model, FalconH1ForCausalLM, FalconHybridMambaAttentionDynamicCache, ) except: from transformers import __version__ as transformers_version transformers_version = Version(transformers_version) if not transformers_version >= Version( "4.53.0" ): # TODO: Update when transformers is updated raise ImportError( f"Unsloth: Your transformers version of {transformers_version} does not support FalconH1.\n" f"The minimum required version is 4.53.0.\n" f'Try `pip install --upgrade "transformers>=4.53.0"`\n' f"to obtain the latest transformers build, then restart this session." ) from transformers.modeling_attn_mask_utils import ( _prepare_4d_causal_attention_mask_for_sdpa, ) from transformers.utils import ( is_torchdynamo_compiling, ) # For Pytorch 2.1.1 try: from transformers.models.falcon_h1.modeling_falcon_h1 import ( FalconH1Attention, ) except ModuleNotFoundError: # if we are on an old version of transformers technically it should fail in the try except above # but if somehow we make it here, we need to raise an error since FalconH1Attention is not available # or renamed raise ImportError( "Unsloth: Could not import FalconH1Attention from transformers.models.falcon_h1.modeling_falcon_h1." ) def FalconH1Attention_fast_forward( self, hidden_states: torch.Tensor, causal_mask: Optional[BlockDiagonalCausalMask] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: bool = False, use_cache: bool = False, padding_mask: Optional[torch.LongTensor] = None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, *args, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: # Clear inference if hasattr(self, "paged_attention"): del self.paged_attention_K del self.paged_attention_V del self.paged_attention del self.temp_QA del self.temp_KV del self.RH_Q del self.attention bsz, q_len, _ = hidden_states.size() n_heads = self.config.num_attention_heads n_groups = self.num_key_value_groups n_kv_heads = self.config.num_key_value_heads head_dim = self.head_dim assert n_kv_heads * n_groups == n_heads Q, K, V = self.apply_qkv(self, hidden_states) Q = Q.view(bsz, q_len, n_heads, head_dim) K = K.view(bsz, q_len, n_kv_heads, head_dim) V = V.view(bsz, q_len, n_kv_heads, head_dim).transpose(1, 2) seq_info = get_packed_info_from_kwargs(kwargs, hidden_states.device) # Falcon H1 multiplies key states by a multiplier K = K * self.config.key_multiplier Q = Q.transpose(1, 2) K = K.transpose(1, 2) kv_seq_len = K.shape[-2] if past_key_value is not None: kv_seq_len += past_key_value[0].shape[-2] # Extend RoPE dynamically to fit in VRAM if position_embeddings and kv_seq_len <= position_embeddings[0].shape[0]: cos, sin = position_embeddings else: rotary_emb = self.rotary_emb rotary_emb.extend_rope_embedding(V, seq_len = kv_seq_len) cos, sin = rotary_emb.get_cached(kv_seq_len, Q.device.index) rope_position_ids = ( position_ids if position_ids is not None else kwargs.get("position_ids") ) # Useful for LongRoPE Q, K = fast_rope_embedding(Q, K, cos, sin, rope_position_ids) if past_key_value is not None: K = torch.cat([past_key_value[0], K], dim = 2) V = torch.cat([past_key_value[1], V], dim = 2) past_key_value = (K, V) if use_cache else None # Attention module window = (-1, -1) use_varlen = ( attention_mask is None and seq_info is not None and past_key_value is None and window == (-1, -1) ) backend = ( SDPA if attention_mask is not None else select_attention_backend(use_varlen) ) attention_config = AttentionConfig( backend = backend, n_kv_heads = n_kv_heads, n_groups = n_groups, flash_dense_kwargs = { "causal": True, "window_size": (kv_seq_len, kv_seq_len), }, flash_varlen_kwargs = { "dropout_p": 0.0, "softmax_scale": None, "causal": True, }, sdpa_kwargs = {} if attention_mask is None else {"attn_mask": attention_mask}, ) context = AttentionContext( bsz = bsz, q_len = q_len, kv_seq_len = kv_seq_len, n_heads = n_heads, head_dim = head_dim, requires_grad = hidden_states.requires_grad, seq_info = seq_info, attention_mask = attention_mask, causal_mask = causal_mask, ) A = run_attention(config = attention_config, context = context, Q = Q, K = K, V = V) attn_output = A.reshape(bsz, q_len, n_heads * head_dim) attn_output = self.apply_o(self, attn_output) attn_weights = None return attn_output, attn_weights, past_key_value torch_matmul = torch.matmul def FalconH1Attention_fast_forward_inference( self, hidden_states: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]], position_ids, do_prefill = False, attention_mask = None, **kwargs, ): """ https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L406 Fast inference using KV cache. QK^T can be computed in 4 chunks [Q, q] @ [K, k].T where q, k are the new tokens. [QK^T, Qk^T] [qK^T, qk^T] Since the attention mask wipes Qk^T, we just get [QK^T, 0] [qK^T, qk^T] Since softmax is row-wise, we get softmax([QK^T, 0]) softmax([qK^T, qk^T]) We then multiply by [V] [v] softmax([QK^T, 0]) [softmax(QK^T)V] * softmax([qK^T, qk^T]) [softmax([qK^T, qk^T]) @ [V, v]] But notice * [softmax(QK^T)V] is just the last attention. We just need to compute the last final row. This means we can pass in a row of Q, but we need to remember K and V, which are called the KV cache. """ Xn = hidden_states bsz, _, hd = hidden_states.size() K1, V1 = past_key_value dtype = Xn.dtype n_heads = self.config.num_attention_heads n_groups = self.num_key_value_groups n_kv_heads = self.config.num_key_value_heads head_dim = self.head_dim # assert(n_kv_heads * n_groups == n_heads) hidden_size = self.config.hidden_size attention_size = n_heads * head_dim seq_len = K1.shape[-2] kv_seq_len = seq_len + 1 # Prefill phase # if not hasattr(self, "paged_attention"): device = hidden_states.device if do_prefill: self.paged_attention = torch.empty( (KV_CACHE_INCREMENT + seq_len + 1, 2, bsz, n_kv_heads, head_dim), dtype = dtype, device = device, ) self.paged_attention_K = self.paged_attention[:, 0] self.paged_attention_V = self.paged_attention[:, 1] self.paged_attention_K[:seq_len] = K1.permute(2, 0, 1, 3) self.paged_attention_V[:seq_len] = V1.permute(2, 0, 1, 3) self.temp_QA = torch.empty( (2, bsz, 1, attention_size), dtype = dtype, device = device ) self.temp_KV = torch.empty( (2, bsz, 1, n_kv_heads * head_dim), dtype = dtype, device = device ) self.RH_Q = torch.empty((bsz, n_heads, 1, head_dim), dtype = dtype, device = device) # Mistral Nemo 12b has weird dimensions if attention_size != hidden_size: self.temp_O = torch.empty((bsz, 1, hidden_size), dtype = dtype, device = device) else: self.temp_O = self.temp_QA[1][:, :, :hidden_size] self.attention = torch.empty( (bsz, n_heads, 1, KV_CACHE_INCREMENT + seq_len), dtype = dtype, device = device ) self.scalar = 1.0 / math_sqrt(self.head_dim) self.half_head_dim = head_dim // 2 elif kv_seq_len >= self.paged_attention.shape[0]: self.paged_attention.resize_( ( self.paged_attention.shape[0] + KV_CACHE_INCREMENT, 2, bsz, n_kv_heads, head_dim, ) ) self.paged_attention_K = self.paged_attention[:, 0] self.paged_attention_V = self.paged_attention[:, 1] self.attention.resize_( (bsz, n_heads, 1, self.attention.shape[-1] + KV_CACHE_INCREMENT) ) Qn = fast_linear_forward(self.q_proj, Xn, out = self.temp_QA[0]) Kn = fast_linear_forward(self.k_proj, Xn, out = self.temp_KV[0]) Kn.mul_(self.config.key_multiplier) Vn = fast_linear_forward(self.v_proj, Xn, out = self.temp_KV[1]) Qn = Qn.view( bsz, 1, n_heads, head_dim ) # .transpose(1, 2) # we will transpose after normalisation Kn = Kn.view( bsz, 1, n_kv_heads, head_dim ) # .transpose(1, 2) # we will transpose after normalisation Vn = Vn.view(bsz, 1, n_kv_heads, head_dim).transpose(1, 2) Qn = Qn.transpose(1, 2) Kn = Kn.transpose(1, 2) # cos, sin = self.rotary_emb(Vn, seq_len = kv_seq_len) # Qn, Kn = inplace_rope_embedding(Qn, Kn, cos, sin, position_ids) # Need to do it prior 2 steps before hitting full on short KV cache # or else error self.rotary_emb.extend_rope_embedding(Vn, seq_len + 2) cos, sin = self.rotary_emb.get_cached(kv_seq_len, Qn.device.index) cos = cos[position_ids].unsqueeze(1) sin = sin[position_ids].unsqueeze(1) h = self.half_head_dim RH_Q = self.RH_Q RH_Q[:, :, :, :h] = Qn[:, :, :, h:] RH_Q[:, :, :, h:] = Qn[:, :, :, :h] RH_Q[:, :, :, :h].neg_() # torch.neg(RH_Q[:,:,:,:h], out = RH_Q[:,:,:,:h]) Qn *= cos Qn.addcmul_(RH_Q, sin) RH_K = RH_Q[ :, :n_kv_heads, :, : ] # torch.empty((n_kv_heads, 1, head_dim), dtype = dtype, device = "cuda:0") RH_K[:, :, :, :h] = Kn[:, :, :, h:] RH_K[:, :, :, h:] = Kn[:, :, :, :h] RH_K[:, :, :, :h].neg_() # torch.neg(RH_K[:,:,:,:h], out = RH_K[:,:,:,:h]) Kn *= cos Kn.addcmul_(RH_K, sin) # New KV cache # Kn = torch.cat([K1, Kn], dim = 2) # Vn = torch.cat([V1, Vn], dim = 2) self.paged_attention_K[seq_len] = Kn.permute(2, 0, 1, 3) self.paged_attention_V[seq_len] = Vn.permute(2, 0, 1, 3) Kn = self.paged_attention_K[:kv_seq_len].permute(1, 2, 0, 3) Vn = self.paged_attention_V[:kv_seq_len].permute(1, 2, 0, 3) # Handle sliding windows sliding_window = getattr(self.config, "sliding_window", None) if sliding_window is not None and kv_seq_len > sliding_window: start = kv_seq_len - sliding_window Knn = Kn[:, :, start:, :] # .contiguous() Vnn = Vn[:, :, start:, :] # .contiguous() if attention_mask is not None: attention_mask = attention_mask[..., start:] else: Knn, Vnn = Kn, Vn # Grouped query attention _, _, cached_len, _ = Knn.shape if bsz == 1 or not SDPA_HAS_GQA and n_groups != 1: Knn = Knn[:, :, None, :, :].expand( bsz, n_kv_heads, n_groups, cached_len, head_dim ) Vnn = Vnn[:, :, None, :, :].expand( bsz, n_kv_heads, n_groups, cached_len, head_dim ) Knn = Knn.reshape(bsz, n_heads, cached_len, head_dim) Vnn = Vnn.reshape(bsz, n_heads, cached_len, head_dim) # Attention if bsz == 1: Qn *= self.scalar # See https://github.com/ggerganov/llama.cpp/issues/7805#issuecomment-2153349963 # It seems like doing (Q * scalar) @ K is better than (Q @ K) * scalar to stop overflows A = torch_matmul( Qn, Knn.transpose(2, 3), out = self.attention[:, :, :, :cached_len] ) A[:] = torch_nn_functional_softmax( A, dim = -1, dtype = torch.float32 ) # .to(A.dtype) A = torch_matmul(A, Vnn, out = Qn) else: if SDPA_HAS_GQA: A = scaled_dot_product_attention( Qn, Knn, Vnn, attn_mask = attention_mask, is_causal = False, enable_gqa = True ) else: A = scaled_dot_product_attention( Qn, Knn, Vnn, attn_mask = attention_mask, is_causal = False ) A = A.transpose(1, 2) A = A.reshape(bsz, 1, attention_size) A = fast_linear_forward(self.o_proj, A, out = self.temp_O) return A, (Kn, Vn) # https://github.com/huggingface/transformers/blob/main/src/transformers/models/falcon_h1/modeling_falcon_h1.py def FalconH1DecoderLayer_fast_forward( self, hidden_states: torch.Tensor, causal_mask = None, attention_mask: Optional[torch.Tensor] = None, mamba_attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, cache_position: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, padding_mask: Optional[torch.LongTensor] = None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, *args, **kwargs, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states """ if use_cache and hasattr(self, "_flag_for_generation"): residual = hidden_states hidden_states = fast_rms_layernorm_inference( self.input_layernorm, hidden_states ) attention_hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states = hidden_states, causal_mask = causal_mask, attention_mask = attention_mask, position_ids = position_ids, past_key_value = past_key_value, output_attentions = output_attentions, use_cache = use_cache, padding_mask = padding_mask, position_embeddings = position_embeddings, **kwargs, ) attention_hidden_states = attention_hidden_states * self.attn_out_multiplier mamba_hidden_states = self.mamba( hidden_states = hidden_states, cache_params = past_key_value, cache_position = cache_position, attention_mask = mamba_attention_mask, ) mamba_hidden_states = mamba_hidden_states * self.ssm_out_multiplier hidden_states = mamba_hidden_states + attention_hidden_states hidden_states += residual # Fully Connected residual = hidden_states hidden_states = fast_rms_layernorm_inference( self.pre_ff_layernorm, hidden_states ) hidden_states = fast_swiglu_inference(self.feed_forward, hidden_states) hidden_states += residual else: residual = hidden_states hidden_states = fast_rms_layernorm(self.input_layernorm, hidden_states) mamba_hidden_states = self.mamba( hidden_states = hidden_states, cache_params = past_key_value, cache_position = cache_position, attention_mask = mamba_attention_mask, ) mamba_hidden_states = mamba_hidden_states * self.ssm_out_multiplier attention_hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states = hidden_states, causal_mask = causal_mask, attention_mask = attention_mask, position_ids = position_ids, past_key_value = past_key_value, output_attentions = output_attentions, use_cache = use_cache, padding_mask = padding_mask, position_embeddings = position_embeddings, **kwargs, ) attention_hidden_states = attention_hidden_states * self.attn_out_multiplier hidden_states = mamba_hidden_states + attention_hidden_states # residual connection after attention + Mamba hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = fast_rms_layernorm(self.pre_ff_layernorm, hidden_states) hidden_states = self.feed_forward(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) if use_cache: outputs += (present_key_value,) return outputs def _FalconH1_fast_forward_inference( attention_fast_forward_inference = FalconH1Attention_fast_forward_inference, mlp_fast_forward_inference = fast_swiglu_inference, ): # This makes the attention and MLP customisable. # Now for models like qwen3 or cohere which use custom attention operations, we can use this function def FalconH1Model_fast_forward_inference_custom( self, input_ids, past_key_values, position_ids, cache_position = None, attention_mask = None, mamba_attention_mask = None, ): input_ids = input_ids[:, : self.max_seq_length] bsz, q_len = input_ids.shape hd = self.config.hidden_size mlp_size = self.config.intermediate_size gate_multiplier, down_multiplier = self.config.mlp_multipliers X = self.model.embed_tokens(input_ids) X = X * self.config.embedding_multiplier X = X.to(_get_dtype(dtype_from_config(self.config))) bsz, q_len, hd = X.shape assert q_len == 1 # Get saved buffers to reduce memory movement residual = torch.empty( (bsz, q_len, hd), dtype = torch.float32, device = f"{DEVICE_TYPE_TORCH}:0" ) _XX = torch.empty( (2, bsz, q_len, hd), dtype = torch.float32, device = f"{DEVICE_TYPE_TORCH}:0" ) XX, XX2 = _XX[0], _XX[1] variance = torch.empty( (bsz, q_len, 1), dtype = torch.float32, device = f"{DEVICE_TYPE_TORCH}:0" ) temp_mlp = torch.empty( (2, bsz, 1, mlp_size), dtype = X.dtype, device = f"{DEVICE_TYPE_TORCH}:0" ) temp_gate, temp_up = temp_mlp[0], temp_mlp[1] seq_len = past_key_values[0][0].shape[-2] if bsz != 1: attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( attention_mask, (bsz, q_len), X, seq_len, sliding_window = getattr(self.config, "sliding_window", None), ) else: attention_mask = None next_decoder_cache = [] for idx, decoder_layer in enumerate(self.model.layers): residual.copy_(X) # residual = X X = fast_rms_layernorm_inference( decoder_layer.input_layernorm, X, XX = XX, XX2 = XX2, variance = variance, ) attention_hidden_states, present_key_value = ( attention_fast_forward_inference( decoder_layer.self_attn, hidden_states = X * decoder_layer.attention_in_multiplier, past_key_value = past_key_values[idx], position_ids = position_ids, attention_mask = attention_mask, do_prefill = not hasattr(decoder_layer.self_attn, "paged_attention"), ) ) attention_hidden_states = ( attention_hidden_states * decoder_layer.attn_out_multiplier ) mamba_hidden_states = decoder_layer.mamba( hidden_states = X, cache_params = present_key_value, cache_position = cache_position, attention_mask = mamba_attention_mask, ) mamba_hidden_states = mamba_hidden_states * decoder_layer.ssm_out_multiplier X = mamba_hidden_states + attention_hidden_states X += residual residual.copy_(X) # residual = X X = fast_rms_layernorm_inference( decoder_layer.pre_ff_layernorm, X, XX = XX, XX2 = XX2, variance = variance, ) X = mlp_fast_forward_inference( decoder_layer.feed_forward, X, temp_gate = temp_gate, temp_up = temp_up, gate_multiplier = gate_multiplier, down_multiplier = down_multiplier, ) X += residual next_decoder_cache.append(present_key_value) X = fast_rms_layernorm_inference( self.model.final_layernorm, X, XX = XX, XX2 = XX2, variance = variance, ) return BaseModelOutputWithPast( last_hidden_state = X, past_key_values = next_decoder_cache, hidden_states = [], attentions = [], ) return FalconH1Model_fast_forward_inference_custom # Separate prepare_inputs_for_generation for Hybrid FalconH1 def _fast_prepare_inputs_for_generation( self, input_ids, past_key_values = None, attention_mask = None, inputs_embeds = None, cache_position = None, position_ids = None, use_cache = True, **kwargs, ): # Overwritten -- has a unique cache type, `FalconHybridMambaAttentionDynamicCache` empty_past_kv = past_key_values is None # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens # Exception 1: when passing input_embeds, input_ids may be missing entries # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case. # (we can't check exception 3 while compiling) if not empty_past_kv: if ( inputs_embeds is not None # Exception 1 or ( is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1] ) # Exception 3 ): input_ids = input_ids[:, -cache_position.shape[0] :] elif ( input_ids.shape[1] != cache_position.shape[0] ): # Default case (the "else", a no op, is Exception 2) input_ids = input_ids[:, cache_position] # TODO: Wire up Cache to work for inference. # else: # past_key_values = FalconHybridMambaAttentionDynamicCache( # self.config, # input_ids.shape[0], # self.dtype, # devices=[ # self.model.layers[i].mamba.conv1d.weight.device for i in range(self.config.num_hidden_layers) # ], # ) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if not empty_past_kv: position_ids = position_ids[:, -input_ids.shape[1] :] # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and empty_past_kv: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = { "input_ids": input_ids.contiguous() } # `contiguous()` needed for compilation use cases model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "use_cache": use_cache, "attention_mask": attention_mask, "logits_to_keep": self.config.num_logits_to_keep, "cache_position": cache_position, } ) return model_inputs def fix_prepare_inputs_for_generation(module): # Fix prepare_inputs_for_generation if hasattr(module, "prepare_inputs_for_generation"): module.prepare_inputs_for_generation = _fast_prepare_inputs_for_generation class FastFalconH1Model(FastLlamaModel): @staticmethod def pre_patch(): init_name, function = patch_linear_scaling( model_name = "FalconH1", rope_module = LlamaRotaryEmbedding, scaled_rope_module = LlamaLinearScalingRotaryEmbedding, attention_module = FalconH1Attention, ) if init_name is not None: exec(function, globals()) FalconH1Attention.__init__ = eval(init_name) FalconH1Attention.forward = FalconH1Attention_fast_forward FalconH1DecoderLayer.forward = FalconH1DecoderLayer_fast_forward FalconH1Model.forward = LlamaModel_fast_forward FalconH1ForCausalLM.forward = CausalLM_fast_forward( _FalconH1_fast_forward_inference(FalconH1Attention_fast_forward_inference) ) PeftModelForCausalLM.forward = PeftModel_fast_forward fix_prepare_inputs_for_generation(FalconH1ForCausalLM) # Solves https://github.com/unslothai/unsloth/issues/168 # Static KV Cache was introduced in 4.38.0, causing training to be much slower. # Inference can now be CUDAGraphed, but we shall retain the old rotary embeddings. # https://github.com/huggingface/transformers/pull/27931 # https://github.com/huggingface/transformers/blob/v4.37.2/src/transformers/models/llama/modeling_llama.py import transformers.models.falcon_h1.modeling_falcon_h1 transformers.models.falcon_h1.modeling_falcon_h1.FalconH1RotaryEmbedding = ( LlamaRotaryEmbedding ) return @staticmethod def from_pretrained( # TODO: Change after release model_name = "Qwen/FalconH1-7B", max_seq_length = 4096, dtype = None, load_in_4bit = True, token = None, device_map = "sequential", rope_scaling = None, fix_tokenizer = True, model_patcher = None, tokenizer_name = None, trust_remote_code = False, **kwargs, ): return FastLlamaModel.from_pretrained( model_name = model_name, max_seq_length = max_seq_length, dtype = dtype, load_in_4bit = load_in_4bit, token = token, device_map = device_map, rope_scaling = rope_scaling, fix_tokenizer = fix_tokenizer, model_patcher = FastFalconH1Model, tokenizer_name = tokenizer_name, trust_remote_code = trust_remote_code, **kwargs, )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/models/falcon_h1.py", "license": "Apache License 2.0", "lines": 690, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:tests/saving/non_peft/test_mistral_non_peft.py
from unsloth import FastLanguageModel from transformers import AutoModelForCausalLM from peft import PeftModel from pathlib import Path import sys import warnings REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory print(f"\n{'='*80}") print("🔍 PHASE 1: Loading Base Model") print(f"{'='*80}") model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/mistral-7b-v0.3", max_seq_length = 2048, dtype = None, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, ) print("✅ Base model loaded successfully!") ### Attemtping save merge print(f"\n{'='*80}") print("🔍 PHASE 2: Attempting save_pretrained_merged (Should Warn)") print(f"{'='*80}") with warnings.catch_warnings(record = True) as w: warnings.simplefilter("always") model.save_pretrained_merged("test_output", tokenizer) # Verify warning assert len(w) >= 1, "Expected warning but none raised" warning_msg = str(w[0].message) expected_msg = "Model is not a PeftModel (no Lora adapters detected). Skipping Merge. Please use save_pretrained() or push_to_hub() instead!" assert expected_msg in warning_msg, f"Unexpected warning: {warning_msg}" assert expected_msg in warning_msg, f"Unexpected warning: {warning_msg}" print("✅ Correct warning detected for non-PeftModel merge attempt!") print(f"\n{'='*80}") print("🔍 PHASE 3: Using save_pretrained (Should Succeed)") print(f"{'='*80}") try: with warnings.catch_warnings(): warnings.simplefilter("error") # Treat warnings as errors here model.save_pretrained("test_output") print("✅ Standard save_pretrained completed successfully!") except Exception as e: assert False, f"Phase 3 failed: {e}" safe_remove_directory("./test_output") safe_remove_directory("./unsloth_compiled_cache")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/non_peft/test_mistral_non_peft.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/non_peft/test_whisper_non_peft.py
from unsloth import FastLanguageModel, FastModel from transformers import AutoModelForCausalLM, WhisperForConditionalGeneration from peft import PeftModel from pathlib import Path import sys import warnings REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory print(f"\n{'='*80}") print("🔍 PHASE 1: Loading Base Model") print(f"{'='*80}") model, tokenizer = FastModel.from_pretrained( model_name = "unsloth/whisper-large-v3", dtype = None, # Leave as None for auto detection load_in_4bit = False, # Set to True to do 4bit quantization which reduces memory auto_model = WhisperForConditionalGeneration, whisper_language = "English", whisper_task = "transcribe", # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf ) print("✅ Base model loaded successfully!") ### Attemtping save merge print(f"\n{'='*80}") print("🔍 PHASE 2: Attempting save_pretrained_merged (Should Warn)") print(f"{'='*80}") with warnings.catch_warnings(record = True) as w: warnings.simplefilter("always") model.save_pretrained_merged("test_output", tokenizer) # Verify warning assert len(w) >= 1, "Expected warning but none raised" warning_msg = str(w[0].message) expected_msg = "Model is not a PeftModel (no Lora adapters detected). Skipping Merge. Please use save_pretrained() or push_to_hub() instead!" assert expected_msg in warning_msg, f"Unexpected warning: {warning_msg}" assert expected_msg in warning_msg, f"Unexpected warning: {warning_msg}" print("✅ Correct warning detected for non-PeftModel merge attempt!") print(f"\n{'='*80}") print("🔍 PHASE 3: Using save_pretrained (Should Succeed)") print(f"{'='*80}") try: with warnings.catch_warnings(): warnings.simplefilter("error") # Treat warnings as errors here model.save_pretrained("test_output") print("✅ Standard save_pretrained completed successfully!") except Exception as e: assert False, f"Phase 3 failed: {e}" safe_remove_directory("./test_output") safe_remove_directory("./unsloth_compiled_cache")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/non_peft/test_whisper_non_peft.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/text_to_speech_models/test_csm.py
from unsloth import FastLanguageModel, FastModel from transformers import CsmForConditionalGeneration import torch # ruff: noqa import sys from pathlib import Path from peft import PeftModel import warnings import requests REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.os_utils import require_package, require_python_package require_package("ffmpeg", "ffmpeg") require_python_package("soundfile") import soundfile as sf print(f"\n{'='*80}") print("🔍 SECTION 1: Loading Model and LoRA Adapters") print(f"{'='*80}") model, tokenizer = FastModel.from_pretrained( model_name = "unsloth/csm-1b", max_seq_length = 2048, # Choose any for long context! dtype = None, # Leave as None for auto-detection auto_model = CsmForConditionalGeneration, load_in_4bit = False, # Select True for 4bit - reduces memory usage ) base_model_class = model.__class__.__name__ model = FastModel.get_peft_model( model, r = 32, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 target_modules = [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", ], lora_alpha = 32, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes! use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ ) print("✅ Model and LoRA adapters loaded successfully!") print(f"\n{'='*80}") print("🔍 SECTION 2: Checking Model Class Type") print(f"{'='*80}") assert isinstance(model, PeftModel), "Model should be an instance of PeftModel" print("✅ Model is an instance of PeftModel!") print(f"\n{'='*80}") print("🔍 SECTION 3: Checking Config Model Class Type") print(f"{'='*80}") def find_lora_base_model(model_to_inspect): current = model_to_inspect if hasattr(current, "base_model"): current = current.base_model if hasattr(current, "model"): current = current.model return current config_model = find_lora_base_model(model) if isinstance(model, PeftModel) else model assert ( config_model.__class__.__name__ == base_model_class ), f"Expected config_model class to be {base_model_class}" print("✅ config_model returns correct Base Model class:", str(base_model_class)) print(f"\n{'='*80}") print("🔍 SECTION 4: Saving and Merging Model") print(f"{'='*80}") with warnings.catch_warnings(): warnings.simplefilter("error") # Treat warnings as errors try: model.save_pretrained_merged("csm", tokenizer) print("✅ Model saved and merged successfully without warnings!") except Exception as e: assert False, f"Model saving/merging failed with exception: {e}" print(f"\n{'='*80}") print("🔍 SECTION 5: Loading Model for Inference") print(f"{'='*80}") model, processor = FastModel.from_pretrained( model_name = "./csm", max_seq_length = 2048, # Choose any for long context! dtype = None, # Leave as None for auto-detection auto_model = CsmForConditionalGeneration, load_in_4bit = False, # Select True for 4bit - reduces memory usage ) from transformers import AutoProcessor processor = AutoProcessor.from_pretrained("unsloth/csm-1b") print("✅ Model loaded for inference successfully!") print(f"\n{'='*80}") print("🔍 SECTION 6: Running Inference") print(f"{'='*80}") from transformers import pipeline import torch output_audio_path = "csm_audio.wav" try: text = ( "We just finished fine tuning a text to speech model... and it's pretty good!" ) speaker_id = 0 inputs = processor(f"[{speaker_id}]{text}", add_special_tokens = True).to("cuda") audio_values = model.generate( **inputs, max_new_tokens = 125, # 125 tokens is 10 seconds of audio, for longer speech increase this # play with these parameters to get the best results depth_decoder_temperature = 0.6, depth_decoder_top_k = 0, depth_decoder_top_p = 0.9, temperature = 0.8, top_k = 50, top_p = 1.0, ######################################################### output_audio = True, ) audio = audio_values[0].to(torch.float32).cpu().numpy() sf.write("example_without_context.wav", audio, 24000) print(f"✅ Audio generated and saved to {output_audio_path}!") except Exception as e: assert False, f"Inference failed with exception: {e}" ## assert that transcribed_text contains The birch canoe slid on the smooth planks. Glued the sheet to the dark blue background. It's easy to tell the depth of a well. Four hours of steady work faced us. print("✅ All sections passed successfully!") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./csm")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/text_to_speech_models/test_csm.py", "license": "Apache License 2.0", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/text_to_speech_models/test_lasa.py
from unsloth import FastLanguageModel, FastModel from transformers import CsmForConditionalGeneration import torch # ruff: noqa import sys from pathlib import Path from peft import PeftModel import warnings import requests REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.os_utils import require_package, require_python_package require_package("ffmpeg", "ffmpeg") require_python_package("soundfile") require_python_package("xcodec2") import soundfile as sf from xcodec2.modeling_xcodec2 import XCodec2Model XCODEC2_MODEL_NAME = "HKUST-Audio/xcodec2" SAMPLE_RATE = 16000 DEVICE = "cuda" try: codec_model = XCodec2Model.from_pretrained(XCODEC2_MODEL_NAME) except Exception as e: raise f"ERROR loading XCodec2 model: {e}." codec_model.to("cpu") print(f"\n{'='*80}") print("🔍 SECTION 1: Loading Model and LoRA Adapters") print(f"{'='*80}") max_seq_length = 2048 model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Llasa-1B", max_seq_length = max_seq_length, dtype = None, # Select None for auto detection load_in_4bit = False, # Choose True for 4bit which reduces memory # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf ) base_model_class = model.__class__.__name__ model = FastLanguageModel.get_peft_model( model, r = 128, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 target_modules = ["q_proj", "v_proj"], lora_alpha = 128, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes! use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ ) print("✅ Model and LoRA adapters loaded successfully!") print(f"\n{'='*80}") print("🔍 SECTION 2: Checking Model Class Type") print(f"{'='*80}") assert isinstance(model, PeftModel), "Model should be an instance of PeftModel" print("✅ Model is an instance of PeftModel!") print(f"\n{'='*80}") print("🔍 SECTION 3: Checking Config Model Class Type") print(f"{'='*80}") def find_lora_base_model(model_to_inspect): current = model_to_inspect if hasattr(current, "base_model"): current = current.base_model if hasattr(current, "model"): current = current.model return current config_model = find_lora_base_model(model) if isinstance(model, PeftModel) else model assert ( config_model.__class__.__name__ == base_model_class ), f"Expected config_model class to be {base_model_class}" print("✅ config_model returns correct Base Model class:", str(base_model_class)) print(f"\n{'='*80}") print("🔍 SECTION 4: Saving and Merging Model") print(f"{'='*80}") with warnings.catch_warnings(): warnings.simplefilter("error") # Treat warnings as errors try: model.save_pretrained_merged("lasa", tokenizer) print("✅ Model saved and merged successfully without warnings!") except Exception as e: assert False, f"Model saving/merging failed with exception: {e}" print(f"\n{'='*80}") print("🔍 SECTION 5: Loading Model for Inference") print(f"{'='*80}") model, tokenizer = FastLanguageModel.from_pretrained( model_name = "./lasa", max_seq_length = max_seq_length, dtype = None, # Select None for auto detection load_in_4bit = False, # Choose True for 4bit which reduces memory # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf ) # from transformers import AutoProcessor # processor = AutoProcessor.from_pretrained("unsloth/csm-1b") print("✅ Model loaded for inference successfully!") print(f"\n{'='*80}") print("🔍 SECTION 6: Running Inference") print(f"{'='*80}") from transformers import pipeline import torch output_audio_path = "lasa_audio.wav" input_text = "Hey there my name is Elise, <giggles> and I'm a speech generation model that can sound like a person." FastLanguageModel.for_inference(model) def ids_to_speech_tokens(speech_ids): speech_tokens_str = [] for speech_id in speech_ids: speech_tokens_str.append(f"<|s_{speech_id}|>") return speech_tokens_str def extract_speech_ids(speech_tokens_str): speech_ids = [] for token_str in speech_tokens_str: if token_str.startswith("<|s_") and token_str.endswith("|>"): num_str = token_str[4:-2] num = int(num_str) speech_ids.append(num) else: print(f"Unexpected token: {token_str}") return speech_ids # TTS start! with torch.inference_mode(): with torch.amp.autocast("cuda", dtype = model.dtype): formatted_text = ( f"<|TEXT_UNDERSTANDING_START|>{input_text}<|TEXT_UNDERSTANDING_END|>" ) # Tokenize the text chat = [ {"role": "user", "content": "Convert the text to speech:" + formatted_text}, {"role": "assistant", "content": "<|SPEECH_GENERATION_START|>"}, ] input_ids = tokenizer.apply_chat_template( chat, tokenize = True, return_tensors = "pt", continue_final_message = True ) input_ids = input_ids.to("cuda") speech_end_id = tokenizer.convert_tokens_to_ids("<|SPEECH_GENERATION_END|>") # Generate the speech autoregressively outputs = model.generate( input_ids, max_length = 2048, # We trained our model with a max length of 2048 eos_token_id = speech_end_id, do_sample = True, top_p = 1.2, # Adjusts the diversity of generated content temperature = 1.2, # Controls randomness in output ) # Extract the speech tokens generated_ids = outputs[0][input_ids.shape[1] : -1] speech_tokens = tokenizer.batch_decode(generated_ids, skip_special_tokens = True) # Convert token <|s_23456|> to int 23456 speech_tokens = extract_speech_ids(speech_tokens) speech_tokens = torch.tensor(speech_tokens).cpu().unsqueeze(0).unsqueeze(0) # Decode the speech tokens to speech waveform gen_wav = codec_model.decode_code(speech_tokens) try: sf.write(output_audio_path, gen_wav[0, 0, :].cpu().numpy(), 16000) except Exception as e: assert False, f"Inference failed with exception: {e}" ## assert that transcribed_text contains The birch canoe slid on the smooth planks. Glued the sheet to the dark blue background. It's easy to tell the depth of a well. Four hours of steady work faced us. print("✅ All sections passed successfully!") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./lasa")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/text_to_speech_models/test_lasa.py", "license": "Apache License 2.0", "lines": 159, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/text_to_speech_models/test_orpheus.py
from unsloth import FastLanguageModel, FastModel from transformers import CsmForConditionalGeneration import torch # ruff: noqa import sys from pathlib import Path from peft import PeftModel import warnings import requests REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.os_utils import require_package, require_python_package require_package("ffmpeg", "ffmpeg") require_python_package("soundfile") require_python_package("snac") import soundfile as sf from snac import SNAC snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz") snac_model = snac_model.to("cuda") print(f"\n{'='*80}") print("🔍 SECTION 1: Loading Model and LoRA Adapters") print(f"{'='*80}") model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/orpheus-3b-0.1-ft", max_seq_length = 2048, # Choose any for long context! dtype = None, # Select None for auto detection load_in_4bit = False, # Select True for 4bit which reduces memory usage # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf ) base_model_class = model.__class__.__name__ model = FastLanguageModel.get_peft_model( model, r = 64, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 target_modules = [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", ], lora_alpha = 64, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes! use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ ) print("✅ Model and LoRA adapters loaded successfully!") print(f"\n{'='*80}") print("🔍 SECTION 2: Checking Model Class Type") print(f"{'='*80}") assert isinstance(model, PeftModel), "Model should be an instance of PeftModel" print("✅ Model is an instance of PeftModel!") print(f"\n{'='*80}") print("🔍 SECTION 3: Checking Config Model Class Type") print(f"{'='*80}") def find_lora_base_model(model_to_inspect): current = model_to_inspect if hasattr(current, "base_model"): current = current.base_model if hasattr(current, "model"): current = current.model return current config_model = find_lora_base_model(model) if isinstance(model, PeftModel) else model assert ( config_model.__class__.__name__ == base_model_class ), f"Expected config_model class to be {base_model_class}" print("✅ config_model returns correct Base Model class:", str(base_model_class)) print(f"\n{'='*80}") print("🔍 SECTION 4: Saving and Merging Model") print(f"{'='*80}") with warnings.catch_warnings(): warnings.simplefilter("error") # Treat warnings as errors try: model.save_pretrained_merged("orpheus", tokenizer) print("✅ Model saved and merged successfully without warnings!") except Exception as e: assert False, f"Model saving/merging failed with exception: {e}" print(f"\n{'='*80}") print("🔍 SECTION 5: Loading Model for Inference") print(f"{'='*80}") model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/orpheus-3b-0.1-ft", max_seq_length = 2048, # Choose any for long context! dtype = None, # Select None for auto detection load_in_4bit = False, # Select True for 4bit which reduces memory usage # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf ) # from transformers import AutoProcessor # processor = AutoProcessor.from_pretrained("unsloth/csm-1b") print("✅ Model loaded for inference successfully!") print(f"\n{'='*80}") print("🔍 SECTION 6: Running Inference") print(f"{'='*80}") # @title Run Inference FastLanguageModel.for_inference(model) # Enable native 2x faster inference # Moving snac_model cuda to cpu snac_model.to("cpu") prompts = [ "Hey there my name is Elise, <giggles> and I'm a speech generation model that can sound like a person.", ] chosen_voice = None # None for single-speaker prompts_ = [(f"{chosen_voice}: " + p) if chosen_voice else p for p in prompts] all_input_ids = [] for prompt in prompts_: input_ids = tokenizer(prompt, return_tensors = "pt").input_ids all_input_ids.append(input_ids) start_token = torch.tensor([[128259]], dtype = torch.int64) # Start of human end_tokens = torch.tensor( [[128009, 128260]], dtype = torch.int64 ) # End of text, End of human all_modified_input_ids = [] for input_ids in all_input_ids: modified_input_ids = torch.cat( [start_token, input_ids, end_tokens], dim = 1 ) # SOH SOT Text EOT EOH all_modified_input_ids.append(modified_input_ids) all_padded_tensors = [] all_attention_masks = [] max_length = max( [modified_input_ids.shape[1] for modified_input_ids in all_modified_input_ids] ) for modified_input_ids in all_modified_input_ids: padding = max_length - modified_input_ids.shape[1] padded_tensor = torch.cat( [torch.full((1, padding), 128263, dtype = torch.int64), modified_input_ids], dim = 1 ) attention_mask = torch.cat( [ torch.zeros((1, padding), dtype = torch.int64), torch.ones((1, modified_input_ids.shape[1]), dtype = torch.int64), ], dim = 1, ) all_padded_tensors.append(padded_tensor) all_attention_masks.append(attention_mask) all_padded_tensors = torch.cat(all_padded_tensors, dim = 0) all_attention_masks = torch.cat(all_attention_masks, dim = 0) input_ids = all_padded_tensors.to("cuda") attention_mask = all_attention_masks.to("cuda") generated_ids = model.generate( input_ids = input_ids, attention_mask = attention_mask, max_new_tokens = 1200, do_sample = True, temperature = 0.6, top_p = 0.95, repetition_penalty = 1.1, num_return_sequences = 1, eos_token_id = 128258, use_cache = True, ) token_to_find = 128257 token_to_remove = 128258 token_indices = (generated_ids == token_to_find).nonzero(as_tuple = True) if len(token_indices[1]) > 0: last_occurrence_idx = token_indices[1][-1].item() cropped_tensor = generated_ids[:, last_occurrence_idx + 1 :] else: cropped_tensor = generated_ids mask = cropped_tensor != token_to_remove processed_rows = [] for row in cropped_tensor: masked_row = row[row != token_to_remove] processed_rows.append(masked_row) code_lists = [] for row in processed_rows: row_length = row.size(0) new_length = (row_length // 7) * 7 trimmed_row = row[:new_length] trimmed_row = [t - 128266 for t in trimmed_row] code_lists.append(trimmed_row) def redistribute_codes(code_list): layer_1 = [] layer_2 = [] layer_3 = [] for i in range((len(code_list) + 1) // 7): layer_1.append(code_list[7 * i]) layer_2.append(code_list[7 * i + 1] - 4096) layer_3.append(code_list[7 * i + 2] - (2 * 4096)) layer_3.append(code_list[7 * i + 3] - (3 * 4096)) layer_2.append(code_list[7 * i + 4] - (4 * 4096)) layer_3.append(code_list[7 * i + 5] - (5 * 4096)) layer_3.append(code_list[7 * i + 6] - (6 * 4096)) codes = [ torch.tensor(layer_1).unsqueeze(0), torch.tensor(layer_2).unsqueeze(0), torch.tensor(layer_3).unsqueeze(0), ] # codes = [c.to("cuda") for c in codes] audio_hat = snac_model.decode(codes) return audio_hat my_samples = [] for code_list in code_lists: samples = redistribute_codes(code_list) my_samples.append(samples) output_path = "orpheus_audio.wav" try: for i, samples in enumerate(my_samples): audio_data = samples.detach().squeeze().cpu().numpy() import soundfile as sf sf.write(output_path, audio_data, 24000) # Explicitly pass sample rate print(f"✅ Audio saved to {output_path}!") except Exception as e: assert False, f"Inference failed with exception: {e}" # Verify the file exists import os assert os.path.exists(output_path), f"Audio file not found at {output_path}" print("✅ Audio file exists on disk!") del my_samples, samples ## assert that transcribed_text contains The birch canoe slid on the smooth planks. Glued the sheet to the dark blue background. It's easy to tell the depth of a well. Four hours of steady work faced us. print("✅ All sections passed successfully!") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./orpheus")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/text_to_speech_models/test_orpheus.py", "license": "Apache License 2.0", "lines": 219, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/text_to_speech_models/test_whisper.py
from unsloth import FastLanguageModel, FastModel from transformers import WhisperForConditionalGeneration, WhisperProcessor import torch # ruff: noqa import sys from pathlib import Path from peft import PeftModel import warnings import requests REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.os_utils import require_package, require_python_package require_package("ffmpeg", "ffmpeg") require_python_package("soundfile") import soundfile as sf print(f"\n{'='*80}") print("🔍 SECTION 1: Loading Model and LoRA Adapters") print(f"{'='*80}") model, tokenizer = FastModel.from_pretrained( model_name = "unsloth/whisper-large-v3", dtype = None, # Leave as None for auto detection load_in_4bit = False, # Set to True to do 4bit quantization which reduces memory auto_model = WhisperForConditionalGeneration, whisper_language = "English", whisper_task = "transcribe", # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf ) base_model_class = model.__class__.__name__ # https://github.com/huggingface/transformers/issues/37172 model.generation_config.input_ids = model.generation_config.forced_decoder_ids model.generation_config.forced_decoder_ids = None model = FastModel.get_peft_model( model, r = 64, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 target_modules = ["q_proj", "v_proj"], lora_alpha = 64, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes! use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ task_type = None, # ** MUST set this for Whisper ** ) print("✅ Model and LoRA adapters loaded successfully!") print(f"\n{'='*80}") print("🔍 SECTION 2: Checking Model Class Type") print(f"{'='*80}") assert isinstance(model, PeftModel), "Model should be an instance of PeftModel" print("✅ Model is an instance of PeftModel!") print(f"\n{'='*80}") print("🔍 SECTION 3: Checking Config Model Class Type") print(f"{'='*80}") def find_lora_base_model(model_to_inspect): current = model_to_inspect if hasattr(current, "base_model"): current = current.base_model if hasattr(current, "model"): current = current.model return current config_model = find_lora_base_model(model) if isinstance(model, PeftModel) else model assert ( config_model.__class__.__name__ == base_model_class ), f"Expected config_model class to be {base_model_class}" print("✅ config_model returns correct Base Model class:", str(base_model_class)) print(f"\n{'='*80}") print("🔍 SECTION 4: Saving and Merging Model") print(f"{'='*80}") with warnings.catch_warnings(): warnings.simplefilter("error") # Treat warnings as errors try: model.save_pretrained_merged("whisper", tokenizer) print("✅ Model saved and merged successfully without warnings!") except Exception as e: assert False, f"Model saving/merging failed with exception: {e}" print(f"\n{'='*80}") print("🔍 SECTION 5: Loading Model for Inference") print(f"{'='*80}") model, tokenizer = FastModel.from_pretrained( model_name = "./whisper", dtype = None, # Leave as None for auto detection load_in_4bit = False, # Set to True to do 4bit quantization which reduces memory auto_model = WhisperForConditionalGeneration, whisper_language = "English", whisper_task = "transcribe", # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf ) # model = WhisperForConditionalGeneration.from_pretrained("./whisper") # processor = WhisperProcessor.from_pretrained("./whisper") print("✅ Model loaded for inference successfully!") print(f"\n{'='*80}") print("🔍 SECTION 6: Downloading Sample Audio File") print(f"{'='*80}") audio_url = "https://upload.wikimedia.org/wikipedia/commons/5/5b/Speech_12dB_s16.flac" audio_file = "Speech_12dB_s16.flac" try: headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } response = requests.get(audio_url, headers = headers) response.raise_for_status() with open(audio_file, "wb") as f: f.write(response.content) print("✅ Audio file downloaded successfully!") except Exception as e: assert False, f"Failed to download audio file: {e}" print(f"\n{'='*80}") print("🔍 SECTION 7: Running Inference") print(f"{'='*80}") from transformers import pipeline import torch FastModel.for_inference(model) model.eval() # Create pipeline without specifying the device whisper = pipeline( "automatic-speech-recognition", model = model, tokenizer = tokenizer.tokenizer, feature_extractor = tokenizer.feature_extractor, processor = tokenizer, return_language = True, torch_dtype = torch.float16, # Remove the device parameter ) # Example usage audio_file = "Speech_12dB_s16.flac" transcribed_text = whisper(audio_file) # audio, sr = sf.read(audio_file) # input_features = processor(audio, return_tensors="pt").input_features # transcribed_text = model.generate(input_features=input_features) print(f"📝 Transcribed Text: {transcribed_text['text']}") ## assert that transcribed_text contains The birch canoe slid on the smooth planks. Glued the sheet to the dark blue background. It's easy to tell the depth of a well. Four hours of steady work faced us. expected_phrases = [ "birch canoe slid on the smooth planks", "sheet to the dark blue background", "easy to tell the depth of a well", "Four hours of steady work faced us", ] transcribed_lower = transcribed_text["text"].lower() all_phrases_found = all( phrase.lower() in transcribed_lower for phrase in expected_phrases ) assert ( all_phrases_found ), f"Expected phrases not found in transcription: {transcribed_text['text']}" print("✅ Transcription contains all expected phrases!") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./whisper")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/text_to_speech_models/test_whisper.py", "license": "Apache License 2.0", "lines": 149, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/utils/os_utils.py
import subprocess import sys import os import shutil import importlib def detect_package_manager(): """Detect the available package manager""" package_managers = { "apt": "/usr/bin/apt", "yum": "/usr/bin/yum", "dnf": "/usr/bin/dnf", "pacman": "/usr/bin/pacman", "zypper": "/usr/bin/zypper", } for pm, path in package_managers.items(): if os.path.exists(path): return pm return None def check_package_installed(package_name, package_manager = None): """Check if a package is installed using the system package manager""" if package_manager is None: package_manager = detect_package_manager() if package_manager is None: print("Warning: Could not detect package manager") return None try: if package_manager == "apt": # Check with dpkg result = subprocess.run( ["dpkg", "-l", package_name], capture_output = True, text = True ) return result.returncode == 0 elif package_manager in ["yum", "dnf"]: # Check with rpm result = subprocess.run( ["rpm", "-q", package_name], capture_output = True, text = True ) return result.returncode == 0 elif package_manager == "pacman": result = subprocess.run( ["pacman", "-Q", package_name], capture_output = True, text = True ) return result.returncode == 0 elif package_manager == "zypper": result = subprocess.run( ["zypper", "se", "-i", package_name], capture_output = True, text = True ) return package_name in result.stdout except Exception as e: print(f"Error checking package: {e}") return None def require_package(package_name, executable_name = None): """Require a package to be installed, exit if not found""" # First check if executable is in PATH (most reliable) if executable_name: if shutil.which(executable_name): print(f"✓ {executable_name} is available") return # Then check with package manager pm = detect_package_manager() is_installed = check_package_installed(package_name, pm) if is_installed: print(f"✓ Package {package_name} is installed") return # Package not found - show installation instructions print(f"❌ Error: {package_name} is not installed") print(f"\nPlease install {package_name} using your system package manager:") install_commands = { "apt": f"sudo apt update && sudo apt install {package_name}", "yum": f"sudo yum install {package_name}", "dnf": f"sudo dnf install {package_name}", "pacman": f"sudo pacman -S {package_name}", "zypper": f"sudo zypper install {package_name}", } if pm and pm in install_commands: print(f" {install_commands[pm]}") else: for pm_name, cmd in install_commands.items(): print(f" {pm_name}: {cmd}") print(f"\nAlternatively, install with conda:") print(f" conda install -c conda-forge {package_name}") print(f"\nPlease install the required package and run the script again.") sys.exit(1) # Usage # require_package("ffmpeg", "ffmpeg") def require_python_package(package_name, import_name = None, pip_name = None): """Require a Python package to be installed, exit if not found""" if import_name is None: import_name = package_name if pip_name is None: pip_name = package_name if importlib.util.find_spec(import_name) is None: print(f"❌ Error: Python package '{package_name}' is not installed") print(f"\nPlease install {package_name} using pip:") print(f" pip install {pip_name}") print(f" # or with conda:") print(f" conda install {pip_name}") print(f"\nAfter installation, run this script again.") sys.exit(1) else: print(f"✓ Python package '{package_name}' is installed")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/os_utils.py", "license": "Apache License 2.0", "lines": 101, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_merge_model_perplexity_llama-3.2.py
from unsloth import FastLanguageModel, FastVisionModel, UnslothVisionDataCollator from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import ( DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, TrainingArguments, ) from datasets import load_dataset, Dataset import torch from tqdm import tqdm import pandas as pd import multiprocessing as mp from multiprocessing import Process, Queue import gc # ruff: noqa import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.perplexity_eval import ( ppl_model, add_to_comparison, print_model_comparison, ) # Define helper functions outside of main def formatting_prompts_func(examples): convos = examples["messages"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} def load_and_compute_8bit_ppl(result_queue, load_in_4bit = False, load_in_8bit = False): """Load model and compute perplexity in subprocess""" from unsloth import FastLanguageModel from unsloth.chat_templates import get_chat_template from tests.utils.perplexity_eval import ppl_model # Load model merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_llama_text_model", max_seq_length = 2048, load_in_4bit = load_in_4bit, load_in_8bit = load_in_8bit, ) # Set up tokenizer merged_tokenizer = get_chat_template( merged_tokenizer, chat_template = "llama-3.1", ) # Load dataset fresh in subprocess dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) # Format the dataset def formatting_prompts_func(examples): convos = examples["messages"] texts = [ merged_tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) # Compute perplexity using the passed dataset ppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl) # IMPORTANT: Convert to Python float if it's a tensor if torch.is_tensor(ppl_value): ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar elif hasattr(ppl_value, "item"): ppl_value = ppl_value.item() # Convert numpy or other array types else: ppl_value = float(ppl_value) # Ensure it's a float # Return only the perplexity value result_queue.put(ppl_value) # Clean up del merged_model del merged_tokenizer del dataset_ppl torch.cuda.empty_cache() gc.collect() # Main execution code should be wrapped in this guard if __name__ == "__main__": mp.set_start_method("spawn", force = True) if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Llama-3.2-3B-Instruct", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) tokenizer = get_chat_template( tokenizer, chat_template = "llama-3.1", ) from unsloth.chat_templates import standardize_sharegpt dataset_train = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "train" ) dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) dataset_train = dataset_train.map(formatting_prompts_func, batched = True) dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) add_to_comparison("Base model 4 bits", ppl_model(model, tokenizer, dataset_ppl)) model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 10, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 50, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) from unsloth.chat_templates import train_on_responses_only trainer = train_on_responses_only( trainer, instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n", response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n", ) # run training trainer_stats = trainer.train() add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl)) # saving and merging the model to local disk print("merge and save to local disk") model.save_pretrained_merged( save_directory = "./unsloth_out/merged_llama_text_model", tokenizer = tokenizer ) # print("cleaning") # del model # del tokenizer # torch.cuda.empty_cache() # gc.collect() # load model from local disk and test print("Loading merged model in 4 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_llama_text_model", max_seq_length = 2048, load_in_4bit = True, load_in_8bit = False, ) add_to_comparison( "merged model load 4bit", ppl_model(merged_model, merged_tokenizer, dataset_ppl) ) print("Computing 8-bit model perplexity in subprocess...") result_queue = mp.Queue() p = mp.Process(target = load_and_compute_8bit_ppl, args = (result_queue, False, True)) p.start() p.join() ppl_8bit = result_queue.get() add_to_comparison("merged model loaded 8bits", ppl_8bit) print("Loading merged model in 16 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_llama_text_model", max_seq_length = 2048, load_in_4bit = False, load_in_8bit = False, ) add_to_comparison( "merged model loaded 16bits", ppl_model(merged_model, merged_tokenizer, dataset_ppl), ) print_model_comparison() # final cleanup safe_remove_directory("./outputs") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./unsloth_out")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_merge_model_perplexity_llama-3.2.py", "license": "Apache License 2.0", "lines": 216, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_merge_model_perplexity_mistral.py
from unsloth import FastLanguageModel, FastVisionModel, UnslothVisionDataCollator from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import ( DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, TrainingArguments, ) from datasets import load_dataset, Dataset import torch from tqdm import tqdm import pandas as pd import multiprocessing as mp from multiprocessing import Process, Queue import gc # ruff: noqa import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.perplexity_eval import ( ppl_model, add_to_comparison, print_model_comparison, ) def load_and_compute_8bit_ppl(result_queue, load_in_4bit = False, load_in_8bit = False): """Load model and compute perplexity in subprocess""" from unsloth import FastLanguageModel from tests.utils.perplexity_eval import ppl_model # Load model merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_mistral_text_model", max_seq_length = 2048, load_in_4bit = load_in_4bit, load_in_8bit = load_in_8bit, ) # Set up tokenizer # merged_tokenizer = get_chat_template( # merged_tokenizer, # chat_template="llama-3.1", # ) # Load dataset fresh in subprocess dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. ### Instruction: {} ### Input: {} ### Response: {}""" EOS_TOKEN = merged_tokenizer.eos_token def formatting_prompts_func(examples): instructions = [] inputs = [] outputs = [] texts = [] for conversation in examples["messages"]: # Extract user message and assistant response user_message = "" assistant_message = "" for turn in conversation: if turn["role"] == "user": user_message = turn["content"] elif turn["role"] == "assistant": assistant_message = turn["content"] # Store intermediate format instruction = "Complete the statement" instructions.append(instruction) inputs.append(user_message) outputs.append(assistant_message) # Create formatted text text = ( alpaca_prompt.format(instruction, user_message, assistant_message) + EOS_TOKEN ) texts.append(text) return { "instruction": instructions, "input": inputs, "output": outputs, "text": texts, } dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) # Compute perplexity using the passed dataset ppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl) # IMPORTANT: Convert to Python float if it's a tensor if torch.is_tensor(ppl_value): ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar elif hasattr(ppl_value, "item"): ppl_value = ppl_value.item() # Convert numpy or other array types else: ppl_value = float(ppl_value) # Ensure it's a float # Return only the perplexity value result_queue.put(ppl_value) # Clean up del merged_model del merged_tokenizer del dataset_ppl torch.cuda.empty_cache() gc.collect() # Main execution code should be wrapped in this guard if __name__ == "__main__": mp.set_start_method("spawn", force = True) if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/mistral-7b-v0.3", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) EOS_TOKEN = tokenizer.eos_token alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. ### Instruction: {} ### Input: {} ### Response: {}""" # Define helper functions outside of main def formatting_prompts_func(examples): instructions = [] inputs = [] outputs = [] texts = [] for conversation in examples["messages"]: # Extract user message and assistant response user_message = "" assistant_message = "" for turn in conversation: if turn["role"] == "user": user_message = turn["content"] elif turn["role"] == "assistant": assistant_message = turn["content"] # Store intermediate format instruction = "Complete the statement" instructions.append(instruction) inputs.append(user_message) outputs.append(assistant_message) # Create formatted text text = ( alpaca_prompt.format(instruction, user_message, assistant_message) + EOS_TOKEN ) texts.append(text) return { "instruction": instructions, "input": inputs, "output": outputs, "text": texts, } dataset_train = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "train" ) dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) dataset_train = dataset_train.map(formatting_prompts_func, batched = True) dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) add_to_comparison("Base model 4 bits", ppl_model(model, tokenizer, dataset_ppl)) model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 200, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 50, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) # run training trainer_stats = trainer.train() add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl)) # saving and merging the model to local disk print("merge and save to local disk") model.save_pretrained_merged( save_directory = "./unsloth_out/merged_mistral_text_model", tokenizer = tokenizer ) # print("cleaning") # del model # del tokenizer # torch.cuda.empty_cache() # gc.collect() # load model from local disk and test print("Loading merged model in 4 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_mistral_text_model", max_seq_length = 2048, load_in_4bit = True, load_in_8bit = False, ) add_to_comparison( "merged model load 4bit", ppl_model(merged_model, merged_tokenizer, dataset_ppl) ) print("Computing 8-bit model perplexity in subprocess...") result_queue = mp.Queue() p = mp.Process(target = load_and_compute_8bit_ppl, args = (result_queue, False, True)) p.start() p.join() ppl_8bit = result_queue.get() add_to_comparison("merged model loaded 8bits", ppl_8bit) print("Loading merged model in 16 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_mistral_text_model", max_seq_length = 2048, load_in_4bit = False, load_in_8bit = False, ) add_to_comparison( "merged model loaded 16bits", ppl_model(merged_model, merged_tokenizer, dataset_ppl), ) print_model_comparison() safe_remove_directory("./outputs") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./unsloth_out")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_merge_model_perplexity_mistral.py", "license": "Apache License 2.0", "lines": 261, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_merge_model_perplexity_phi_4.py
from unsloth import FastLanguageModel, FastVisionModel, UnslothVisionDataCollator from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import ( DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, TrainingArguments, ) from datasets import load_dataset, Dataset import torch from tqdm import tqdm import pandas as pd import multiprocessing as mp from multiprocessing import Process, Queue import gc # ruff: noqa import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.perplexity_eval import ( ppl_model, add_to_comparison, print_model_comparison, ) # Define helper functions outside of main def formatting_prompts_func(examples): convos = examples["messages"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return { "text": texts, } def load_and_compute_8bit_ppl(result_queue, load_in_4bit = False, load_in_8bit = False): """Load model and compute perplexity in subprocess""" from unsloth import FastLanguageModel from unsloth.chat_templates import get_chat_template from tests.utils.perplexity_eval import ppl_model # Load model merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_phi4_text_model", max_seq_length = 2048, load_in_4bit = load_in_4bit, load_in_8bit = load_in_8bit, ) # Set up tokenizer merged_tokenizer = get_chat_template( merged_tokenizer, chat_template = "phi-4", ) # Load dataset fresh in subprocess dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) # Format the dataset def formatting_prompts_func(examples): convos = examples["messages"] texts = [ merged_tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) # Compute perplexity using the passed dataset ppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl) # IMPORTANT: Convert to Python float if it's a tensor if torch.is_tensor(ppl_value): ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar elif hasattr(ppl_value, "item"): ppl_value = ppl_value.item() # Convert numpy or other array types else: ppl_value = float(ppl_value) # Ensure it's a float # Return only the perplexity value result_queue.put(ppl_value) # Clean up del merged_model del merged_tokenizer del dataset_ppl torch.cuda.empty_cache() gc.collect() # Main execution code should be wrapped in this guard if __name__ == "__main__": mp.set_start_method("spawn", force = True) if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Phi-4", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) tokenizer = get_chat_template( tokenizer, chat_template = "phi-4", ) dataset_train = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "train" ) dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) dataset_train = dataset_train.map(formatting_prompts_func, batched = True) dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) add_to_comparison("Base model 4 bits", ppl_model(model, tokenizer, dataset_ppl)) model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 200, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 50, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) from unsloth.chat_templates import train_on_responses_only trainer = train_on_responses_only( trainer, instruction_part = "<|im_start|>user<|im_sep|>\n\n", response_part = "<|im_start|>assistant<|im_sep|>\n\n", ) # run training trainer_stats = trainer.train() add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl)) # saving and merging the model to local disk print("merge and save to local disk") model.save_pretrained_merged( save_directory = "./unsloth_out/merged_phi4_text_model", tokenizer = tokenizer ) # print("cleaning") # del model # del tokenizer # torch.cuda.empty_cache() # gc.collect() # load model from local disk and test print("Loading merged model in 4 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_phi4_text_model", max_seq_length = 2048, load_in_4bit = True, load_in_8bit = False, ) add_to_comparison( "merged model load 4bit", ppl_model(merged_model, merged_tokenizer, dataset_ppl) ) print("Computing 8-bit model perplexity in subprocess...") result_queue = mp.Queue() p = mp.Process(target = load_and_compute_8bit_ppl, args = (result_queue, False, True)) p.start() p.join() ppl_8bit = result_queue.get() add_to_comparison("merged model loaded 8bits", ppl_8bit) print("Loading merged model in 16 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_phi4_text_model", max_seq_length = 2048, load_in_4bit = False, load_in_8bit = False, ) add_to_comparison( "merged model loaded 16bits", ppl_model(merged_model, merged_tokenizer, dataset_ppl), ) print_model_comparison() # final cleanup safe_remove_directory("./outputs") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./unsloth_out")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_merge_model_perplexity_phi_4.py", "license": "Apache License 2.0", "lines": 217, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_merged_model_perplexity_llama-3.1-8b.py
from unsloth import FastLanguageModel, FastVisionModel, UnslothVisionDataCollator from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import ( DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, TrainingArguments, ) from datasets import load_dataset, Dataset import torch from tqdm import tqdm import pandas as pd import multiprocessing as mp from multiprocessing import Process, Queue import gc # ruff: noqa import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.perplexity_eval import ( ppl_model, add_to_comparison, print_model_comparison, ) # Define helper functions outside of main def formatting_prompts_func(examples): convos = examples["messages"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} def load_and_compute_8bit_ppl(result_queue, load_in_4bit = False, load_in_8bit = False): """Load model and compute perplexity in subprocess""" from unsloth import FastLanguageModel from unsloth.chat_templates import get_chat_template from tests.utils.perplexity_eval import ppl_model # Load model merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_llama_text_model", max_seq_length = 2048, load_in_4bit = load_in_4bit, load_in_8bit = load_in_8bit, ) # Set up tokenizer merged_tokenizer = get_chat_template( merged_tokenizer, chat_template = "llama-3.1", ) # Load dataset fresh in subprocess dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) # Format the dataset def formatting_prompts_func(examples): convos = examples["messages"] texts = [ merged_tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) # Compute perplexity using the passed dataset ppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl) # IMPORTANT: Convert to Python float if it's a tensor if torch.is_tensor(ppl_value): ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar elif hasattr(ppl_value, "item"): ppl_value = ppl_value.item() # Convert numpy or other array types else: ppl_value = float(ppl_value) # Ensure it's a float # Return only the perplexity value result_queue.put(ppl_value) # Clean up del merged_model del merged_tokenizer del dataset_ppl torch.cuda.empty_cache() gc.collect() # Main execution code should be wrapped in this guard if __name__ == "__main__": mp.set_start_method("spawn", force = True) if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Llama-3.1-8B-Instruct", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) tokenizer = get_chat_template( tokenizer, chat_template = "llama-3.1", ) from unsloth.chat_templates import standardize_sharegpt dataset_train = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "train" ) dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) dataset_train = dataset_train.map(formatting_prompts_func, batched = True) dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) print("\n dataset sample [0]") print(dataset_train[0]) add_to_comparison("Base model 4 bits", ppl_model(model, tokenizer, dataset_ppl)) model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 200, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 50, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) from unsloth.chat_templates import train_on_responses_only trainer = train_on_responses_only( trainer, instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n", response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n", ) tokenizer.decode(trainer.train_dataset[0]["input_ids"]) # run training trainer_stats = trainer.train() add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl)) # saving and merging the model to local disk print("merge and save to local disk") model.save_pretrained_merged( save_directory = "./unsloth_out/merged_llama_text_model", tokenizer = tokenizer ) # print("cleaning") # del model # del tokenizer # torch.cuda.empty_cache() # gc.collect() # load model from local disk and test print("Loading merged model in 4 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_llama_text_model", max_seq_length = 2048, load_in_4bit = True, load_in_8bit = False, ) add_to_comparison( "merged model load 4bit", ppl_model(merged_model, merged_tokenizer, dataset_ppl) ) print("Computing 8-bit model perplexity in subprocess...") result_queue = mp.Queue() p = mp.Process(target = load_and_compute_8bit_ppl, args = (result_queue, False, True)) p.start() p.join() ppl_8bit = result_queue.get() add_to_comparison("merged model loaded 8bits", ppl_8bit) print("Loading merged model in 16 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_llama_text_model", max_seq_length = 2048, load_in_4bit = False, load_in_8bit = False, ) add_to_comparison( "merged model loaded 16bits", ppl_model(merged_model, merged_tokenizer, dataset_ppl), ) print_model_comparison() # final cleanup safe_remove_directory("./outputs") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./unsloth_out")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_merged_model_perplexity_llama-3.1-8b.py", "license": "Apache License 2.0", "lines": 219, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_merged_model_perplexity_qwen_2.5.py
from unsloth import FastLanguageModel, FastVisionModel, UnslothVisionDataCollator from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import ( DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, TrainingArguments, ) from datasets import load_dataset, Dataset import torch from tqdm import tqdm import pandas as pd import multiprocessing as mp from multiprocessing import Process, Queue import gc # ruff: noqa import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.perplexity_eval import ( ppl_model, add_to_comparison, print_model_comparison, ) alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. ### Instruction: {} ### Input: {} ### Response: {}""" # Define helper functions outside of main def formatting_prompts_func(examples): instructions = [] inputs = [] outputs = [] texts = [] for conversation in examples["messages"]: # Extract user message and assistant response user_message = "" assistant_message = "" for turn in conversation: if turn["role"] == "user": user_message = turn["content"] elif turn["role"] == "assistant": assistant_message = turn["content"] # Store intermediate format instruction = "Complete the statement" instructions.append(instruction) inputs.append(user_message) outputs.append(assistant_message) # Create formatted text text = alpaca_prompt.format(instruction, user_message, assistant_message) texts.append(text) return { "instruction": instructions, "input": inputs, "output": outputs, "text": texts, } def load_and_compute_8bit_ppl(result_queue, load_in_4bit = False, load_in_8bit = False): """Load model and compute perplexity in subprocess""" from unsloth import FastLanguageModel from tests.utils.perplexity_eval import ppl_model # Load model merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_qwen_text_model", max_seq_length = 2048, load_in_4bit = load_in_4bit, load_in_8bit = load_in_8bit, ) # Set up tokenizer # merged_tokenizer = get_chat_template( # merged_tokenizer, # chat_template="llama-3.1", # ) # Load dataset fresh in subprocess dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. ### Instruction: {} ### Input: {} ### Response: {}""" def formatting_prompts_func(examples): instructions = [] inputs = [] outputs = [] texts = [] for conversation in examples["messages"]: # Extract user message and assistant response user_message = "" assistant_message = "" for turn in conversation: if turn["role"] == "user": user_message = turn["content"] elif turn["role"] == "assistant": assistant_message = turn["content"] # Store intermediate format instruction = "Complete the statement" instructions.append(instruction) inputs.append(user_message) outputs.append(assistant_message) # Create formatted text text = alpaca_prompt.format(instruction, user_message, assistant_message) texts.append(text) return { "instruction": instructions, "input": inputs, "output": outputs, "text": texts, } dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) # Compute perplexity using the passed dataset ppl_value = ppl_model(merged_model, merged_tokenizer, dataset_ppl) # IMPORTANT: Convert to Python float if it's a tensor if torch.is_tensor(ppl_value): ppl_value = ppl_value.cpu().item() # Move to CPU and convert to Python scalar elif hasattr(ppl_value, "item"): ppl_value = ppl_value.item() # Convert numpy or other array types else: ppl_value = float(ppl_value) # Ensure it's a float # Return only the perplexity value result_queue.put(ppl_value) # Clean up # del merged_model # del merged_tokenizer # del dataset_ppl # torch.cuda.empty_cache() # gc.collect() # Main execution code should be wrapped in this guard if __name__ == "__main__": mp.set_start_method("spawn", force = True) if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Qwen2.5-7B-Instruct", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) dataset_train = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "train" ) dataset_ppl = load_dataset( "allenai/openassistant-guanaco-reformatted", split = "eval" ) dataset_train = dataset_train.map(formatting_prompts_func, batched = True) dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) add_to_comparison("Base model 4 bits", ppl_model(model, tokenizer, dataset_ppl)) model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 200, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 50, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) # run training trainer_stats = trainer.train() add_to_comparison("Qlora model", ppl_model(model, tokenizer, dataset_ppl)) # saving and merging the model to local disk print("merge and save to local disk") model.save_pretrained_merged( save_directory = "./unsloth_out/merged_qwen_text_model", tokenizer = tokenizer ) # print("cleaning") # del model # del tokenizer # torch.cuda.empty_cache() # gc.collect() # load model from local disk and test print("Loading merged model in 4 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_qwen_text_model", max_seq_length = 2048, load_in_4bit = True, load_in_8bit = False, ) add_to_comparison( "merged model load 4bit", ppl_model(merged_model, merged_tokenizer, dataset_ppl) ) print("Computing 8-bit model perplexity in subprocess...") result_queue = mp.Queue() p = mp.Process(target = load_and_compute_8bit_ppl, args = (result_queue, False, True)) p.start() p.join() ppl_8bit = result_queue.get() add_to_comparison("merged model loaded 8bits", ppl_8bit) print("Loading merged model in 16 bit for perplexity test") merged_model, merged_tokenizer = FastLanguageModel.from_pretrained( model_name = "./unsloth_out/merged_qwen_text_model", max_seq_length = 2048, load_in_4bit = False, load_in_8bit = False, ) add_to_comparison( "merged model loaded 16bits", ppl_model(merged_model, merged_tokenizer, dataset_ppl), ) print_model_comparison() safe_remove_directory("./outputs") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./unsloth_out")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_merged_model_perplexity_qwen_2.5.py", "license": "Apache License 2.0", "lines": 254, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_push_to_hub_merged.py
from unsloth import FastLanguageModel, FastVisionModel, UnslothVisionDataCollator from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import ( DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, TrainingArguments, ) from datasets import load_dataset, Dataset import torch from tqdm import tqdm import pandas as pd import multiprocessing as mp from multiprocessing import Process, Queue import gc import os from huggingface_hub import HfFileSystem, hf_hub_download # ruff: noqa import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.perplexity_eval import ( ppl_model, add_to_comparison, print_model_comparison, ) # Define helper functions outside of main def formatting_prompts_func(examples): convos = examples["messages"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Llama-3.2-1B-Instruct", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) tokenizer = get_chat_template( tokenizer, chat_template = "llama-3.1", ) from unsloth.chat_templates import standardize_sharegpt dataset_train = load_dataset("allenai/openassistant-guanaco-reformatted", split = "train") dataset_ppl = load_dataset("allenai/openassistant-guanaco-reformatted", split = "eval") dataset_train = dataset_train.map(formatting_prompts_func, batched = True) dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) add_to_comparison("Base model 4 bits", ppl_model(model, tokenizer, dataset_ppl)) model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 30, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 50, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) from unsloth.chat_templates import train_on_responses_only trainer = train_on_responses_only( trainer, instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n", response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n", ) # run training trainer_stats = trainer.train() # saving and merging the model to local disk hf_username = os.environ.get("HF_USER", "") if not hf_username: hf_username = input("Please enter your Hugging Face username: ").strip() os.environ["HF_USER"] = hf_username hf_token = os.environ.get("HF_TOKEN", "") if not hf_token: hf_token = input("Please enter your Hugging Face token: ").strip() os.environ["HF_TOKEN"] = hf_token repo_name = f"{hf_username}/merged_llama_text_model" success = { "upload": False, "download": False, } # Stage 1: Upload model to Hub try: print("\n" + "=" * 80) print("=== UPLOADING MODEL TO HUB ===".center(80)) print("=" * 80 + "\n") model.push_to_hub_merged(repo_name, tokenizer = tokenizer, token = hf_token) success["upload"] = True print("✅ Model uploaded successfully!") except Exception as e: print(f"❌ Failed to upload model: {e}") raise Exception("Model upload failed.") t # Stage 2: Test downloading the model (even if cached) safe_remove_directory(f"./{hf_username}") try: print("\n" + "=" * 80) print("=== TESTING MODEL DOWNLOAD ===".center(80)) print("=" * 80 + "\n") # Force download even if cached model, tokenizer = FastLanguageModel.from_pretrained( f"{hf_username}/merged_llama_text_model" ) success["download"] = True print("✅ Model downloaded successfully!") except Exception as e: print(f"❌ Download failed: {e}") raise Exception("Model download failed.") # Final report print("\n" + "=" * 80) print("=== VALIDATION REPORT ===".center(80)) print("=" * 80 + "\n") for stage, passed in success.items(): status = "✓" if passed else "✗" print(f"{status} {stage.replace('_', ' ').title()}") print("\n" + "=" * 80) if all(success.values()): print("\n🎉 All stages completed successfully!") else: raise Exception("Validation failed for one or more stages.") # final cleanup safe_remove_directory("./outputs") safe_remove_directory("./unsloth_compiled_cache")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_push_to_hub_merged.py", "license": "Apache License 2.0", "lines": 173, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_push_to_hub_merged_sharded_index_file.py
from unsloth import FastLanguageModel, FastVisionModel, UnslothVisionDataCollator from unsloth.chat_templates import get_chat_template from trl import SFTTrainer, SFTConfig from transformers import ( DataCollatorForLanguageModeling, DataCollatorForSeq2Seq, TrainingArguments, ) from datasets import load_dataset, Dataset import torch from tqdm import tqdm import pandas as pd import multiprocessing as mp from multiprocessing import Process, Queue import gc import os from huggingface_hub import HfFileSystem, hf_hub_download # ruff: noqa import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.perplexity_eval import ( ppl_model, add_to_comparison, print_model_comparison, ) # Define helper functions outside of main def formatting_prompts_func(examples): convos = examples["messages"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return {"text": texts} if torch.cuda.is_bf16_supported(): compute_dtype = torch.bfloat16 attn_implementation = "flash_attention_2" else: compute_dtype = torch.float16 attn_implementation = "sdpa" model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/Llama-3.1-8B-Instruct", max_seq_length = 2048, dtype = compute_dtype, load_in_4bit = True, load_in_8bit = False, full_finetuning = False, attn_implementation = attn_implementation, ) tokenizer = get_chat_template( tokenizer, chat_template = "llama-3.1", ) from unsloth.chat_templates import standardize_sharegpt dataset_train = load_dataset("allenai/openassistant-guanaco-reformatted", split = "train") dataset_ppl = load_dataset("allenai/openassistant-guanaco-reformatted", split = "eval") dataset_train = dataset_train.map(formatting_prompts_func, batched = True) dataset_ppl = dataset_ppl.map(formatting_prompts_func, batched = True) add_to_comparison("Base model 4 bits", ppl_model(model, tokenizer, dataset_ppl)) model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = [ "k_proj", "q_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj", ], lora_alpha = 16, lora_dropout = 0, bias = "none", use_gradient_checkpointing = "unsloth", random_state = 3407, use_rslora = False, loftq_config = None, ) from unsloth import is_bfloat16_supported trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = dataset_train, dataset_text_field = "text", max_seq_length = 2048, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_ratio = 0.1, max_steps = 30, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 50, optim = "adamw_8bit", lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", ), ) from unsloth.chat_templates import train_on_responses_only trainer = train_on_responses_only( trainer, instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n", response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n", ) # run training trainer_stats = trainer.train() # saving and merging the model to local disk hf_username = os.environ.get("HF_USER", "") if not hf_username: hf_username = input("Please enter your Hugging Face username: ").strip() os.environ["HF_USER"] = hf_username hf_token = os.environ.get("HF_TOKEN", "") if not hf_token: hf_token = input("Please enter your Hugging Face token: ").strip() os.environ["HF_TOKEN"] = hf_token repo_name = f"{hf_username}/merged_llama_text_model" success = { "upload": False, "safetensors_check": False, "download": False, } # Stage 1: Upload model to Hub try: print("\n" + "=" * 80) print("=== UPLOADING MODEL TO HUB ===".center(80)) print("=" * 80 + "\n") model.push_to_hub_merged(repo_name, tokenizer = tokenizer, token = hf_token) success["upload"] = True print("✅ Model uploaded successfully!") except Exception as e: print(f"❌ Failed to upload model: {e}") raise Exception("Model upload failed.") # Stage 2: Verify safetensors.index.json exists try: print("\n" + "=" * 80) print("=== VERIFYING REPO CONTENTS ===".center(80)) print("=" * 80 + "\n") fs = HfFileSystem(token = hf_token) file_list = fs.ls(repo_name, detail = True) safetensors_found = any( file["name"].endswith("model.safetensors.index.json") for file in file_list ) if safetensors_found: success["safetensors_check"] = True print("✅ model.safetensors.index.json found in repo!") else: raise Exception("model.safetensors.index.json not found in repo.") except Exception as e: print(f"❌ Verification failed: {e}") raise Exception("Repo verification failed.") # Stage 3: Test downloading the model (even if cached) safe_remove_directory("./RTannous") try: print("\n" + "=" * 80) print("=== TESTING MODEL DOWNLOAD ===".center(80)) print("=" * 80 + "\n") # Force download even if cached model, tokenizer = FastLanguageModel.from_pretrained( f"{hf_username}/merged_llama_text_model" ) success["download"] = True print("✅ Model downloaded successfully!") except Exception as e: print(f"❌ Download failed: {e}") raise Exception("Model download failed.") # Final report print("\n" + "=" * 80) print("=== VALIDATION REPORT ===".center(80)) print("=" * 80 + "\n") for stage, passed in success.items(): status = "✓" if passed else "✗" print(f"{status} {stage.replace('_', ' ').title()}") print("\n" + "=" * 80) if all(success.values()): print("\n🎉 All stages completed successfully!") else: raise Exception("Validation failed for one or more stages.") # final cleanup safe_remove_directory("./outputs") safe_remove_directory("./unsloth_compiled_cache")
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_push_to_hub_merged_sharded_index_file.py", "license": "Apache License 2.0", "lines": 191, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/language_models/test_save_merged_grpo_model.py
# -*- coding: utf-8 -*- """test_Llama3_1_(3B)_GRPO_LoRA (1).ipynb ### Unsloth """ from unsloth import FastLanguageModel import torch import sys from pathlib import Path import multiprocessing as mp import gc from multiprocessing import Queue REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.aime_eval import evaluate_model_aime, compare_aime_results max_seq_length = 2048 # Can increase for longer reasoning traces lora_rank = 64 # Larger rank = smarter, but slower def evaluate_merged_model(result_queue, load_in_4bit = False, load_in_8bit = False): from unsloth import FastLanguageModel from tests.utils.aime_eval import evaluate_model_aime max_seq_length = 2048 # Can increase for longer reasoning traces lora_rank = 64 # Larger rank = smarter, but slower model, tokenizer = FastLanguageModel.from_pretrained( model_name = "./final_merged_model", max_seq_length = max_seq_length, load_in_4bit = True, # False for LoRA 16bit fast_inference = True, # Enable vLLM fast inference max_lora_rank = lora_rank, gpu_memory_utilization = 0.8, # Reduce if out of memory ) print(f"\n{'='*60}") if load_in_4bit: print("🔍 EVALUATION Merged model: 4 bits load") model_type = "merged_model_4bits" elif load_in_8bit: print("🔍 EVALUATION Merged model: 8 bits load") model_type = "merged_model_8bits" else: print("🔍 EVALUATION Merged model: 16 bits load") model_type = "merged_model_16bits" print(f"{'='*60}") evaluate_model_aime( model = model, tokenizer = tokenizer, model_type = model_type, temperature = 0.3, n_sampling = 8, max_tokens = 32768, top_p = 0.95, seed = 0, ) result_queue.put(results) del model del tokenizer torch.cuda.empty_cache() gc.collect() # Main execution code should be wrapped in this guard def training_run(result_queue): model, tokenizer = FastLanguageModel.from_pretrained( model_name = "meta-llama/Llama-3.2-3B-Instruct", max_seq_length = max_seq_length, load_in_4bit = False, # False for LoRA 16bit fast_inference = True, # Enable vLLM fast inference max_lora_rank = lora_rank, gpu_memory_utilization = 0.8, # Reduce if out of memory ) """### Helper Functions <a name="Data"></a> #### Helper functions - Data Prep """ import re import json reasoning_start = "<reasoning>" reasoning_end = "</reasoning>" solution_start = "<answer>" solution_end = "</answer>" def extract_hash_answer(text): """Extract answer from GSM8K format""" if "####" not in text: return None return text.split("####")[1].strip() def prepare_gsm8k_dataset(dataset): """Format GSM8K dataset for training""" reasoning_start = "<reasoning>" reasoning_end = "</reasoning>" solution_start = "<answer>" solution_end = "</answer>" system_prompt = ( f"You are given a problem. Think about the problem and reason step by step. " f"Place your thinking process between {reasoning_start} and {reasoning_end}. " f"Then, provide your final numerical solution between {solution_start}{solution_end}" ) def format_gsm8k(example): return { "prompt": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": example["question"]}, ], "answer": extract_hash_answer(example["answer"]), } return dataset.map(format_gsm8k) def prepare_limo_dataset(dataset): """Format LIMO dataset for SFT training""" if dataset is None: return None system_prompt = """You are a helpful reasoning assistant. When given a problem, think through it step by step and provide your answer in the following format: <reasoning> [Your detailed step-by-step reasoning and solution process] </reasoning> <answer> [Your final numerical answer] </answer>""" def format_limo(example): # Create the assistant response assistant_response = f"<reasoning>\n{example['solution']}\n</reasoning>\n<answer>\n{example['answer']}\n</answer>" # Return a DICTIONARY with the conversation in a field return { "prompt": [ # ← This is the key change - wrap in a dict {"role": "system", "content": system_prompt}, {"role": "user", "content": example["question"]}, {"role": "assistant", "content": assistant_response}, ] } return dataset.map(format_limo) print("\n✅ Dataset preparation functions defined!") """#### Helper functions - Evaluation""" def get_max_prompt_length(dataset, tokenizer): """Calculate maximum and average prompt length in dataset""" print("Analyzing prompt lengths...") lengths = dataset.map( lambda x: { "tokens": tokenizer.apply_chat_template( x["prompt"], add_generation_prompt = True, tokenize = True ) }, batched = True, ).map(lambda x: {"length": len(x["tokens"])})["length"] max_length = max(lengths) avg_length = sum(lengths) / len(lengths) min_length = min(lengths) print( f"Prompt lengths - Min: {min_length}, Max: {max_length}, Avg: {avg_length:.1f}" ) return max_length, avg_length def extract_unsloth_answer(text, start_tag = "<SOLUTION>", end_tag = "</SOLUTION>"): """Extract answer from Unsloth SOLUTION tags""" pattern = re.escape(start_tag) + r"(.*?)" + re.escape(end_tag) matches = re.findall(pattern, text, re.DOTALL) if matches: answer = matches[-1] # Get the last match answer = re.sub(r"[%$,]", "", answer).strip() return answer return "" def find_number(search_string): """Find the last number in a string""" numbers = re.compile( r"-?[\d,]*\.?\d+", re.MULTILINE | re.DOTALL | re.IGNORECASE, ).findall(search_string) if numbers: return numbers[-1].replace(",", "").strip() return "" def remove_symbols(x: str) -> str: """Remove commas, percent and dollar symbols""" if not x: return "" return x.replace(",", "").replace("%", "").replace("$", "").strip() def get_num_tokens(text, tokenizer_instance): """Count tokens in text""" if not text: return 0 encoding = tokenizer_instance(text, return_tensors = "pt") return len(encoding["input_ids"][0]) def check_format_compliance(text, format_type = "unsloth"): """Check if response follows expected format""" if format_type == "unsloth": reasoning_start = "<start_reasoning>" reasoning_end = "<end_reasoning>" solution_start = "<SOLUTION>" solution_end = "</SOLUTION>" pattern = ( rf"^[\s]*{re.escape(reasoning_start)}.+?{re.escape(reasoning_end)}.*?" rf"{re.escape(solution_start)}.+?{re.escape(solution_end)}[\s]*$" ) else: return False return bool(re.match(pattern, text.strip(), re.DOTALL)) def normalize_answer(answer): """Normalize answer for comparison""" if not answer: return "" normalized = remove_symbols(str(answer)) try: float_val = float(normalized) if float_val.is_integer(): return str(int(float_val)) else: return str(float_val) except (ValueError, TypeError): return normalized def evaluate_answer_correctness(extracted_answer, ground_truth): """Evaluate answer correctness with multiple criteria""" if not extracted_answer or not ground_truth: return False, False, 0.0 norm_extracted = normalize_answer(extracted_answer) norm_ground_truth = normalize_answer(ground_truth) if norm_extracted == norm_ground_truth: return True, True, 1.0 try: extracted_num = float(norm_extracted) ground_truth_num = float(norm_ground_truth) if ground_truth_num != 0: relative_error = abs(extracted_num - ground_truth_num) / abs( ground_truth_num ) if relative_error < 0.01: return True, True, 0.9 elif relative_error < 0.05: return False, True, 0.7 elif relative_error < 0.10: return False, True, 0.5 else: if extracted_num == 0: return True, True, 1.0 elif abs(extracted_num) < 0.01: return False, True, 0.7 except (ValueError, TypeError): if norm_extracted.lower() == norm_ground_truth.lower(): return True, True, 1.0 return False, False, 0.0 """#### Reward Functions for GRPO""" def match_format_exactly(completions, **kwargs): """Reward function for exact format matching""" reasoning_start = "<reasoning>" reasoning_end = "</reasoning>" solution_start = "<answer>" solution_end = "</answer>" pattern = ( rf"^[\s]*{re.escape(reasoning_start)}.+?{re.escape(reasoning_end)}.*?" rf"{re.escape(solution_start)}.+?{re.escape(solution_end)}[\s]*$" ) responses = [completion[0]["content"] for completion in completions] rewards = [ 3.0 if re.match(pattern, response, re.DOTALL) else 0.0 for response in responses ] return rewards def match_format_approximately(completions, **kwargs): """Reward function for approximate format matching""" reasoning_start = "<reasoning>" reasoning_end = "</reasoning>" solution_start = "<answerr>" solution_end = "</answer>" scores = [] for completion in completions: score = 0 response = completion[0]["content"] score += 0.5 if response.count(reasoning_start) == 1 else -1.0 score += 0.5 if response.count(reasoning_end) == 1 else -1.0 score += 0.5 if response.count(solution_start) == 1 else -1.0 score += 0.5 if response.count(solution_end) == 1 else -1.0 scores.append(score) return scores def check_answer_correctness(prompts, completions, answer, **kwargs): """Reward function for answer correctness""" def extract_solution_answer(text): pattern = r"<answer>(.*?)</answer>" match = re.search(pattern, text, re.DOTALL) if match: return re.sub(r"[%$,]", "", match.group(1)).strip() return "" responses = [completion[0]["content"] for completion in completions] extracted_responses = [extract_solution_answer(r) for r in responses] scores = [] for guess, true_answer in zip(extracted_responses, answer): score = 0 if not guess: scores.append(0) continue if guess == true_answer: score += 3.0 elif guess.strip() == true_answer.strip(): score += 1.5 else: try: ratio = float(guess) / float(true_answer) if 0.9 <= ratio <= 1.1: score += 1.0 elif 0.8 <= ratio <= 1.2: score += 0.5 else: score -= 1.5 except: score -= 1.5 scores.append(score) return scores print("✅ Reward functions defined!") """#### Main Evaluation Function""" import gc """#### Comparison and Memory Management""" def compare_model_results(all_results): """Generate comprehensive comparison of multiple model results""" print(f"\n{'='*80}") print("COMPREHENSIVE MODEL COMPARISON") print(f"{'='*80}") # Main table print( f"{'Model':<15} {'Format %':<10} {'Exact %':<10} {'Plausible %':<12} {'Confidence':<12}" ) print("-" * 80) for result in all_results: print( f"{result['model_type']:<15} " f"{result['correct_format_pct']:<10.1f} " f"{result['exact_match_pct']:<10.1f} " f"{result['plausible_match_pct']:<12.1f} " f"{result['avg_confidence']:<12.3f}" ) # Improvement analysis if len(all_results) > 1: print(f"\n{'='*50}") print("IMPROVEMENT ANALYSIS") print(f"{'='*50}") base_result = all_results[0] for result in all_results[1:]: print(f"\n{result['model_type']} vs {base_result['model_type']}:") format_improvement = ( result["correct_format_pct"] - base_result["correct_format_pct"] ) exact_improvement = ( result["exact_match_pct"] - base_result["exact_match_pct"] ) plausible_improvement = ( result["plausible_match_pct"] - base_result["plausible_match_pct"] ) print(f" Format compliance: {format_improvement:+.1f}%") print(f" Exact matches: {exact_improvement:+.1f}%") print(f" Plausible matches: {plausible_improvement:+.1f}%") # Save comparison comparison_data = { "summary": all_results, "best_model": max(all_results, key = lambda x: x["exact_match_pct"]), } with open("model_comparison_comprehensive.json", "w") as f: json.dump(comparison_data, f, indent = 4) print( f"\nBest performing model: {comparison_data['best_model']['model_type']} " f"({comparison_data['best_model']['exact_match_pct']:.1f}% exact matches)" ) def cleanup_memory(): """Comprehensive memory cleanup""" print("🧹 Cleaning up GPU memory...") for _ in range(10): torch.cuda.empty_cache() gc.collect() if torch.cuda.is_available(): allocated = torch.cuda.memory_allocated() / 1024**3 reserved = torch.cuda.memory_reserved() / 1024**3 print( f"GPU memory - Allocated: {allocated:.2f} GB, Reserved: {reserved:.2f} GB" ) """#### Data Loading and Preparation""" from datasets import load_dataset # Load GSM8K gsm8k_dataset = load_dataset("openai/gsm8k", "main", split = "train") # Load LIMO (adjust this based on your access method) limo_train = load_dataset("GAIR/LIMO", split = "train") # Prepare datasets gsm8k_train = prepare_gsm8k_dataset(gsm8k_dataset) limo_train = prepare_limo_dataset(limo_train) print(f" GSM8K train: {len(gsm8k_train)}") print(f" LIMO train: {len(limo_train) if limo_train else 0}") # Store results all_results = [] # Single temperature evaluation on combined dataset results = evaluate_model_aime( model = model, tokenizer = tokenizer, model_type = "base", temperature = 0.3, n_sampling = 8, max_tokens = 32768, top_p = 0.95, seed = 0, ) from unsloth.chat_templates import get_chat_template tokenizer = get_chat_template( tokenizer, chat_template = "llama-3.1", ) def formatting_prompts_func(examples): convos = examples["prompt"] texts = [ tokenizer.apply_chat_template( convo, tokenize = False, add_generation_prompt = False ) for convo in convos ] return { "text": texts, } limo_train = limo_train.map( formatting_prompts_func, batched = True, ) from trl import SFTTrainer from transformers import DataCollatorForSeq2Seq, TrainingArguments from unsloth import is_bfloat16_supported print(f"\n{'*'*60}") print("🎯 STAGE 1: Qlora Fine-Tuning on LIMO") print(f"{'*'*60}") model = FastLanguageModel.get_peft_model( model, r = lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 target_modules = [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", ], # Remove QKVO if out of memory lora_alpha = lora_rank, use_gradient_checkpointing = "unsloth", # Enable long context finetuning random_state = 3407, ) if limo_train is not None: trainer = SFTTrainer( model = model, tokenizer = tokenizer, train_dataset = limo_train, dataset_text_field = "text", max_seq_length = max_seq_length, data_collator = DataCollatorForSeq2Seq(tokenizer = tokenizer), dataset_num_proc = 2, packing = False, # Can make training 5x faster for short sequences. args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_steps = 5, num_train_epochs = 1, # Set this for 1 full training run. # max_steps = 60, learning_rate = 2e-4, fp16 = not is_bfloat16_supported(), bf16 = is_bfloat16_supported(), logging_steps = 1, optim = "adamw_8bit", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "outputs", report_to = "none", # Use this for WandB etc ), ) from unsloth.chat_templates import train_on_responses_only trainer = train_on_responses_only( trainer, instruction_part = "<|start_header_id|>user<|end_header_id|>\n\n", response_part = "<|start_header_id|>assistant<|end_header_id|>\n\n", ) # Train print(f"🚂 Starting SFT training on {len(limo_train)} examples...") trainer.train() # Save checkpoint model.save_pretrained("qlora_checkpoint") tokenizer.save_pretrained("qlora_checkpoint") print("💾 Qlora checkpoint saved!") # Cleanup del trainer cleanup_memory() print("✅ Qlora training completed!") else: print("⚠️ Skipping Qlora training - no LIMO dataset available") # Cleanup cleanup_memory() global PRINTED_TIMES PRINTED_TIMES = 0 global PRINT_EVERY_STEPS PRINT_EVERY_STEPS = 5 match_numbers = re.compile( solution_start + r".*?([\d\.\,]{1,})", flags = re.MULTILINE | re.DOTALL ) def check_numbers(prompts, completions, answer, **kwargs): question = prompts[0][-1]["content"] responses = [completion[0]["content"] for completion in completions] extracted_responses = [ guess.group(1) if (guess := match_numbers.search(r)) is not None else None for r in responses ] scores = [] # Print only every few steps global PRINTED_TIMES global PRINT_EVERY_STEPS if PRINTED_TIMES % PRINT_EVERY_STEPS == 0: print( "*" * 20, f"Question:\n{question}", f"\nAnswer:\n{answer[0]}", f"\nResponse:\n{responses[0]}", f"\nExtracted:\n{extracted_responses[0]}", ) PRINTED_TIMES += 1 for guess, true_answer in zip(extracted_responses, answer): if guess is None: scores.append(0) continue # Convert to numbers try: true_answer = float(true_answer.strip()) # Remove commas like in 123,456 guess = float(guess.strip().replace(",", "")) scores.append(1.5 if guess == true_answer else -0.5) except: scores.append(0) continue return scores print(f"\n{'*'*60}") print("🎯 STAGE 2: GRPO Fine-Tuning on GSM8K") print(f"{'*'*60}") # Get max prompt length max_prompt_length, _ = get_max_prompt_length(gsm8k_train, tokenizer) max_prompt_length = min(max_prompt_length + 10, 512) # Add buffer, cap at 512 print(f"Using max_prompt_length: {max_prompt_length}") from trl import GRPOConfig, GRPOTrainer training_args = GRPOConfig( learning_rate = 5e-6, weight_decay = 0.1, warmup_ratio = 0.1, lr_scheduler_type = "cosine", optim = "adamw_torch_fused", logging_steps = 1, per_device_train_batch_size = 1, gradient_accumulation_steps = 4, # Increase to 4 for smoother training num_generations = 8, # Decrease if out of memory max_prompt_length = max_prompt_length, max_completion_length = max_seq_length - max_prompt_length, # num_train_epochs = 1, # Set to 1 for a full training run # max_steps = 250, max_steps = 1000, save_steps = 250, max_grad_norm = 0.1, report_to = "none", # Can use Weights & Biases output_dir = "outputs", ) trainer = GRPOTrainer( model = model, processing_class = tokenizer, reward_funcs = [ match_format_exactly, match_format_approximately, check_answer_correctness, check_numbers, ], args = training_args, train_dataset = gsm8k_train, ) # Train print(f"🚂 Starting GRPO training on {len(gsm8k_train)} examples...") trainer.train() # Save checkpoint model.save_pretrained("grpo_checkpoint") tokenizer.save_pretrained("grpo_checkpoint") print("💾 GRPO checkpoint saved!") # Cleanup del trainer del training_args cleanup_memory() print("✅ GRPO training completed!") print(f"\n{'='*60}") print("🔍 EVALUATION 3: Final GRPO Model") print(f"{'='*60}") grpo_results = evaluate_model_aime( model = model, tokenizer = tokenizer, model_type = "grpo", temperature = 0.3, n_sampling = 8, max_tokens = 32768, top_p = 0.95, seed = 0, ) all_results.append(grpo_results) print("✅ Final model evaluation complete!") print(f"\n{'='*60}") print("💾 SAVING FINAL MODEL") print(f"{'='*60}") # Save as merged model try: model.save_pretrained_merged( "final_merged_model", tokenizer, save_method = "merged_16bit" ) print("✅ Merged model saved to: final_merged_model/") except Exception as e: print(f"⚠️ Could not save merged model: {e}") print("Final model saved as LoRA adapter only") print("💾 Model saving complete!") safe_remove_directory("./unsloth_compiled_cache") result_queue.put(results) # Clean up del model del tokenizer torch.cuda.empty_cache() gc.collect() # # Merged model load 16 bits model AIME eval # result_queue = mp.Queue() # p = mp.Process(target=evaluate_merged_model, args=(result_queue, False, False)) # p.start() # p.join() # # merged_16bits = result_queue.get() # all_results.append(merged_16bits) # # # Clean up # del merged_model # del merged_tokenizer # del dataset_ppl # torch.cuda.empty_cache() # gc.collect() # # safe_remove_directory("./unsloth_compiled_cache") # # # Merged model load 8 bits model AIME eval # # result_queue = mp.Queue() # p = mp.Process(target=evaluate_merged_model, args=(result_queue, False, True)) # p.start() # p.join() # # merged_16bits = result_queue.get() # all_results.append(merged_16bits) # Merged model load 4 bits AIME eval # result_queue = mp.Queue() # p = mp.Process(target=evaluate_merged_model, args=(result_queue, True, False)) # p.start() # p.join() # # merged_16bits = result_queue.get() # all_results.append(merged_16bits) if __name__ == "__main__": mp.set_start_method("spawn", force = True) result_queue = mp.Queue() all_results = [] # run main finetuning and grpo loop p = mp.Process(target = training_run, args = (result_queue,)) p.start() p.join() results = result_queue.get() all_results = results # evaluate merged model loaded 16bits p = mp.Process(target = evaluate_merged_model, args = (result_queue, False, False)) p.start() p.join() merged_load_16bits = result_queue.get() all_results.append(merged_load_16bits) safe_remove_directory("./unsloth_compiled_cache") # Merged model load 8 bits model AIME eval p = mp.Process(target = evaluate_merged_model, args = (result_queue, False, True)) p.start() p.join() merged_load_8bits = result_queue.get() all_results.append(merged_load_8bits) safe_remove_directory("./unsloth_compiled_cache") # Merged model load 4 bits model AIME eval p = mp.Process(target = evaluate_merged_model, args = (result_queue, True, False)) p.start() p.join() merged_load_4bits = result_queue.get() all_results.append(merged_load_4bits) safe_remove_directory("./unsloth_compiled_cache") # AIME-specific comparison function print(f"\n{'='*80}") print("🏆 FINAL TRAINING PIPELINE RESULTS") print(f"{'='*80}") # Use the AIME-specific comparison compare_aime_results(all_results)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/language_models/test_save_merged_grpo_model.py", "license": "Apache License 2.0", "lines": 676, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/vision_models/test_index_file_sharded_model.py
## Import required libraries from unsloth import FastVisionModel, is_bf16_supported from unsloth.trainer import UnslothVisionDataCollator import torch import os from datasets import load_dataset from trl import SFTTrainer, SFTConfig from huggingface_hub import HfFileSystem import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory ## Dataset Preparation""" print("\n📊 Loading and preparing dataset...") dataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train") # To select the first 2000 examples train_dataset = dataset.select(range(2000)) # To select the next 200 examples for evaluation eval_dataset = dataset.select(range(2000, 2200)) print(f"✅ Dataset loaded successfully!") print(f" 📈 Training samples: {len(train_dataset)}") print(f" 📊 Evaluation samples: {len(eval_dataset)}") # Convert dataset to OAI messages def format_data(sample): return { "messages": [ { "role": "system", "content": [{"type": "text", "text": system_message}], }, { "role": "user", "content": [ { "type": "text", "text": sample["question"], }, { "type": "image", "image": sample["image"], }, ], }, { "role": "assistant", "content": [{"type": "text", "text": sample["answer"]}], }, ], } print("\n🔄 Formatting dataset for vision training...") system_message = "You are an expert french ocr system." # Convert dataset to OAI messages # need to use list comprehension to keep Pil.Image type, .mape convert image to bytes train_dataset = [format_data(sample) for sample in train_dataset] eval_dataset = [format_data(sample) for sample in eval_dataset] print("✅ Dataset formatting completed!") """## Finetuning Setup and Run""" print("\n" + "=" * 80) print("=== MODEL LOADING AND SETUP ===".center(80)) print("=" * 80 + "\n") # Load Base Model print("🤖 Loading base vision model...") try: model, tokenizer = FastVisionModel.from_pretrained( # model_name = "unsloth/Qwen2-VL-7B-Instruct", model_name = "unsloth/Qwen2-VL-7B-Instruct", max_seq_length = 2048, # Choose any for long context! load_in_4bit = True, # 4 bit quantization to reduce memory load_in_8bit = False, # [NEW!] A bit more accurate, uses 2x memory full_finetuning = False, # [NEW!] We have full finetuning now! ) except Exception as e: print(f"❌ Failed to load base model: {e}") raise print("\n🔧 Setting up LoRA configuration...") ## Lora Finetuning try: model = FastVisionModel.get_peft_model( model, finetune_vision_layers = True, # Turn off for just text! finetune_language_layers = True, # Should leave on! finetune_attention_modules = True, # Attention good for GRPO finetune_mlp_modules = True, # SHould leave on always! r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 lora_alpha = 32, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ ) print("✅ LoRA configuration applied successfully!") print(f" 🎯 LoRA rank (r): 16") print(f" 📊 LoRA alpha: 32") print(f" 🔍 Vision layers: Enabled") print(f" 💬 Language layers: Enabled") except Exception as e: print(f"❌ Failed to apply LoRA configuration: {e}") raise print("\n" + "=" * 80) print("=== TRAINING SETUP ===".center(80)) print("=" * 80 + "\n") print("🏋️ Preparing trainer...") FastVisionModel.for_training(model) # Enable for training! try: trainer = SFTTrainer( model = model, tokenizer = tokenizer, data_collator = UnslothVisionDataCollator(model, tokenizer), train_dataset = train_dataset, args = SFTConfig( # per_device_train_batch_size = 4, # gradient_accumulation_steps = 8, per_device_train_batch_size = 2, gradient_accumulation_steps = 4, gradient_checkpointing = True, gradient_checkpointing_kwargs = { "use_reentrant": False }, # use reentrant checkpointing max_grad_norm = 0.3, # max gradient norm based on QLoRA paper warmup_ratio = 0.03, # num_train_epochs = 2, # Set this instead of max_steps for full training runs max_steps = 10, learning_rate = 2e-4, fp16 = not is_bf16_supported(), bf16 = is_bf16_supported(), logging_steps = 5, save_strategy = "epoch", optim = "adamw_torch_fused", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "checkpoints", report_to = "none", # For Weights and Biases # You MUST put the below items for vision finetuning: remove_unused_columns = False, dataset_text_field = "", dataset_kwargs = {"skip_prepare_dataset": True}, dataset_num_proc = 4, max_seq_length = 2048, ), ) print("✅ Trainer setup completed!") print(f" 📦 Batch size: 2") print(f" 🔄 Gradient accumulation steps: 4") print(f" 📈 Max training steps: 10") print(f" 🎯 Learning rate: 2e-4") print(f" 💾 Precision: {'BF16' if is_bf16_supported() else 'FP16'}") except Exception as e: print(f"❌ Failed to setup trainer: {e}") raise print("\n" + "=" * 80) print("=== STARTING TRAINING ===".center(80)) print("=" * 80 + "\n") # run training try: print("🚀 Starting training process...") trainer_stats = trainer.train() except Exception as e: print(f"❌ Training failed: {e}") raise print("\n" + "=" * 80) print("=== SAVING MODEL ===".center(80)) print("=" * 80 + "\n") print("💾 Saving adapter model and tokenizer locally...") try: model.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter", tokenizer) tokenizer.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter") print("✅ Model saved locally!") except Exception as e: print(f"❌ Failed to save model locally: {e}") raise hf_username = os.environ.get("HF_USER", "") if not hf_username: hf_username = input("Please enter your Hugging Face username: ").strip() os.environ["HF_USER"] = hf_username hf_token = os.environ.get("HF_TOKEN", "") if not hf_token: hf_token = input("Please enter your Hugging Face token: ").strip() os.environ["HF_TOKEN"] = hf_token repo_name = f"{hf_username}/qwen2-7b-ocr-merged" success = { "upload": False, "safetensors_check": False, "download": False, } # Stage 1: Upload model to Hub try: print("\n" + "=" * 80) print("=== UPLOADING MODEL TO HUB ===".center(80)) print("=" * 80 + "\n") print(f"🚀 Uploading to repository: {repo_name}") model.push_to_hub_merged(repo_name, tokenizer = tokenizer, token = hf_token) success["upload"] = True print("✅ Model uploaded successfully!") except Exception as e: print(f"❌ Failed to upload model: {e}") raise Exception("Model upload failed.") # Stage 2: Verify safetensors.index.json exists try: print("\n" + "=" * 80) print("=== VERIFYING REPO CONTENTS ===".center(80)) print("=" * 80 + "\n") fs = HfFileSystem(token = hf_token) file_list = fs.ls(repo_name, detail = True) safetensors_found = any( file["name"].endswith("model.safetensors.index.json") for file in file_list ) if safetensors_found: success["safetensors_check"] = True print("✅ model.safetensors.index.json found in repo!") else: raise Exception("model.safetensors.index.json not found in repo.") except Exception as e: print(f"❌ Verification failed: {e}") raise Exception("Repo verification failed.") # test downloading model even if cached safe_remove_directory(f"./{hf_username}") try: print("\n" + "=" * 80) print("=== TESTING MODEL DOWNLOAD ===".center(80)) print("=" * 80 + "\n") print("📥 Testing model download...") # Force download even if cached test_model, test_tokenizer = FastVisionModel.from_pretrained(repo_name) success["download"] = True print("✅ Model downloaded successfully!") # Clean up test model del test_model, test_tokenizer torch.cuda.empty_cache() except Exception as e: print(f"❌ Download failed: {e}") raise Exception("Model download failed.") # Final report print("\n" + "=" * 80) print("=== VALIDATION REPORT ===".center(80)) print("=" * 80 + "\n") for stage, passed in success.items(): status = "✅" if passed else "❌" print(f"{status} {stage.replace('_', ' ').title()}") print("\n" + "=" * 80) if all(success.values()): print("\n🎉 All stages completed successfully!") print(f"🌐 Your model is available at: https://huggingface.co/{repo_name}") else: raise Exception("Validation failed for one or more stages.") # Final cleanup print("\n🧹 Cleaning up temporary files...") safe_remove_directory("./checkpoints") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./unsloth-qwen2-7vl-french-ocr-adapter") print("\n🎯 Pipeline completed successfully!") print("=" * 80)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/vision_models/test_index_file_sharded_model.py", "license": "Apache License 2.0", "lines": 255, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/vision_models/test_push_to_hub_merged.py
## Import required libraries from unsloth import FastVisionModel, is_bf16_supported from unsloth.trainer import UnslothVisionDataCollator import torch import os from datasets import load_dataset from trl import SFTTrainer, SFTConfig import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory ## Dataset Preparation""" print("\n📊 Loading and preparing dataset...") dataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train") # To select the first 2000 examples train_dataset = dataset.select(range(2000)) # To select the next 200 examples for evaluation eval_dataset = dataset.select(range(2000, 2200)) print(f"✅ Dataset loaded successfully!") print(f" 📈 Training samples: {len(train_dataset)}") print(f" 📊 Evaluation samples: {len(eval_dataset)}") # Convert dataset to OAI messages def format_data(sample): return { "messages": [ { "role": "system", "content": [{"type": "text", "text": system_message}], }, { "role": "user", "content": [ { "type": "text", "text": sample["question"], }, { "type": "image", "image": sample["image"], }, ], }, { "role": "assistant", "content": [{"type": "text", "text": sample["answer"]}], }, ], } print("\n🔄 Formatting dataset for vision training...") system_message = "You are an expert french ocr system." # Convert dataset to OAI messages # need to use list comprehension to keep Pil.Image type, .mape convert image to bytes train_dataset = [format_data(sample) for sample in train_dataset] eval_dataset = [format_data(sample) for sample in eval_dataset] print("✅ Dataset formatting completed!") """## Finetuning Setup and Run""" print("\n" + "=" * 80) print("=== MODEL LOADING AND SETUP ===".center(80)) print("=" * 80 + "\n") # Load Base Model print("🤖 Loading base vision model...") try: model, tokenizer = FastVisionModel.from_pretrained( # model_name = "unsloth/Qwen2-VL-7B-Instruct", model_name = "unsloth/Qwen2-VL-2B-Instruct", max_seq_length = 2048, # Choose any for long context! load_in_4bit = True, # 4 bit quantization to reduce memory load_in_8bit = False, # [NEW!] A bit more accurate, uses 2x memory full_finetuning = False, # [NEW!] We have full finetuning now! ) except Exception as e: print(f"❌ Failed to load base model: {e}") raise print("\n🔧 Setting up LoRA configuration...") ## Lora Finetuning try: model = FastVisionModel.get_peft_model( model, finetune_vision_layers = True, # Turn off for just text! finetune_language_layers = True, # Should leave on! finetune_attention_modules = True, # Attention good for GRPO finetune_mlp_modules = True, # SHould leave on always! r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 lora_alpha = 32, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ ) print("✅ LoRA configuration applied successfully!") print(f" 🎯 LoRA rank (r): 16") print(f" 📊 LoRA alpha: 32") print(f" 🔍 Vision layers: Enabled") print(f" 💬 Language layers: Enabled") except Exception as e: print(f"❌ Failed to apply LoRA configuration: {e}") raise print("\n" + "=" * 80) print("=== TRAINING SETUP ===".center(80)) print("=" * 80 + "\n") print("🏋️ Preparing trainer...") FastVisionModel.for_training(model) # Enable for training! try: trainer = SFTTrainer( model = model, tokenizer = tokenizer, data_collator = UnslothVisionDataCollator(model, tokenizer), train_dataset = train_dataset, args = SFTConfig( # per_device_train_batch_size = 4, # gradient_accumulation_steps = 8, per_device_train_batch_size = 2, gradient_accumulation_steps = 4, gradient_checkpointing = True, gradient_checkpointing_kwargs = { "use_reentrant": False }, # use reentrant checkpointing max_grad_norm = 0.3, # max gradient norm based on QLoRA paper warmup_ratio = 0.03, # num_train_epochs = 2, # Set this instead of max_steps for full training runs max_steps = 10, learning_rate = 2e-4, fp16 = not is_bf16_supported(), bf16 = is_bf16_supported(), logging_steps = 5, save_strategy = "epoch", optim = "adamw_torch_fused", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "checkpoints", report_to = "none", # For Weights and Biases # You MUST put the below items for vision finetuning: remove_unused_columns = False, dataset_text_field = "", dataset_kwargs = {"skip_prepare_dataset": True}, dataset_num_proc = 4, max_seq_length = 2048, ), ) print("✅ Trainer setup completed!") print(f" 📦 Batch size: 2") print(f" 🔄 Gradient accumulation steps: 4") print(f" 📈 Max training steps: 10") print(f" 🎯 Learning rate: 2e-4") print(f" 💾 Precision: {'BF16' if is_bf16_supported() else 'FP16'}") except Exception as e: print(f"❌ Failed to setup trainer: {e}") raise print("\n" + "=" * 80) print("=== STARTING TRAINING ===".center(80)) print("=" * 80 + "\n") # run training try: print("🚀 Starting training process...") trainer_stats = trainer.train() except Exception as e: print(f"❌ Training failed: {e}") raise print("\n" + "=" * 80) print("=== SAVING MODEL ===".center(80)) print("=" * 80 + "\n") print("💾 Saving adapter model and tokenizer locally...") try: model.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter", tokenizer) tokenizer.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter") print("✅ Model saved locally!") except Exception as e: print(f"❌ Failed to save model locally: {e}") raise hf_username = os.environ.get("HF_USER", "") if not hf_username: hf_username = input("Please enter your Hugging Face username: ").strip() os.environ["HF_USER"] = hf_username hf_token = os.environ.get("HF_TOKEN", "") if not hf_token: hf_token = input("Please enter your Hugging Face token: ").strip() os.environ["HF_TOKEN"] = hf_token repo_name = f"{hf_username}/qwen2-ocr-merged" success = { "upload": False, "download": False, } # Stage 1: Upload model to Hub try: print("\n" + "=" * 80) print("=== UPLOADING MODEL TO HUB ===".center(80)) print("=" * 80 + "\n") print(f"🚀 Uploading to repository: {repo_name}") model.push_to_hub_merged(repo_name, tokenizer = tokenizer, token = hf_token) success["upload"] = True print("✅ Model uploaded successfully!") except Exception as e: print(f"❌ Failed to upload model: {e}") raise Exception("Model upload failed.") try: print("\n" + "=" * 80) print("=== TESTING MODEL DOWNLOAD ===".center(80)) print("=" * 80 + "\n") print("📥 Testing model download...") # Force download even if cached test_model, test_tokenizer = FastVisionModel.from_pretrained(repo_name) success["download"] = True print("✅ Model downloaded successfully!") # Clean up test model del test_model, test_tokenizer torch.cuda.empty_cache() except Exception as e: print(f"❌ Download failed: {e}") raise Exception("Model download failed.") # Final report print("\n" + "=" * 80) print("=== VALIDATION REPORT ===".center(80)) print("=" * 80 + "\n") for stage, passed in success.items(): status = "✅" if passed else "❌" print(f"{status} {stage.replace('_', ' ').title()}") print("\n" + "=" * 80) if all(success.values()): print("\n🎉 All stages completed successfully!") print(f"🌐 Your model is available at: https://huggingface.co/{repo_name}") else: raise Exception("Validation failed for one or more stages.") # Final cleanup print("\n🧹 Cleaning up temporary files...") safe_remove_directory("./checkpoints") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./unsloth-qwen2-7vl-french-ocr-adapter") safe_remove_directory(f"./{hf_username}") print("\n🎯 Pipeline completed successfully!") print("=" * 80)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/vision_models/test_push_to_hub_merged.py", "license": "Apache License 2.0", "lines": 234, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/saving/vision_models/test_save_merge_vision_model_ocr_benchmark.py
# -*- coding: utf-8 -*- from unsloth import FastVisionModel import torch from qwen_vl_utils import process_vision_info import os from datasets import load_dataset from trl import SFTTrainer, SFTConfig import sys from pathlib import Path REPO_ROOT = Path(__file__).parents[3] sys.path.insert(0, str(REPO_ROOT)) from tests.utils.cleanup_utils import safe_remove_directory from tests.utils.ocr_eval import OCRModelEvaluator ## Dataset Preparation from datasets import load_dataset dataset = load_dataset("lbourdois/OCR-liboaccn-OPUS-MIT-5M-clean", "en", split = "train") # To select the first 2000 examples train_dataset = dataset.select(range(2000)) # To select the next 200 examples for evaluation eval_dataset = dataset.select(range(2000, 2200)) # Convert dataset to OAI messages def format_data(sample): return { "messages": [ { "role": "system", "content": [{"type": "text", "text": system_message}], }, { "role": "user", "content": [ { "type": "text", "text": sample["question"], }, { "type": "image", "image": sample["image"], }, ], }, { "role": "assistant", "content": [{"type": "text", "text": sample["answer"]}], }, ], } system_message = "You are an expert french ocr system." # Convert dataset to OAI messages # need to use list comprehension to keep Pil.Image type, .mape convert image to bytes train_dataset = [format_data(sample) for sample in train_dataset] eval_dataset = [format_data(sample) for sample in eval_dataset] ## Setup OCR main evaluation function and helpers import os import torch from tqdm import tqdm import pandas as pd from jiwer import wer, cer from qwen_vl_utils import process_vision_info # ocr_evaluator = OCRModelEvaluator() model_comparison_results = {} ## Finetuning Setup and Run # Load Base Model model, tokenizer = FastVisionModel.from_pretrained( model_name = "unsloth/Qwen2-VL-7B-Instruct", max_seq_length = 2048, # Choose any for long context! load_in_4bit = True, # 4 bit quantization to reduce memory load_in_8bit = False, # [NEW!] A bit more accurate, uses 2x memory full_finetuning = False, # [NEW!] We have full finetuning now! ) # benchmark base model performance model_name = "Unsloth Base model" FastVisionModel.for_inference(model) avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_base_model_results" ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) ## Lora Finetuning model = FastVisionModel.get_peft_model( model, finetune_vision_layers = True, # Turn off for just text! finetune_language_layers = True, # Should leave on! finetune_attention_modules = True, # Attention good for GRPO finetune_mlp_modules = True, # SHould leave on always! r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128 # target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", # "gate_proj", "up_proj", "down_proj",], lora_alpha = 32, lora_dropout = 0, # Supports any, but = 0 is optimized bias = "none", # Supports any, but = "none" is optimized # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes! use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context random_state = 3407, use_rslora = False, # We support rank stabilized LoRA loftq_config = None, # And LoftQ ) from unsloth import is_bf16_supported from unsloth.trainer import UnslothVisionDataCollator FastVisionModel.for_training(model) # Enable for training! model.config.use_cache = False trainer = SFTTrainer( model = model, tokenizer = tokenizer, data_collator = UnslothVisionDataCollator(model, tokenizer), train_dataset = train_dataset, args = SFTConfig( # per_device_train_batch_size = 4, # gradient_accumulation_steps = 8, per_device_train_batch_size = 2, gradient_accumulation_steps = 4, gradient_checkpointing = True, gradient_checkpointing_kwargs = { "use_reentrant": False }, # use reentrant checkpointing max_grad_norm = 0.3, # max gradient norm based on QLoRA paper warmup_ratio = 0.03, # num_train_epochs = 2, # Set this instead of max_steps for full training runs max_steps = 60, learning_rate = 2e-4, fp16 = not is_bf16_supported(), bf16 = is_bf16_supported(), logging_steps = 5, save_strategy = "epoch", optim = "adamw_torch_fused", weight_decay = 0.01, lr_scheduler_type = "linear", seed = 3407, output_dir = "unsloth-qwen2-7vl-french-ocr-checkpoints", report_to = "none", # For Weights and Biases # You MUST put the below items for vision finetuning: remove_unused_columns = False, dataset_text_field = "", dataset_kwargs = {"skip_prepare_dataset": True}, dataset_num_proc = 4, max_seq_length = 2048, ), ) # run training trainer_stats = trainer.train() model.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter", tokenizer) tokenizer.save_pretrained("unsloth-qwen2-7vl-french-ocr-adapter") ## Measure Adapter Performance # benchmark lora model performance model_name = "Unsloth lora adapter model" FastVisionModel.for_inference(model) avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_lora_model_results" ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) ## Merge Model def find_lora_base_model(model_to_inspect): current = model_to_inspect if hasattr(current, "base_model"): current = current.base_model if hasattr(current, "model"): current = current.model return current base = find_lora_base_model(model) print((base.__class__.__name__)) # merge default 16 bits model.save_pretrained_merged( save_directory = "qwen2-ocr-merged-finetune-merge-16bit", tokenizer = tokenizer ) ## Benchmark merged model performance ### 16 bits merged model model, tokenizer = FastVisionModel.from_pretrained( "./qwen2-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = False ) # benchmark 4bit loaded, 16bits merged model performance model_name = "Unsloth 16bits-merged model load-16bits" model.config.use_cache = True avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_16bits_merged_model_load_16bits_results", ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # load 16bits-merged model in 4 bits model, tokenizer = FastVisionModel.from_pretrained( "./qwen2-ocr-merged-finetune-merge-16bit", load_in_4bit = True, load_in_8bit = False ) # benchmark 4bit loaded, 16bits merged model performance model_name = "Unsloth 16bits-merged model load-4bits" model.config.use_cache = True avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_16bits_merged_model_load_4bits_results", ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # load model in 8 bits model, tokenizer = FastVisionModel.from_pretrained( "./qwen2-ocr-merged-finetune-merge-16bit", load_in_4bit = False, load_in_8bit = True ) # benchmark 4bit loaded, 16bits merged model performance model_name = "Unsloth 16bits-merged model load-8bits" avg_wer, avg_cer = ocr_evaluator.evaluate_model( model, tokenizer, eval_dataset, output_dir = "unsloth_16bits_merged_model_load_8bits_results", ) ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # """### 4 bits merged model""" # # # load 4bits-merged model in 4 bits # model, tokenizer = FastVisionModel.from_pretrained("./qwen2-ocr-merged-finetune-merge-4bit",load_in_4bit=True, load_in_8bit=False) # # # benchmark 4bit loaded, 4bits merged model performance # model_name = "Unsloth 4bits-merged model load-4bits" # # avg_wer, avg_cer = ocr_evaluator.evaluate_model(model, tokenizer, eval_dataset, output_dir="unsloth_4bits_merged_model_load_4bits_results") # ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # # # load model in 8 bits # model, tokenizer = FastVisionModel.from_pretrained("./qwen2-ocr-merged-finetune-merge-4bit",load_in_4bit=False, load_in_8bit=True) # # # benchmark 8bit loaded, 4bits merged model performance # model_name = "Unsloth 4bits-merged model load-8bits" # # avg_wer, avg_cer = ocr_evaluator.evaluate_model(model, tokenizer, eval_dataset, output_dir="unsloth_4bits_merged_model_load_8bits_results") # ocr_evaluator.add_to_comparison(model_name, avg_wer, avg_cer) # Model comparison report # print model comparison ocr_evaluator.print_model_comparison() # Final cleanup print("\n🧹 Cleaning up temporary files...") safe_remove_directory("./unsloth-qwen2-7vl-french-ocr-adapter") safe_remove_directory("./unsloth-qwen2-7vl-french-ocr-checkpoints") safe_remove_directory("./unsloth_compiled_cache") safe_remove_directory("./qwen2-ocr-merged-finetune-merge-16bit") print("\n🎯 Pipeline completed successfully!") print("=" * 80)
{ "repo_id": "unslothai/unsloth", "file_path": "tests/saving/vision_models/test_save_merge_vision_model_ocr_benchmark.py", "license": "Apache License 2.0", "lines": 236, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/utils/aime_eval.py
""" AIME Dataset Evaluation Module This module provides functions to evaluate language models on the combined AIME dataset (test2024 + test2025-I + test2025-II). """ import json import requests import os import re import logging from typing import List, Dict, Any from tqdm import tqdm from vllm import SamplingParams def download_and_combine_aime_datasets(data_dir: str = "./data/aime") -> str: """Download all AIME datasets and combine them into a single file""" datasets = { "test2024": "https://raw.githubusercontent.com/GAIR-NLP/AIME-Preview/main/eval/data/aime/test2024.jsonl", "test2025-I": "https://raw.githubusercontent.com/GAIR-NLP/AIME-Preview/main/eval/data/aime/test2025-I.jsonl", "test2025-II": "https://raw.githubusercontent.com/GAIR-NLP/AIME-Preview/main/eval/data/aime/test2025-II.jsonl", } os.makedirs(data_dir, exist_ok = True) combined_filepath = os.path.join(data_dir, "aime.jsonl") # Check if combined file already exists if os.path.exists(combined_filepath): print(f"Combined AIME dataset already exists at {combined_filepath}") return combined_filepath print("Downloading and combining AIME datasets...") all_problems = [] global_id = 0 for dataset_name, url in datasets.items(): print(f" Downloading {dataset_name}...") try: response = requests.get(url) response.raise_for_status() # Parse each line and add source information for line_num, line in enumerate(response.text.strip().split("\n")): if line.strip(): try: data = json.loads(line) # Add source dataset information and global ID data["source_dataset"] = dataset_name data["original_id"] = data.get("id", line_num) data["global_id"] = global_id global_id += 1 all_problems.append(data) except json.JSONDecodeError as e: print( f" Warning: Error parsing line {line_num + 1} in {dataset_name}: {e}" ) continue except requests.RequestException as e: print(f" Error downloading {dataset_name}: {e}") continue # Write combined dataset if all_problems: with open(combined_filepath, "w", encoding = "utf-8") as f: for problem in all_problems: f.write(json.dumps(problem, ensure_ascii = False) + "\n") print(f"✅ Combined {len(all_problems)} problems from {len(datasets)} datasets") print(f" Saved to: {combined_filepath}") # Print summary by dataset for dataset_name in datasets.keys(): count = sum(1 for p in all_problems if p["source_dataset"] == dataset_name) print(f" {dataset_name}: {count} problems") else: raise RuntimeError("No problems were successfully downloaded") return combined_filepath def load_aime_dataset(data_dir: str = "./data/aime") -> List[Dict[str, Any]]: """Load combined AIME dataset and format for evaluation""" # Download and combine if needed filepath = download_and_combine_aime_datasets(data_dir) examples = [] with open(filepath, "r", encoding = "utf-8") as f: for line_num, line in enumerate(f): line = line.strip() if line: try: data = json.loads(line) # Format as expected by our evaluation formatted_example = { "global_id": data.get("global_id", line_num), "original_id": data.get( "original_id", data.get("id", line_num) ), "source_dataset": data.get("source_dataset", "unknown"), "problem": data["problem"], "answer": str(data["answer"]), # Ensure answer is string "solution": data.get("solution", ""), "url": data.get("url", ""), # Format as chat messages for the model "prompt": [ { "role": "system", "content": "You are a mathematical problem solver. Solve the given problem step by step and provide your final answer clearly.", }, { "role": "user", "content": f"Problem: {data['problem']}\n\nSolve this step by step and provide your final numerical answer.", }, ], } examples.append(formatted_example) except json.JSONDecodeError as e: print(f"Error parsing line {line_num + 1}: {e}") continue print(f"Loaded {len(examples)} problems from combined AIME dataset") # Print breakdown by source source_counts = {} for example in examples: source = example["source_dataset"] source_counts[source] = source_counts.get(source, 0) + 1 for source, count in source_counts.items(): print(f" {source}: {count} problems") return examples def extract_aime_answer(response: str) -> str: """Extract numerical answer from AIME response""" # AIME answers are integers from 0-999 # Look for patterns like "The answer is 123" or just standalone numbers patterns = [ r"(?:the )?(?:final )?answer is (\d{1,3})", r"(?:therefore|thus|so),?\s*(?:the )?(?:final )?answer is (\d{1,3})", r"\\boxed\{(\d{1,3})\}", r"\$\\boxed\{(\d{1,3})\}\$", r"(?:answer|result):\s*(\d{1,3})", r"(?:^|\n)\s*(\d{1,3})\s*(?:\n|$)", # Standalone number ] response_lower = response.lower().strip() for pattern in patterns: matches = re.findall(pattern, response_lower, re.MULTILINE | re.IGNORECASE) if matches: # Get the last match (most likely to be final answer) answer = matches[-1] try: num = int(answer) if 0 <= num <= 999: # AIME answers are in range 0-999 return str(num) except ValueError: continue # If no clear pattern found, try to extract any 1-3 digit number numbers = re.findall(r"\b(\d{1,3})\b", response) if numbers: for num_str in reversed(numbers): # Check from end try: num = int(num_str) if 0 <= num <= 999: return str(num) except ValueError: continue return "" def get_num_tokens(text, tokenizer_instance): """Count tokens in text""" if not text: return 0 encoding = tokenizer_instance(text, return_tensors = "pt") return len(encoding["input_ids"][0]) def evaluate_model_aime( model, tokenizer, model_type = "base", lora_request = None, temperature = 0.3, n_sampling = 8, max_tokens = 32768, top_p = 0.95, seed = 0, ): """Evaluate model on combined AIME dataset with official configuration""" print(f"\n{'='*70}") print(f"🧮 AIME EVALUATION - {model_type.upper()} MODEL") print(f"Combined Dataset: test2024 + test2025-I + test2025-II") print(f"{'='*70}") # Load combined AIME dataset try: eval_dataset = load_aime_dataset() except Exception as e: print(f"Error loading dataset: {e}") return None if not eval_dataset: print("No examples found in dataset") return None # Initialize tracking variables records = {} input_tokens = [] output_tokens = [] correct_answers = 0 # Track performance by source dataset source_stats = {} for example in eval_dataset: source = example["source_dataset"] if source not in source_stats: source_stats[source] = {"total": 0, "correct": 0} source_stats[source]["total"] += 1 # Setup sampling parameters (AIME configuration) sampling_params = SamplingParams( temperature = temperature, top_p = top_p, max_tokens = max_tokens, n = n_sampling, # Multiple samples per question seed = seed, ) print(f"\n🔧 Configuration:") print(f" Temperature: {temperature}") print(f" Samples per question: {n_sampling}") print(f" Max tokens: {max_tokens}") print(f" Top-p: {top_p}") print(f" Seed: {seed}") # Temporarily suppress verbose logging original_levels = {} loggers_to_suppress = [ "vllm", "vllm.engine", "vllm.worker", "vllm.model_executor", "vllm.executor", "ray", ] for logger_name in loggers_to_suppress: logger = logging.getLogger(logger_name) original_levels[logger_name] = logger.level logger.setLevel(logging.WARNING) try: print(f"\n🚀 Evaluating {len(eval_dataset)} problems...") # Main evaluation loop with tqdm( total = len(eval_dataset), desc = "Processing AIME problems", unit = "problem" ) as pbar: for task_id, item in enumerate(eval_dataset): try: # Prepare prompt prompt_text = tokenizer.apply_chat_template( item["prompt"], add_generation_prompt = True, tokenize = False ) input_tokens.append(get_num_tokens(prompt_text, tokenizer)) # Generate multiple responses outputs = model.fast_generate( [prompt_text], sampling_params = sampling_params, lora_request = lora_request, use_tqdm = False, )[0].outputs # Process all generated responses responses = [output.text for output in outputs] extracted_answers = [ extract_aime_answer(response) for response in responses ] # Calculate total output tokens total_output_tokens = sum( get_num_tokens(response, tokenizer) for response in responses ) output_tokens.append(total_output_tokens) # Check if any answer is correct ground_truth = item["answer"] correct_responses = [ ans == ground_truth for ans in extracted_answers ] is_correct = any(correct_responses) if is_correct: correct_answers += 1 source_stats[item["source_dataset"]]["correct"] += 1 # Store detailed record records[task_id] = { "global_id": item["global_id"], "original_id": item["original_id"], "source_dataset": item["source_dataset"], "problem": item["problem"], "ground_truth": ground_truth, "responses": responses, "extracted_answers": extracted_answers, "correct_responses": correct_responses, "is_correct": is_correct, "input_tokens": input_tokens[-1], "output_tokens": total_output_tokens, "n_correct": sum(correct_responses), "n_total": len(responses), "solution": item.get("solution", ""), "url": item.get("url", ""), } # Update progress current_accuracy = correct_answers / (task_id + 1) * 100 pbar.set_postfix( { "accuracy": f"{current_accuracy:.1f}%", "correct": correct_answers, "total": task_id + 1, } ) pbar.update(1) except Exception as e: print(f"\nError processing problem {task_id}: {str(e)}") records[task_id] = { "global_id": item.get("global_id", task_id), "original_id": item.get("original_id", task_id), "source_dataset": item.get("source_dataset", "unknown"), "problem": item["problem"], "ground_truth": item["answer"], "error": str(e), "is_correct": False, } pbar.update(1) continue finally: # Restore logging levels for logger_name, level in original_levels.items(): logging.getLogger(logger_name).setLevel(level) # Calculate metrics total_problems = len(eval_dataset) accuracy = correct_answers / total_problems * 100 # Calculate Pass@k (probability that at least one of k samples is correct) pass_at_k_scores = [] for record in records.values(): if "n_correct" in record and "n_total" in record: n_correct = record["n_correct"] n_total = record["n_total"] if n_correct > 0: pass_at_k_scores.append(1.0) else: pass_at_k_scores.append(0.0) pass_at_k = sum(pass_at_k_scores) / len(pass_at_k_scores) if pass_at_k_scores else 0 # Calculate per-source accuracies source_accuracies = {} for source, stats in source_stats.items(): source_accuracies[source] = ( (stats["correct"] / stats["total"] * 100) if stats["total"] > 0 else 0 ) results = { "model_type": model_type, "dataset": "aime_combined", "total_problems": total_problems, "correct_answers": correct_answers, "accuracy": accuracy, "pass_at_k": pass_at_k * 100, "source_stats": source_stats, "source_accuracies": source_accuracies, "temperature": temperature, "n_sampling": n_sampling, "max_tokens": max_tokens, "top_p": top_p, "seed": seed, "avg_input_tokens": sum(input_tokens) / len(input_tokens) if input_tokens else 0, "avg_output_tokens": sum(output_tokens) / len(output_tokens) if output_tokens else 0, "max_input_tokens": max(input_tokens) if input_tokens else 0, "max_output_tokens": max(output_tokens) if output_tokens else 0, } # Save results filename = f"aime_eval_combined_{model_type}_t{temperature}_n{n_sampling}.json" with open(filename, "w", encoding = "utf-8") as f: json.dump({"results": results, "records": records}, f, indent = 4) # Print comprehensive summary print(f"\n{'='*70}") print(f"📊 AIME EVALUATION RESULTS - {model_type.upper()}") print(f"{'='*70}") print(f"\n🎯 Overall Performance:") print(f" Total problems: {total_problems:>6}") print( f" Correct answers: {correct_answers:>6}/{total_problems} ({accuracy:>5.1f}%)" ) print(f" Pass@{n_sampling}: {pass_at_k:>10.1f}%") print(f"\n📈 Performance by Dataset:") for source, stats in source_stats.items(): source_acc = source_accuracies[source] print( f" {source:>12}: {stats['correct']:>3}/{stats['total']:>3} ({source_acc:>5.1f}%)" ) print(f"\n🔧 Configuration:") print(f" Temperature: {temperature}") print(f" Samples per problem: {n_sampling}") print(f" Max tokens: {max_tokens}") print(f" Top-p: {top_p}") print(f" Seed: {seed}") print(f"\n📝 Token Statistics:") print(f" Avg input tokens: {results['avg_input_tokens']:>10.1f}") print(f" Avg output tokens: {results['avg_output_tokens']:>10.1f}") print(f" Max input tokens: {results['max_input_tokens']:>10}") print(f" Max output tokens: {results['max_output_tokens']:>10}") # Performance assessment for AIME if accuracy >= 50: tier = "🏆 EXCEPTIONAL" elif accuracy >= 30: tier = "✅ EXCELLENT" elif accuracy >= 20: tier = "🎯 VERY GOOD" elif accuracy >= 10: tier = "⚠️ GOOD" elif accuracy >= 5: tier = "📈 FAIR" else: tier = "❌ NEEDS IMPROVEMENT" print(f"\n🎖️ AIME Performance: {tier} ({accuracy:.1f}%)") print(f"\n💾 Detailed results saved to: {filename}") print(f"\n{'='*70}") return results # Comparison functions for multiple model results def compare_aime_results(all_results): """Generate comprehensive comparison for AIME evaluation results""" print(f"\n{'='*80}") print("COMPREHENSIVE AIME MODEL COMPARISON") print(f"{'='*80}") # Main comparison table print( f"{'Model':<15} {'Accuracy %':<12} {'Pass@K %':<10} {'Correct':<8} {'Total':<8}" ) print("-" * 80) for result in all_results: print( f"{result['model_type']:<15} " f"{result['accuracy']:<12.1f} " f"{result['pass_at_k']:<10.1f} " f"{result['correct_answers']:<8} " f"{result['total_problems']:<8}" ) # Performance improvement analysis if len(all_results) > 1: print(f"\n{'='*50}") print("IMPROVEMENT ANALYSIS") print(f"{'='*50}") base_result = all_results[0] # Assume first is base model for i, result in enumerate(all_results[1:], 1): print(f"\n{result['model_type']} vs {base_result['model_type']}:") accuracy_improvement = result["accuracy"] - base_result["accuracy"] pass_k_improvement = result["pass_at_k"] - base_result["pass_at_k"] print(f" Accuracy improvement: {accuracy_improvement:+.1f}%") print(f" Pass@K improvement: {pass_k_improvement:+.1f}%") # Dataset breakdown print(f"\n{'='*50}") print("PERFORMANCE BY DATASET") print(f"{'='*50}") # Get all unique datasets from the first result if all_results and "source_accuracies" in all_results[0]: datasets = list(all_results[0]["source_accuracies"].keys()) print(f"{'Model':<15}", end = "") for dataset in datasets: print(f"{dataset:<15}", end = "") print() print("-" * (15 + 15 * len(datasets))) for result in all_results: print(f"{result['model_type']:<15}", end = "") for dataset in datasets: accuracy = result["source_accuracies"].get(dataset, 0) print(f"{accuracy:<15.1f}", end = "") print() # Save comparison comparison_data = { "summary": all_results, "best_model": max(all_results, key = lambda x: x["accuracy"]), } with open("aime_model_comparison.json", "w") as f: json.dump(comparison_data, f, indent = 4) print( f"\nBest performing model: {comparison_data['best_model']['model_type']} " f"({comparison_data['best_model']['accuracy']:.1f}% accuracy)" )
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/aime_eval.py", "license": "Apache License 2.0", "lines": 455, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/utils/cleanup_utils.py
import gc import logging import os import shutil import torch import sys import warnings def clear_memory(variables_to_clear = None, verbose = False, clear_all_caches = True): """ Comprehensive memory clearing for persistent memory leaks. Args: variables_to_clear: List of variable names to clear verbose: Print memory status clear_all_caches: Clear all types of caches (recommended for memory leaks) """ # Save current logging levels saved_log_levels = {} for name, logger in logging.Logger.manager.loggerDict.items(): if isinstance(logger, logging.Logger): saved_log_levels[name] = logger.level root_level = logging.getLogger().level if variables_to_clear is None: variables_to_clear = [ "inputs", "model", "base_model", "processor", "tokenizer", "base_processor", "base_tokenizer", "trainer", "peft_model", "bnb_config", ] # 1. Clear LRU caches FIRST (very important for memory leaks) if clear_all_caches: clear_all_lru_caches(verbose) # 2. Delete specified variables g = globals() deleted_vars = [] for var in variables_to_clear: if var in g: del g[var] deleted_vars.append(var) if verbose and deleted_vars: print(f"Deleted variables: {deleted_vars}") # 3. Multiple garbage collection passes (important for circular references) for i in range(3): collected = gc.collect() if verbose and collected > 0: print(f"GC pass {i+1}: collected {collected} objects") # 4. CUDA cleanup if torch.cuda.is_available(): # Get memory before cleanup if verbose: mem_before = torch.cuda.memory_allocated() / 1024**3 torch.cuda.empty_cache() torch.cuda.synchronize() # Additional CUDA cleanup for persistent leaks if clear_all_caches: # Reset memory stats torch.cuda.reset_peak_memory_stats() torch.cuda.reset_accumulated_memory_stats() # Clear JIT cache if hasattr(torch.jit, "_state") and hasattr( torch.jit._state, "_clear_class_state" ): torch.jit._state._clear_class_state() # Force another CUDA cache clear torch.cuda.empty_cache() # Final garbage collection gc.collect() if verbose: mem_after = torch.cuda.memory_allocated() / 1024**3 mem_reserved = torch.cuda.memory_reserved() / 1024**3 print( f"GPU memory - Before: {mem_before:.2f} GB, After: {mem_after:.2f} GB" ) print(f"GPU reserved memory: {mem_reserved:.2f} GB") if mem_before > 0: print(f"Memory freed: {mem_before - mem_after:.2f} GB") # restore original logging levels logging.getLogger().setLevel(root_level) for name, level in saved_log_levels.items(): if name in logging.Logger.manager.loggerDict: logger = logging.getLogger(name) logger.setLevel(level) def clear_all_lru_caches(verbose = True): """Clear all LRU caches in loaded modules.""" cleared_caches = [] # Modules to skip to avoid warnings skip_modules = { "torch.distributed", "torchaudio", "torch._C", "torch.distributed.reduce_op", "torchaudio.backend", } # Create a static list of modules to avoid RuntimeError modules = list(sys.modules.items()) # Method 1: Clear caches in all loaded modules for module_name, module in modules: if module is None: continue # Skip problematic modules if any(module_name.startswith(skip) for skip in skip_modules): continue try: # Look for functions with lru_cache for attr_name in dir(module): try: # Suppress warnings when checking attributes with warnings.catch_warnings(): warnings.simplefilter("ignore", FutureWarning) warnings.simplefilter("ignore", UserWarning) warnings.simplefilter("ignore", DeprecationWarning) attr = getattr(module, attr_name) if hasattr(attr, "cache_clear"): attr.cache_clear() cleared_caches.append(f"{module_name}.{attr_name}") except Exception: continue # Skip problematic attributes except Exception: continue # Skip problematic modules # Method 2: Clear specific known caches known_caches = [ "transformers.utils.hub.cached_file", "transformers.tokenization_utils_base.get_tokenizer", "torch._dynamo.utils.counters", ] for cache_path in known_caches: try: parts = cache_path.split(".") module = sys.modules.get(parts[0]) if module: obj = module for part in parts[1:]: obj = getattr(obj, part, None) if obj is None: break if obj and hasattr(obj, "cache_clear"): obj.cache_clear() cleared_caches.append(cache_path) except Exception: continue # Skip problematic caches if verbose and cleared_caches: print(f"Cleared {len(cleared_caches)} LRU caches") def clear_specific_lru_cache(func): """Clear cache for a specific function.""" if hasattr(func, "cache_clear"): func.cache_clear() return True return False # Additional utility for monitoring cache sizes def monitor_cache_sizes(): """Monitor LRU cache sizes across modules.""" cache_info = [] for module_name, module in sys.modules.items(): if module is None: continue try: for attr_name in dir(module): try: attr = getattr(module, attr_name) if hasattr(attr, "cache_info"): info = attr.cache_info() cache_info.append( { "function": f"{module_name}.{attr_name}", "size": info.currsize, "hits": info.hits, "misses": info.misses, } ) except: pass except: pass return sorted(cache_info, key = lambda x: x["size"], reverse = True) def safe_remove_directory(path): try: if os.path.exists(path) and os.path.isdir(path): shutil.rmtree(path) return True else: print(f"Path {path} is not a valid directory") return False except Exception as e: print(f"Failed to remove directory {path}: {e}") return False
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/cleanup_utils.py", "license": "Apache License 2.0", "lines": 190, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/utils/ocr_eval.py
""" OCR Model Evaluation Module This module provides functionality to evaluate OCR models on datasets with word error rate (WER) and character error rate (CER) metrics. """ import os import torch from tqdm import tqdm import pandas as pd from jiwer import wer, cer from qwen_vl_utils import process_vision_info import matplotlib.pyplot as plt from typing import List, Dict, Tuple, Optional, Any import traceback class OCRModelEvaluator: """ A comprehensive OCR model evaluator that supports multiple models and provides detailed analysis with WER and CER metrics. """ def __init__(self): """Initialize the OCR evaluator.""" self.model_comparison_results = {} def evaluate_model( self, model: Any, processor: Any, dataset: List[Dict], output_dir: str = "ocr_evaluation_results", max_new_tokens: int = 1024, temperature: float = 1.5, min_p: float = 0.1, verbose: bool = True, ) -> Tuple[Optional[float], Optional[float]]: """ Evaluate a model on an OCR dataset. """ # Create output directory if it doesn't exist os.makedirs(output_dir, exist_ok = True) # Initialize results storage results = [] # Process each sample in the dataset for i, sample in enumerate( tqdm(dataset, desc = "Evaluating OCR performance", disable = not verbose) ): try: # Extract components from sample messages = sample["messages"] # Get ground truth, image, and question ground_truth, image, question, input_messages = ( self._extract_sample_components(messages, i, verbose) ) if ground_truth is None or image is None or question is None: continue # Generate model response generated_response = self._generate_response( model, processor, input_messages, max_new_tokens, temperature, min_p ) # Calculate metrics word_error = wer(ground_truth, generated_response) char_error = cer(ground_truth, generated_response) # Save individual result self._save_individual_result( output_dir, i, question, generated_response, ground_truth, word_error, char_error, ) # Store results for summary results.append( { "sample_id": i, "wer": word_error, "cer": char_error, "model_output": generated_response.strip(), "ground_truth": ground_truth, "question": question, } ) except Exception as e: if verbose: print(f"Error processing sample {i}: {str(e)}") traceback.print_exc() # Generate summary report return self._generate_summary_report(results, output_dir, verbose) def _extract_sample_components( self, messages: List[Dict], sample_idx: int, verbose: bool ) -> Tuple[Optional[str], Optional[Any], Optional[str], List[Dict]]: """Extract ground truth, image, question, and input messages from sample.""" # Extract system message (if present) system_message = next( (msg for msg in messages if msg["role"] == "system"), None ) # Extract user message with the image and question user_message = next((msg for msg in messages if msg["role"] == "user"), None) if not user_message: if verbose: print(f"Skipping sample {sample_idx}: No user message found") return None, None, None, [] # Extract assistant message with ground truth assistant_message = next( (msg for msg in messages if msg["role"] == "assistant"), None ) if not assistant_message: if verbose: print( f"Skipping sample {sample_idx}: No assistant message (ground truth) found" ) return None, None, None, [] # Extract ground truth text ground_truth = None for content_item in assistant_message["content"]: if content_item["type"] == "text": ground_truth = content_item["text"] break if not ground_truth: if verbose: print( f"Skipping sample {sample_idx}: No text found in assistant message" ) return None, None, None, [] # Extract image and question from user message image = None question = None for content_item in user_message["content"]: if content_item["type"] == "image": image = content_item["image"] elif content_item["type"] == "text": question = content_item["text"] if not image: if verbose: print(f"Skipping sample {sample_idx}: No image found in user message") return None, None, None, [] if not question: if verbose: print( f"Skipping sample {sample_idx}: No question found in user message" ) return None, None, None, [] # Construct messages for the model input (excluding assistant message) input_messages = [] if system_message: input_messages.append(system_message) input_messages.append(user_message) return ground_truth, image, question, input_messages def _generate_response( self, model: Any, processor: Any, input_messages: List[Dict], max_new_tokens: int, temperature: float, min_p: float, ) -> str: """Generate response from the model.""" # Preparation for inference using Qwen's specific processing text = processor.apply_chat_template( input_messages, tokenize = False, add_generation_prompt = True ) # Process vision info (images/videos) from messages image_inputs, video_inputs = process_vision_info(input_messages) # Create model inputs inputs = processor( text = [text], images = image_inputs, videos = video_inputs, padding = True, return_tensors = "pt", ) inputs = inputs.to(model.device) # Generate response with torch.no_grad(): generated_ids = model.generate( **inputs, max_new_tokens = max_new_tokens, temperature = temperature, min_p = min_p, use_cache = True, ) # Extract only the generated part (not the input) generated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) ] # Decode the generated text generated_response = processor.batch_decode( generated_ids_trimmed, skip_special_tokens = True, clean_up_tokenization_spaces = False, )[0] return generated_response def _save_individual_result( self, output_dir: str, sample_idx: int, question: str, generated_response: str, ground_truth: str, word_error: float, char_error: float, ): """Save individual sample result to file.""" output_file = os.path.join(output_dir, f"sample_{sample_idx}.txt") with open(output_file, "w", encoding = "utf-8") as f: f.write(f"Sample {sample_idx}\n") f.write(f"Question: {question}\n\n") f.write(f"Model output:\n{generated_response.strip()}\n\n") f.write(f"Ground truth:\n{ground_truth}\n\n") f.write(f"WER: {word_error:.4f}, CER: {char_error:.4f}") def _generate_summary_report( self, results: List[Dict], output_dir: str, verbose: bool ) -> Tuple[Optional[float], Optional[float]]: """Generate and save summary report.""" if not results: if verbose: print("No results to summarize.") return None, None df = pd.DataFrame(results) # Calculate overall averages avg_wer = df["wer"].mean() avg_cer = df["cer"].mean() # Save average metrics with open(os.path.join(output_dir, "avg_metrics.txt"), "w") as f: f.write(f"Average WER: {avg_wer:.4f}\n") f.write(f"Average CER: {avg_cer:.4f}\n") # Save detailed results df.to_csv(os.path.join(output_dir, "detailed_results.csv"), index = False) if verbose: print("\nResults Summary:") print(f"Average WER: {avg_wer:.4f}") print(f"Average CER: {avg_cer:.4f}") print(f"\nDetailed results saved to {output_dir}/") return avg_wer, avg_cer def add_to_comparison(self, model_name: str, wer: float, cer: float): """Add model results to the comparison tracker.""" self.model_comparison_results[model_name] = {"wer": wer, "cer": cer} def print_model_comparison( self, save_csv: bool = True, save_plot: bool = True ) -> Optional[pd.DataFrame]: """Print a comparison of all models evaluated so far.""" if not self.model_comparison_results: print("No model results available for comparison") return None print("\n==== MODEL COMPARISON REPORT ====") # Create a comparison dataframe comparison_df = pd.DataFrame( { "Model": list(self.model_comparison_results.keys()), "WER": [ results["wer"] for results in self.model_comparison_results.values() ], "CER": [ results["cer"] for results in self.model_comparison_results.values() ], } ) # Sort by WER (best performance first) comparison_df = comparison_df.sort_values("WER") # Display the comparison table print("\nComparison Table (sorted by WER):") print(comparison_df.to_string(index = False)) # Save the comparison table if save_csv: comparison_file = "model_comparison_results.csv" comparison_df.to_csv(comparison_file, index = False) print(f"\nComparison table saved to {comparison_file}") # Generate a bar chart visualization if save_plot: self._create_comparison_plot(comparison_df) return comparison_df def _create_comparison_plot(self, comparison_df: pd.DataFrame): """Create and save comparison plot.""" plt.figure(figsize = (12, 6)) # Plot WER plt.subplot(1, 2, 1) plt.bar(comparison_df["Model"], comparison_df["WER"], color = "skyblue") plt.title("Word Error Rate Comparison") plt.ylabel("WER (lower is better)") plt.ylim(bottom = 0) plt.xticks(rotation = 45, ha = "right") # Plot CER plt.subplot(1, 2, 2) plt.bar(comparison_df["Model"], comparison_df["CER"], color = "lightgreen") plt.title("Character Error Rate Comparison") plt.ylabel("CER (lower is better)") plt.ylim(bottom = 0) plt.xticks(rotation = 45, ha = "right") plt.tight_layout() plt.savefig("ocr_model_comparison.png") plt.show() print(f"\nVisualization saved to ocr_model_comparison.png") def get_comparison_results(self) -> Dict[str, Dict[str, float]]: """Get the current comparison results.""" return self.model_comparison_results.copy() def clear_comparison_results(self): """Clear all comparison results.""" self.model_comparison_results.clear() def evaluate_ocr_model( model, processor, dataset, output_dir = "ocr_evaluation_results", **kwargs ): """ Convenience function that maintains backward compatibility with the original function. """ evaluator = OCRModelEvaluator() return evaluator.evaluate_model(model, processor, dataset, output_dir, **kwargs) def create_evaluator(): """Create a new OCR evaluator instance.""" return OCRModelEvaluator()
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/ocr_eval.py", "license": "Apache License 2.0", "lines": 310, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:tests/utils/perplexity_eval.py
from tqdm import tqdm import torch import pandas as pd model_comparison_results = {} # return the perplexity of the model on the dataset # The perplexity is computed on each example, individually, with a sliding window for examples longer than 512 tokens. def ppl_model(model, tokenizer, dataset): nlls = [] max_length = 2048 stride = 512 for s in tqdm(range(len(dataset["text"]))): encodings = tokenizer(dataset["text"][s], return_tensors = "pt") seq_len = encodings.input_ids.size(1) prev_end_loc = 0 for begin_loc in range(0, seq_len, stride): end_loc = min(begin_loc + max_length, seq_len) trg_len = end_loc - prev_end_loc input_ids = encodings.input_ids[:, begin_loc:end_loc].to("cuda") target_ids = input_ids.clone() target_ids[:, :-trg_len] = -100 # Create attention mask based on pad token id pad_token_id = ( tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0 ) attention_mask = (input_ids != pad_token_id).long() with torch.no_grad(): outputs = model( input_ids, labels = target_ids, attention_mask = attention_mask ) neg_log_likelihood = outputs.loss nlls.append(neg_log_likelihood) prev_end_loc = end_loc if end_loc == seq_len: break ppl = torch.exp(torch.stack(nlls).mean()) return ppl # -------------------------------------------------------------------- ## ----------- Reporting helper function ----------- ## # Create a simple function to add results to the comparison def add_to_comparison(model_name, ppl): """Add model results to the comparison tracker""" model_comparison_results[model_name] = {"ppl": ppl} # return model_comparison_results # Create a function to print the comparison report whenever needed def print_model_comparison(): """Print a comparison of all models evaluated so far""" if not model_comparison_results: print("No model results available for comparison") return print("\n==== MODEL COMPARISON REPORT ====") # Create a comparison dataframe comparison_df = pd.DataFrame( { "Model": list(model_comparison_results.keys()), # "Perplexity": [results["ppl"] for results in model_comparison_results.values()], "Perplexity": [ # Convert tensors to CPU and then to float if needed results["ppl"].cpu().item() if torch.is_tensor(results["ppl"]) else results["ppl"] for results in model_comparison_results.values() ], } ) # Display the comparison table print("\nComparison Table:") print(comparison_df.to_string(index = False))
{ "repo_id": "unslothai/unsloth", "file_path": "tests/utils/perplexity_eval.py", "license": "Apache License 2.0", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import dataclass from typing import Tuple import torch import torch.nn.functional as F from transformers.models.llama4 import Llama4TextConfig from transformers.models.llama4.modeling_llama4 import Llama4TextMoe from ...interface import grouped_gemm from ...kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from ..moe_ops import ( get_routing_indices, permute, torch_grouped_gemm, unpermute, ) """ Reference implementation of Llama4 MoE block using triton grouped gemm. `Llama4GroupedGemmTextMoe` is the HF `Llama4TextMoe` block implemented with a torch-native grouped gemm. `Llama4TritonTextMoe` is the HF `Llama4TextMoe` implemented with triton grouped gemm. """ @dataclass class Llama4MoeResult: token_counts_by_expert: torch.Tensor gather_indices: torch.Tensor topk_weights: torch.Tensor hidden_states_after_weight_merge: torch.Tensor first_gemm: torch.Tensor intermediate: torch.Tensor second_gemm: torch.Tensor hidden_states_unpermute: torch.Tensor shared_expert_out: torch.Tensor final_out: torch.Tensor router_logits: torch.Tensor = None class Llama4GroupedGemmTextMoe(Llama4TextMoe): EXPERT_WEIGHT_NAMES = ["experts.gate_up_proj", "experts.down_proj"] def __init__( self, config: Llama4TextConfig, overlap_router_shared = False, verbose = False, debug = False, ): super().__init__(config) self.overlap_router_shared = overlap_router_shared self.verbose = verbose self.debug = debug # Permute in-place expert weights E, K, N = self.num_experts, self.hidden_dim, self.experts.expert_dim assert self.experts.gate_up_proj.shape == torch.Size( [E, K, 2 * N] ), f"{self.experts.gate_up_proj.shape} != {[E, K, 2 * N]}" permuted_shape = [E, 2 * N, K] permuted_stride = [2 * N * K, K, 1] if verbose: print( f"Changing gate_up_proj from {self.experts.gate_up_proj.size()}:{self.experts.gate_up_proj.stride()} to {permuted_shape}:{permuted_stride}" ) with torch.no_grad(): self.experts.gate_up_proj.as_strided_(permuted_shape, permuted_stride) if verbose: print( f"{self.experts.gate_up_proj.shape}:{self.experts.gate_up_proj.stride()}" ) assert self.experts.down_proj.shape == torch.Size( [E, N, K] ), f"{self.experts.down_proj.shape} != {[E, N, K]}" permuted_shape = [E, K, N] permuted_stride = [K * N, N, 1] if verbose: print( f"Changing down_proj from {self.experts.down_proj.size()}:{self.experts.down_proj.stride()} to {permuted_shape}:{permuted_stride}" ) with torch.no_grad(): self.experts.down_proj.as_strided_(permuted_shape, permuted_stride) if verbose: print(f"{self.experts.down_proj.shape}:{self.experts.down_proj.stride()}") if overlap_router_shared: self.shared_expert_stream = torch.cuda.Stream() self.default_event = torch.cuda.Event() self.shared_expert_end_event = torch.cuda.Event() @torch.no_grad def copy_weights(self, other: Llama4TextMoe): for name, param_to_copy in other.named_parameters(): if self.verbose: print(f"Copying {name} with shape {param_to_copy.shape}") param = self.get_parameter(name) if any(n in name for n in self.EXPERT_WEIGHT_NAMES): param_to_copy = param_to_copy.permute(0, 2, 1) assert ( param.shape == param_to_copy.shape ), f"{param.shape} != {param_to_copy.shape}" param.copy_(param_to_copy) return self def check_weights(self, other: Llama4TextMoe): for name, other_param in other.named_parameters(): if any(n in name for n in self.EXPERT_WEIGHT_NAMES): other_param = other_param.permute(0, 2, 1) param = self.get_parameter(name) assert param.equal(other_param), f"Param {name} not equal!" assert param.is_contiguous(), f"{name} not contiguous!" def act_and_mul(self, x: torch.Tensor) -> torch.Tensor: assert x.shape[-1] == 2 * self.experts.expert_dim gate_proj = x[..., : self.experts.expert_dim] up_proj = x[..., self.experts.expert_dim :] return self.experts.act_fn(gate_proj) * up_proj def run_router(self, hidden_states: torch.Tensor) -> torch.Tensor: # router_logits: (batch * sequence_length, n_experts) hidden_states = hidden_states.view(-1, self.hidden_dim) router_logits = self.router(hidden_states) routing_weights, selected_experts = torch.topk( router_logits, self.top_k, dim = -1 ) routing_weights = F.sigmoid(routing_weights.float()).to(hidden_states.dtype) return router_logits, routing_weights, selected_experts def get_token_counts_and_gather_indices( self, selected_experts: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: token_counts_by_expert, gather_indices = get_routing_indices( selected_experts, self.num_experts ) assert not token_counts_by_expert.requires_grad assert not gather_indices.requires_grad return token_counts_by_expert, gather_indices def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """ """ batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) if self.overlap_router_shared: # Marker for all prior ops on default stream self.default_event.record() router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) assert routing_weights.shape == ( num_tokens, self.top_k, ), f"{routing_weights.shape} != {(num_tokens, self.top_k)}" if self.overlap_router_shared: with torch.cuda.stream(self.shared_expert_stream): # Ensure prior kernels on default stream complete self.default_event.wait() shared_expert_out = self.shared_expert(hidden_states) # Ensure hidden states remains valid on this stream hidden_states.record_stream(self.shared_expert_stream) self.shared_expert_end_event.record() # Ensure shared expert still valid on default stream shared_expert_out.record_stream(torch.cuda.current_stream()) self.shared_expert_end_event.wait() else: shared_expert_out = self.shared_expert(hidden_states) hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) if self.top_k > 1: hidden_states = hidden_states.sum(dim = 1) hidden_states_after_weight_merge = hidden_states.view(-1, hidden_dim) # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. Permute tokens from token order to expert order hidden_states = permute( hidden_states_after_weight_merge, gather_indices, self.top_k ) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation first_gemm = torch_grouped_gemm( X = hidden_states, W = self.experts.gate_up_proj, m_sizes = token_counts_by_expert ) assert first_gemm.shape == (total_tokens, 2 * self.experts.expert_dim) intermediate = self.act_and_mul(first_gemm) assert intermediate.shape == (total_tokens, self.experts.expert_dim) # See comment above second_gemm = torch_grouped_gemm( X = intermediate, W = self.experts.down_proj, m_sizes = token_counts_by_expert ) assert second_gemm.shape == (total_tokens, hidden_dim) # Post-processing hidden_states_unpermute = unpermute(second_gemm, gather_indices) assert hidden_states_unpermute.shape == (total_tokens, hidden_dim) # grouped_gemm_out = hidden_states.view(batch_size, sequence_length, hidden_dim) final_out = hidden_states_unpermute + shared_expert_out result = ( Llama4MoeResult( token_counts_by_expert = token_counts_by_expert, gather_indices = gather_indices, topk_weights = routing_weights, hidden_states_after_weight_merge = hidden_states_after_weight_merge, first_gemm = first_gemm, intermediate = intermediate, second_gemm = second_gemm, hidden_states_unpermute = hidden_states_unpermute, shared_expert_out = shared_expert_out, final_out = final_out, router_logits = router_logits, ) if self.debug else (final_out, routing_weights) ) return result class Llama4TritonTextMoe(Llama4GroupedGemmTextMoe): def __init__( self, config: Llama4TextConfig, overlap_router_shared = False, permute_x: bool = False, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, verbose = False, ): super().__init__(config, overlap_router_shared = overlap_router_shared) assert not permute_x, "Llama4 triton grouped gemm does not support permute x due to pre-multiplication of router weights" self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX self.dW_only = dW_only self.dX_only = dX_only @torch.no_grad def copy_weights(self, other: Llama4TextMoe): for name, param_to_copy in other.named_parameters(): if self.verbose: print(f"Copying {name} with shape {param_to_copy.shape}") param = self.get_parameter(name) if any(n in name for n in self.EXPERT_WEIGHT_NAMES): param_to_copy = param_to_copy.permute(0, 2, 1) assert ( param.shape == param_to_copy.shape ), f"{param.shape} != {param_to_copy.shape}" param.copy_(param_to_copy) return self def check_weights(self, other: Llama4TextMoe): for name, other_param in other.named_parameters(): if any(n in name for n in self.EXPERT_WEIGHT_NAMES): other_param = other_param.permute(0, 2, 1) param = self.get_parameter(name) assert param.equal(other_param), f"Param {name} not equal!" assert param.is_contiguous(), f"{name} not contiguous!" def act_and_mul(self, x: torch.Tensor) -> torch.Tensor: assert x.shape[-1] == 2 * self.experts.expert_dim gate_proj = x[..., : self.experts.expert_dim] up_proj = x[..., self.experts.expert_dim :] return self.experts.act_fn(gate_proj) * up_proj def run_router(self, hidden_states: torch.Tensor) -> torch.Tensor: # router_logits: (batch * sequence_length, n_experts) hidden_states = hidden_states.view(-1, self.hidden_dim) router_logits = self.router(hidden_states) routing_weights, selected_experts = torch.topk( router_logits, self.top_k, dim = -1 ) routing_weights = F.sigmoid(routing_weights.float()).to(hidden_states.dtype) return router_logits, routing_weights, selected_experts def get_token_counts_and_gather_indices( self, selected_experts: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: token_counts_by_expert, gather_indices = get_routing_indices( selected_experts, self.num_experts ) assert not token_counts_by_expert.requires_grad assert not gather_indices.requires_grad return token_counts_by_expert, gather_indices def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """ """ batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) if self.overlap_router_shared: # Marker for all prior ops on default stream self.default_event.record() router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) assert routing_weights.shape == ( num_tokens, self.top_k, ), f"{routing_weights.shape} != {(num_tokens, self.top_k)}" if self.overlap_router_shared: with torch.cuda.stream(self.shared_expert_stream): # Ensure prior kernels on default stream complete self.default_event.wait() shared_expert_out = self.shared_expert(hidden_states) # Ensure hidden states remains valid on this stream hidden_states.record_stream(self.shared_expert_stream) self.shared_expert_end_event.record() # Ensure shared expert still valid on default stream shared_expert_out.record_stream(torch.cuda.current_stream()) self.shared_expert_end_event.wait() else: shared_expert_out = self.shared_expert(hidden_states) hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) if self.top_k > 1: hidden_states = hidden_states.sum(dim = 1) hidden_states = hidden_states.view(-1, hidden_dim) # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. Permute tokens from token order to expert order hidden_states = permute(hidden_states, gather_indices, self.top_k) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation hidden_states = grouped_gemm( X = hidden_states, W = self.experts.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, dW_only = self.dW_only, dX_only = self.dX_only, ) hidden_states = self.act_and_mul(hidden_states) hidden_states = grouped_gemm( X = hidden_states, W = self.experts.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, dW_only = self.dW_only, dX_only = self.dX_only, ) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states = unpermute(hidden_states, gather_indices) hidden_states += shared_expert_out return hidden_states, routing_weights
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/reference/layers/llama4_moe.py", "license": "Apache License 2.0", "lines": 367, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import dataclass from typing import Tuple import torch import torch.nn.functional as F from transformers.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import ( ACT2FN, Qwen3MoeSparseMoeBlock, ) from ...interface import grouped_gemm from ...kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from ..moe_ops import ( get_routing_indices, permute, torch_grouped_gemm, unpermute, ) """ Reference implementation of HF Qwen3 MoE block using grouped gemm. The Qwen3MoeGroupedGEMMBlock is a reference torch-native implementation. Qwen3MoeFusedGroupedGEMMBlock is a version using the triton grouped gemm kernel. NOTE: This is NOT to be used for production as it contains many extra checks and saves all intermediate results for debugging. """ @dataclass class GroupedGEMMResult: token_counts_by_expert: torch.Tensor gather_indices: torch.Tensor topk_weights: torch.Tensor first_gemm: torch.Tensor intermediate: torch.Tensor second_gemm: torch.Tensor hidden_states_unpermute: torch.Tensor hidden_states: torch.Tensor # final output class Qwen3MoeGroupedGEMMBlock(torch.nn.Module): def __init__( self, config, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, ): super().__init__() self.num_experts = config.num_experts self.top_k = config.num_experts_per_tok self.norm_topk_prob = config.norm_topk_prob self.hidden_size = config.hidden_size self.moe_intermediate_size = config.moe_intermediate_size assert gate.shape == (config.num_experts, config.hidden_size) assert gate_up_proj.shape == ( config.num_experts, 2 * config.moe_intermediate_size, config.hidden_size, ) assert down_proj.shape == ( config.num_experts, config.hidden_size, config.moe_intermediate_size, ) # gating self.gate = torch.nn.Parameter(gate) # experts self.gate_up_proj = torch.nn.Parameter(gate_up_proj, requires_grad = True) self.down_proj = torch.nn.Parameter(down_proj, requires_grad = True) self.act_fn = ACT2FN[config.hidden_act] @staticmethod def extract_hf_weights(moe_block: Qwen3MoeSparseMoeBlock): config: Qwen3MoeConfig = moe_block.experts[0].config num_experts = config.num_experts gate = moe_block.gate.weight.data gate_proj = torch.stack( [moe_block.experts[i].gate_proj.weight.data for i in range(num_experts)], dim = 0, ) up_proj = torch.stack( [moe_block.experts[i].up_proj.weight.data for i in range(num_experts)], dim = 0, ) down_proj = torch.stack( [moe_block.experts[i].down_proj.weight.data for i in range(num_experts)], dim = 0, ) gate_up_proj = torch.cat([gate_proj, up_proj], dim = 1) return gate, gate_up_proj, down_proj @classmethod def from_hf(cls, moe_block: Qwen3MoeSparseMoeBlock): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = cls.extract_hf_weights(moe_block) return cls(config, gate, gate_up_proj, down_proj) def check_weights(self, moe_block: Qwen3MoeSparseMoeBlock): for i in range(self.num_experts): assert self.gate_up_proj[i].equal( torch.cat( [ moe_block.experts[i].gate_proj.weight.data, moe_block.experts[i].up_proj.weight.data, ], dim = 0, ) ) assert self.down_proj[i].equal(moe_block.experts[i].down_proj.weight.data) def act_and_mul(self, x: torch.Tensor) -> torch.Tensor: assert x.shape[-1] == 2 * self.moe_intermediate_size gate_proj = x[..., : self.moe_intermediate_size] up_proj = x[..., self.moe_intermediate_size :] return self.act_fn(gate_proj) * up_proj def run_router(self, hidden_states: torch.Tensor) -> torch.Tensor: # router_logits: (batch * sequence_length, n_experts) router_logits = torch.nn.functional.linear(hidden_states, self.gate) routing_weights = F.softmax(router_logits, dim = 1, dtype = torch.float) routing_weights, selected_experts = torch.topk( routing_weights, self.top_k, dim = -1 ) if self.norm_topk_prob: # only diff with mixtral sparse moe block! routing_weights /= routing_weights.sum(dim = -1, keepdim = True) # we cast back to the input dtype routing_weights = routing_weights.to(hidden_states.dtype) return router_logits, routing_weights, selected_experts def get_token_counts_and_gather_indices( self, selected_experts: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: token_counts_by_expert, gather_indices = get_routing_indices( selected_experts, self.num_experts ) assert not token_counts_by_expert.requires_grad assert not gather_indices.requires_grad return token_counts_by_expert, gather_indices def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """ """ batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. Permute tokens from token order to expert order hidden_states = permute(hidden_states, gather_indices, self.top_k) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation first_gemm = torch_grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert ) assert first_gemm.shape == (total_tokens, 2 * self.moe_intermediate_size) intermediate = self.act_and_mul(first_gemm) assert intermediate.shape == (total_tokens, self.moe_intermediate_size) second_gemm = torch_grouped_gemm( X = intermediate, W = self.down_proj, m_sizes = token_counts_by_expert ) assert second_gemm.shape == (total_tokens, hidden_dim) # Post-processing # 1. Unpermute from expert order to token order hidden_states_unpermute = unpermute(second_gemm, gather_indices) assert hidden_states_unpermute.shape == (total_tokens, hidden_dim) # 2. Merge topk weights hidden_states = ( hidden_states_unpermute.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) assert hidden_states.shape == (num_tokens, hidden_dim) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return GroupedGEMMResult( token_counts_by_expert = token_counts_by_expert, gather_indices = gather_indices, topk_weights = routing_weights, first_gemm = first_gemm, intermediate = intermediate, second_gemm = second_gemm, hidden_states_unpermute = hidden_states_unpermute, hidden_states = hidden_states, ), router_logits class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock): def __init__( self, config: Qwen3MoeConfig, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): super().__init__(config, gate, gate_up_proj, down_proj) self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX self.dW_only = dW_only self.dX_only = dX_only @classmethod def from_hf( cls, moe_block: Qwen3MoeSparseMoeBlock, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = Qwen3MoeGroupedGEMMBlock.extract_hf_weights( moe_block ) return cls( config, gate, gate_up_proj, down_proj, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dW_only = dW_only, dX_only = dX_only, ) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # Pre-processing # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. permute_x -> permutation will be fused in prologue of first grouped gemm if not self.permute_x: hidden_states = permute(hidden_states, gather_indices, self.top_k) # Start expert computation hidden_states = grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, dW_only = self.dW_only, dX_only = self.dX_only, ) hidden_states = self.act_and_mul(hidden_states) hidden_states = grouped_gemm( X = hidden_states, W = self.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, dW_only = self.dW_only, dX_only = self.dX_only, ) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states = unpermute(hidden_states, gather_indices) # 2. Merge topk weights hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return hidden_states, router_logits
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/reference/layers/qwen3_moe.py", "license": "Apache License 2.0", "lines": 307, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/kernels/moe/tests/test_llama4_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import argparse import sys from contextlib import contextmanager from functools import partial import pytest import torch from transformers import AutoConfig from transformers.models.llama4 import Llama4Config, Llama4TextConfig from transformers.models.llama4.modeling_llama4 import Llama4TextMoe from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.layers.llama4_moe import ( Llama4GroupedGemmTextMoe, Llama4TritonTextMoe, ) TOLERANCES = { torch.bfloat16: (1e-2, 1e-2), torch.float16: (1e-3, 1e-3), torch.float: (1e-5, 1e-5), } LLAMA4_SCOUT_ID = "meta-llama/Llama-4-Scout-17B-16E" SEED = 42 SEQ_LENS = [1024] DTYPES = [torch.bfloat16] # Reduce the number of autotuning configs to prevent excessive runtime NUM_AUTOTUNE_CONFIGS = 50 @contextmanager def annotated_context(prelude, epilogue = "Passed!", char = "-", num_chars = 80): print(char * num_chars) print(prelude) yield print(epilogue) print(char * num_chars) def get_text_config(model_id): config: Llama4Config = AutoConfig.from_pretrained(model_id) return config.text_config def prep_triton_kernel_traits(autotune): if not autotune: kernel_config_fwd = KernelConfigForward() kernel_config_bwd_dW = KernelConfigBackward_dW() kernel_config_bwd_dX = KernelConfigBackward_dX() else: from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel # Hack to reduce number of autotuning configs _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dW_kernel.configs = ( _autotuned_grouped_gemm_dW_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) kernel_config_fwd = None kernel_config_bwd_dW = None kernel_config_bwd_dX = None return kernel_config_fwd, kernel_config_bwd_dW, kernel_config_bwd_dX def sparse_to_dense(t: torch.Tensor): t = t.sum(dim = 0).view(-1) return t @torch.no_grad() def _check_diff( t1: torch.Tensor, t2: torch.Tensor, atol, rtol, precision = ".6f", verbose = False, msg = "", ): t2 = t2.view_as(t1) diff = t1.sub(t2).abs().max().item() if verbose: if msg == "": msg = "diff" print(f"{msg}: {diff:{precision}}") assert torch.allclose(t1, t2, atol = atol, rtol = rtol) def run_backwards(y: torch.Tensor, grad_output: torch.Tensor, module: torch.nn.Module): y.backward(grad_output) for name, param in module.named_parameters(): assert param.grad is not None, f"{name} missing grad!" def _check_grads( m1: torch.nn.Module, m2: torch.nn.Module, atol, rtol, precision = ".6f", verbose = False, msg = "", ): for name, param in m1.named_parameters(): _check_diff( param.grad, m2.get_parameter(name).grad, atol = atol, rtol = rtol, precision = precision, verbose = verbose, msg = f"{msg}:{name}.grad", ) @pytest.fixture def model_config(): return AutoConfig.from_pretrained(LLAMA4_SCOUT_ID).text_config @pytest.mark.parametrize( "overlap_router_shared", [False, True], ids = lambda x: "overlap_router_shared" if x else "no_overlap", ) @pytest.mark.parametrize( "permute_y", [False, True], ids = lambda x: "permute_y" if x else "no_permute_y" ) @pytest.mark.parametrize( "permute_x", [False], ids = lambda x: "permute_x" if x else "no_permute_x" ) # Llama4 does not support permute_x @pytest.mark.parametrize( "autotune", [True], ids = lambda x: "autotune" if x else "manual" ) @pytest.mark.parametrize("seqlen", SEQ_LENS, ids = lambda x: f"seqlen={x}") @pytest.mark.parametrize("dtype", DTYPES, ids = str) def test_llama4_ref( dtype: torch.dtype, seqlen, autotune: bool, permute_x: bool, permute_y: bool, overlap_router_shared: bool, model_config: Llama4TextConfig, # test fixture bs: int = 1, device = "cuda", precision = ".6f", verbose = False, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_dim = model_config.hidden_size atol, rtol = TOLERANCES[dtype] check_diff = partial( _check_diff, atol = atol, rtol = rtol, precision = precision, verbose = verbose ) check_grads = partial( _check_grads, atol = atol, rtol = rtol, precision = precision, verbose = verbose ) # Reference op -- HF llama4_ref = Llama4TextMoe(model_config).to(dtype = dtype, device = device) # Torch grouped gemm impl llama4_gg_ref = Llama4GroupedGemmTextMoe( model_config, overlap_router_shared = overlap_router_shared ).to(dtype = dtype, device = device) llama4_gg_ref.copy_weights(llama4_ref) llama4_gg_ref.check_weights(llama4_ref) x_ref = torch.randn( bs, seqlen, hidden_dim, dtype = dtype, device = device, requires_grad = True ) x_torch_gg = x_ref.detach().clone().requires_grad_() x_triton = x_ref.detach().clone().requires_grad_() y_ref, routing_ref = llama4_ref(x_ref) y_torch_gg, routing_torch_gg = llama4_gg_ref(x_torch_gg) assert y_ref.shape == y_torch_gg.shape, f"{y_ref.shape} != {y_torch_gg.shape}" with annotated_context("Testing torch grouped gemm Llama4TextMoe"): check_diff(y_ref, y_torch_gg, msg = "y_torch_gg") check_diff( sparse_to_dense(routing_ref), routing_torch_gg, msg = "routing_torch_gg" ) kernel_config_fwd, kernel_config_bwd_dW, kernel_config_bwd_dX = ( prep_triton_kernel_traits(autotune) ) llama4_triton = Llama4TritonTextMoe( model_config, overlap_router_shared = overlap_router_shared, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ).to(device = device, dtype = dtype) llama4_triton.copy_weights(llama4_ref) llama4_triton.check_weights(llama4_ref) y_triton, routing_triton = llama4_triton(x_triton) with annotated_context("Testing triton grouped gemm Llama4TextMoe forward"): check_diff(y_ref, y_triton, msg = "y_triton") check_diff(sparse_to_dense(routing_ref), routing_triton, msg = "routing_triton") ref_grad = torch.randn_like(y_ref) run_backwards(y_ref, ref_grad, llama4_ref) run_backwards(y_torch_gg, ref_grad, llama4_gg_ref) with annotated_context("Testing torch group gemm Llama4TextMoe backward"): check_grads(llama4_ref, llama4_gg_ref, msg = "torch_gg") run_backwards(y_triton, ref_grad, llama4_triton) with annotated_context("Testing triton group gemm Llama4TextMoe backward"): check_grads(llama4_ref, llama4_triton, msg = "triton") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--seqlen", type = int, default = 1024) parser.add_argument( "--dtype", type = str, choices = ["bfloat16", "float16"], default = "bfloat16" ) args = parser.parse_args() args.dtype = getattr(torch, args.dtype) args_dict = vars(args) model_id = LLAMA4_SCOUT_ID text_config: Llama4TextConfig = get_text_config(model_id) for overlap in [False, True]: test_llama4_ref( seqlen = args.seqlen, model_config = text_config, dtype = args.dtype, autotune = True, permute_x = False, permute_y = True, overlap_router_shared = overlap, verbose = True, )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/tests/test_llama4_moe.py", "license": "Apache License 2.0", "lines": 223, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/kernels/moe/benchmark/benchmark_fused_moe.py
import argparse import time from contextlib import nullcontext import torch from transformers import AutoConfig from transformers.models.llama4 import Llama4TextConfig from transformers.models.llama4.modeling_llama4 import Llama4TextMoe from transformers.models.qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from triton.testing import do_bench from utils import ( create_kernel_configs, get_autotuner, post_process_results, postprocess_autotune_results, save_results, ) from grouped_gemm.kernels.autotuning import ( DEFAULT_K_BLOCK_SIZES, DEFAULT_M_BLOCK_SIZES, DEFAULT_N_BLOCK_SIZES, DEFAULT_NUM_STAGES, DEFAULT_NUM_WARPS, ) from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, KernelResult, TritonTuningContext, ) from grouped_gemm.reference.layers.llama4_moe import Llama4TritonTextMoe from grouped_gemm.reference.layers.qwen3_moe import Qwen3MoeFusedGroupedGEMMBlock SEED = 42 LLAMA4_ID = "meta-llama/Llama-4-Scout-17B-16E" QWEN3_MODEL_ID = "Qwen/Qwen3-30B-A3B" def run_benchmark_forward( ref_model: torch.nn.Module, tt_model: torch.nn.Module, config: AutoConfig, seqlen: int, dtype: torch.dtype, autotune: bool, kernel_config_fwd: KernelConfigForward = None, bs: int = 1, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_size = config.hidden_size X = torch.randn( bs, seqlen, hidden_size, dtype = dtype, device = device, requires_grad = True ) # Forward bench_forward_ref = lambda: ref_model(X) # noqa: E731 bench_forward_fused = lambda: tt_model(X) # noqa: E731 ref_forward_time = do_bench(bench_forward_ref) if not autotune: assert kernel_config_fwd is not None tuning_context = TritonTuningContext(kernel_config_fwd) else: tuning_context = nullcontext() with tuning_context: fused_forward_time = do_bench(bench_forward_fused) if (not autotune) and (not tuning_context.success): return 0, 1 print( f"Forward: ref {ref_forward_time:.4f}, fused {fused_forward_time:.4f}, speedup {ref_forward_time / fused_forward_time:.1f}x" ) return ref_forward_time, fused_forward_time def run_benchmark_backward( ref_model: torch.nn.Module, tt_model: torch.nn.Module, config: AutoConfig, seqlen: int, dtype: torch.dtype, bs = 1, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_size = config.hidden_size X = torch.randn( bs, seqlen, hidden_size, dtype = dtype, device = device, requires_grad = True ) X_test = X.detach().clone().requires_grad_(True) output, _ = ref_model(X) # Prevent autotuning forward pass from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:20] ) test_output, _ = tt_model(X_test) # Bench grad_output = torch.randn_like(output) bench_backward_ref = lambda: output.backward(grad_output, retain_graph = True) # noqa: E731 bench_backward_fused = lambda: test_output.backward(grad_output, retain_graph = True) # noqa: E731 ref_backward_time = do_bench( bench_backward_ref, grad_to_none = [X, *ref_model.parameters()] ) fused_backward_time = do_bench( bench_backward_fused, grad_to_none = [X_test, *tt_model.parameters()] ) print( f"Backward: ref {ref_backward_time:.4f}, fused {fused_backward_time:.4f}, speedup {ref_backward_time / fused_backward_time:.1f}x" ) return ref_backward_time, fused_backward_time def setup_model( config: Qwen3MoeConfig | Llama4TextConfig, dtype, permute_x, permute_y, autotune, kernel_config_fwd, kernel_config_bwd_dW, kernel_config_bwd_dX, dX_only = False, dW_only = False, overlap_router_shared = False, device = "cuda", ): if isinstance(config, Qwen3MoeConfig): ref_model = Qwen3MoeSparseMoeBlock(config).to(device, dtype) # Triton kernel grouped gemm version of MoE Block -- this is what we're testing tt_model = Qwen3MoeFusedGroupedGEMMBlock.from_hf( ref_model, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dX_only = dX_only, dW_only = dW_only, ).to(device, dtype) elif isinstance(config, Llama4TextConfig): ref_model = Llama4TextMoe(config).to(device, dtype) tt_model = Llama4TritonTextMoe( config, overlap_router_shared = overlap_router_shared, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dX_only = dX_only, dW_only = dW_only, ).to(device, dtype) else: raise ValueError(f"Unrecognized config {type(config).__name__}") return ref_model, tt_model def run_benchmark( mode: str, model_config: Qwen3MoeConfig | Llama4TextConfig, seqlen: int, dtype: torch.dtype, permute_x: bool, permute_y: bool, autotune: bool, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, overlap_router_shared: bool = False, results_dir: str = None, ): if autotune: autotuner = get_autotuner(mode) if mode == "dW": dW_only = True elif mode == "dX": dX_only = True else: dW_only = dX_only = False ref_model, tt_model = setup_model( model_config, dtype = dtype, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dX_only = dX_only, dW_only = dW_only, overlap_router_shared = overlap_router_shared, ) if mode == "forward": ref_time, fused_time = run_benchmark_forward( ref_model, tt_model, config = model_config, seqlen = seqlen, dtype = dtype, autotune = autotune, kernel_config_fwd = kernel_config_fwd, ) else: ref_time, fused_time = run_benchmark_backward( ref_model, tt_model, config = model_config, seqlen = seqlen, dtype = dtype ) if autotune: if mode == "backward": autotuner_dW, autotuner_dX = autotuner postprocess_autotune_results( autotuner_dW, "dW", ref_time, fused_time, results_dir ) postprocess_autotune_results( autotuner_dX, "dX", ref_time, fused_time, results_dir ) else: postprocess_autotune_results( autotuner, mode, ref_time, fused_time, results_dir ) return ref_time, fused_time if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--results_dir", type = str, default = "benchmark_results") parser.add_argument("--model", type = str, choices = ["llama4", "qwen3"], required = True) parser.add_argument("--seqlen", type = int, default = 1024) parser.add_argument( "--dtype", type = str, choices = ["bfloat16", "float16"], default = "bfloat16" ) parser.add_argument("--permute_x", action = "store_true") parser.add_argument("--permute_y", action = "store_true") parser.add_argument("--autotune", action = "store_true") parser.add_argument("--overlap_router_shared", action = "store_true") parser.add_argument( "--BLOCK_SIZE_M", nargs = 2, type = int, default = [DEFAULT_M_BLOCK_SIZES[0], DEFAULT_M_BLOCK_SIZES[-1]], ) parser.add_argument( "--BLOCK_SIZE_N", nargs = 2, type = int, default = [DEFAULT_N_BLOCK_SIZES[0], DEFAULT_N_BLOCK_SIZES[-1]], ) parser.add_argument( "--BLOCK_SIZE_K", nargs = 2, type = int, default = [DEFAULT_K_BLOCK_SIZES[0], DEFAULT_K_BLOCK_SIZES[-1]], ) parser.add_argument( "--num_warps", nargs = 2, type = int, default = [DEFAULT_NUM_WARPS[0], DEFAULT_NUM_WARPS[-1]], ) parser.add_argument( "--num_stages", nargs = 2, type = int, default = [DEFAULT_NUM_STAGES[0], DEFAULT_NUM_STAGES[-1]], ) parser.add_argument( "--use_tma_load_w", action = "store_true" ) # No need to specify, will automatically parametrize these for each kernel config parser.add_argument( "--use_tma_load_x", action = "store_true" ) # No need to specify, will automatically parametrize these for each kernel config parser.add_argument( "--use_tma_load_dy", action = "store_true" ) # No need to specify, will automatically parametrize these for each kernel config parser.add_argument( "--mode", type = str, choices = ["forward", "backward", "dW", "dX"], default = "forward", ) args = parser.parse_args() args.dtype = getattr(torch, args.dtype) model_id = QWEN3_MODEL_ID if args.model == "qwen3" else LLAMA4_ID model_config = AutoConfig.from_pretrained(model_id) model_config = model_config.text_config if args.model == "llama4" else model_config mode = args.mode if args.autotune: # logging.basicConfig(level=logging.INFO) print( f"Benchmarking {model_id} {mode}: seqlen={args.seqlen}, dtype={args.dtype}, permute_x={args.permute_x}, permute_y={args.permute_y}, autotune" ) start_time = time.time() ref_time, fused_time = run_benchmark( args.mode, model_config, seqlen = args.seqlen, dtype = args.dtype, permute_x = args.permute_x, permute_y = args.permute_y, autotune = args.autotune, overlap_router_shared = args.overlap_router_shared, results_dir = args.results_dir, ) end_time = time.time() print(f"Total time: {end_time - start_time:.4f} seconds") # NOTE: better to use autotuner for now, since the MoE block needs 2 different kernel configs for forward (2 grouped gemms, gate_up_proj and down_proj) # and the backward pass needs 4 different kernel configs (2 grouped gemms each for dW and dX) # The benchmark only supports 1 kernel config at a time so the same config will be used for both grouped gemms, which is suboptimal. else: assert False, "Use autotune for now" kernel_configs = create_kernel_configs(args, args.permute_x, args.permute_y) print(f"Running {len(kernel_configs)} kernel configs") default_kernel_config_fwd = KernelConfigForward( permute_x = args.permute_x, permute_y = args.permute_y ) default_kernel_config_bwd_dW = KernelConfigBackward_dW( permute_x = args.permute_x, permute_y = args.permute_y ) default_kernel_config_bwd_dX = KernelConfigBackward_dX( permute_x = args.permute_x, permute_y = args.permute_y ) results = [] for kernel_config in kernel_configs: if args.mode == "forward": kernel_config_fwd = kernel_config kernel_config_bwd_dW = default_kernel_config_bwd_dW kernel_config_bwd_dX = default_kernel_config_bwd_dX elif args.mode == "dW": kernel_config_fwd = default_kernel_config_fwd kernel_config_bwd_dW = kernel_config kernel_config_bwd_dX = default_kernel_config_bwd_dX elif args.mode == "dX": kernel_config_fwd = default_kernel_config_fwd kernel_config_bwd_dW = default_kernel_config_bwd_dW kernel_config_bwd_dX = kernel_config else: raise ValueError(f"Invalid mode: {args.mode}") print( f"Benchmarking {model_id} {args.mode} with seqlen={args.seqlen}, dtype={args.dtype}, permute_x={args.permute_x}, permute_y={args.permute_y}, kernel_config_fwd={kernel_config_fwd}, kernel_config_bwd_dW={kernel_config_bwd_dW}, kernel_config_bwd_dX={kernel_config_bwd_dX}" ) ref_time, fused_time = run_benchmark( args.mode, model_config, seqlen = args.seqlen, dtype = args.dtype, permute_x = kernel_config.permute_x, permute_y = kernel_config.permute_y, autotune = False, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ) results.append( KernelResult( torch_time = ref_time, triton_time = fused_time, speedup = ref_time / fused_time, kernel_config = kernel_config, ) ) df = post_process_results( results, args.mode, args.seqlen, args.dtype, args.autotune ) save_results( df, args.results_dir, args.mode, args.seqlen, args.dtype, args.autotune )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/benchmark/benchmark_fused_moe.py", "license": "Apache License 2.0", "lines": 360, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unslothai/unsloth:unsloth/kernels/moe/benchmark/utils.py
import argparse import datetime import json import logging import math import os from itertools import product import pandas as pd import torch from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, KernelResult, ) SEED = 42 def create_merged_results( df: pd.DataFrame, mode: str, seqlen: int, dtype: torch.dtype, autotune: bool ): kernel_result_cols = df.columns.to_list() test_config_dict = { "mode": mode, "seqlen": seqlen, "dtype": dtype, "autotune": autotune, } test_config_cols = list(test_config_dict.keys()) for col in test_config_cols: df[col] = test_config_dict[col] # Reorder columns so that test config cols are first df = df[test_config_cols + kernel_result_cols] return df def post_process_results( results: list[KernelResult], mode: str, seqlen: int, dtype: torch.dtype, autotune: bool, ): df = KernelResult.to_dataframe(results, sort_by = "speedup") df = create_merged_results(df, mode, seqlen, dtype, autotune) return df def save_results( df: pd.DataFrame, results_dir: str, mode: str, seqlen: int, dtype: torch.dtype, autotune: bool, ): dt = datetime.datetime.now().strftime("%Y%m%d_%H%M") save_dir = f"{results_dir}/{mode}" save_path = f"{save_dir}/{dt}_{seqlen}_{str(dtype).split('.')[-1]}.csv" if not os.path.exists(save_dir): os.makedirs(save_dir) print(f"Saving results to {save_path}") df.to_csv(save_path, index = False) def create_kernel_configs(args: argparse.Namespace, permute_x: bool, permute_y: bool): block_m_range = power_of_two_range(args.BLOCK_SIZE_M[0], args.BLOCK_SIZE_M[1]) block_n_range = power_of_two_range(args.BLOCK_SIZE_N[0], args.BLOCK_SIZE_N[1]) block_k_range = power_of_two_range(args.BLOCK_SIZE_K[0], args.BLOCK_SIZE_K[1]) num_warps_range = multiples_of_range(args.num_warps[0], args.num_warps[1], step = 2) num_stages_range = multiples_of_range( args.num_stages[0], args.num_stages[1], step = 1 ) mode = args.mode kernel_configs = [] for ( block_m, block_n, block_k, num_warps, num_stages, tma_load_a, tma_load_b, ) in product( block_m_range, block_n_range, block_k_range, num_warps_range, num_stages_range, [True, False], [True, False], ): if mode == "forward": kernel_config = KernelConfigForward( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = num_warps, num_stages = num_stages, use_tma_load_w = tma_load_a, use_tma_load_x = tma_load_b, permute_x = permute_x, permute_y = permute_y, ) elif mode == "dW": kernel_config = KernelConfigBackward_dW( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = tma_load_a, use_tma_load_x = tma_load_b, permute_x = permute_x, permute_y = permute_y, ) elif mode == "dX": kernel_config = KernelConfigBackward_dX( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = tma_load_a, use_tma_load_w = tma_load_b, permute_x = permute_x, permute_y = permute_y, ) else: raise ValueError(f"Invalid mode: {mode}") kernel_configs.append(kernel_config) logging.info(f"Pruning {len(kernel_configs)} kernel configs") pruned_configs = [] for config in kernel_configs: if mode == "forward": if permute_x and config.use_tma_load_x: continue elif mode == "dW": if permute_x and config.use_tma_load_x: continue if permute_y and config.use_tma_load_dy: continue elif mode == "dX": if permute_y and config.use_tma_load_dy: continue pruned_configs.append(config) logging.info(f"After pruning, {len(pruned_configs)} kernel configs") return pruned_configs def power_of_two_range(start, end): start = math.log2(start) end = math.log2(end) return [2**i for i in range(int(start), int(end) + 1)] def multiples_of_range(start, end, step = 1): return list(range(start, end + step, step)) def map_key_to_args(key, mode): pass def save_autotune_results(autotune_cache, mode, ref_time, fused_time, results_dir): device_name = torch.cuda.get_device_name().replace(" ", "_") dt = datetime.datetime.now().strftime("%Y%m%d_%H%M") save_dir = f"{results_dir}/{mode}/autotune/{dt}/{device_name}" if not os.path.exists(save_dir): os.makedirs(save_dir) for key, config in autotune_cache.items(): key = [ str(k) if not "torch" in str(k) else str(k.split("torch.")[-1]) for k in key ] filename = "_".join(key) save_path = f"{save_dir}/{filename}.json" print(f"Saving autotune results to {save_path}") with open(save_path, "w") as f: result = { **config.all_kwargs(), "ref_time": ref_time, "fused_time": fused_time, } json.dump(result, f) def get_autotuner(mode): if mode == "forward": from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel return _autotuned_grouped_gemm_forward_kernel elif mode == "dW": from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dW_kernel return _autotuned_grouped_gemm_dW_kernel elif mode == "dX": from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dX_kernel return _autotuned_grouped_gemm_dX_kernel elif mode == "backward": from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) return _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel else: raise ValueError(f"Invalid mode: {mode}") def postprocess_autotune_results(autotuner, mode, ref_time, fused_time, results_dir): for key, value in autotuner.cache.items(): print(f"{mode} {key}: {value.all_kwargs()}") save_autotune_results( autotuner.cache, mode = mode, ref_time = ref_time, fused_time = fused_time, results_dir = results_dir, )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/benchmark/utils.py", "license": "Apache License 2.0", "lines": 196, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/kernels/autotuning.py
# Unsloth # Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. """ Autotuning utils """ import logging from itertools import product from typing import List import torch import triton logger = logging.getLogger(__name__) DEFAULT_M_BLOCK_SIZES = [64, 128] DEFAULT_N_BLOCK_SIZES = [64, 128, 256] DEFAULT_K_BLOCK_SIZES = [64, 128, 256] DEFAULT_NUM_CTAS = 1 DEFAULT_NUM_WARPS = [4, 8] DEFAULT_NUM_STAGES = [3, 4, 5] BOOLS = [True, False] def val_to_list(val): if val is None: return None elif isinstance(val, list): return val else: return [val] def convert_args_to_list(args): return [val_to_list(arg) for arg in args] def _triton_supports_tma(): """Check if current Triton version supports TMA API.""" import triton.language as tl # Check for both old experimental and new stable API names return hasattr(tl, "make_tensor_descriptor") or hasattr( tl, "_experimental_make_tensor_descriptor" ) # Precompute at module import # NOTE: TMA is disabled for now due to compatibility issues with permute_x/permute_y settings # in the MoE grouped GEMM forward/backward passes. Re-enable once these are resolved. _TRITON_HAS_TMA = False # _triton_supports_tma() def get_forward_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, TMA_LOAD_X = None, # Auto-detect if not specified TMA_LOAD_W = None, # Auto-detect if not specified TMA_STORE = False, # NOTE: TMA_STORE is disabled for now num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, num_ctas = DEFAULT_NUM_CTAS, ): # Auto-detect TMA support if TMA_LOAD_X is None: TMA_LOAD_X = _TRITON_HAS_TMA if TMA_LOAD_W is None: TMA_LOAD_W = _TRITON_HAS_TMA ( BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_X, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ) = convert_args_to_list( [ BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_X, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ] ) kernel_configs = [] for ( block_m, block_n, block_k, w, s, tma_load_x, tma_load_w, tma_store, num_ctas, ) in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, TMA_LOAD_X, TMA_LOAD_W, TMA_STORE, num_ctas, ): kernel_configs.append( triton.Config( dict( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, USE_TMA_LOAD_X = tma_load_x, USE_TMA_LOAD_W = tma_load_w, USE_TMA_STORE = tma_store, ), num_warps = w, num_stages = s, num_ctas = num_ctas, ) ) return kernel_configs def get_dX_kernel_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, TMA_LOAD_dY = None, # Auto-detect if not specified TMA_LOAD_W = None, # Auto-detect if not specified TMA_STORE = False, # NOTE: TMA_STORE is disabled for now num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, num_ctas = DEFAULT_NUM_CTAS, ): # Auto-detect TMA support if TMA_LOAD_dY is None: TMA_LOAD_dY = _TRITON_HAS_TMA if TMA_LOAD_W is None: TMA_LOAD_W = _TRITON_HAS_TMA ( BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_dY, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ) = convert_args_to_list( [ BLOCK_M, BLOCK_N, BLOCK_K, TMA_LOAD_dY, TMA_LOAD_W, TMA_STORE, num_warps, num_stages, num_ctas, ] ) kernel_configs = [] for ( block_m, block_n, block_k, w, s, tma_load_dy, tma_load_w, tma_store, num_ctas, ) in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, TMA_LOAD_dY, TMA_LOAD_W, TMA_STORE, num_ctas, ): kernel_configs.append( triton.Config( dict( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, USE_TMA_LOAD_dY = tma_load_dy, USE_TMA_LOAD_W = tma_load_w, USE_TMA_STORE = tma_store, ), num_warps = w, num_stages = s, num_ctas = num_ctas, ) ) return kernel_configs def get_dW_kernel_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, num_ctas = DEFAULT_NUM_CTAS, TMA_LOAD_dY = None, # Auto-detect if not specified TMA_LOAD_X = None, # Auto-detect if not specified TMA_STORE = False, ): # Auto-detect TMA support if TMA_LOAD_dY is None: TMA_LOAD_dY = _TRITON_HAS_TMA if TMA_LOAD_X is None: TMA_LOAD_X = _TRITON_HAS_TMA ( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, num_ctas, TMA_LOAD_dY, TMA_LOAD_X, TMA_STORE, ) = convert_args_to_list( [ BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, num_ctas, TMA_LOAD_dY, TMA_LOAD_X, TMA_STORE, ] ) kernel_configs = [] for ( block_m, block_n, block_k, w, s, tma_load_dy, tma_load_x, tma_store, num_ctas, ) in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, TMA_LOAD_dY, TMA_LOAD_X, TMA_STORE, num_ctas, ): kernel_configs.append( triton.Config( dict( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, USE_TMA_LOAD_dY = tma_load_dy, USE_TMA_LOAD_X = tma_load_x, USE_TMA_STORE = tma_store, ), num_warps = w, num_stages = s, num_ctas = num_ctas, ) ) return kernel_configs def estimate_smem_reqs( num_stages: int, BLOCK_SIZE_M: int, BLOCK_SIZE_N: int, BLOCK_SIZE_K: int, dtype: torch.dtype, ): num_bytes = dtype.itemsize return ( num_stages * BLOCK_SIZE_K * (BLOCK_SIZE_M + BLOCK_SIZE_N) + BLOCK_SIZE_M * BLOCK_SIZE_N ) * num_bytes def exceeds_smem_capacity( num_stages: int, BLOCK_SIZE_M: int, BLOCK_SIZE_N: int, BLOCK_SIZE_K: int, dtype: torch.dtype, smem_size: int, slack: float = 50000, ): smem_reqs = estimate_smem_reqs( num_stages, BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K, dtype ) return smem_reqs > smem_size + slack def common_prune_criteria(config: triton.Config, kwargs: dict, dtype): from ..interface import supports_tma from .tuning import get_device_properties smem_size = get_device_properties().SIZE_SMEM num_stages = config.num_stages BLOCK_SIZE_M = config.kwargs["BLOCK_SIZE_M"] BLOCK_SIZE_N = config.kwargs["BLOCK_SIZE_N"] BLOCK_SIZE_K = config.kwargs["BLOCK_SIZE_K"] num_tokens = kwargs["NUM_TOKENS"] num_experts = kwargs["NUM_EXPERTS"] permute_x = kwargs["PERMUTE_X"] permute_y = kwargs["PERMUTE_Y"] tokens_per_expert = num_tokens // num_experts # use_tma = [k for k in config.kwargs.keys() if k.startswith("USE_TMA_")] MIN_BLOCK_SIZE_M = DEFAULT_M_BLOCK_SIZES[0] if exceeds_smem_capacity( num_stages, BLOCK_SIZE_M, BLOCK_SIZE_N, BLOCK_SIZE_K, dtype, smem_size ): return True if BLOCK_SIZE_M > tokens_per_expert * 2 and tokens_per_expert > MIN_BLOCK_SIZE_M: return True if permute_x and permute_y: return True # if not supports_tma() and any(use_tma): # return True return False def maybe_disable_tma(config: triton.Config): from ..interface import supports_tma tma_keys = [k for k in config.kwargs.keys() if k.startswith("USE_TMA_")] if not supports_tma(): logger.info("Disabling TMA") for k in tma_keys: config.kwargs[k] = False def prune_kernel_configs_fwd(configs: list[triton.Config], args, **kwargs): x = kwargs["x_ptr"] dtype = x.dtype logger.debug(f"Pruning configs: {len(configs)}") pruned_configs = [] for config in configs: # disable TMA if gpu does not support it maybe_disable_tma(config) if common_prune_criteria(config, kwargs, dtype): continue if config.kwargs["USE_TMA_LOAD_X"] and kwargs["PERMUTE_X"]: # Dynamically disable TMA_LOAD_X for permuted X config.kwargs["USE_TMA_LOAD_X"] = False if config.kwargs["USE_TMA_STORE"] and kwargs["PERMUTE_Y"]: continue pruned_configs.append(config) logger.debug(f"Pruned configs: {len(pruned_configs)}") return pruned_configs def prune_dX_configs(configs: List[triton.Config], args, **kwargs): dtype = kwargs["w_ptr"].dtype logger.debug(f"Pruning configs: {len(configs)}") pruned_configs = [] for config in configs: if common_prune_criteria(config, kwargs, dtype): continue if config.kwargs["USE_TMA_LOAD_dY"] and kwargs["PERMUTE_Y"]: # dynamically disable TMA_LOAD_dY for permuted Y config.kwargs["USE_TMA_LOAD_dY"] = False if config.kwargs["USE_TMA_STORE"] and kwargs["PERMUTE_X"]: continue pruned_configs.append(config) logger.debug(f"Pruned configs: {len(pruned_configs)}") return pruned_configs def prune_kernel_configs_backward_dW(configs: list[triton.Config], args, **kwargs): dtype = kwargs["x_ptr"].dtype pruned_configs = [] logger.debug(f"Pruning configs: {len(configs)}") for config in configs: if common_prune_criteria(config, kwargs, dtype): continue if config.kwargs["USE_TMA_LOAD_dY"] and kwargs["PERMUTE_Y"]: config.kwargs["USE_TMA_LOAD_dY"] = False if config.kwargs["USE_TMA_LOAD_X"] and kwargs["PERMUTE_X"]: config.kwargs["USE_TMA_LOAD_X"] = False pruned_configs.append(config) logger.debug(f"Pruned configs: {len(pruned_configs)}") return pruned_configs
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/kernels/autotuning.py", "license": "Apache License 2.0", "lines": 387, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/kernels/backward.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch import triton import triton.language as tl from .autotuning import ( get_dW_kernel_configs, get_dX_kernel_configs, prune_dX_configs, prune_kernel_configs_backward_dW, ) """ dX backward kernel - Shapes - the forward pass input X shape is [NUM_TOKENS, K] if permute_x else [NUM_TOKENS * TOPK, K]; output y is [NUM_TOKENS * TOPK, N] - the backward pass input dy shape is [NUM_TOKENS * TOPK, N], reduce across N, output dX is [NUM_TOKENS * TOPK, K] - Note that in the backward pass, the output size is still [NUM_TOKENS * TOPK, K] since we still need to accumulate gradients for each expert chosen by the token in a post-processing step. `permute_x` notes: - In the forward pass, if we permute X on load, we need to permute on store in the backward pass to restore to original token order - the output dX with have shape [NUM_TOKENS * TOPK, K] and we need to perform an additional reduction across topk to accumulate gradients - This is done as a post-processing step in autograd.Function. - If not `permute_x`, this postprocessing step should take place outside autograd.Function such that the gradient shape matches the input X shape. `permute_y` notes: - In the forward pass, if we permuted output on store (e.g., in the second grouped GEMM in fused MoE MLP), we need to permute on load to get from token order to expert grouped order - We still store in contiguous order since we are writing out dX which will be the input to the backwards pass of the first grouped GEMM `fused_mul` notes: - In the forward pass, if we used the multiplication of topk weights (e.g., in the second grouped GEMM in fused MoE MLP), we need to make a few additional changes: 1) We load topk_weights in natural (token) order. Since we only enable `fuse_mul` when permuting on store (`permute_y`), we multiply grad_output by topk_weights before backpropagating 2) We need to calculate the gradient of the topk_weights. This gets messy since we need do an additional elementwise multiplication in the GEMM main loop and then write out in unpermuted order. For now, we do not fuse this step but calculate as a simple Invalid combinations: - permute_y and use_tma_load: permuting y on store in forward -> load in permuted order in backward, therefore can't use TMA load (unless Blackwell which supports gather / scatter TMA) - permute_x and use_tma_store: permuting x on load in forward -> store in permuted order in backward, therefore can't use TMA store (unless Blackwell which supports gather / scatter TMA) TODO: - We define indices for all conditions and expect that unused indices will be DCE'd during compilation. Check that this is the case otherwise will result in unnecessary register usage. """ @triton.jit def _grouped_gemm_dX_kernel( dY_ptr, # [M_total, N] w_ptr, # [E, N, K] dX_ptr, # [M_total, K] gather_indices_ptr, m_sizes_ptr, # problem sizes NUM_EXPERTS: tl.constexpr, NUM_TOKENS, TOPK: tl.constexpr, N: tl.constexpr, K: tl.constexpr, NUM_SMS, # Tuning parameters BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, PERMUTE_X: tl.constexpr = False, PERMUTE_Y: tl.constexpr = False, USE_TMA_LOAD_W: tl.constexpr = False, USE_TMA_LOAD_dY: tl.constexpr = False, USE_TMA_STORE: tl.constexpr = False, FLATTEN: tl.constexpr = True, ) -> None: TOTAL_TOKENS = NUM_TOKENS * TOPK output_dtype = dX_ptr.dtype.element_ty tidx = tl.program_id(0) # This removes the need for predication along N in the GEMM main loop tl.static_assert(N % BLOCK_SIZE_N == 0, "N must be divisible by BLOCK_SIZE_N") tl.static_assert(K % BLOCK_SIZE_K == 0, "K must be divisible by BLOCK_SIZE_K") # Create TMA descriptors for loading sorted tokens # When using TMA load, we don't permute_x, so shape should be [TOTAL_TOKENS, K] # Also, we are defining a single global descriptor with single block shape # Need to check that this does not result in errors when crossing expert boundaries if USE_TMA_LOAD_dY: dY_desc = tl.make_tensor_descriptor( dY_ptr, shape = [TOTAL_TOKENS, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) if USE_TMA_LOAD_W: expert_stride = N * K w_desc = tl.make_tensor_descriptor( w_ptr, shape = [NUM_EXPERTS, N, K], strides = [expert_stride, K, 1], block_shape = [1, BLOCK_SIZE_N, BLOCK_SIZE_K], ) m_end = 0 processed_tiles = 0 m_block_range = tl.arange(0, BLOCK_SIZE_M) n_block_range = tl.arange(0, BLOCK_SIZE_N) k_block_range = tl.arange(0, BLOCK_SIZE_K) for expert_idx in range(NUM_EXPERTS, flatten = FLATTEN): m_start = m_end m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32) m_end = m_start + m_size if m_size > 0: # Advance n offset to the weights for that respective expert n_start = expert_idx * N # N_start_offset = g.to(tl.int64) * N # tiles for this group's GEMM num_m_tiles = tl.cdiv(m_size, BLOCK_SIZE_M) num_k_tiles = tl.cdiv(K, BLOCK_SIZE_K) num_tiles_per_expert = num_m_tiles * num_k_tiles if USE_TMA_STORE: # Need to define descript within loop to predicate store along M tl.static_assert( K % BLOCK_SIZE_K == 0, "K must be divisible by BLOCK_SIZE_K" ) dX_desc = tl.make_tensor_descriptor( dX_ptr, shape = [m_end, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) # Lower bound and upper bound are defined relative to the total tiles processed so far # This ensures that we are only processing tiles for the current expert group AND # we never exceed the total number of tiles for all expert groups while tidx >= processed_tiles and tidx < ( processed_tiles + num_tiles_per_expert ): group_index = tidx - processed_tiles # Output tile for this thread block for this expert group tile_m_idx = group_index % num_m_tiles tile_k_idx = group_index // num_m_tiles if PERMUTE_X or PERMUTE_Y: # These will be used for loading and storing in permuted order gather_offsets = tile_m_idx * BLOCK_SIZE_M + m_block_range # indices_to_gather = m_start + gather_offsets indices_to_gather = m_start + tl.max_contiguous( tl.multiple_of(gather_offsets % m_size, BLOCK_SIZE_M), BLOCK_SIZE_M, ) expert_token_idx = tl.load( gather_indices_ptr + indices_to_gather, mask = indices_to_gather < TOTAL_TOKENS, ) expert_token_offsets = expert_token_idx[:, None] # Masks for permuted load and store row_mask = gather_offsets < m_size row_mask = row_mask[:, None] # We only take into account the following two cases: (PERMUTE_X and NOT PERMUTE_Y) and (NOT PERMUTE_X and PERMUTE_Y) # Hence, we can make the following simplifying assumptions when loading and storing # Note the different strides between the two cases: the offsets for loading and storing are flipped and the strides must also be adjusted if PERMUTE_X: # Case where we permuted on load in the forward pass (typically first grouped GEMM in MoE MLP) load_a_idx = ( indices_to_gather[:, None] * N ) # Load in contiguous (expert grouped) order store_idx = ( expert_token_offsets * K ) # Permute on store from expert -> token order else: # Case where we permuted on store in the forward pass (typically second grouped GEMM in MoE MLP) load_a_idx = ( expert_token_offsets * N ) # Permute on load from token -> expert order store_idx = ( indices_to_gather[:, None] * K ) # Store in contiguous order else: # # Position in full matrix - needed for TMA # m_offset = (M_start + (tile_m_idx * BLOCK_SIZE_M)).to(tl.int32) # k_offset = (tile_k_idx * BLOCK_SIZE_K).to(tl.int32) # Offsets *relative* to the *current* expert -- m_start will then advance to this expert's start token offs_am = tile_m_idx * BLOCK_SIZE_M + m_block_range # [M, N] @ [N, K] -> [M, K] => Stride for A is N, stride for B is K # We need two additional offsets: # 1. For A, m_start to advance to this expert's start token # 2. For B, n_start to advance to this expert's weights since we are passing in an [E, N, K] weight matrix row_offsets_a = m_start + offs_am[:, None] load_a_idx = row_offsets_a * N store_idx = row_offsets_a * K row_mask = offs_am[:, None] < m_size if not USE_TMA_LOAD_dY: dY_ptrs = dY_ptr + load_a_idx + n_block_range[None, :] offs_bk = tile_k_idx * BLOCK_SIZE_K + k_block_range if not USE_TMA_LOAD_W: row_offsets_b = n_start + n_block_range # offs_bn = n_start + n_block_range # row_offsets_b = tl.max_contiguous(tl.multiple_of(offs_bn, BLOCK_SIZE_N), BLOCK_SIZE_N) w_ptrs = w_ptr + row_offsets_b[:, None] * K + offs_bk[None, :] # TODO: check whether predication along K is needed since we checked that K is divisible by BLOCK_SIZE_K in the forward kernel # col_mask = offs_bk[None, :] < K store_mask = row_mask # & col_mask accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_K), dtype = tl.float32) # GEMM main loop for n_offset in range(0, N, BLOCK_SIZE_N): # dY block [M, N] if not USE_TMA_LOAD_dY: dY = tl.load(dY_ptrs, mask = row_mask) else: dY = dY_desc.load( [m_start + tile_m_idx * BLOCK_SIZE_M, n_offset] ) if not USE_TMA_LOAD_W: w = tl.load(w_ptrs) # , mask=col_mask) else: w = w_desc.load( [expert_idx, n_offset, tile_k_idx * BLOCK_SIZE_K] ) w = tl.reshape(w, (BLOCK_SIZE_N, BLOCK_SIZE_K)) # TODO: check if predication along K is needed since we checked that K is divisible by BLOCK_SIZE_K in the forward kernel # [M, N] @ [N, K] -> [M, K] dY = dY.to(w.dtype) accumulator += tl.dot(dY, w) # NOTE: no transpose of b # Advance A along contiguous dimension if not USE_TMA_LOAD_dY: dY_ptrs += BLOCK_SIZE_N # Note we are no longer advancing B along contiguous dimension since weights are arranged as [N, K] # Instead, we need to stride by K to advance to the [N_BLOCK_SIZE, K_BLOCK_SIZE] tile if not USE_TMA_LOAD_W: w_ptrs += BLOCK_SIZE_N * K dX = accumulator.to(output_dtype) # Writing out a BLOCK_M x BLOCK_K tile, so we need to stride by K if USE_TMA_STORE: offset_m = tile_m_idx * BLOCK_SIZE_M # .to(tl.int32) offset_k = tile_k_idx * BLOCK_SIZE_K # .to(tl.int32) dX_desc.store([m_start + offset_m, offset_k], dX) else: tl.store( dX_ptr + store_idx + offs_bk[None, :], dX, mask = store_mask, ) # Move to the next tile within this expert group tidx += NUM_SMS # Update the total tiles count for the next expert group processed_tiles += num_tiles_per_expert _autotuned_grouped_gemm_dX_kernel = triton.autotune( configs = get_dX_kernel_configs(), prune_configs_by = {"early_config_prune": prune_dX_configs}, # NOTE: NUM_TOKENS removed from key to avoid recompilation for every sequence length key = ["NUM_EXPERTS", "N", "K", "PERMUTE_X", "PERMUTE_Y"], )(_grouped_gemm_dX_kernel) """ notes on permute_x: - for the first grouped GEMM, we permuted on load -> X was [num_tokens, K] and stored y in expert grouped order [num_tokens * topk, K] - in the backwards pass, we need to permute on load of X while loading dy in contiguous (expert grouped) order - since we are writing out dW, there is no need to permute on store notes on permute_y: - for the second grouped GEMM, we permuted on store -> y was permuted from expert grouped order to token order, x was loaded in expert grouped order since it was the output of the first grouped GEMM - in the backwards pass, we need to permute on load of dy to get from token order to expert grouped order to match the order of X - since we are writing out dW, there is no need to permute on store notes on TMA loading: - if we're TMA loading both X and dY, then we need to mask along the M dimension to account for expert boundaries - we can either - define TMA descriptors within the outer for loop to predicate loads or - mask along M after loading """ @triton.jit def _grouped_gemm_dW_kernel( x_ptr, dY_ptr, dW_ptr, m_sizes_ptr, gather_indices_ptr, # problem sizes NUM_TOKENS, TOPK: tl.constexpr, NUM_EXPERTS: tl.constexpr, N: tl.constexpr, K: tl.constexpr, NUM_SMS, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, PERMUTE_X: tl.constexpr = False, PERMUTE_Y: tl.constexpr = False, USE_TMA_LOAD_dY: tl.constexpr = False, USE_TMA_LOAD_X: tl.constexpr = False, USE_TMA_STORE: tl.constexpr = False, FLATTEN: tl.constexpr = True, acc_dtype: tl.constexpr = tl.float32, ) -> None: TOTAL_TOKENS = NUM_TOKENS * TOPK TMA_LOAD_BOTH: tl.constexpr = USE_TMA_LOAD_X and USE_TMA_LOAD_dY tidx = tl.program_id(0) output_dtype = dW_ptr.dtype.element_ty if USE_TMA_LOAD_dY and not TMA_LOAD_BOTH: dY_desc = tl.make_tensor_descriptor( dY_ptr, shape = [TOTAL_TOKENS, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) if USE_TMA_LOAD_X and not TMA_LOAD_BOTH: x_desc = tl.make_tensor_descriptor( x_ptr, shape = [TOTAL_TOKENS, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) # Output tiles per expert, since each expert weight matrix is [N, K] num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N) num_k_tiles = tl.cdiv(K, BLOCK_SIZE_K) output_tiles_per_expert = num_n_tiles * num_k_tiles block_range_m = tl.arange(0, BLOCK_SIZE_M) block_range_n = tl.arange(0, BLOCK_SIZE_N) block_range_k = tl.arange(0, BLOCK_SIZE_K) # NOTE: Important that N % BLOCK_SIZE_N == 0 and K % BLOCK_SIZE_K == 0 when using TMA store if USE_TMA_STORE: tl.static_assert(N % BLOCK_SIZE_N == 0, "N must be divisible by BLOCK_SIZE_N") tl.static_assert(K % BLOCK_SIZE_K == 0, "K must be divisible by BLOCK_SIZE_K") dW_desc = tl.make_tensor_descriptor( dW_ptr, shape = [NUM_EXPERTS, N, K], strides = [N * K, K, 1], block_shape = [1, BLOCK_SIZE_N, BLOCK_SIZE_K], ) for tile_idx in range( tidx, output_tiles_per_expert, NUM_SMS ): # , flatten=FLATTEN): # Output tile index tile_n_idx = tile_idx % num_n_tiles tile_k_idx = tile_idx // num_n_tiles # Output tile offsets n_offset = tile_n_idx * BLOCK_SIZE_N k_offset = tile_k_idx * BLOCK_SIZE_K # For storing # TODO: Check whether the k mask is needed since we statically check that K is divisible by BLOCK_SIZE_K in the forward kernel # ditto for n_mask n_mask = block_range_n + n_offset < N k_mask = block_range_k + k_offset < K nk_mask = n_mask[:, None] & k_mask[None, :] m_end = 0 for expert_idx in range(NUM_EXPERTS): # We need to instantiate a fresh accumulator for each expert accumulator = tl.zeros((BLOCK_SIZE_N, BLOCK_SIZE_K), dtype = acc_dtype) m_start = m_end # Need to figure out why this cast is needed, otherwise compiler complains about mismatching types m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32) m_end = m_start + m_size # NOTE: when storing the result, we need to offset by n_start since we are storing the result for this expert to the global [E, N, K] weight matrix n_start = expert_idx * N store_row_offs = n_start + n_offset + block_range_n if m_size > 0: if TMA_LOAD_BOTH: dY_desc = tl.make_tensor_descriptor( dY_ptr, shape = [m_end, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) x_desc = tl.make_tensor_descriptor( x_ptr, shape = [m_end, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) for tile_m_idx in range(0, m_size, BLOCK_SIZE_M): m_block_size = tl.minimum(BLOCK_SIZE_M, m_size - tile_m_idx) if m_block_size > 0: # Global offset for this chunk m_global_offset = m_start + tile_m_idx m_offsets = m_global_offset + block_range_m if PERMUTE_X or PERMUTE_Y: # These will be used for loading and storing in permuted order gather_offsets = ( tile_m_idx + block_range_m ) # NOTE: tile_m_idx is already strided by BLOCK_SIZE_M indices_to_gather = m_start + tl.max_contiguous( tl.multiple_of(gather_offsets % m_size, BLOCK_SIZE_M), BLOCK_SIZE_M, ) # indices_to_gather = m_start + gather_offsets expert_token_idx = tl.load( gather_indices_ptr + indices_to_gather, mask = indices_to_gather < TOTAL_TOKENS, ) expert_token_offsets = expert_token_idx[:, None] # Masks for permuted load and store row_load_mask = gather_offsets < m_size # We only take into account the following two cases: (PERMUTE_X and NOT PERMUTE_Y) and (NOT PERMUTE_X and PERMUTE_Y) # Hence, we can make the following simplifying assumptions when loading and storing # Note the different strides between the two cases: the offsets for loading and storing are flipped and the strides must also be adjusted if PERMUTE_X: x_row_load_idx = ( (expert_token_offsets // TOPK) * K ) # Permute on load from token -> expert order, divide by TOPK to index from original number of tokens dY_row_load_idx = m_offsets[:, None] * N else: x_row_load_idx = ( indices_to_gather[:, None] * K ) # Load in contiguous order (no permutation on load) dY_row_load_idx = expert_token_offsets * N else: x_row_load_idx = m_offsets[:, None] * K dY_row_load_idx = m_offsets[:, None] * N row_load_mask = block_range_m < m_block_size mk_mask = row_load_mask[:, None] & k_mask[None, :] mn_mask = row_load_mask[:, None] & n_mask[None, :] if USE_TMA_LOAD_X: x = x_desc.load([m_global_offset, k_offset]) else: x = tl.load( x_ptr + x_row_load_idx + (k_offset + block_range_k)[None, :], mask = mk_mask, ) if USE_TMA_LOAD_dY: dY = dY_desc.load([m_global_offset, n_offset]) else: dY = tl.load( dY_ptr + dY_row_load_idx + (n_offset + block_range_n)[None, :], mask = mn_mask, ) accumulator += tl.dot( dY.T.to(x.dtype), # [BLOCK_N, BLOCK_M] x, # [BLOCK_M, BLOCK_K] ) y = accumulator.to(output_dtype) if USE_TMA_STORE: # Need to expand dims to match [E, N, K] shape y = tl.expand_dims(y, 0) dW_desc.store([expert_idx, n_offset, k_offset], y) else: tl.store( dW_ptr # + (n_offset + offs_n)[:, None] * K + store_row_offs[:, None] * K + (k_offset + block_range_k)[None, :], y, mask = nk_mask, ) _autotuned_grouped_gemm_dW_kernel = triton.autotune( configs = get_dW_kernel_configs(), prune_configs_by = {"early_config_prune": prune_kernel_configs_backward_dW}, # NOTE: NUM_TOKENS removed from key to avoid recompilation for every sequence length key = ["NUM_EXPERTS", "N", "K", "PERMUTE_X", "PERMUTE_Y"], )(_grouped_gemm_dW_kernel)
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/kernels/backward.py", "license": "Apache License 2.0", "lines": 434, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/kernels/forward.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch import triton import triton.language as tl from .autotuning import ( get_forward_configs, prune_kernel_configs_fwd, ) # # PERMUTE_X -> permute tokens so that they are ordered by expert # PERMUTE_Y -> permute output so that they are ordered by token # These are effectively the same thing: the former loads in permuted order, the latter stores in permuted order => we only need to define the permutation indices once # In the former, we use these row indices when loading X # For the latter, we use these row indices when storing Y # FUSE_MUL -> multiply routed outputs by their respective weights # topk_weights are in token order # Only account for the case when X is in expert order and we are permuting Y when fusing mul -- this precondition is checked in the interface @triton.jit def _grouped_gemm_forward_kernel( x_ptr, w_ptr, y_ptr, # Variable depending on routed probs m_sizes_ptr, gather_indices_ptr, topk_weights_ptr, # Constant problem shapes NUM_EXPERTS: tl.constexpr, NUM_TOKENS, TOPK: tl.constexpr, N: tl.constexpr, K: tl.constexpr, NUM_SMS, # Tuning params BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr, PERMUTE_X: tl.constexpr = False, PERMUTE_Y: tl.constexpr = False, FUSE_MUL_PRE: tl.constexpr = False, FUSE_MUL_POST: tl.constexpr = False, USE_FAST_ACCUM: tl.constexpr = False, USE_TMA_LOAD_W: tl.constexpr = False, USE_TMA_LOAD_X: tl.constexpr = False, USE_TMA_STORE: tl.constexpr = False, acc_dtype: tl.constexpr = tl.float32, FLATTEN: tl.constexpr = True, ) -> None: tl.static_assert(K % BLOCK_SIZE_K == 0) TOTAL_TOKENS = NUM_TOKENS * TOPK SHOULD_PERMUTE: tl.constexpr = PERMUTE_X or PERMUTE_Y SHOULD_FUSE_MUL: tl.constexpr = FUSE_MUL_PRE or FUSE_MUL_POST SHOULD_PERMUTE_OR_FUSE: tl.constexpr = SHOULD_PERMUTE or SHOULD_FUSE_MUL # tl.static_print("SHOULD_PERMUTE", PERMUTE_X, PERMUTE_Y, FUSE_MUL_PRE, FUSE_MUL_POST, SHOULD_PERMUTE, SHOULD_FUSE, SHOULD_PERMUTE_OR_FUSE) tidx = tl.program_id(0) output_dtype: tl.dtype = y_ptr.dtype.element_ty # Create TMA descriptors for loading sorted tokens # When using TMA load, we don't permute_x, so shape should be [TOTAL_TOKENS, K] # Also, we are defining a single global descriptor with single block shape # Need to check that this does not result in errors when crossing expert boundaries if USE_TMA_LOAD_X: x_desc = tl.make_tensor_descriptor( x_ptr, shape = [TOTAL_TOKENS, K], strides = [K, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_K], ) if USE_TMA_LOAD_W: expert_stride = N * K w_desc = tl.make_tensor_descriptor( w_ptr, shape = [NUM_EXPERTS, N, K], strides = [expert_stride, K, 1], block_shape = [1, BLOCK_SIZE_N, BLOCK_SIZE_K], ) m_end = 0 processed_tiles = 0 m_block_range = tl.arange(0, BLOCK_SIZE_M) for expert_idx in tl.range(NUM_EXPERTS, flatten = FLATTEN): m_start = m_end m_size = tl.load(m_sizes_ptr + expert_idx).to(tl.int32) m_end = m_start + m_size if m_size > 0: n_start = expert_idx * N num_m_tiles = tl.cdiv(m_size, BLOCK_SIZE_M) num_n_tiles = tl.cdiv(N, BLOCK_SIZE_N) num_tiles_per_expert = num_m_tiles * num_n_tiles # Need to create tma_store within loop since we need to predicate stores based on m_size if USE_TMA_STORE: y_desc = tl.make_tensor_descriptor( y_ptr, # + m_start * N, shape = [m_end, N], strides = [N, 1], block_shape = [BLOCK_SIZE_M, BLOCK_SIZE_N], ) # Process tiles for this expert while ( tidx >= processed_tiles and tidx < processed_tiles + num_tiles_per_expert ): tile_idx = tidx - processed_tiles # Check if L2 cache re-use for this order is optimal tile_m_idx = tile_idx % num_m_tiles tile_n_idx = tile_idx // num_m_tiles if SHOULD_PERMUTE_OR_FUSE: # These will be used for loading and storing in permuted order gather_offsets = tile_m_idx * BLOCK_SIZE_M + m_block_range indices_to_gather = m_start + tl.max_contiguous( tl.multiple_of(gather_offsets % m_size, BLOCK_SIZE_M), BLOCK_SIZE_M, ) expert_token_idx = tl.load( gather_indices_ptr + indices_to_gather, mask = indices_to_gather < TOTAL_TOKENS, ) expert_token_offsets = expert_token_idx[:, None] # Masks for permuted load and store row_mask = gather_offsets < m_size row_mask = row_mask[:, None] # row_mask = indices_to_gather < m_end # row_mask = row_mask[:, None] # We only take into account the following two cases: (PERMUTE_X and NOT PERMUTE_Y) and (NOT PERMUTE_X and PERMUTE_Y) # Hence, we can make the following simplifying assumptions when loading and storing # Note the different strides between the two cases: the offsets for loading and storing are flipped and the strides must also be adjusted if PERMUTE_X: load_idx = ( (expert_token_offsets // TOPK) * K ) # Permute on load from token -> expert order, divide by TOPK to index from original number of tokens store_idx = ( indices_to_gather[:, None] * N ) # Store in contiguous order else: off_am = tile_m_idx * BLOCK_SIZE_M if not PERMUTE_Y: # These will already be computed if permuting y offs_am = off_am + m_block_range row_mask = offs_am[:, None] < m_size row_idx = m_start + offs_am[:, None] store_idx = row_idx * N if not USE_TMA_LOAD_X: load_idx = row_idx * K if PERMUTE_Y: if not USE_TMA_LOAD_X: load_idx = ( indices_to_gather[:, None] * K ) # Load in contiguous order (no permutation on load) # offs_am = off_am + m_block_range # row_mask = offs_am[:, None] < m_size store_idx = ( expert_token_offsets * N ) # Permute on store from expert -> token order # We always load topk weights in expert order # In the pre-multiplication case, we multiply permuted hidden states by weights before the first gemm # In the post-multiplication case, we multiply permuted hidden states by weights after the second gemm # In either case, the hidden states are grouped by expert, so we always permute on load of topk weights if SHOULD_FUSE_MUL: topk_load_idx = expert_token_offsets accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype = acc_dtype) offs_k = tl.arange(0, BLOCK_SIZE_K) if not USE_TMA_LOAD_X: x_ptrs = x_ptr + load_idx + offs_k[None, :] if not USE_TMA_LOAD_W: offs_bn = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) offs_bn = tl.max_contiguous( tl.multiple_of(offs_bn % N, BLOCK_SIZE_N), BLOCK_SIZE_N ) w_ptrs = w_ptr + (n_start + offs_bn[:, None]) * K + offs_k[None, :] for k_offset in range(0, K, BLOCK_SIZE_K): if not USE_TMA_LOAD_X: x = tl.load(x_ptrs, mask = row_mask) else: x = x_desc.load([m_start + off_am, k_offset]) if FUSE_MUL_PRE: # Check for correct broadcasting topk_weights = tl.load( topk_weights_ptr + topk_load_idx, mask = row_mask ) x *= topk_weights.to(x.dtype) if not USE_TMA_LOAD_W: w = tl.load(w_ptrs, mask = offs_bn[:, None] < N) else: w = w_desc.load( [expert_idx, tile_n_idx * BLOCK_SIZE_N, k_offset] ) w = tl.reshape(w, (BLOCK_SIZE_N, BLOCK_SIZE_K)) x = x.to(w.dtype) accumulator += tl.dot(x, w.T) if not USE_TMA_LOAD_X: x_ptrs += BLOCK_SIZE_K if not USE_TMA_LOAD_W: w_ptrs += BLOCK_SIZE_K y = accumulator.to(output_dtype) # NOTE: order of fusing multiplication is important # Fusing before accumulator dtype conversion results in numerical diffs if FUSE_MUL_POST: # Check for correct broadcasting topk_weights = tl.load( topk_weights_ptr + topk_load_idx, mask = row_mask ) y *= topk_weights.to(output_dtype) offs_bn = tile_n_idx * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) store_mask = row_mask & (offs_bn[None, :] < N) if USE_TMA_STORE: offset_m = tile_m_idx * BLOCK_SIZE_M # .to(tl.int32) offset_n = tile_n_idx * BLOCK_SIZE_N # .to(tl.int32) y_desc.store([m_start + offset_m, offset_n], y) else: tl.store( y_ptr + store_idx + offs_bn[None, :], y, mask = store_mask, ) tidx += NUM_SMS processed_tiles += num_tiles_per_expert _autotuned_grouped_gemm_forward_kernel = triton.autotune( configs = get_forward_configs(), prune_configs_by = {"early_config_prune": prune_kernel_configs_fwd}, # NOTE: NUM_TOKENS removed from key to avoid recompilation for every sequence length # The kernel handles variable token counts via m_sizes and tile-based processing key = [ "NUM_EXPERTS", "N", "K", "PERMUTE_X", "PERMUTE_Y", "FUSE_MUL_POST", ], )(_grouped_gemm_forward_kernel)
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/kernels/forward.py", "license": "Apache License 2.0", "lines": 229, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/kernels/tuning.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. """ Manual tuning utils """ from collections import OrderedDict from dataclasses import asdict, dataclass, fields from itertools import product from typing import Optional import pandas as pd import torch import triton from triton.runtime.errors import OutOfResources from .autotuning import ( BOOLS, DEFAULT_K_BLOCK_SIZES, DEFAULT_M_BLOCK_SIZES, DEFAULT_N_BLOCK_SIZES, DEFAULT_NUM_STAGES, DEFAULT_NUM_WARPS, ) @dataclass class DeviceProperties: NUM_SM: int NUM_REGS: int SIZE_SMEM: int WARP_SIZE: int _DEVICE_PROPERTIES: Optional[DeviceProperties] = None def get_device_properties(): global _DEVICE_PROPERTIES if _DEVICE_PROPERTIES is None: properties = triton.runtime.driver.active.utils.get_device_properties( torch.cuda.current_device() ) NUM_SM = properties["multiprocessor_count"] NUM_REGS = properties["max_num_regs"] SIZE_SMEM = properties["max_shared_mem"] WARP_SIZE = properties["warpSize"] _DEVICE_PROPERTIES = DeviceProperties(NUM_SM, NUM_REGS, SIZE_SMEM, WARP_SIZE) return _DEVICE_PROPERTIES @dataclass class KernelConfig: BLOCK_SIZE_M: int = 32 BLOCK_SIZE_N: int = 32 BLOCK_SIZE_K: int = 32 num_warps: int = 4 num_stages: int = 2 flatten: bool = True permute_x: bool = False permute_y: bool = False fuse_mul_post: bool = False use_tma_store: bool = False def to_string(self, include_tuning_params: bool = False, include_tma: bool = False): s = [] if self.permute_x: s.append("permute_x") if self.permute_y: s.append("permute_y") if include_tuning_params: s.append( f"BLOCK_SIZE_M={self.BLOCK_SIZE_M},BLOCK_SIZE_N={self.BLOCK_SIZE_N},BLOCK_SIZE_K={self.BLOCK_SIZE_K},num_warps={self.num_warps},num_stages={self.num_stages},flatten={self.flatten}" ) if include_tma: for f in fields(self): if f.name.startswith("use_tma_"): if getattr(self, f.name): s.append(f.name) return ",".join(s) @dataclass class KernelConfigForward(KernelConfig): use_tma_load_w: bool = False use_tma_load_x: bool = False @dataclass class KernelConfigBackward_dW(KernelConfig): use_tma_load_dy: bool = False use_tma_load_x: bool = False @dataclass class KernelConfigBackward_dX(KernelConfig): use_tma_load_dy: bool = False use_tma_load_w: bool = False @dataclass class KernelResult: torch_time: float triton_time: float speedup: float kernel_config: KernelConfig def to_dict(self): return OrderedDict( **asdict(self.kernel_config), torch_time = self.torch_time, triton_time = self.triton_time, speedup = self.speedup, ) @staticmethod def to_dataframe( results: list["KernelResult"], sort_by: str = "speedup", ascending: bool = False ): df = pd.DataFrame([result.to_dict() for result in results]) df = df.sort_values(by = sort_by, ascending = ascending) return df @staticmethod def to_csv( results: list["KernelResult"], sort_by: str = "speedup", ascending: bool = False, filename: str = "results.csv", ): df = KernelResult.to_dataframe(results, sort_by, ascending) df.to_csv(filename, index = False) @staticmethod def print_table( results: list["KernelResult"], sort_by: str = "speedup", ascending: bool = False, num_results: int = 10, ): df = KernelResult.to_dataframe(results, sort_by, ascending) print(df.head(num_results).to_string(index = False)) def get_kernel_configs( BLOCK_M = DEFAULT_M_BLOCK_SIZES, BLOCK_N = DEFAULT_N_BLOCK_SIZES, BLOCK_K = DEFAULT_K_BLOCK_SIZES, num_warps = DEFAULT_NUM_WARPS, num_stages = DEFAULT_NUM_STAGES, use_tma_loads = BOOLS, fuse_permute = BOOLS, ): kernel_configs_fwd = [] kernel_configs_backward_dW = [] kernel_configs_backward_dX = [] for block_m, block_n, block_k, w, s, use_tma_load, permute in product( BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages, use_tma_loads, fuse_permute ): kernel_configs_fwd.append( KernelConfigForward( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = w, num_stages = s, use_tma_load_x = use_tma_load, use_tma_load_w = use_tma_load, use_tma_store = False, permute_x = permute, permute_y = permute, ) ) kernel_configs_backward_dW.append( KernelConfigBackward_dW( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = w, num_stages = s, use_tma_load_dy = use_tma_load, use_tma_load_x = use_tma_load, use_tma_store = False, permute_x = permute, permute_y = permute, ) ) kernel_configs_backward_dX.append( KernelConfigBackward_dX( BLOCK_SIZE_M = block_m, BLOCK_SIZE_N = block_n, BLOCK_SIZE_K = block_k, num_warps = w, num_stages = s, use_tma_load_dy = use_tma_load, use_tma_load_w = use_tma_load, use_tma_store = False, permute_x = permute, permute_y = permute, ) ) kernel_configs_fwd = prune_kernel_configs_fwd(kernel_configs_fwd) kernel_configs_backward_dW = prune_kernel_configs_backward_dW( kernel_configs_backward_dW ) kernel_configs_backward_dX = prune_kernel_configs_backward_dX( kernel_configs_backward_dX ) return kernel_configs_fwd, kernel_configs_backward_dW, kernel_configs_backward_dX def prune_kernel_configs_fwd(configs: list[KernelConfigForward]): pruned_configs = [] for config in configs: if config.use_tma_load_x and config.permute_x: continue if config.permute_x and config.permute_y: continue if config.use_tma_store and config.permute_y: continue pruned_configs.append(config) return pruned_configs def prune_kernel_configs_backward_dX(configs: list[KernelConfigBackward_dX]): pruned_configs = [] for config in configs: if config.use_tma_load_dy and config.permute_y: continue if config.permute_x and config.permute_y: continue if config.use_tma_store and config.permute_x: continue pruned_configs.append(config) return pruned_configs def prune_kernel_configs_backward_dW(configs: list[KernelConfigBackward_dW]): pruned_configs = [] for config in configs: if config.use_tma_load_dy and config.permute_y: continue if config.use_tma_load_x and config.permute_x: continue if config.permute_x and config.permute_y: continue pruned_configs.append(config) return pruned_configs class TritonTuningContext: def __init__(self, kernel_config: KernelConfig): self.kernel_config = kernel_config self.success = True def __enter__(self): # Setup code can be added here if needed return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is OutOfResources: name = exc_value.name required = exc_value.required limit = exc_value.limit print( f"Kernel config {self.kernel_config} failed: {name}, required: {required}, limit: {limit}" ) self.success = False elif exc_type is not None: print( f"Error running Triton grouped GEMM for kernel config: {self.kernel_config}: {exc_value}" ) self.success = False # Return False to propagate exceptions, True to suppress them return True
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/kernels/tuning.py", "license": "Apache License 2.0", "lines": 239, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/reference/moe_block.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch from transformers.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from ..interface import grouped_gemm from ..kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from .moe_ops import ( Qwen3MoeGroupedGEMMBlock, permute, unpermute, ) """ Reference implementation of MoE block using grouped gemm. This is the same as the Qwen3MoeGroupedGEMMBlock but with triton grouped gemm in place of torch-native grouped gemm implementation. NOTE: This is NOT to be used for production as it contains many extra checks and saves all intermediate results for debugging. """ class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock): def __init__( self, config: Qwen3MoeConfig, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): super().__init__(config, gate, gate_up_proj, down_proj) self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX self.dW_only = dW_only self.dX_only = dX_only @classmethod def from_hf( cls, moe_block: Qwen3MoeSparseMoeBlock, permute_x: bool = True, permute_y: bool = True, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, dW_only: bool = False, dX_only: bool = False, ): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = Qwen3MoeGroupedGEMMBlock.extract_hf_weights( moe_block ) return cls( config, gate, gate_up_proj, down_proj, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, dW_only = dW_only, dX_only = dX_only, ) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # Pre-processing # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. permute_x -> permutation will be fused in prologue of first grouped gemm if not self.permute_x: hidden_states = permute(hidden_states, gather_indices, self.top_k) # Start expert computation hidden_states = grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, dW_only = self.dW_only, dX_only = self.dX_only, ) hidden_states = self.act_and_mul(hidden_states) hidden_states = grouped_gemm( X = hidden_states, W = self.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, dW_only = self.dW_only, dX_only = self.dX_only, ) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states = unpermute(hidden_states, gather_indices) # 2. Merge topk weights hidden_states = ( hidden_states.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return hidden_states, router_logits
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/reference/moe_block.py", "license": "Apache License 2.0", "lines": 146, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/reference/moe_ops.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import torch import torch.nn.functional as F def permute(X: torch.Tensor, gather_indices: torch.Tensor, topk: int): """ Scatters X to a new tensor with shape [total_tokens, hidden_dim] where total_tokens is num_tokens * topk, permuting the tokens according to sorted_token_idx. Helper for grouped gemm where hidden states need be ordered by expert. X: [num_tokens, hidden_dim] sorted_token_idx: [num_tokens * topk] topk: int Returns: [total_tokens, hidden_dim] """ assert gather_indices.ndim == 1 X = X.view(-1, X.shape[-1]) # Shortcut for topk == 1 if topk == 1: return X[gather_indices] return X[gather_indices // topk] def unpermute(X: torch.Tensor, gather_indices: torch.Tensor): X = X.view(-1, X.shape[-1]) if X.ndim > 2 else X unpermuted = torch.empty_like(X) unpermuted.index_copy_(0, gather_indices, X) return unpermuted.view_as(X) def calculate_topk( gating_output: torch.Tensor, top_k: int, use_sigmoid: bool, renormalize: bool, pre_act: bool = True, post_act: bool = False, ): """ If post_act is True, then activation function is run AFTER topk If post_act is False, then activation function is run BEFORE topk This is to align with triton_bench implementation (post_act) whereas most models use pre_act (e.g. llama4, deepseek) """ assert pre_act ^ post_act, "only one of pre_act or post_act can be True" def _activation(gating_output: torch.Tensor): if use_sigmoid: scores = torch.sigmoid(gating_output.to(torch.float32)).to( gating_output.dtype ) else: scores = F.softmax(gating_output.to(torch.float32), dim = 1).to( gating_output.dtype ) return scores if pre_act: scores = _activation(gating_output) else: scores = gating_output topk_weights, topk_ids = torch.topk(scores, k = top_k, dim = 1) if post_act: topk_weights = _activation(topk_weights) if renormalize: topk_weights /= torch.sum(topk_weights, dim = -1, keepdim = True).to( gating_output.dtype ) return topk_weights, topk_ids @torch.no_grad() def get_routing_indices( selected_experts, num_experts, return_scatter_indices: bool = False ): """ Returns: token_counts_by_expert: [num_experts] gather_indices: [num_tokens] scatter_indices [Optional] (torch.Tensor): Indices for unpermuting gathered inputs back to token order, shape ``(bs * seqlen * top_k,)``. """ # group tokens together by expert indices from 0 to num_experts and pass that to experts forward token_counts_by_expert = torch.histc( selected_experts.view(-1), bins = num_experts, min = 0, max = num_experts, ) # token_indices_experts_sorted shape (bs*slen*top_k,) gather_indices = torch.argsort(selected_experts.view(-1), stable = True) if return_scatter_indices: scatter_indices = gather_indices.argsort() return token_counts_by_expert, gather_indices, scatter_indices else: return token_counts_by_expert, gather_indices def torch_grouped_gemm(X, W, m_sizes, transpose = True): """ X: [M, K] if forward, else [M, N] W: [E, N, K] m_sizes: [E] Returns: Y: [M, N] if forward, else [M, K] """ X = X.view(-1, X.shape[-1]) M, K = X.shape assert m_sizes.ndim == 1 E = m_sizes.shape[0] assert W.ndim == 3 assert W.shape[0] == E N = W.shape[1] result = torch.zeros((M, N), dtype = X.dtype, device = X.device) m_start = 0 for g in range(E): m_size = m_sizes[g] if m_size > 0: m_end = m_start + m_size # Extract group input # m_size x K X_g = X[m_start:m_end] # N x K W_g = W[g] # Y_g = X_g @ W_g.T -> [m_size, N] W_g = W_g.T if transpose else W_g Y_g = X_g @ W_g result[m_start:m_end] = Y_g m_start = m_end return result
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/grouped_gemm/reference/moe_ops.py", "license": "Apache License 2.0", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/kernels/moe/tests/common.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import itertools from contextlib import contextmanager from dataclasses import dataclass, field import torch from grouped_gemm.kernels.tuning import ( KernelConfig, KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, prune_kernel_configs_backward_dW, prune_kernel_configs_backward_dX, prune_kernel_configs_fwd, ) def print_delimiter(char = "-", length = 80): print(char * length) @contextmanager def delimiter_context(): print_delimiter() yield print_delimiter() def make_inputs(M, N, K, E, topk, dtype, requires_grad = False): X1 = ( torch.randn((M, K), device = "cuda", dtype = dtype, requires_grad = requires_grad) / 10 ) X2 = ( torch.randn( (M * topk, N), device = "cuda", dtype = dtype, requires_grad = requires_grad ) / 10 ) W1 = ( torch.randn( (E, 2 * N, K), device = "cuda", dtype = dtype, requires_grad = requires_grad ) / 10 ) W2 = ( torch.randn((E, K, N), device = "cuda", dtype = dtype, requires_grad = requires_grad) / 10 ) score = torch.randn((M, E), device = "cuda", dtype = dtype, requires_grad = requires_grad) if requires_grad: X1.retain_grad() X2.retain_grad() W1.retain_grad() W2.retain_grad() score.retain_grad() return X1, X2, W1, W2, score @dataclass(kw_only = True) class DataConfig: seq_len: int dtype: torch.dtype device: str = "cuda" bs: int = 1 @dataclass(kw_only = True) class ModelConfig: hidden_size: int intermediate_size: int num_experts: int topk: int use_sigmoid: bool renormalize: bool pre_mul: bool = False post_mul: bool = field(init = False) def __post_init__(self): self.post_mul = not self.pre_mul @dataclass(kw_only = True) class GroupedGEMMTestConfig: name: str = "test" data_config: DataConfig model_config: ModelConfig TOLERANCE = { torch.bfloat16: (1e-3, 1e-3), torch.float16: (1e-4, 1e-4), torch.float32: (1e-5, 1e-5), } # from https://github.com/triton-lang/triton/blob/main/bench/triton_bench/testing.py def assert_equal(ref, tri): if isinstance(ref, torch.Tensor): assert torch.all(ref == tri), f"tensors not equal {ref} != {tri}" else: assert ref == tri, f"ref not equal to tri {ref} != {tri}" def assert_close(ref, tri, maxtol = None, rmstol = None, description = "--", verbose = True): if tri.dtype.itemsize == 1: ref_as_type = ref.to(tri.dtype) if ref.dtype == tri.dtype: assert torch.all(ref_as_type == tri) return ref = ref_as_type if maxtol is None: maxtol = 2e-2 if rmstol is None: rmstol = 4e-3 """ Compare reference values against obtained values. """ # cast to float32: ref = ref.to(torch.float32).detach() tri = tri.to(torch.float32).detach() assert ( ref.shape == tri.shape ), f"Tensors must have same size {ref.shape = } {tri.shape = }" # deal with infinite elements: inf_mask_ref = torch.isinf(ref) inf_mask_tri = torch.isinf(tri) assert torch.equal( inf_mask_ref, inf_mask_tri ), "Tensor must have same infinite elements" refn = torch.where(inf_mask_ref, 0, ref) trin = torch.where(inf_mask_tri, 0, tri) # normalise so that RMS calculation doesn't overflow: eps = 1.0e-30 multiplier = 1.0 / (torch.max(torch.abs(refn)) + eps) refn *= multiplier trin *= multiplier ref_rms = torch.sqrt(torch.square(refn).mean()) + eps rel_err = torch.abs(refn - trin) / torch.maximum(ref_rms, torch.abs(refn)) max_err = torch.max(rel_err).item() rms_err = torch.sqrt(torch.square(rel_err).mean()).item() if verbose: print( "%s maximum relative error = %s (threshold = %s)" % (description, max_err, maxtol) ) print( "%s RMS relative error = %s (threshold = %s)" % (description, rms_err, rmstol) ) if max_err > maxtol: bad_idxs = torch.nonzero(rel_err > maxtol) num_nonzero = bad_idxs.size(0) bad_idxs = bad_idxs[:1000] print( "%d / %d mismatched elements (shape = %s) at coords %s" % (num_nonzero, rel_err.numel(), tuple(rel_err.shape), bad_idxs.tolist()) ) bad_idxs = bad_idxs.unbind(-1) print("ref values: ", ref[*bad_idxs].cpu()) print("tri values: ", tri[*bad_idxs].cpu()) assert max_err <= maxtol assert rms_err <= rmstol def assert_indx_equal(ref, tri): assert_equal(ref, tri[: len(ref)]) assert torch.all(tri[len(ref) :] == -1) def get_kernel_test_configs( BLOCK_SIZE_M = 32, BLOCK_SIZE_N = 32, BLOCK_SIZE_K = 32, num_warps = 4, num_stages = 2, ) -> list[KernelConfig]: configs_fwd = [] configs_bwd_dX = [] configs_bwd_dW = [] for permute_x in [False, True]: for permute_y in [False, True]: for use_tma_load_w in [True, False]: for use_tma_load_x in [True, False]: for use_tma_store in [True, False]: configs_fwd.append( KernelConfigForward( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, use_tma_load_w = use_tma_load_w, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, permute_x = permute_x, permute_y = permute_y, ) ) configs_bwd_dX.append( KernelConfigBackward_dX( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = use_tma_load_x, use_tma_load_w = use_tma_load_w, permute_x = permute_x, permute_y = permute_y, use_tma_store = use_tma_store, ) ) configs_bwd_dW.append( KernelConfigBackward_dW( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, use_tma_load_dy = use_tma_load_w, use_tma_load_x = use_tma_load_x, permute_x = permute_x, permute_y = permute_y, use_tma_store = use_tma_store, ) ) configs_fwd = prune_kernel_configs_fwd(configs_fwd) configs_bwd_dX = prune_kernel_configs_backward_dX(configs_bwd_dX) configs_bwd_dW = prune_kernel_configs_backward_dW(configs_bwd_dW) return configs_fwd, configs_bwd_dX, configs_bwd_dW def remove_feature_flags( kernel_configs: list[KernelConfig], permute_x: bool = True, permute_y: bool = True, tma_loads: bool = True, tma_store: bool = True, ): pruned_configs = [] for config in kernel_configs: # Remove permute flags first: if permute_x and config.permute_x: continue if permute_y and config.permute_y: continue if tma_loads: if isinstance(config, KernelConfigForward): if config.use_tma_load_w or config.use_tma_load_x: continue if isinstance(config, KernelConfigBackward_dX): if config.use_tma_load_dy or config.use_tma_load_w: continue if isinstance(config, KernelConfigBackward_dW): if config.use_tma_load_dy or config.use_tma_load_x: continue if tma_store: if config.use_tma_store: continue pruned_configs.append(config) return pruned_configs # Test Configs TOPK = [1, 4] NUM_EXPERTS = [4, 16] TEST_MODEL_SIZES = [ (32, 32), # Debug (128, 128), # Small (512, 512), # Medium ] SMALL_MODEL_CONFIGS = [ ModelConfig( topk = topk, num_experts = num_experts, hidden_size = model_size[0], intermediate_size = model_size[1], use_sigmoid = False, renormalize = False, ) for topk, num_experts, model_size in itertools.product( TOPK, NUM_EXPERTS, TEST_MODEL_SIZES ) ] LLAMA_MODEL_CONFIG = ModelConfig( topk = 1, num_experts = 16, hidden_size = 5120, intermediate_size = 8192, use_sigmoid = True, renormalize = False, ) QWEN_MODEL_CONFIG = ModelConfig( topk = 8, num_experts = 128, hidden_size = 2048, intermediate_size = 768, use_sigmoid = False, renormalize = False, ) SEQLENS = [128, 1024] DTYPE = [torch.bfloat16] DATA_CONFIGS = [ DataConfig(seq_len = seq_len, dtype = dtype) for seq_len, dtype in itertools.product(SEQLENS, DTYPE) ] KERNEL_CONFIGS_FWD, KERNEL_CONFIGS_BWD_dX, KERNEL_CONFIGS_BWD_dW = ( get_kernel_test_configs() ) if __name__ == "__main__": print( KERNEL_CONFIGS_BWD_dX[0].to_string( include_tuning_params = False, include_tma = False ) )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/tests/common.py", "license": "Apache License 2.0", "lines": 289, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/kernels/moe/tests/moe_utils.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import dataclass, fields import torch import torch.nn as nn from huggingface_hub import HfApi from huggingface_hub.utils import _safetensors from transformers.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from grouped_gemm.interface import grouped_gemm from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.layers.qwen3_moe import ( GroupedGEMMResult, Qwen3MoeGroupedGEMMBlock, ) from grouped_gemm.reference.moe_ops import permute, unpermute def rebind_experts_to_shared_buffer( moe_block: Qwen3MoeSparseMoeBlock, config: Qwen3MoeConfig ): num_experts = config.num_experts hidden_size = config.hidden_size interm_size = config.moe_intermediate_size device = moe_block.experts[0].down_proj.weight.device dtype = moe_block.experts[0].down_proj.weight.dtype buffer_up = torch.empty( num_experts, interm_size, hidden_size, device = device, dtype = dtype ) buffer_gate = torch.empty( num_experts, interm_size, hidden_size, device = device, dtype = dtype ) buffer_down = torch.empty( num_experts, hidden_size, interm_size, device = device, dtype = dtype ) # Step 2: Copy existing expert weights into buffers for i, expert in enumerate(moe_block.experts): buffer_up[i].copy_(expert.up_proj.weight.data) buffer_gate[i].copy_(expert.gate_proj.weight.data) buffer_down[i].copy_(expert.down_proj.weight.data) # Step 3: Rebind expert weights to views in shared buffer for i, expert in enumerate(moe_block.experts): expert.up_proj.weight = torch.nn.Parameter(buffer_up[i]) expert.gate_proj.weight = torch.nn.Parameter(buffer_gate[i]) expert.down_proj.weight = torch.nn.Parameter(buffer_down[i]) return buffer_up, buffer_gate, buffer_down def get_expert_metadata(model_id: str): api = HfApi() metadata: _safetensors.SafetensorsRepoMetadata = api.get_safetensors_metadata( model_id ) return metadata.files_metadata def clone_experts( moe_block: Qwen3MoeSparseMoeBlock, config: Qwen3MoeConfig, copy: bool = True ): down_projs = torch.empty( config.num_experts, config.hidden_size, config.moe_intermediate_size ) up_projs = torch.empty( config.num_experts, config.moe_intermediate_size, config.hidden_size ) gate_projs = torch.empty( config.num_experts, config.moe_intermediate_size, config.hidden_size ) for expert_idx, expert in enumerate(moe_block.experts): down_projs[expert_idx].copy_(expert.down_proj.weight.data) up_projs[expert_idx].copy_(expert.up_proj.weight.data) gate_projs[expert_idx].copy_(expert.gate_proj.weight.data) return gate_projs, up_projs, down_projs @dataclass class ForwardResult: output: torch.Tensor router_logits: torch.Tensor X: torch.Tensor # When using grouped gemm MoE implementation to additional debugging / checking of intermediate results grouped_gemm_result: GroupedGEMMResult = None @dataclass class BackwardResult: X_grad: torch.Tensor gate_grad: torch.Tensor gate_proj_grad: torch.Tensor up_proj_grad: torch.Tensor down_proj_grad: torch.Tensor def check_down_proj_grad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): for i, expert in enumerate(moe_block.experts): ref_grad = expert.down_proj.weight.grad assert ref_grad is not None test_grad = grouped_gemm_block.down_proj.grad[i] assert test_grad is not None diff = (ref_grad - test_grad).abs().max() if not torch.allclose(ref_grad, test_grad, atol = atol, rtol = rtol): print(f"expert {i} down_proj_grad_diff: {diff.detach().cpu().item():.6f}") def check_gate_up_proj_grad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): moe_intermediate_size = grouped_gemm_block.moe_intermediate_size for i, expert in enumerate(moe_block.experts): ref_gate_proj_grad = expert.gate_proj.weight.grad ref_up_proj_grad = expert.up_proj.weight.grad assert ref_gate_proj_grad is not None assert ref_up_proj_grad is not None # Extract gradients test_gate_proj_grad = grouped_gemm_block.gate_up_proj.grad[ i, :moe_intermediate_size ] test_up_proj_grad = grouped_gemm_block.gate_up_proj.grad[ i, moe_intermediate_size: ] assert test_gate_proj_grad is not None assert test_up_proj_grad is not None # Sanity check shapes assert ( ref_gate_proj_grad.shape == test_gate_proj_grad.shape ), f"{ref_gate_proj_grad.shape} != {test_gate_proj_grad.shape}" assert ( ref_up_proj_grad.shape == test_up_proj_grad.shape ), f"{ref_up_proj_grad.shape} != {test_up_proj_grad.shape}" # Check gradients diff = (ref_gate_proj_grad - test_gate_proj_grad).abs().max() if not torch.allclose( ref_gate_proj_grad, test_gate_proj_grad, atol = atol, rtol = rtol ): print(f"expert {i} gate_proj_grad_diff: {diff.detach().cpu().item():.6f}") diff = (ref_up_proj_grad - test_up_proj_grad).abs().max() if not torch.allclose( ref_up_proj_grad, test_up_proj_grad, atol = atol, rtol = rtol ): print(f"expert {i} up_proj_grad_diff: {diff.detach().cpu().item():.6f}") def check_gate_grad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): ref_grad = moe_block.gate.weight.grad assert ref_grad is not None test_grad = grouped_gemm_block.gate.grad assert test_grad is not None diff = (ref_grad - test_grad).abs().max() if not torch.allclose(ref_grad, test_grad, atol = atol, rtol = rtol): print(f"gate_grad_diff: {diff.detach().cpu().item():.6f}") def check_wgrad( moe_block: Qwen3MoeSparseMoeBlock, grouped_gemm_block: Qwen3MoeGroupedGEMMBlock, atol: float, rtol: float, ): check_down_proj_grad(moe_block, grouped_gemm_block, atol, rtol) check_gate_up_proj_grad(moe_block, grouped_gemm_block, atol, rtol) check_gate_grad(moe_block, grouped_gemm_block, atol, rtol) def check_tensor_allclose( X_ref: torch.Tensor, X_test: torch.Tensor, atol: float, rtol: float, name: str, verbose: bool = False, ): diff = (X_ref - X_test).abs().max() if verbose: print(f"{name} diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( X_ref, X_test, atol = atol, rtol = rtol ), f"{name} diff: {diff.detach().cpu().item():.6f}" def check_expert_grads( ref_result: BackwardResult, test_result: BackwardResult, atol: float, rtol: float, verbose: bool = False, ): fields_to_check = [f.name for f in fields(BackwardResult) if "proj" in f.name] assert len(fields_to_check) == 3 for field in fields_to_check: ref_grads = getattr(ref_result, field) test_grads = getattr(test_result, field) assert ( ref_grads.shape == test_grads.shape ), f"{field}: {ref_grads.shape} != {test_grads.shape}" # Test each expert for i in range(ref_grads.shape[0]): ref_grad = ref_grads[i] test_grad = test_grads[i] diff = (ref_grad - test_grad).abs().max() assert torch.allclose( ref_grad, test_grad, atol = atol, rtol = rtol ), f"{field}[{i}] diff: {diff.detach().cpu().item():.6f}" # Test all experts diff = (ref_grads - test_grads).abs().max() if verbose: print(f"{field} diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_grads, test_grads, atol = atol, rtol = rtol ), f"{field} diff: {diff.detach().cpu().item():.6f}" def check_grads( ref_result: BackwardResult, test_result: BackwardResult, atol: float, rtol: float, verbose: bool = False, ): check_tensor_allclose( ref_result.X_grad, test_result.X_grad, atol, rtol, "X.grad", verbose ) check_tensor_allclose( ref_result.gate_grad, test_result.gate_grad, atol, rtol, "gate.grad", verbose ) check_expert_grads(ref_result, test_result, atol, rtol, verbose) def check_fwd( ref_result: ForwardResult, test_result: ForwardResult, atol: float, rtol: float, verbose: bool = False, ): # First check hidden states (output) ref_output = ref_result.output test_output = test_result.output diff = (ref_output - test_output).abs().max() if verbose: print(f"output diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_output, test_output, atol = atol, rtol = rtol ), f"output diff: {diff.detach().cpu().item():.6f}" # Check router logits ref_router_logits = ref_result.router_logits test_router_logits = test_result.router_logits diff = (ref_router_logits - test_router_logits).abs().max() if verbose: print(f"router_logits diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_router_logits, test_router_logits, atol = atol, rtol = rtol ), f"router_logits diff: {diff.detach().cpu().item():.6f}" def check_grouped_gemm_results( grouped_result: GroupedGEMMResult, fused_result: GroupedGEMMResult, permute_y: bool, atol: float, rtol: float, verbose: bool = False, ): for field in fields(GroupedGEMMResult): ref_value = getattr(grouped_result, field.name) test_value = getattr(fused_result, field.name) diff = (ref_value - test_value).abs().max() # second_gemm in torch grouped gemm is not yet unpermuted so comparing the fused unpermuted second_gemm will result in error # instead the hidden_states_unpermute should match since hidden_states_unpermute for the fused result is the same as second_gemm if field.name == "second_gemm" and permute_y: continue if verbose: print(f"{field.name} diff: {diff.detach().cpu().item():.6f}") assert torch.allclose( ref_value, test_value, atol = atol, rtol = rtol ), f"{field.name} diff: {diff.detach().cpu().item():.6f}" def run_forward(model: nn.Module, X: torch.Tensor, is_grouped_gemm: bool = False): X = X.detach().clone().requires_grad_(True) output, router_logits = model(X) if is_grouped_gemm: result = ForwardResult( output = output.hidden_states, router_logits = router_logits, X = X, grouped_gemm_result = output, ) else: result = ForwardResult(output = output, router_logits = router_logits, X = X) return result def run_backward( model: nn.Module, grad_output: torch.Tensor, output: torch.Tensor, X: torch.Tensor ): output.backward(grad_output) assert X.grad is not None for name, param in model.named_parameters(): assert param.grad is not None, f"{name} grad is None" if isinstance(model, Qwen3MoeSparseMoeBlock): gate_grad = model.gate.weight.grad gate_proj_grad = torch.stack( [expert.gate_proj.weight.grad for expert in model.experts] ) up_proj_grad = torch.stack( [expert.up_proj.weight.grad for expert in model.experts] ) down_proj_grad = torch.stack( [expert.down_proj.weight.grad for expert in model.experts] ) elif isinstance(model, Qwen3MoeGroupedGEMMBlock): gate_grad = model.gate.grad gate_proj_grad, up_proj_grad = model.gate_up_proj.grad.chunk(2, dim = 1) down_proj_grad = model.down_proj.grad else: raise ValueError(f"Unsupported model type: {type(model)}") return BackwardResult( X_grad = X.grad, gate_grad = gate_grad, gate_proj_grad = gate_proj_grad, up_proj_grad = up_proj_grad, down_proj_grad = down_proj_grad, ) class Qwen3MoeFusedGroupedGEMMBlock(Qwen3MoeGroupedGEMMBlock): """ Reference implementation of MoE block using grouped gemm. This is the same as the Qwen3MoeGroupedGEMMBlock but with triton grouped gemm in place of torch-native grouped gemm implementation. NOTE: This is NOT to be used for production as it contains many extra checks and saves all intermediate results for debugging. See grouped_gemm/reference/moe_block.py for a cleaner implementation. """ def __init__( self, config: Qwen3MoeConfig, gate: torch.Tensor, gate_up_proj: torch.Tensor, down_proj: torch.Tensor, permute_x: bool = False, permute_y: bool = False, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, ): super().__init__(config, gate, gate_up_proj, down_proj) self.permute_x = permute_x self.permute_y = permute_y self.autotune = autotune if not autotune: assert ( kernel_config_fwd is not None and kernel_config_bwd_dW is not None and kernel_config_bwd_dX is not None ), "Kernel configs must be provided if autotune is False" self.kernel_config_fwd = kernel_config_fwd self.kernel_config_bwd_dW = kernel_config_bwd_dW self.kernel_config_bwd_dX = kernel_config_bwd_dX @classmethod def from_hf( cls, moe_block: Qwen3MoeSparseMoeBlock, permute_x: bool = False, permute_y: bool = False, autotune: bool = True, kernel_config_fwd: KernelConfigForward = None, kernel_config_bwd_dW: KernelConfigBackward_dW = None, kernel_config_bwd_dX: KernelConfigBackward_dX = None, ): config: Qwen3MoeConfig = moe_block.experts[0].config gate, gate_up_proj, down_proj = Qwen3MoeGroupedGEMMBlock.extract_hf_weights( moe_block ) return cls( config, gate, gate_up_proj, down_proj, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ) def forward(self, hidden_states: torch.Tensor, debug: bool = False) -> torch.Tensor: batch_size, sequence_length, hidden_dim = hidden_states.shape num_tokens = batch_size * sequence_length total_tokens = num_tokens * self.top_k hidden_states = hidden_states.view(-1, hidden_dim) router_logits, routing_weights, selected_experts = self.run_router( hidden_states ) # Pre-processing # 1. Compute tokens per expert and indices for gathering tokes from token order to expert order # NOTE: these are auxiliary data structs which don't need to be recorded in autograd graph token_counts_by_expert, gather_indices = ( self.get_token_counts_and_gather_indices(selected_experts) ) # 2. permute_x -> permutation will be fused in prologue of first grouped gemm if not self.permute_x: hidden_states = permute(hidden_states, gather_indices, self.top_k) assert hidden_states.shape == (total_tokens, hidden_dim) # Start expert computation first_gemm = grouped_gemm( X = hidden_states, W = self.gate_up_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = self.permute_x, permute_y = False, # output of first grouped gemm should never be permuted autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = True, ) assert first_gemm.shape == (total_tokens, 2 * self.moe_intermediate_size) intermediate = self.act_and_mul(first_gemm) assert intermediate.shape == (total_tokens, self.moe_intermediate_size) second_gemm = grouped_gemm( X = intermediate, W = self.down_proj, m_sizes = token_counts_by_expert, gather_indices = gather_indices, topk = self.top_k, permute_x = False, permute_y = self.permute_y, autotune = self.autotune, kernel_config_fwd = self.kernel_config_fwd, kernel_config_bwd_dW = self.kernel_config_bwd_dW, kernel_config_bwd_dX = self.kernel_config_bwd_dX, is_first_gemm = False, ) assert second_gemm.shape == (total_tokens, hidden_dim) # Post-processing # 1. Unpermute from expert order to token order if not self.permute_y: hidden_states_unpermute = unpermute(second_gemm, gather_indices) assert hidden_states_unpermute.shape == (total_tokens, hidden_dim) else: hidden_states_unpermute = second_gemm # 2. Merge topk weights hidden_states = ( hidden_states_unpermute.view(num_tokens, self.top_k, hidden_dim) * routing_weights[..., None] ) hidden_states = hidden_states.sum(dim = 1) assert hidden_states.shape == (num_tokens, hidden_dim) hidden_states = hidden_states.view(batch_size, sequence_length, hidden_dim) return GroupedGEMMResult( token_counts_by_expert = token_counts_by_expert, gather_indices = gather_indices, topk_weights = routing_weights, first_gemm = first_gemm, intermediate = intermediate, second_gemm = second_gemm, hidden_states_unpermute = hidden_states_unpermute, hidden_states = hidden_states, ), router_logits
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/tests/moe_utils.py", "license": "Apache License 2.0", "lines": 444, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/kernels/moe/tests/test_grouped_gemm.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. from dataclasses import asdict import pytest import torch from grouped_gemm.interface import ( grouped_gemm, grouped_gemm_dW, grouped_gemm_dX, grouped_gemm_forward, ) from grouped_gemm.kernels.tuning import ( KernelConfig, KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.moe_ops import ( calculate_topk, get_routing_indices, permute, torch_grouped_gemm, unpermute, ) from .common import ( DATA_CONFIGS, KERNEL_CONFIGS_FWD, LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG, SMALL_MODEL_CONFIGS, TOLERANCE, DataConfig, KERNEL_CONFIGS_BWD_dW, KERNEL_CONFIGS_BWD_dX, ModelConfig, make_inputs, ) SEED = 0 # Only certain combinations of permute_x, permute_y, use_W1 are valid. # use_W1 => first grouped GEMM in a fused MoE MLP # use_W2 => second grouped GEMM in a fused MoE MLP # permute_x => permute the input to the grouped GEMM, only done for the first grouped GEMM # permute_y => permute the output of the grouped GEMM, only done for the second grouped GEMM # fuse_mul_post => fuse the multiplication of topk weights in the epilogue of the second grouped GEMM; only used for inference, not currently tested def check_valid_config( permute_x, permute_y, use_W1, fuse_mul_post = False, is_backward = False, verbose = False ): use_W2 = not use_W1 if permute_x and permute_y: if verbose: print(f"Skipping test: {permute_x = } {permute_y = }") return False if use_W2 and permute_x: if verbose: print(f"Skipping test: {permute_x = } {use_W2 = }") return False if use_W1 and permute_y: if verbose: print(f"Skipping test: {permute_y = } {use_W1 = }") return False if fuse_mul_post and use_W1: if verbose: print(f"Skipping test: {fuse_mul_post = } {use_W1 = }") return False if is_backward and fuse_mul_post: if verbose: print(f"Skipping test: {fuse_mul_post = } {is_backward = }") return False return True """ grouped_gemm_forward permute_x: typically in a fused MoE MLP, we can fuse the permutation of hidden states (X) from token order to expert grouped order needed for grouped GEMM by directly loading X in permuted order rather than launching a separate permutation kernel. permute_y: We can also fuse the unpermutation of tokens after the second grouped GEMM to restore to original token order. This is fused into the second grouped GEMM by directly storing the output in unpermuted order. fuse_mul: We can also fuse the multiplication of topk weights in the epilogue of the second grouped GEMM. Note that this is only supported for inference and not training, although this may change in the future. use_W1 test the shapes for the first grouped GEMM in a fused MoE MLP use_W2 = `not use_W1` tests the shapes for the second grouped GEMM in a fused MoE MLP Given the above, only certain combinations are valid: - use_W1 is always False when permute_y is True since we only permute the second grouped GEMM - use_W2 is always False when permute_x is True since we only permute the first grouped GEMM - only one of permute_x and permute_y can be True - fuse_mul is only True if permute_y is also True See `check_valid_config` for more details. """ def _test_grouped_gemm_forward( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, # W1 -> first grouped GEMM in a fused MoE MLP, not W1 -> second grouped GEMM in a fused MoE MLP fuse_mul_post: bool = False, flatten: bool = True, # Manually tuned parameters use_tma_load_w: bool = False, use_tma_load_x: bool = False, use_tma_store: bool = False, BLOCK_SIZE_M: int = None, BLOCK_SIZE_N: int = None, BLOCK_SIZE_K: int = None, num_warps: int = None, num_stages: int = None, # Autotuning parameters autotune: bool = False, num_autotune_configs: int = None, # Flag to manually enable TMA store allow_tma_store: bool = False, use_autograd: bool = False, ): if not check_valid_config( permute_x, permute_y, use_W1 = use_W1, fuse_mul_post = fuse_mul_post ): pytest.skip( f"Skipping test due to invalid config: {permute_x = } {permute_y = } {use_W1 = } {fuse_mul_post = }" ) if use_tma_store and not allow_tma_store: pytest.skip("TMA store needs to be debugged due to non-deterministic behavior") X1, X2, W1, W2, gating_output = make_inputs( M = data_config.bs * data_config.seq_len, N = model_config.intermediate_size, K = model_config.hidden_size, E = model_config.num_experts, topk = model_config.topk, dtype = data_config.dtype, ) topk = model_config.topk use_sigmoid = model_config.use_sigmoid renormalize = model_config.renormalize X = X1 if use_W1 else X2 num_tokens = data_config.bs * data_config.seq_len E, K, N = W2.shape # E = num_experts, K = hidden_size, N = intermediate_size assert W1.shape == (E, 2 * N, K) W = W1 if use_W1 else W2 if use_W1: assert X.shape == ( num_tokens, K, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, K: {K}" else: assert X.shape == ( num_tokens * topk, N, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, topk: {topk}, N: {N}" total_tokens = num_tokens * topk output_shape = (total_tokens, 2 * N) if use_W1 else (total_tokens, K) topk_weights, topk_ids = calculate_topk( gating_output, topk, use_sigmoid = use_sigmoid, renormalize = renormalize ) topk_weights = topk_weights.view(-1) # num_tokens * topk topk_ids = topk_ids.view(-1) # num_tokens * topk expert_token_counts, gather_indices = get_routing_indices(topk_ids, num_experts = E) assert len(gather_indices) == total_tokens assert len(expert_token_counts) == E atol, rtol = TOLERANCE[X.dtype] Xperm = permute(X, gather_indices, topk) Xref = Xperm assert ( Xperm.shape == (total_tokens, K) if use_W1 else (total_tokens, N) ), f"Xperm.shape: {Xperm.shape}, total_tokens: {total_tokens}, K: {K}" ref_output = torch_grouped_gemm(X = Xref, W = W, m_sizes = expert_token_counts) if permute_x: X_test = X else: X_test = Xperm # No need to run all configs for tests, otherwise takes too long if autotune: from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel if num_autotune_configs is not None: _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:num_autotune_configs] ) # Use autograd.Function interface if use_autograd: from grouped_gemm.interface import grouped_gemm kernel_config_fwd = KernelConfigForward( BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, permute_x = permute_x, permute_y = permute_y, fuse_mul_post = fuse_mul_post, use_tma_load_w = use_tma_load_w, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, ) test_output = grouped_gemm( X = X_test, W = W, topk = topk, m_sizes = expert_token_counts, gather_indices = gather_indices, topk_weights = topk_weights if fuse_mul_post else None, permute_x = permute_x, permute_y = permute_y, fuse_mul_post = fuse_mul_post, kernel_config_fwd = kernel_config_fwd, autotune = autotune, is_first_gemm = use_W1, ) # Use manual interface else: test_output = grouped_gemm_forward( X = X_test, W = W, topk = topk, m_sizes = expert_token_counts, gather_indices = gather_indices, topk_weights = topk_weights if fuse_mul_post else None, permute_x = permute_x, permute_y = permute_y, fuse_mul_post = fuse_mul_post, use_tma_load_w = use_tma_load_w, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, autotune = autotune, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, flatten = flatten, ) assert ref_output.shape == output_shape assert test_output.shape == output_shape if permute_y: ref_output = unpermute(ref_output, gather_indices) if fuse_mul_post: # if we don't permute_y, then test output is permuted with topk weights applied # the ref output needs to be unpermuted before multiplying by topk weights since topk weights are in token order if not permute_y: ref_output = unpermute(ref_output, gather_indices) test_output = unpermute(test_output, gather_indices) ref_output = ref_output * topk_weights[:, None] assert torch.allclose( ref_output, test_output, atol = atol, rtol = rtol ), f"Grouped gemm forward failed: {(ref_output - test_output).abs().max().item():.6f}" # NOTE: Fuse multiplication of topk weights is only supported for inference and not training, although this may change in the future; not currently tested. @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_FWD, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS + [QWEN_MODEL_CONFIG, LLAMA_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_manual( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigForward, use_W1: bool, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, use_W1 = use_W1, **asdict(kernel_config), ) @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_FWD, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS + [QWEN_MODEL_CONFIG, LLAMA_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_manual_autograd( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigForward, use_W1: bool, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = True, **asdict(kernel_config), ) @pytest.mark.parametrize( "num_autotune_configs", [10], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_autotune( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, num_autotune_configs = num_autotune_configs, autotune = True, use_autograd = False, ) @pytest.mark.parametrize( "num_autotune_configs", [10], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_forward_autotune_autograd( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): _test_grouped_gemm_forward( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, num_autotune_configs = num_autotune_configs, autotune = True, use_autograd = True, ) """ grouped_gemm_backward_dX use_W1 test the shapes for the first grouped GEMM in a fused MoE MLP use_W2 = `not use_W1` tests the shapes for the second grouped GEMM in a fused MoE MLP Only certain combinations of permute_x, permute_y, and fuse_mul are supported. Typically in a fused MoE MLP, we can fuse the permutation of hidden states (X) from token order to expert grouped order needed for grouped GEMM by directly loading X in permuted order rather than launching a separate permutation kernel. We can also fuse the unpermutation of tokens after the second grouped GEMM to restore to original token order. This is fused into the second grouped GEMM by directly storing the output in unpermuted order. Hence the following conditions: - If use_W1 there are two cases: - permute_x is False and topk > 1: - dX_test is still in permuted order and has shape (total_tokens, K) - it needs to be unpermuted and summed across topk before comparing to ref_grad - permute_x is True: - dX_test is already unpermuted and summed across topk with shape (num_tokens, K) - no further processing is needed - permute_x is False and topk == 1: - dX_test needs to be permuted, no need to sum since topk == 1 - If use_W2: - permute_x is always False - if permute_y: - grad_output needs to be unpermuted before passing to grouped_gemm_dX - dX_test is permuted and has shape (total_tokens, N) - it needs to be unpermuted before comparing to ref_grad or can be compared directly to Xperm.grad - if not permute_y: - dX_test is not permuted and has shape (total_tokens, N) - no further processing is needed """ def _test_grouped_gemm_backward_dX( data_config: DataConfig, model_config: ModelConfig, permute_x: bool = False, permute_y: bool = False, use_tma_load_dy: bool = False, use_tma_load_w: bool = False, use_tma_store: bool = False, use_W1: bool = True, autotune: bool = False, num_autotune_configs: int = None, BLOCK_SIZE_M: int = None, BLOCK_SIZE_N: int = None, BLOCK_SIZE_K: int = None, num_warps: int = None, num_stages: int = None, flatten: bool = True, allow_tma_store: bool = False, use_autograd: bool = False, fuse_mul_post: bool = False, ): if not check_valid_config(permute_x, permute_y, use_W1 = use_W1, is_backward = True): pytest.skip( f"Skipping test due to invalid config: {permute_x = } {permute_y = } {use_W1 = }" ) if use_tma_store and not allow_tma_store: pytest.skip("TMA store needs to be debugged due to non-deterministic behavior") if ( autotune and model_config.intermediate_size <= 128 and model_config.hidden_size <= 128 ): pytest.skip("Skipping autotuning for small model configs") # Prevent OOM for large intermediate sizes if model_config.intermediate_size > 2048: model_config.intermediate_size = 1024 if model_config.hidden_size > 2048: model_config.hidden_size = 1024 use_W2 = not use_W1 X1, X2, W1, W2, gating_output = make_inputs( M = data_config.bs * data_config.seq_len, N = model_config.intermediate_size, K = model_config.hidden_size, E = model_config.num_experts, topk = model_config.topk, dtype = data_config.dtype, requires_grad = True, ) topk = model_config.topk num_experts = model_config.num_experts use_sigmoid = model_config.use_sigmoid renormalize = model_config.renormalize X = X1 if use_W1 else X2 num_tokens = data_config.bs * data_config.seq_len total_tokens = num_tokens * topk E, K, N = W2.shape # E = num_experts, K = hidden_size, N = intermediate_size assert W1.shape == (E, 2 * N, K) W = W1 if use_W1 else W2 if use_W1: assert X.shape == ( num_tokens, K, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, K: {K}" else: assert X.shape == ( total_tokens, N, ), f"X.shape: {X.shape}, total_tokens: {total_tokens}, N: {N}" W_test = W.detach().clone().requires_grad_(True) topk_weights, topk_ids = calculate_topk( gating_output, topk, use_sigmoid = use_sigmoid, renormalize = renormalize ) topk_weights = topk_weights.view(-1) # num_tokens * topk topk_ids = topk_ids.view(-1) # num_tokens * topk expert_token_counts, gather_indices = get_routing_indices(topk_ids, num_experts = E) assert len(gather_indices) == total_tokens assert len(expert_token_counts) == num_experts atol, rtol = TOLERANCE[X.dtype] Xperm = permute(X, gather_indices, topk) # Need to retain grad otherwise grad is not propagated X.retain_grad() W.retain_grad() Xperm.retain_grad() assert Xperm.shape == (total_tokens, K) if use_W1 else (total_tokens, N) output_shape = (total_tokens, 2 * N) if use_W1 else (total_tokens, K) ref_output = torch_grouped_gemm(X = Xperm, W = W, m_sizes = expert_token_counts) assert ( ref_output.shape == output_shape ), f"ref_output.shape: {ref_output.shape}, output_shape: {output_shape}" if permute_y: ref_output = unpermute(ref_output, gather_indices) grad_output = torch.randn_like(ref_output) ref_output.backward(grad_output) assert X.grad is not None assert W.grad is not None ref_grad = Xperm.grad if autotune: # No need to run all configs for autotuning from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dX_kernel if num_autotune_configs is not None: _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:num_autotune_configs] ) if use_autograd: from grouped_gemm.interface import grouped_gemm if not autotune: kernel_config_fwd = KernelConfigForward() kernel_config_bwd_dX = KernelConfigBackward_dX( use_tma_load_dy = use_tma_load_dy, use_tma_load_w = use_tma_load_w, use_tma_store = use_tma_store, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, ) kernel_config_bwd_dW = KernelConfigBackward_dW() else: from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) from grouped_gemm.kernels.forward import ( _autotuned_grouped_gemm_forward_kernel, ) if num_autotune_configs is not None: _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:num_autotune_configs] ) _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[ :num_autotune_configs ] ) kernel_config_fwd = None kernel_config_bwd_dX = None X_ = ( X.detach().clone().requires_grad_(True) if permute_x else Xperm.detach().clone().requires_grad_(True) ) test_output = grouped_gemm( X = X_, W = W_test, m_sizes = expert_token_counts, gather_indices = gather_indices, topk = topk, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dX = kernel_config_bwd_dX, is_first_gemm = use_W1, dX_only = True, ) assert ( test_output.shape == ref_output.shape ), f"test_output.shape: {test_output.shape}, ref_output.shape: {ref_output.shape}" assert torch.allclose( test_output, ref_output, atol = atol, rtol = rtol ), f"Grouped gemm backward_dX forward outputs mismatch: {(test_output - ref_output).abs().max().item():.6f}" test_output.backward(grad_output) assert X_.grad is not None # NOTE:need to handle grad differenlty in this case due to errors arising to do how torch autograd handles unpermute and sum reduction # the grad of Xperm unpermuted and reduced across topk should match X_.grad # However, both will have a numerical difference with that of ref_grad # This is due to the fact that torch autograd handles unpermute and sum reduction differently see: https://discuss.pytorch.org/t/permute-unpermute-gradient/219557 else: if permute_x and use_W1: X_grad_unperm = unpermute(Xperm.grad, gather_indices) manual_grad_check = X_grad_unperm.view(num_tokens, topk, K).sum(dim = 1) assert ( manual_grad_check.shape == X_.grad.shape ), f"manual_grad_check.shape: {manual_grad_check.shape}, X_.grad.shape: {X_.grad.shape}" assert torch.allclose( manual_grad_check, X_.grad, atol = atol, rtol = rtol ), f"Grouped gemm backward_dX forward outputs mismatch: {(manual_grad_check - X_.grad).abs().max().item():.6f}" manual_diff = (X_.grad - manual_grad_check).abs().max().item() autograd_diff = (X_.grad - X.grad).abs().max().item() print(f"manual_diff: {manual_diff:.6f}, autograd_diff: {autograd_diff:.6f}") else: assert torch.allclose( X_.grad, ref_grad, atol = atol, rtol = rtol ), f"Grouped gemm backward_dX forward outputs mismatch: {(X_.grad - ref_grad).abs().max().item():.6f}" return else: dX_test = grouped_gemm_dX( dY = grad_output, W = W_test, gather_indices = gather_indices, m_sizes = expert_token_counts, topk = topk, permute_x = permute_x, permute_y = permute_y, use_tma_load_w = use_tma_load_w, use_tma_load_dy = use_tma_load_dy, use_tma_store = use_tma_store, autotune = autotune, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, flatten = flatten, # debug=True, ) # if permute_x and use_W1 (first grouped GEMM) then the kernel should have unpermuted the dX # therefore we need to unpermute the ref_grad to compare to the output of the kernel if permute_x and use_W1: ref_grad = unpermute(ref_grad, gather_indices) assert ( ref_grad.shape == dX_test.shape ), f"Grouped gemm manual backward_dX outputs mismatch: ref_grad: {ref_grad.shape}, dX_test: {dX_test.shape}" diff = (ref_grad - dX_test).abs().max().item() assert torch.allclose( ref_grad, dX_test, atol = atol, rtol = rtol ), f"Grouped gemm manual backward_dX outputs mismatch: {diff:.6f}" if permute_x and use_W1: # Show that reduction results in diffs # First calculate X.grad manually by backpropping through unpermuted ref_grad dX_ref_check = ref_grad.view(num_tokens, topk, K).sum(dim = 1) # Do the same for the actual output of the kernel dX_test_check = dX_test.view(num_tokens, topk, K).sum(dim = 1) # Show diffs for each combination diff_ref_check = (X.grad - dX_ref_check).abs().max().item() diff_test_check = (X.grad - dX_test_check).abs().max().item() diff_check_test = (dX_ref_check - dX_test_check).abs().max().item() print( f"diff_ref_check: {diff_ref_check:.6f}, diff_test_check: {diff_test_check:.6f}, diff_check_test: {diff_check_test:.6f}" ) # NOTE: We reduce the size of the Llama4 model configs to prevent OOM # Important to note that for the full model size (5120, 8192), the tests do result in diffs on the order of 1e-2. @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_BWD_dX, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS[:1] + [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_manual( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigBackward_dX, use_W1: bool, ): _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = False, **asdict(kernel_config), ) @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_BWD_dX, ids = lambda x: x.to_string(include_tuning_params = True, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS[:1] + [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_manual_autograd( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfigBackward_dX, use_W1: bool, ): _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = True, **asdict(kernel_config), ) @pytest.mark.parametrize( "num_autotune_configs", [20], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_autotune( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): # TMA loads / stores will be autotuned _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, autotune = True, use_autograd = False, num_autotune_configs = num_autotune_configs, ) @pytest.mark.parametrize( "num_autotune_configs", [20], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dX_autotune_autograd( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): # TMA loads / stores will be autotuned _test_grouped_gemm_backward_dX( data_config = data_config, model_config = model_config, permute_x = permute_x, permute_y = permute_y, use_W1 = use_W1, autotune = True, use_autograd = True, num_autotune_configs = num_autotune_configs, ) def _test_grouped_gemm_backward_dW( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, use_tma_load_dy: bool = False, use_tma_load_x: bool = False, use_tma_store: bool = False, BLOCK_SIZE_M: int = None, BLOCK_SIZE_N: int = None, BLOCK_SIZE_K: int = None, num_warps: int = None, num_stages: int = None, flatten: bool = True, autotune: bool = False, num_autotune_configs: int = None, allow_tma_store: bool = False, debug: bool = False, fuse_mul_post: bool = False, # Unused for backward_dW use_autograd: bool = False, ): if not check_valid_config( permute_x, permute_y, fuse_mul_post = fuse_mul_post, use_W1 = use_W1, is_backward = True, ): pytest.skip( f"Skipping test due to invalid config: {permute_x = } {permute_y = } {use_W1 = }" ) if use_tma_store and not allow_tma_store: pytest.skip("TMA store needs to be debugged due to non-deterministic behavior") X1, X2, W1, W2, gating_output = make_inputs( M = data_config.bs * data_config.seq_len, N = model_config.intermediate_size, K = model_config.hidden_size, E = model_config.num_experts, topk = model_config.topk, dtype = data_config.dtype, requires_grad = True, ) topk = model_config.topk num_experts = model_config.num_experts use_sigmoid = model_config.use_sigmoid renormalize = model_config.renormalize X = X1 if use_W1 else X2 num_tokens = data_config.bs * data_config.seq_len E, K, N = W2.shape # E = num_experts, K = hidden_size, N = intermediate_size assert W1.shape == (E, 2 * N, K) W = W1 if use_W1 else W2 if use_W1: assert X.shape == ( num_tokens, K, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, K: {K}" else: assert X.shape == ( num_tokens * topk, N, ), f"X.shape: {X.shape}, num_tokens: {num_tokens}, topk: {topk}, N: {N}" total_tokens = num_tokens * topk output_shape = (total_tokens, 2 * N) if use_W1 else (total_tokens, K) X_test = X.detach().clone().requires_grad_(True) W_test = W.detach().clone().requires_grad_(True) topk_weights, topk_ids = calculate_topk( gating_output, topk, use_sigmoid = use_sigmoid, renormalize = renormalize ) topk_weights = topk_weights.view(-1) # num_tokens * topk topk_ids = topk_ids.view(-1) # num_tokens * topk expert_token_counts, gather_indices = get_routing_indices(topk_ids, num_experts = E) assert len(gather_indices) == total_tokens assert len(expert_token_counts) == num_experts atol, rtol = TOLERANCE[X.dtype] Xperm = permute(X, gather_indices, topk) Xperm_test = Xperm.detach().clone().requires_grad_(True) # Need to retain grad otherwise grad is not propagated X.retain_grad() W.retain_grad() Xperm.retain_grad() assert Xperm.shape == (total_tokens, K) if use_W1 else (total_tokens, N) output_shape = (total_tokens, 2 * N) if use_W1 else (total_tokens, K) ref_output = torch_grouped_gemm(X = Xperm, W = W, m_sizes = expert_token_counts) assert ref_output.shape == output_shape # if permute_y then the assumption is that the output of grouped_gemm was unpermuted on store # Therefore we have to unpermute before backpropping to ensure proper alignment if permute_y: ref_output = unpermute(ref_output, gather_indices) grad_output = torch.randn_like(ref_output) ref_output.backward(grad_output) assert X.grad is not None assert W.grad is not None # Test backward kernel directly X_ = X_test if permute_x else Xperm_test if debug: torch.set_printoptions(precision = 4) for i in range(num_experts): print(f"Expert {i} weight grad:\n{W.grad[i, :5, :5]}") if autotune: from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dW_kernel if num_autotune_configs is not None: _autotuned_grouped_gemm_dW_kernel.configs = ( _autotuned_grouped_gemm_dW_kernel.configs[:num_autotune_configs] ) if use_autograd: from grouped_gemm.interface import grouped_gemm if not autotune: kernel_config_fwd = KernelConfigForward( # Only care about backward_dW config use_tma_load_w = False, use_tma_load_x = False, use_tma_store = False, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, ) kernel_config_bwd_dW = KernelConfigBackward_dW( use_tma_load_dy = use_tma_load_dy, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, ) else: from grouped_gemm.kernels.backward import _autotuned_grouped_gemm_dW_kernel from grouped_gemm.kernels.forward import ( _autotuned_grouped_gemm_forward_kernel, ) if num_autotune_configs is not None: _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[ :num_autotune_configs ] ) _autotuned_grouped_gemm_dW_kernel.configs = ( _autotuned_grouped_gemm_dW_kernel.configs[:num_autotune_configs] ) kernel_config_fwd = None kernel_config_bwd_dW = None test_output = grouped_gemm( X = X_, W = W_test, m_sizes = expert_token_counts, gather_indices = gather_indices, topk = topk, permute_x = permute_x, permute_y = permute_y, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, autotune = autotune, is_first_gemm = use_W1, dW_only = True, ) assert ( test_output.shape == ref_output.shape ), f"Grouped gemm autograd backward_dW outputs mismatch: {test_output.shape} != {ref_output.shape}" assert torch.allclose( test_output, ref_output, atol = atol, rtol = rtol ), f"Grouped gemm autograd backward_dW forward outputs mismatch: {test_output.shape} != {ref_output.shape}" test_output.backward(grad_output) assert W_test.grad is not None dW_test = W_test.grad else: dW_test = grouped_gemm_dW( dY = grad_output, X = X_, m_sizes = expert_token_counts, gather_indices = gather_indices, topk = topk, permute_x = permute_x, permute_y = permute_y, use_tma_load_dy = use_tma_load_dy, use_tma_load_x = use_tma_load_x, use_tma_store = use_tma_store, BLOCK_SIZE_M = BLOCK_SIZE_M, BLOCK_SIZE_N = BLOCK_SIZE_N, BLOCK_SIZE_K = BLOCK_SIZE_K, num_warps = num_warps, num_stages = num_stages, flatten = flatten, autotune = autotune, debug = debug, ) assert ( W.grad.shape == dW_test.shape ), f"Grouped gemm manual backward_dW outputs mismatch: W.grad: {W.grad.shape}, dW_test: {dW_test.shape}" if debug: with torch.no_grad(): if not torch.allclose(W.grad, dW_test, atol = atol, rtol = rtol): print(f"Ref Wgrad sum: {W.grad.sum().item():.4f}") print(f"Test Wgrad sum: {dW_test.sum().item():.4f}") for i in range(num_experts): print(f"Expert {i} weight grad:\n{W.grad[i, :5, :5]}") print(f"Expert {i} dW_test:\n{dW_test[i, :5, :5]}") expert_diff = (W.grad[i, :, :] - dW_test[i, :, :]).abs().max().item() print(f"Expert {i} diff: {expert_diff:.6f}") diff = (W.grad - dW_test).abs().max().item() assert ( False ), f"Grouped gemm manual backward_dW outputs mismatch: {diff:.6f}" else: diff = (W.grad - dW_test).abs().max().item() assert torch.allclose( W.grad, dW_test, atol = atol, rtol = rtol ), f"Grouped gemm manual backward_dW outputs mismatch: {diff:.6f}" @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_BWD_dW, ids = lambda x: x.to_string(include_tuning_params = False, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS + [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dW_manual( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfig, use_W1: bool, debug: bool = False, ): _test_grouped_gemm_backward_dW( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = False, **asdict(kernel_config), ) @pytest.mark.parametrize( "kernel_config", KERNEL_CONFIGS_BWD_dW, ids = lambda x: x.to_string(include_tuning_params = False, include_tma = True), ) @pytest.mark.parametrize( "model_config", SMALL_MODEL_CONFIGS + [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dW_manual_autograd( data_config: DataConfig, model_config: ModelConfig, kernel_config: KernelConfig, use_W1: bool, debug: bool = False, ): _test_grouped_gemm_backward_dW( data_config = data_config, model_config = model_config, use_W1 = use_W1, use_autograd = True, **asdict(kernel_config), ) @pytest.mark.parametrize( "num_autotune_configs", [20], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dW_autotune( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): _test_grouped_gemm_backward_dW( data_config = data_config, model_config = model_config, use_W1 = use_W1, permute_x = permute_x, permute_y = permute_y, autotune = True, use_autograd = False, num_autotune_configs = num_autotune_configs, ) @pytest.mark.parametrize( "num_autotune_configs", [20], ids = lambda x: f"num_autotune_configs={x}" ) @pytest.mark.parametrize( "permute_x", [True, False], ids = lambda x: "permute_x" if x else "" ) @pytest.mark.parametrize( "permute_y", [True, False], ids = lambda x: "permute_y" if x else "" ) @pytest.mark.parametrize( "model_config", [LLAMA_MODEL_CONFIG, QWEN_MODEL_CONFIG], ids = lambda x: f"topk={x.topk} num_experts={x.num_experts} hidden_size={x.hidden_size} intermediate_size={x.intermediate_size}", ) @pytest.mark.parametrize( "data_config", DATA_CONFIGS, ids = lambda x: f"seq_len={x.seq_len} dtype={x.dtype}" ) @pytest.mark.parametrize("use_W1", [True, False], ids = lambda x: f"use_W1={x}") def test_grouped_gemm_backward_dW_autotune_autograd( data_config: DataConfig, model_config: ModelConfig, permute_x: bool, permute_y: bool, use_W1: bool, num_autotune_configs: int, ): _test_grouped_gemm_backward_dW( data_config = data_config, model_config = model_config, use_W1 = use_W1, permute_x = permute_x, permute_y = permute_y, autotune = True, use_autograd = True, num_autotune_configs = num_autotune_configs, )
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/tests/test_grouped_gemm.py", "license": "Apache License 2.0", "lines": 1088, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/kernels/moe/tests/test_qwen3_moe.py
# SPDX-License-Identifier: GNU Affero General Public License v3.0 # Copyright 2023-present the Unsloth team. All rights reserved. import argparse from contextlib import contextmanager import pytest import torch from transformers import AutoConfig from transformers.models.qwen3_moe import Qwen3MoeConfig from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeSparseMoeBlock from grouped_gemm.kernels.tuning import ( KernelConfigBackward_dW, KernelConfigBackward_dX, KernelConfigForward, ) from grouped_gemm.reference.layers.qwen3_moe import Qwen3MoeGroupedGEMMBlock from .moe_utils import ( Qwen3MoeFusedGroupedGEMMBlock, check_fwd, check_grads, check_grouped_gemm_results, run_backward, run_forward, ) """ Qwen3 MoE tests NOTE: Test this as a module and NOT with pytest as running with pytest results in random numerical errors: python -m tests.test_qwen3_moe --permute_x --permute_y --autotune NOT pytest -sv tests/test_qwen3_moe.py More specifically, all tests pass when run individually, but some will fail randomly (even with the same seed) when the entire test is run as a parametrized test suite using pytest, likely due to how pytest interacts with triton / autotuning. See tests/run_qwen3_moe_tests.sh for a script that runs all the tests The tests run the following: Huggingface's Qwen3 MoE block (Qwen3MoeSparseMoeBlock) Torch-native grouped gemm version of MoE block (Qwen3MoeGroupedGEMMBlock), which is the HF block with the expert computation replaced with a torch-native grouped gemm Triton kernel grouped gemm version of MoE block (Qwen3MoeFusedGroupedGEMMBlock), which is the HF block with the expert computation replaced with the fused triton grouped gemm kernel The tests check the following: - HF MoE block vs torch grouped gemm MoE block (sanity check) - torch grouped gemm MoE block vs fused grouped gemm MoE block -- this allows us to test each of the intermediate results for easier debugging - HF MoE block vs fused grouped gemm MoE block -- this is the actual test Both forward and backward passes are tests: - forward: output of the moe block - backwards: - X: gradient of the input to the moe block - gate.weight: gradient of the gate weights (router weights) - gate_proj: gradient of concatenated gate projections - up_proj: gradient of the concatenated up projections - down_proj: gradient of the concatenated down projections Additionally, for the torch grouped gemm and triton grouped gemm versions, the intermediate outputs of the forward pass are checked: - first_gemm: output of the first grouped gemm (X @ fused_gate_proj) - intermediate: output of silu_mul(first_gemm) - second_gemm: output of the second grouped gemm (intermediate @ down_proj) - hidden_states_unpermute: output of the second_gemm after unpermuting back to token order (from expert grouped order); in the case where the permutation is fused in the triton kernel, this is the same as second_gemm - hidden_states: output with the topk_weights applied """ TOLERANCES = { torch.bfloat16: (1e-2, 1e-2), torch.float16: (1e-3, 1e-3), torch.float: (1e-5, 1e-5), } @pytest.fixture(scope = "module") def model_id(): return "Qwen/Qwen3-30B-A3B" @pytest.fixture(scope = "module") def config(model_id: str): return AutoConfig.from_pretrained(model_id) @contextmanager def annotated_context(prelude, epilogue = "Passed!", char = "-", num_chars = 80): print(char * num_chars) print(prelude) yield print(epilogue) print(char * num_chars) SEED = 42 SEQ_LENS = [1024] DTYPES = [torch.bfloat16] # Reduce the number of autotuning configs to prevent excessive runtime NUM_AUTOTUNE_CONFIGS = 50 @pytest.mark.parametrize( "permute_y", [True], ids = lambda x: "permute_y" if x else "no_permute_y" ) @pytest.mark.parametrize( "permute_x", [True], ids = lambda x: "permute_x" if x else "no_permute_x" ) @pytest.mark.parametrize( "autotune", [True], ids = lambda x: "autotune" if x else "manual" ) @pytest.mark.parametrize("seqlen", SEQ_LENS, ids = lambda x: f"seqlen={x}") @pytest.mark.parametrize("dtype", DTYPES, ids = str) def test_qwen3_moe( config: Qwen3MoeConfig, seqlen: int, dtype: torch.dtype, permute_x: bool, permute_y: bool, autotune: bool, ): torch.manual_seed( SEED ) # Should not be needed when running using pytest -- autouse fixture in conftest.py device = "cuda" hidden_size = config.hidden_size bs = 1 atol, rtol = TOLERANCES[dtype] # Reference op -- HF moe_block = Qwen3MoeSparseMoeBlock(config).to(device, dtype) # Torch-native grouped gemm version of MoE Block -- for sanity checking grouped_gemm_block = Qwen3MoeGroupedGEMMBlock.from_hf(moe_block).to(device, dtype) grouped_gemm_block.check_weights(moe_block) if not autotune: kernel_config_fwd = KernelConfigForward() kernel_config_bwd_dW = KernelConfigBackward_dW() kernel_config_bwd_dX = KernelConfigBackward_dX() else: from grouped_gemm.kernels.backward import ( _autotuned_grouped_gemm_dW_kernel, _autotuned_grouped_gemm_dX_kernel, ) from grouped_gemm.kernels.forward import _autotuned_grouped_gemm_forward_kernel # Hack to reduce number of autotuning configs _autotuned_grouped_gemm_forward_kernel.configs = ( _autotuned_grouped_gemm_forward_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dW_kernel.configs = ( _autotuned_grouped_gemm_dW_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) _autotuned_grouped_gemm_dX_kernel.configs = ( _autotuned_grouped_gemm_dX_kernel.configs[:NUM_AUTOTUNE_CONFIGS] ) kernel_config_fwd = None kernel_config_bwd_dW = None kernel_config_bwd_dX = None # Triton kernel grouped gemm version of MoE Block -- this is what we're testing fused_gemm_block = Qwen3MoeFusedGroupedGEMMBlock.from_hf( moe_block, permute_x = permute_x, permute_y = permute_y, autotune = autotune, kernel_config_fwd = kernel_config_fwd, kernel_config_bwd_dW = kernel_config_bwd_dW, kernel_config_bwd_dX = kernel_config_bwd_dX, ).to(device, dtype) fused_gemm_block.check_weights(moe_block) X = torch.randn( bs, seqlen, hidden_size, dtype = dtype, device = device, requires_grad = True ) # Forward ref_result = run_forward(moe_block, X, is_grouped_gemm = False) grouped_result = run_forward(grouped_gemm_block, X, is_grouped_gemm = True) fused_result = run_forward(fused_gemm_block, X, is_grouped_gemm = True) with annotated_context( "Testing forward pass", epilogue = "Passed forward tests!", char = "=", num_chars = 100, ): # Sanity checks with annotated_context( "Checking HF vs torch grouped gemm MoE forward outputs..." ): check_fwd(ref_result, grouped_result, atol, rtol, verbose = False) with annotated_context( "Checking torch grouped gemm MoE vs fused grouped gemm MoE forward outputs..." ): # We implement a custom check for grouped gemm results to test each of the intermediate results for easier debugging check_grouped_gemm_results( grouped_result.grouped_gemm_result, fused_result.grouped_gemm_result, permute_y = permute_y, atol = atol, rtol = rtol, verbose = False, ) # Actual test with annotated_context( "Checking HF vs fused grouped gemm MoE forward outputs..." ): check_fwd(ref_result, fused_result, atol, rtol, verbose = True) # Backward grad_output = torch.randn_like(ref_result.output) ref_backward_result = run_backward( moe_block, grad_output, output = ref_result.output, X = ref_result.X ) grouped_backward_result = run_backward( grouped_gemm_block, grad_output, output = grouped_result.output, X = grouped_result.X, ) fused_backward_result = run_backward( fused_gemm_block, grad_output, output = fused_result.output, X = fused_result.X ) with annotated_context( "Testing backward pass", epilogue = "Passed backward tests!", char = "=", num_chars = 100, ): # Sanity checks with annotated_context("Checking HF vs torch grouped gemm MoE grads..."): check_grads( ref_backward_result, grouped_backward_result, atol, rtol, verbose = False ) with annotated_context( "Checking torch grouped gemm MoE vs fused grouped gemm MoE grads..." ): check_grads( grouped_backward_result, fused_backward_result, atol, rtol, verbose = False, ) # Actual test with annotated_context("Checking HF vs fused grouped gemm MoE grads..."): check_grads( ref_backward_result, fused_backward_result, atol, rtol, verbose = True ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--seqlen", type = int, default = 1024) parser.add_argument( "--dtype", type = str, choices = ["bfloat16", "float16"], default = "bfloat16" ) parser.add_argument("--permute_x", action = "store_true") parser.add_argument("--permute_y", action = "store_true") parser.add_argument("--autotune", action = "store_true") args = parser.parse_args() args.dtype = getattr(torch, args.dtype) args_dict = vars(args) model_id = "Qwen/Qwen3-30B-A3B" config = AutoConfig.from_pretrained(model_id) atol, rtol = TOLERANCES[args.dtype] print( f"Testing {model_id} with seqlen={args.seqlen}, dtype={args.dtype}, permute_x={args.permute_x}, permute_y={args.permute_y}, autotune={args.autotune}, atol={atol}, rtol={rtol}" ) test_qwen3_moe(config, **args_dict)
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/kernels/moe/tests/test_qwen3_moe.py", "license": "Apache License 2.0", "lines": 233, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
unslothai/unsloth:unsloth/dataprep/synthetic_configs.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. synthetic_qa_config = """\ # Master configuration file for Synthetic Data Kit # Global paths configuration paths: # Input data locations input: pdf: "{data_output_location}/pdf" html: "{data_output_location}/html" youtube: "{data_output_location}/youtube" docx: "{data_output_location}/docx" ppt: "{data_output_location}/ppt" txt: "{data_output_location}/txt" # Output locations output: parsed: "{data_output_location}/output" # Where parsed text files are saved generated: "{data_output_location}/generated" # Where generated content is saved cleaned: "{data_output_location}/cleaned" # Where cleaned content is saved final: "{data_output_location}/final" # Where final formatted content is saved # VLLM server configuration vllm: api_base: "http://localhost:8000/v1" # Base URL for VLLM API port: 8000 # Port for VLLM server model: "{model_name}" # Default model to use max_retries: 3 # Number of retries for API calls retry_delay: 1.0 # Initial delay between retries (seconds) # Ingest configuration ingest: default_format: "txt" # Default output format for parsed files youtube_captions: "auto" # Options: "auto", "manual" - caption preference # LLM generation parameters generation: temperature: {temperature} # Higher = more creative, lower = more deterministic top_p: {top_p} # Nucleus sampling parameter chunk_size: {chunk_size} # Size of text chunks for processing overlap: {overlap} # Overlap between chunks to maintain context max_tokens: {max_tokens} # Maximum tokens in LLM responses num_pairs: {default_num_pairs} # Default number of QA pairs to generate # Content cleanup parameters cleanup: threshold: {cleanup_threshold} # Default quality threshold (1-10) batch_size: {cleanup_batch_size} # Number of items per batch for rating temperature: {cleanup_temperature} # Temperature for rating (lower = more consistent) # Format conversion parameters format: default: "jsonl" # Default output format include_metadata: true # Include metadata in output files pretty_json: true # Use indentation in JSON output # Prompts for different tasks prompts: # Summary generation prompt summary: | Summarize this document in 3-5 sentences, focusing on the main topic and key concepts. # QA pair generation prompt qa_generation: | Create {num_pairs} question-answer pairs from this text for LLM training. Rules: 1. Questions must be about important facts in the text 2. Answers must be directly supported by the text 3. Return JSON format only: [ {{ "question": "Question 1?", "answer": "Answer 1." }}, {{ "question": "Question 2?", "answer": "Answer 2." }} ] Text: {text} # QA pair rating prompt qa_rating: | Rate each of these question-answer pairs for quality and return exactly this JSON format: [ {{"question": "same question text", "answer": "same answer text", "rating": n}} ] Where n is a number from 1-10. DO NOT include any text outside of the JSON array, just return valid JSON: {pairs}"""
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/dataprep/synthetic_configs.py", "license": "Apache License 2.0", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/models/llama4.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from unsloth_studio.models import patch_llama4 # patch_llama4()
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/models/llama4.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
unslothai/unsloth:unsloth/dataprep/synthetic.py
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = [ "SyntheticDataKit", ] import subprocess import threading from collections import deque import time import os os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" import requests import torch import gc import time import re from unsloth_zoo.log import logger import numpy as np from .synthetic_configs import ( synthetic_qa_config, ) def _load_vllm_utils(): from unsloth_zoo.vllm_utils import ( load_vllm, patch_vllm, delete_vllm, ) return load_vllm, patch_vllm, delete_vllm def terminate_tree(proc: subprocess.Popen, timeout = 15): if proc is None or proc.poll() is not None: return try: import psutil parent = psutil.Process(proc.pid) for child in parent.children(recursive = True): child.terminate() parent.terminate() parent.wait(timeout = timeout / 2) return except: pass if os.name == "nt": try: subprocess.run( ["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output = True, timeout = 5, ) proc.wait(timeout = 1) return except: pass proc.kill() try: proc.wait(timeout = 5) except: pass class PipeCapture: """Non blocking pipe capture""" def __init__( self, pipe, keep_lines = 2000, echo = False, name = "", text = True, encoding = "utf-8", errors = "replace", ready_regex = None, ): self.pipe = pipe self.buf = deque(maxlen = keep_lines) self.lock = threading.Lock() self.echo = echo self.name = name self.text = text self.encoding = encoding self.errors = errors self.ready_event = threading.Event() self.closed_event = threading.Event() self.ready_regex = None if ready_regex is not None: if not hasattr(ready_regex, "search"): ready_regex = re.compile(ready_regex) self.ready_regex = ready_regex self.t = threading.Thread(target = self._reader, daemon = True) self.t.start() def _reader(self): try: sentinel = "" if self.text else b"" for raw_line in iter(self.pipe.readline, sentinel): if not self.text: line = raw_line.decode(self.encoding, self.errors) else: line = raw_line line = line.rstrip("\r\n") if self.echo: if "platform is" not in line: print(f"{self.name}: {line}") with self.lock: self.buf.append(line) if self.ready_regex is not None and self.ready_regex.search(line): self.ready_event.set() finally: try: self.pipe.close() except Exception: pass self.closed_event.set() def wait_for_ready(self, timeout = None): return self.ready_event.wait(timeout) def has_closed(self): return self.closed_event.is_set() def wait_until_closed(self, timeout = None): return self.closed_event.wait(timeout) def tail(self, n = 200): with self.lock: return "\n".join(list(self.buf)[-n:]) class SyntheticDataKit: def __init__( self, model_name = "unsloth/Llama-3.1-8B-Instruct-unsloth-bnb-4bit", max_seq_length = 2048, gpu_memory_utilization = 0.98, float8_kv_cache = False, conservativeness = 1.0, token = None, timeout = 1200, # maybe this is not enough for large models if we need to download **kwargs, ): assert type(model_name) is str assert type(max_seq_length) is int assert type(gpu_memory_utilization) is float assert type(float8_kv_cache) is bool assert type(conservativeness) is float assert token is None or type(token) is str self.model_name = model_name self.max_seq_length = max_seq_length from transformers import AutoConfig, AutoTokenizer self.config = AutoConfig.from_pretrained( model_name, token = token, ) self.tokenizer = AutoTokenizer.from_pretrained( model_name, token = token, ) load_vllm, patch_vllm, delete_vllm = _load_vllm_utils() self._delete_vllm = delete_vllm patch_vllm(debug = False) engine_args = load_vllm( model_name = model_name, config = self.config, gpu_memory_utilization = gpu_memory_utilization, max_seq_length = max_seq_length, disable_log_stats = True, float8_kv_cache = float8_kv_cache, conservativeness = conservativeness, return_args = True, enable_lora = False, use_bitsandbytes = False, compilation_config = 3, **kwargs, ) if "dtype" in engine_args: dtype_val = engine_args["dtype"] if dtype_val == torch.float16: dtype_val = "float16" elif dtype_val == torch.bfloat16: dtype_val = "bfloat16" elif dtype_val == torch.float32: dtype_val = "float32" engine_args["dtype"] = dtype_val # Convert torch.bfloat16, torch.float16, etc. to valid CLI string if hasattr(dtype_val, "name"): engine_args["dtype"] = dtype_val.name elif isinstance(dtype_val, str) and dtype_val.startswith("torch."): engine_args["dtype"] = dtype_val.split(".")[-1] # Only allow valid vLLM choices valid_dtypes = {"auto", "bfloat16", "float", "float16", "float32", "half"} if engine_args["dtype"] not in valid_dtypes: engine_args["dtype"] = "auto" if "device" in engine_args: del engine_args["device"] if "model" in engine_args: del engine_args["model"] subprocess_commands = [ "vllm", "serve", str(model_name), ] for key, value in engine_args.items(): flag = key.replace("_", "-") if key == "compilation_config": # [TODO] Unsure why subprocess doesn't process json properly # Also -O3 breaks on T4! # subprocess_commands += ["-O3",] continue which = str(value).replace("torch.", "") if which == "True": # Ignore --enforce-eager True subprocess_commands += [ "--" + flag, ] elif which == "False": # Ignore flag pass elif which == "None": # Ignore flag pass else: subprocess_commands += [ "--" + flag, which, ] logger.info(subprocess_commands) vllm_process = subprocess.Popen( subprocess_commands, stdout = subprocess.PIPE, stderr = subprocess.PIPE, start_new_session = True, ) ready_re = re.compile(r"Starting vLLM API server(?:\s+\d+)?\s+on\b") self.vllm_process = vllm_process self.stdout_capture = PipeCapture( vllm_process.stdout, keep_lines = 1000, echo = True, name = "vLLM STDOUT", ready_regex = ready_re, text = False, ) self.stderr_capture = PipeCapture( vllm_process.stderr, keep_lines = 2000, echo = False, name = "vLLM STDERR", ready_regex = None, text = False, ) # we don't print stderr to console but self.stderr_capture.tail(200) will print the last 200 lines ready = self.stdout_capture.wait_for_ready(timeout = timeout) if not ready: if self.stdout_capture.has_closed() or self.vllm_process.poll() is not None: print("Stdout stream ended before readiness message detected.") print("\n--- stdout tail ---\n", self.stdout_capture.tail(50)) print("\n--- stderr tail ---\n", self.stderr_capture.tail(50)) else: print(f"Unsloth: vllm_process failed to load! (timeout={timeout})") print("\n--- stdout tail ---\n", self.stdout_capture.tail(50)) print("\n--- stderr tail ---\n", self.stderr_capture.tail(50)) terminate_tree(self.vllm_process) return else: print("vLLM Server Ready Detected") trial = 0 while not self.check_vllm_status(): if trial >= 100: print("Unsloth: vllm_process failed to load!") print("\n--- stdout tail ---\n", self.stdout_capture.tail(50)) print("\n--- stderr tail ---\n", self.stderr_capture.tail(50)) terminate_tree(self.vllm_process) return trial += 1 time.sleep(1) return @staticmethod def from_pretrained( model_name = "unsloth/Llama-3.1-8B-Instruct-unsloth-bnb-4bit", max_seq_length = 2048, gpu_memory_utilization = 0.9, float8_kv_cache = False, conservativeness = 1.0, token = None, **kwargs, ): return SyntheticDataKit( model_name = model_name, max_seq_length = max_seq_length, gpu_memory_utilization = gpu_memory_utilization, float8_kv_cache = float8_kv_cache, conservativeness = conservativeness, token = token, **kwargs, ) @staticmethod def check_vllm_status(): try: response = requests.get("http://localhost:8000/metrics") if response.status_code == 200: return True except requests.exceptions.ConnectionError: return False def cleanup(self): if not hasattr(self, "vllm_process"): return vllm_process = self.vllm_process print("Attempting to terminate the VLLM server gracefully...") try: vllm_process.terminate() vllm_process.wait(timeout = 10) print("Server terminated gracefully.") except subprocess.TimeoutExpired: print( "Server did not terminate gracefully after 10 seconds. Forcing kill..." ) vllm_process.kill() vllm_process.wait() print("Server killed forcefully.") except Exception as e: print(f"An error occurred while trying to stop the process: {e}") try: if vllm_process.poll() is None: print("Attempting forceful kill due to error...") vllm_process.kill() vllm_process.wait() print("Server killed forcefully after error.") except Exception as kill_e: print(f"Error during forceful kill: {kill_e}") for _ in range(10): torch.cuda.empty_cache() gc.collect() # Delete vLLM module as well if hasattr(self, "_delete_vllm"): self._delete_vllm(llm = None) def __enter__(self): return self def __exit__(self, *exc): self.cleanup() def __del__(self): self.cleanup() def chunk_data(self, filename = None): # Chunks data by max tokens and generation length assert filename is not None assert os.path.exists(filename) assert hasattr(self, "tokenizer") if not hasattr(self, "max_seq_length"): raise RuntimeError( "Please use SynthetidDataKit.from_pretrained(...) first!" ) if not hasattr(self, "overlap") or not hasattr(self, "max_generation_tokens"): raise RuntimeError("Please use prepare_qa_generation first!") with open(filename, "r", encoding = "utf-8") as f: text = f.read() max_tokens = ( self.max_seq_length - self.max_generation_tokens * 2 - 128 ) # -128 to reduce errors if max_tokens <= 5: raise RuntimeError("Generation length is way too long!") input_ids = self.tokenizer(text, add_special_tokens = False).input_ids # Get left and right boundaries length = len(input_ids) n_chunks = int(np.ceil(length / (max_tokens - self.overlap))) boundaries = np.ceil(np.linspace(0, length - self.overlap, n_chunks)).astype( int ) boundaries = np.stack((boundaries[:-1], (boundaries + self.overlap)[1:])).T boundaries = np.minimum(boundaries, length).tolist() # Get extension of filename like .txt filename, extension = os.path.splitext(filename) if filename.endswith("/"): filename = filename[:-1] all_filenames = [] for i, (left, right) in enumerate(boundaries): chunked_text = self.tokenizer.decode(input_ids[left:right]) new_filename = f"{filename}_{i}{extension}" all_filenames.append(new_filename) with open(new_filename, "w", encoding = "utf-8") as f: f.write(chunked_text) return all_filenames def prepare_qa_generation( self, output_folder = "data", max_generation_tokens = 512, temperature = 0.7, top_p = 0.95, overlap = 64, default_num_pairs = 25, cleanup_threshold = 1.0, cleanup_batch_size = 4, cleanup_temperature = 0.3, ): assert hasattr(self, "model_name") assert hasattr(self, "max_seq_length") assert max_generation_tokens < self.max_seq_length locations = "pdf,html,youtube,docx,ppt,txt,output,generated,cleaned,final" locations = locations.split(",") for path in locations: os.makedirs(os.path.join(output_folder, path), exist_ok = True) self.max_generation_tokens = max_generation_tokens config = ( synthetic_qa_config.replace("{data_output_location}", str(output_folder)) .replace("{model_name}", str(self.model_name)) .replace("{temperature}", str(temperature)) .replace("{top_p}", str(top_p)) .replace( "{chunk_size}", str(self.max_seq_length - max_generation_tokens * 2 - 2) ) .replace("{overlap}", str(overlap)) .replace("{max_tokens}", str(max_generation_tokens)) .replace("{default_num_pairs}", str(default_num_pairs)) .replace("{cleanup_threshold}", str(cleanup_threshold)) .replace("{cleanup_batch_size}", str(cleanup_batch_size)) .replace("{cleanup_temperature}", str(cleanup_temperature)) ) with open("synthetic_data_kit_config.yaml", "w", encoding = "utf-8") as f: f.write(config) self.overlap = overlap
{ "repo_id": "unslothai/unsloth", "file_path": "unsloth/dataprep/synthetic.py", "license": "Apache License 2.0", "lines": 419, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
usestrix/strix:strix/tools/context.py
from contextvars import ContextVar current_agent_id: ContextVar[str] = ContextVar("current_agent_id", default="default") def get_current_agent_id() -> str: return current_agent_id.get() def set_current_agent_id(agent_id: str) -> None: current_agent_id.set(agent_id)
{ "repo_id": "usestrix/strix", "file_path": "strix/tools/context.py", "license": "Apache License 2.0", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
usestrix/strix:strix/utils/resource_paths.py
import sys from pathlib import Path def get_strix_resource_path(*parts: str) -> Path: frozen_base = getattr(sys, "_MEIPASS", None) if frozen_base: base = Path(frozen_base) / "strix" if base.exists(): return base.joinpath(*parts) base = Path(__file__).resolve().parent.parent return base.joinpath(*parts)
{ "repo_id": "usestrix/strix", "file_path": "strix/utils/resource_paths.py", "license": "Apache License 2.0", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
usestrix/strix:strix/config/config.py
import contextlib import json import os from pathlib import Path from typing import Any STRIX_API_BASE = "https://models.strix.ai/api/v1" class Config: """Configuration Manager for Strix.""" # LLM Configuration strix_llm = None llm_api_key = None llm_api_base = None openai_api_base = None litellm_base_url = None ollama_api_base = None strix_reasoning_effort = "high" strix_llm_max_retries = "5" strix_memory_compressor_timeout = "30" llm_timeout = "300" _LLM_CANONICAL_NAMES = ( "strix_llm", "llm_api_key", "llm_api_base", "openai_api_base", "litellm_base_url", "ollama_api_base", "strix_reasoning_effort", "strix_llm_max_retries", "strix_memory_compressor_timeout", "llm_timeout", ) # Tool & Feature Configuration perplexity_api_key = None strix_disable_browser = "false" # Runtime Configuration strix_image = "ghcr.io/usestrix/strix-sandbox:0.1.12" strix_runtime_backend = "docker" strix_sandbox_execution_timeout = "120" strix_sandbox_connect_timeout = "10" # Telemetry strix_telemetry = "1" # Config file override (set via --config CLI arg) _config_file_override: Path | None = None @classmethod def _tracked_names(cls) -> list[str]: return [ k for k, v in vars(cls).items() if not k.startswith("_") and k[0].islower() and (v is None or isinstance(v, str)) ] @classmethod def tracked_vars(cls) -> list[str]: return [name.upper() for name in cls._tracked_names()] @classmethod def _llm_env_vars(cls) -> set[str]: return {name.upper() for name in cls._LLM_CANONICAL_NAMES} @classmethod def _llm_env_changed(cls, saved_env: dict[str, Any]) -> bool: for var_name in cls._llm_env_vars(): current = os.getenv(var_name) if current is None: continue if saved_env.get(var_name) != current: return True return False @classmethod def get(cls, name: str) -> str | None: env_name = name.upper() default = getattr(cls, name, None) return os.getenv(env_name, default) @classmethod def config_dir(cls) -> Path: return Path.home() / ".strix" @classmethod def config_file(cls) -> Path: if cls._config_file_override is not None: return cls._config_file_override return cls.config_dir() / "cli-config.json" @classmethod def load(cls) -> dict[str, Any]: path = cls.config_file() if not path.exists(): return {} try: with path.open("r", encoding="utf-8") as f: data: dict[str, Any] = json.load(f) return data except (json.JSONDecodeError, OSError): return {} @classmethod def save(cls, config: dict[str, Any]) -> bool: try: cls.config_dir().mkdir(parents=True, exist_ok=True) config_path = cls.config_dir() / "cli-config.json" with config_path.open("w", encoding="utf-8") as f: json.dump(config, f, indent=2) except OSError: return False with contextlib.suppress(OSError): config_path.chmod(0o600) # may fail on Windows return True @classmethod def apply_saved(cls, force: bool = False) -> dict[str, str]: saved = cls.load() env_vars = saved.get("env", {}) if not isinstance(env_vars, dict): env_vars = {} cleared_vars = { var_name for var_name in cls.tracked_vars() if var_name in os.environ and os.environ.get(var_name) == "" } if cleared_vars: for var_name in cleared_vars: env_vars.pop(var_name, None) if cls._config_file_override is None: cls.save({"env": env_vars}) if cls._llm_env_changed(env_vars): for var_name in cls._llm_env_vars(): env_vars.pop(var_name, None) if cls._config_file_override is None: cls.save({"env": env_vars}) applied = {} for var_name, var_value in env_vars.items(): if var_name in cls.tracked_vars() and (force or var_name not in os.environ): os.environ[var_name] = var_value applied[var_name] = var_value return applied @classmethod def capture_current(cls) -> dict[str, Any]: env_vars = {} for var_name in cls.tracked_vars(): value = os.getenv(var_name) if value: env_vars[var_name] = value return {"env": env_vars} @classmethod def save_current(cls) -> bool: existing = cls.load().get("env", {}) merged = dict(existing) for var_name in cls.tracked_vars(): value = os.getenv(var_name) if value is None: pass elif value == "": merged.pop(var_name, None) else: merged[var_name] = value return cls.save({"env": merged}) def apply_saved_config(force: bool = False) -> dict[str, str]: return Config.apply_saved(force=force) def save_current_config() -> bool: return Config.save_current() def resolve_llm_config() -> tuple[str | None, str | None, str | None]: """Resolve LLM model, api_key, and api_base based on STRIX_LLM prefix. Returns: tuple: (model_name, api_key, api_base) - model_name: Original model name (strix/ prefix preserved for display) - api_key: LLM API key - api_base: API base URL (auto-set to STRIX_API_BASE for strix/ models) """ model = Config.get("strix_llm") if not model: return None, None, None api_key = Config.get("llm_api_key") if model.startswith("strix/"): api_base: str | None = STRIX_API_BASE else: api_base = ( Config.get("llm_api_base") or Config.get("openai_api_base") or Config.get("litellm_base_url") or Config.get("ollama_api_base") ) return model, api_key, api_base
{ "repo_id": "usestrix/strix", "file_path": "strix/config/config.py", "license": "Apache License 2.0", "lines": 175, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/telemetry/posthog.py
import json import platform import sys import urllib.request from pathlib import Path from typing import TYPE_CHECKING, Any from uuid import uuid4 from strix.config import Config if TYPE_CHECKING: from strix.telemetry.tracer import Tracer _POSTHOG_PUBLIC_API_KEY = "phc_7rO3XRuNT5sgSKAl6HDIrWdSGh1COzxw0vxVIAR6vVZ" _POSTHOG_HOST = "https://us.i.posthog.com" _SESSION_ID = uuid4().hex[:16] def _is_enabled() -> bool: return (Config.get("strix_telemetry") or "1").lower() not in ("0", "false", "no", "off") def _is_first_run() -> bool: marker = Path.home() / ".strix" / ".seen" if marker.exists(): return False try: marker.parent.mkdir(parents=True, exist_ok=True) marker.touch() except Exception: # noqa: BLE001, S110 pass # nosec B110 return True def _get_version() -> str: try: from importlib.metadata import version return version("strix-agent") except Exception: # noqa: BLE001 return "unknown" def _send(event: str, properties: dict[str, Any]) -> None: if not _is_enabled(): return try: payload = { "api_key": _POSTHOG_PUBLIC_API_KEY, "event": event, "distinct_id": _SESSION_ID, "properties": properties, } req = urllib.request.Request( # noqa: S310 f"{_POSTHOG_HOST}/capture/", data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(req, timeout=10): # noqa: S310 # nosec B310 pass except Exception: # noqa: BLE001, S110 pass # nosec B110 def _base_props() -> dict[str, Any]: return { "os": platform.system().lower(), "arch": platform.machine(), "python": f"{sys.version_info.major}.{sys.version_info.minor}", "strix_version": _get_version(), } def start( model: str | None, scan_mode: str | None, is_whitebox: bool, interactive: bool, has_instructions: bool, ) -> None: _send( "scan_started", { **_base_props(), "model": model or "unknown", "scan_mode": scan_mode or "unknown", "scan_type": "whitebox" if is_whitebox else "blackbox", "interactive": interactive, "has_instructions": has_instructions, "first_run": _is_first_run(), }, ) def finding(severity: str) -> None: _send( "finding_reported", { **_base_props(), "severity": severity.lower(), }, ) def end(tracer: "Tracer", exit_reason: str = "completed") -> None: vulnerabilities_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0} for v in tracer.vulnerability_reports: sev = v.get("severity", "info").lower() if sev in vulnerabilities_counts: vulnerabilities_counts[sev] += 1 llm = tracer.get_total_llm_stats() total = llm.get("total", {}) _send( "scan_ended", { **_base_props(), "exit_reason": exit_reason, "duration_seconds": round(tracer._calculate_duration()), "vulnerabilities_total": len(tracer.vulnerability_reports), **{f"vulnerabilities_{k}": v for k, v in vulnerabilities_counts.items()}, "agent_count": len(tracer.agents), "tool_count": tracer.get_real_tool_count(), "llm_tokens": llm.get("total_tokens", 0), "llm_cost": total.get("cost", 0.0), }, ) def error(error_type: str, error_msg: str | None = None) -> None: props = {**_base_props(), "error_type": error_type} if error_msg: props["error_msg"] = error_msg _send("error", props)
{ "repo_id": "usestrix/strix", "file_path": "strix/telemetry/posthog.py", "license": "Apache License 2.0", "lines": 111, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/llm/dedupe.py
import json import logging import re from typing import Any import litellm from strix.config.config import resolve_llm_config from strix.llm.utils import resolve_strix_model logger = logging.getLogger(__name__) DEDUPE_SYSTEM_PROMPT = """You are an expert vulnerability report deduplication judge. Your task is to determine if a candidate vulnerability report describes the SAME vulnerability as any existing report. CRITICAL DEDUPLICATION RULES: 1. SAME VULNERABILITY means: - Same root cause (e.g., "missing input validation" not just "SQL injection") - Same affected component/endpoint/file (exact match or clear overlap) - Same exploitation method or attack vector - Would be fixed by the same code change/patch 2. NOT DUPLICATES if: - Different endpoints even with same vulnerability type (e.g., SQLi in /login vs /search) - Different parameters in same endpoint (e.g., XSS in 'name' vs 'comment' field) - Different root causes (e.g., stored XSS vs reflected XSS in same field) - Different severity levels due to different impact - One is authenticated, other is unauthenticated 3. ARE DUPLICATES even if: - Titles are worded differently - Descriptions have different level of detail - PoC uses different payloads but exploits same issue - One report is more thorough than another - Minor variations in technical analysis COMPARISON GUIDELINES: - Focus on the technical root cause, not surface-level similarities - Same vulnerability type (SQLi, XSS) doesn't mean duplicate - location matters - Consider the fix: would fixing one also fix the other? - When uncertain, lean towards NOT duplicate FIELDS TO ANALYZE: - title, description: General vulnerability info - target, endpoint, method: Exact location of vulnerability - technical_analysis: Root cause details - poc_description: How it's exploited - impact: What damage it can cause YOU MUST RESPOND WITH EXACTLY THIS XML FORMAT AND NOTHING ELSE: <dedupe_result> <is_duplicate>true</is_duplicate> <duplicate_id>vuln-0001</duplicate_id> <confidence>0.95</confidence> <reason>Both reports describe SQL injection in /api/login via the username parameter</reason> </dedupe_result> OR if not a duplicate: <dedupe_result> <is_duplicate>false</is_duplicate> <duplicate_id></duplicate_id> <confidence>0.90</confidence> <reason>Different endpoints: candidate is /api/search, existing is /api/login</reason> </dedupe_result> RULES: - is_duplicate MUST be exactly "true" or "false" (lowercase) - duplicate_id MUST be the exact ID from existing reports or empty if not duplicate - confidence MUST be a decimal (your confidence level in the decision) - reason MUST be a specific explanation mentioning endpoint/parameter/root cause - DO NOT include any text outside the <dedupe_result> tags""" def _prepare_report_for_comparison(report: dict[str, Any]) -> dict[str, Any]: relevant_fields = [ "id", "title", "description", "impact", "target", "technical_analysis", "poc_description", "endpoint", "method", ] cleaned = {} for field in relevant_fields: if report.get(field): value = report[field] if isinstance(value, str) and len(value) > 8000: value = value[:8000] + "...[truncated]" cleaned[field] = value return cleaned def _extract_xml_field(content: str, field: str) -> str: pattern = rf"<{field}>(.*?)</{field}>" match = re.search(pattern, content, re.DOTALL | re.IGNORECASE) if match: return match.group(1).strip() return "" def _parse_dedupe_response(content: str) -> dict[str, Any]: result_match = re.search( r"<dedupe_result>(.*?)</dedupe_result>", content, re.DOTALL | re.IGNORECASE ) if not result_match: logger.warning(f"No <dedupe_result> block found in response: {content[:500]}") raise ValueError("No <dedupe_result> block found in response") result_content = result_match.group(1) is_duplicate_str = _extract_xml_field(result_content, "is_duplicate") duplicate_id = _extract_xml_field(result_content, "duplicate_id") confidence_str = _extract_xml_field(result_content, "confidence") reason = _extract_xml_field(result_content, "reason") is_duplicate = is_duplicate_str.lower() == "true" try: confidence = float(confidence_str) if confidence_str else 0.0 except ValueError: confidence = 0.0 return { "is_duplicate": is_duplicate, "duplicate_id": duplicate_id[:64] if duplicate_id else "", "confidence": confidence, "reason": reason[:500] if reason else "", } def check_duplicate( candidate: dict[str, Any], existing_reports: list[dict[str, Any]] ) -> dict[str, Any]: if not existing_reports: return { "is_duplicate": False, "duplicate_id": "", "confidence": 1.0, "reason": "No existing reports to compare against", } try: candidate_cleaned = _prepare_report_for_comparison(candidate) existing_cleaned = [_prepare_report_for_comparison(r) for r in existing_reports] comparison_data = {"candidate": candidate_cleaned, "existing_reports": existing_cleaned} model_name, api_key, api_base = resolve_llm_config() litellm_model, _ = resolve_strix_model(model_name) litellm_model = litellm_model or model_name messages = [ {"role": "system", "content": DEDUPE_SYSTEM_PROMPT}, { "role": "user", "content": ( f"Compare this candidate vulnerability against existing reports:\n\n" f"{json.dumps(comparison_data, indent=2)}\n\n" f"Respond with ONLY the <dedupe_result> XML block." ), }, ] completion_kwargs: dict[str, Any] = { "model": litellm_model, "messages": messages, "timeout": 120, } if api_key: completion_kwargs["api_key"] = api_key if api_base: completion_kwargs["api_base"] = api_base response = litellm.completion(**completion_kwargs) content = response.choices[0].message.content if not content: return { "is_duplicate": False, "duplicate_id": "", "confidence": 0.0, "reason": "Empty response from LLM", } result = _parse_dedupe_response(content) logger.info( f"Deduplication check: is_duplicate={result['is_duplicate']}, " f"confidence={result['confidence']}, reason={result['reason'][:100]}" ) except Exception as e: logger.exception("Error during vulnerability deduplication check") return { "is_duplicate": False, "duplicate_id": "", "confidence": 0.0, "reason": f"Deduplication check failed: {e}", "error": str(e), } else: return result
{ "repo_id": "usestrix/strix", "file_path": "strix/llm/dedupe.py", "license": "Apache License 2.0", "lines": 171, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/interface/streaming_parser.py
import html import re from dataclasses import dataclass from typing import Literal from strix.llm.utils import normalize_tool_format _FUNCTION_TAG_PREFIX = "<function=" _INVOKE_TAG_PREFIX = "<invoke " _FUNC_PATTERN = re.compile(r"<function=([^>]+)>") _FUNC_END_PATTERN = re.compile(r"</function>") _COMPLETE_PARAM_PATTERN = re.compile(r"<parameter=([^>]+)>(.*?)</parameter>", re.DOTALL) _INCOMPLETE_PARAM_PATTERN = re.compile(r"<parameter=([^>]+)>(.*)$", re.DOTALL) def _get_safe_content(content: str) -> tuple[str, str]: if not content: return "", "" last_lt = content.rfind("<") if last_lt == -1: return content, "" suffix = content[last_lt:] if _FUNCTION_TAG_PREFIX.startswith(suffix) or _INVOKE_TAG_PREFIX.startswith(suffix): return content[:last_lt], suffix return content, "" @dataclass class StreamSegment: type: Literal["text", "tool"] content: str tool_name: str | None = None args: dict[str, str] | None = None is_complete: bool = False def parse_streaming_content(content: str) -> list[StreamSegment]: if not content: return [] content = normalize_tool_format(content) segments: list[StreamSegment] = [] func_matches = list(_FUNC_PATTERN.finditer(content)) if not func_matches: safe_content, _ = _get_safe_content(content) text = safe_content.strip() if text: segments.append(StreamSegment(type="text", content=text)) return segments first_func_start = func_matches[0].start() if first_func_start > 0: text_before = content[:first_func_start].strip() if text_before: segments.append(StreamSegment(type="text", content=text_before)) for i, match in enumerate(func_matches): tool_name = match.group(1) func_start = match.end() func_end_match = _FUNC_END_PATTERN.search(content, func_start) if func_end_match: func_body = content[func_start : func_end_match.start()] is_complete = True end_pos = func_end_match.end() else: if i + 1 < len(func_matches): next_func_start = func_matches[i + 1].start() func_body = content[func_start:next_func_start] else: func_body = content[func_start:] is_complete = False end_pos = len(content) args = _parse_streaming_params(func_body) segments.append( StreamSegment( type="tool", content=func_body, tool_name=tool_name, args=args, is_complete=is_complete, ) ) if is_complete and i + 1 < len(func_matches): next_start = func_matches[i + 1].start() text_between = content[end_pos:next_start].strip() if text_between: segments.append(StreamSegment(type="text", content=text_between)) return segments def _parse_streaming_params(func_body: str) -> dict[str, str]: args: dict[str, str] = {} complete_matches = list(_COMPLETE_PARAM_PATTERN.finditer(func_body)) complete_end_pos = 0 for match in complete_matches: param_name = match.group(1) param_value = html.unescape(match.group(2).strip()) args[param_name] = param_value complete_end_pos = max(complete_end_pos, match.end()) remaining = func_body[complete_end_pos:] incomplete_match = _INCOMPLETE_PARAM_PATTERN.search(remaining) if incomplete_match: param_name = incomplete_match.group(1) param_value = html.unescape(incomplete_match.group(2).strip()) args[param_name] = param_value return args
{ "repo_id": "usestrix/strix", "file_path": "strix/interface/streaming_parser.py", "license": "Apache License 2.0", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/interface/tool_components/agent_message_renderer.py
from functools import cache from typing import Any, ClassVar from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.styles import get_style_by_name from pygments.util import ClassNotFound from rich.text import Text from textual.widgets import Static from .base_renderer import BaseToolRenderer from .registry import register_tool_renderer _HEADER_STYLES = [ ("###### ", 7, "bold #4ade80"), ("##### ", 6, "bold #22c55e"), ("#### ", 5, "bold #16a34a"), ("### ", 4, "bold #15803d"), ("## ", 3, "bold #22c55e"), ("# ", 2, "bold #4ade80"), ] @cache def _get_style_colors() -> dict[Any, str]: style = get_style_by_name("native") return {token: f"#{style_def['color']}" for token, style_def in style if style_def["color"]} def _get_token_color(token_type: Any) -> str | None: colors = _get_style_colors() while token_type: if token_type in colors: return colors[token_type] token_type = token_type.parent return None def _highlight_code(code: str, language: str | None = None) -> Text: text = Text() try: lexer = get_lexer_by_name(language) if language else guess_lexer(code) except ClassNotFound: text.append(code, style="#d4d4d4") return text for token_type, token_value in lexer.get_tokens(code): if not token_value: continue color = _get_token_color(token_type) text.append(token_value, style=color) return text def _try_parse_header(line: str) -> tuple[str, str] | None: for prefix, strip_len, style in _HEADER_STYLES: if line.startswith(prefix): return (line[strip_len:], style) return None def _apply_markdown_styles(text: str) -> Text: # noqa: PLR0912 result = Text() lines = text.split("\n") in_code_block = False code_block_lang: str | None = None code_block_lines: list[str] = [] for i, line in enumerate(lines): if i > 0 and not in_code_block: result.append("\n") if line.startswith("```"): if not in_code_block: in_code_block = True code_block_lang = line[3:].strip() or None code_block_lines = [] if i > 0: result.append("\n") else: in_code_block = False code_content = "\n".join(code_block_lines) if code_content: result.append_text(_highlight_code(code_content, code_block_lang)) code_block_lines = [] code_block_lang = None continue if in_code_block: code_block_lines.append(line) continue header = _try_parse_header(line) if header: result.append(header[0], style=header[1]) elif line.startswith("> "): result.append("┃ ", style="#22c55e") result.append_text(_process_inline_formatting(line[2:])) elif line.startswith(("- ", "* ")): result.append("• ", style="#22c55e") result.append_text(_process_inline_formatting(line[2:])) elif len(line) > 2 and line[0].isdigit() and line[1:3] in (". ", ") "): result.append(line[0] + ". ", style="#22c55e") result.append_text(_process_inline_formatting(line[2:])) elif line.strip() in ("---", "***", "___"): result.append("─" * 40, style="#22c55e") else: result.append_text(_process_inline_formatting(line)) if in_code_block and code_block_lines: code_content = "\n".join(code_block_lines) result.append_text(_highlight_code(code_content, code_block_lang)) return result def _process_inline_formatting(line: str) -> Text: result = Text() i = 0 n = len(line) while i < n: if i + 1 < n and line[i : i + 2] in ("**", "__"): marker = line[i : i + 2] end = line.find(marker, i + 2) if end != -1: result.append(line[i + 2 : end], style="bold #4ade80") i = end + 2 continue if i + 1 < n and line[i : i + 2] == "~~": end = line.find("~~", i + 2) if end != -1: result.append(line[i + 2 : end], style="strike #525252") i = end + 2 continue if line[i] == "`": end = line.find("`", i + 1) if end != -1: result.append(line[i + 1 : end], style="bold #22c55e on #0a0a0a") i = end + 1 continue if line[i] in ("*", "_"): marker = line[i] if i + 1 < n and line[i + 1] != marker: end = line.find(marker, i + 1) if end != -1 and (end + 1 >= n or line[end + 1] != marker): result.append(line[i + 1 : end], style="italic #86efac") i = end + 1 continue result.append(line[i]) i += 1 return result @register_tool_renderer class AgentMessageRenderer(BaseToolRenderer): tool_name: ClassVar[str] = "agent_message" css_classes: ClassVar[list[str]] = ["chat-message", "agent-message"] @classmethod def render(cls, tool_data: dict[str, Any]) -> Static: content = tool_data.get("content", "") if not content: return Static(Text(), classes=" ".join(cls.css_classes)) styled_text = _apply_markdown_styles(content) return Static(styled_text, classes=" ".join(cls.css_classes)) @classmethod def render_simple(cls, content: str) -> Text: if not content: return Text() from strix.llm.utils import clean_content cleaned = clean_content(content) if not cleaned: return Text() return _apply_markdown_styles(cleaned)
{ "repo_id": "usestrix/strix", "file_path": "strix/interface/tool_components/agent_message_renderer.py", "license": "Apache License 2.0", "lines": 148, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/interface/tool_components/todo_renderer.py
from typing import Any, ClassVar from rich.text import Text from textual.widgets import Static from .base_renderer import BaseToolRenderer from .registry import register_tool_renderer STATUS_MARKERS: dict[str, str] = { "pending": "[ ]", "in_progress": "[~]", "done": "[•]", } def _format_todo_lines(text: Text, result: dict[str, Any]) -> None: todos = result.get("todos") if not isinstance(todos, list) or not todos: text.append("\n ") text.append("No todos", style="dim") return for todo in todos: status = todo.get("status", "pending") marker = STATUS_MARKERS.get(status, STATUS_MARKERS["pending"]) title = todo.get("title", "").strip() or "(untitled)" text.append("\n ") text.append(marker) text.append(" ") if status == "done": text.append(title, style="dim strike") elif status == "in_progress": text.append(title, style="italic") else: text.append(title) @register_tool_renderer class CreateTodoRenderer(BaseToolRenderer): tool_name: ClassVar[str] = "create_todo" css_classes: ClassVar[list[str]] = ["tool-call", "todo-tool"] @classmethod def render(cls, tool_data: dict[str, Any]) -> Static: result = tool_data.get("result") text = Text() text.append("📋 ") text.append("Todo", style="bold #a78bfa") if isinstance(result, str) and result.strip(): text.append("\n ") text.append(result.strip(), style="dim") elif result and isinstance(result, dict): if result.get("success"): _format_todo_lines(text, result) else: error = result.get("error", "Failed to create todo") text.append("\n ") text.append(error, style="#ef4444") else: text.append("\n ") text.append("Creating...", style="dim") css_classes = cls.get_css_classes("completed") return Static(text, classes=css_classes) @register_tool_renderer class ListTodosRenderer(BaseToolRenderer): tool_name: ClassVar[str] = "list_todos" css_classes: ClassVar[list[str]] = ["tool-call", "todo-tool"] @classmethod def render(cls, tool_data: dict[str, Any]) -> Static: result = tool_data.get("result") text = Text() text.append("📋 ") text.append("Todos", style="bold #a78bfa") if isinstance(result, str) and result.strip(): text.append("\n ") text.append(result.strip(), style="dim") elif result and isinstance(result, dict): if result.get("success"): _format_todo_lines(text, result) else: error = result.get("error", "Unable to list todos") text.append("\n ") text.append(error, style="#ef4444") else: text.append("\n ") text.append("Loading...", style="dim") css_classes = cls.get_css_classes("completed") return Static(text, classes=css_classes) @register_tool_renderer class UpdateTodoRenderer(BaseToolRenderer): tool_name: ClassVar[str] = "update_todo" css_classes: ClassVar[list[str]] = ["tool-call", "todo-tool"] @classmethod def render(cls, tool_data: dict[str, Any]) -> Static: result = tool_data.get("result") text = Text() text.append("📋 ") text.append("Todo Updated", style="bold #a78bfa") if isinstance(result, str) and result.strip(): text.append("\n ") text.append(result.strip(), style="dim") elif result and isinstance(result, dict): if result.get("success"): _format_todo_lines(text, result) else: error = result.get("error", "Failed to update todo") text.append("\n ") text.append(error, style="#ef4444") else: text.append("\n ") text.append("Updating...", style="dim") css_classes = cls.get_css_classes("completed") return Static(text, classes=css_classes) @register_tool_renderer class MarkTodoDoneRenderer(BaseToolRenderer): tool_name: ClassVar[str] = "mark_todo_done" css_classes: ClassVar[list[str]] = ["tool-call", "todo-tool"] @classmethod def render(cls, tool_data: dict[str, Any]) -> Static: result = tool_data.get("result") text = Text() text.append("📋 ") text.append("Todo Completed", style="bold #a78bfa") if isinstance(result, str) and result.strip(): text.append("\n ") text.append(result.strip(), style="dim") elif result and isinstance(result, dict): if result.get("success"): _format_todo_lines(text, result) else: error = result.get("error", "Failed to mark todo done") text.append("\n ") text.append(error, style="#ef4444") else: text.append("\n ") text.append("Marking done...", style="dim") css_classes = cls.get_css_classes("completed") return Static(text, classes=css_classes) @register_tool_renderer class MarkTodoPendingRenderer(BaseToolRenderer): tool_name: ClassVar[str] = "mark_todo_pending" css_classes: ClassVar[list[str]] = ["tool-call", "todo-tool"] @classmethod def render(cls, tool_data: dict[str, Any]) -> Static: result = tool_data.get("result") text = Text() text.append("📋 ") text.append("Todo Reopened", style="bold #f59e0b") if isinstance(result, str) and result.strip(): text.append("\n ") text.append(result.strip(), style="dim") elif result and isinstance(result, dict): if result.get("success"): _format_todo_lines(text, result) else: error = result.get("error", "Failed to reopen todo") text.append("\n ") text.append(error, style="#ef4444") else: text.append("\n ") text.append("Reopening...", style="dim") css_classes = cls.get_css_classes("completed") return Static(text, classes=css_classes) @register_tool_renderer class DeleteTodoRenderer(BaseToolRenderer): tool_name: ClassVar[str] = "delete_todo" css_classes: ClassVar[list[str]] = ["tool-call", "todo-tool"] @classmethod def render(cls, tool_data: dict[str, Any]) -> Static: result = tool_data.get("result") text = Text() text.append("📋 ") text.append("Todo Removed", style="bold #94a3b8") if isinstance(result, str) and result.strip(): text.append("\n ") text.append(result.strip(), style="dim") elif result and isinstance(result, dict): if result.get("success"): _format_todo_lines(text, result) else: error = result.get("error", "Failed to remove todo") text.append("\n ") text.append(error, style="#ef4444") else: text.append("\n ") text.append("Removing...", style="dim") css_classes = cls.get_css_classes("completed") return Static(text, classes=css_classes)
{ "repo_id": "usestrix/strix", "file_path": "strix/interface/tool_components/todo_renderer.py", "license": "Apache License 2.0", "lines": 179, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/tools/todo/todo_actions.py
import json import uuid from datetime import UTC, datetime from typing import Any from strix.tools.registry import register_tool VALID_PRIORITIES = ["low", "normal", "high", "critical"] VALID_STATUSES = ["pending", "in_progress", "done"] _todos_storage: dict[str, dict[str, dict[str, Any]]] = {} def _get_agent_todos(agent_id: str) -> dict[str, dict[str, Any]]: if agent_id not in _todos_storage: _todos_storage[agent_id] = {} return _todos_storage[agent_id] def _normalize_priority(priority: str | None, default: str = "normal") -> str: candidate = (priority or default or "normal").lower() if candidate not in VALID_PRIORITIES: raise ValueError(f"Invalid priority. Must be one of: {', '.join(VALID_PRIORITIES)}") return candidate def _sorted_todos(agent_id: str) -> list[dict[str, Any]]: agent_todos = _get_agent_todos(agent_id) todos_list: list[dict[str, Any]] = [] for todo_id, todo in agent_todos.items(): entry = todo.copy() entry["todo_id"] = todo_id todos_list.append(entry) priority_order = {"critical": 0, "high": 1, "normal": 2, "low": 3} status_order = {"done": 0, "in_progress": 1, "pending": 2} todos_list.sort( key=lambda x: ( status_order.get(x.get("status", "pending"), 99), priority_order.get(x.get("priority", "normal"), 99), x.get("created_at", ""), ) ) return todos_list def _normalize_todo_ids(raw_ids: Any) -> list[str]: if raw_ids is None: return [] if isinstance(raw_ids, str): stripped = raw_ids.strip() if not stripped: return [] try: data = json.loads(stripped) except json.JSONDecodeError: data = stripped.split(",") if "," in stripped else [stripped] if isinstance(data, list): return [str(item).strip() for item in data if str(item).strip()] return [str(data).strip()] if isinstance(raw_ids, list): return [str(item).strip() for item in raw_ids if str(item).strip()] return [str(raw_ids).strip()] def _normalize_bulk_updates(raw_updates: Any) -> list[dict[str, Any]]: if raw_updates is None: return [] data = raw_updates if isinstance(raw_updates, str): stripped = raw_updates.strip() if not stripped: return [] try: data = json.loads(stripped) except json.JSONDecodeError as e: raise ValueError("Updates must be valid JSON") from e if isinstance(data, dict): data = [data] if not isinstance(data, list): raise TypeError("Updates must be a list of update objects") normalized: list[dict[str, Any]] = [] for item in data: if not isinstance(item, dict): raise TypeError("Each update must be an object with todo_id") todo_id = item.get("todo_id") or item.get("id") if not todo_id: raise ValueError("Each update must include 'todo_id'") normalized.append( { "todo_id": str(todo_id).strip(), "title": item.get("title"), "description": item.get("description"), "priority": item.get("priority"), "status": item.get("status"), } ) return normalized def _normalize_bulk_todos(raw_todos: Any) -> list[dict[str, Any]]: if raw_todos is None: return [] data = raw_todos if isinstance(raw_todos, str): stripped = raw_todos.strip() if not stripped: return [] try: data = json.loads(stripped) except json.JSONDecodeError: entries = [line.strip(" -*\t") for line in stripped.splitlines() if line.strip(" -*\t")] return [{"title": entry} for entry in entries] if isinstance(data, dict): data = [data] if not isinstance(data, list): raise TypeError("Todos must be provided as a list, dict, or JSON string") normalized: list[dict[str, Any]] = [] for item in data: if isinstance(item, str): title = item.strip() if title: normalized.append({"title": title}) continue if not isinstance(item, dict): raise TypeError("Each todo entry must be a string or object with a title") title = item.get("title", "") if not isinstance(title, str) or not title.strip(): raise ValueError("Each todo entry must include a non-empty 'title'") normalized.append( { "title": title.strip(), "description": (item.get("description") or "").strip() or None, "priority": item.get("priority"), } ) return normalized @register_tool(sandbox_execution=False) def create_todo( agent_state: Any, title: str | None = None, description: str | None = None, priority: str = "normal", todos: Any | None = None, ) -> dict[str, Any]: try: agent_id = agent_state.agent_id default_priority = _normalize_priority(priority) tasks_to_create: list[dict[str, Any]] = [] if todos is not None: tasks_to_create.extend(_normalize_bulk_todos(todos)) if title and title.strip(): tasks_to_create.append( { "title": title.strip(), "description": description.strip() if description else None, "priority": default_priority, } ) if not tasks_to_create: return { "success": False, "error": "Provide a title or 'todos' list to create.", "todo_id": None, } agent_todos = _get_agent_todos(agent_id) created: list[dict[str, Any]] = [] for task in tasks_to_create: task_priority = _normalize_priority(task.get("priority"), default_priority) todo_id = str(uuid.uuid4())[:6] timestamp = datetime.now(UTC).isoformat() todo = { "title": task["title"], "description": task.get("description"), "priority": task_priority, "status": "pending", "created_at": timestamp, "updated_at": timestamp, "completed_at": None, } agent_todos[todo_id] = todo created.append( { "todo_id": todo_id, "title": task["title"], "priority": task_priority, } ) except (ValueError, TypeError) as e: return {"success": False, "error": f"Failed to create todo: {e}", "todo_id": None} else: todos_list = _sorted_todos(agent_id) response: dict[str, Any] = { "success": True, "created": created, "count": len(created), "todos": todos_list, "total_count": len(todos_list), } return response @register_tool(sandbox_execution=False) def list_todos( agent_state: Any, status: str | None = None, priority: str | None = None, ) -> dict[str, Any]: try: agent_id = agent_state.agent_id agent_todos = _get_agent_todos(agent_id) status_filter = status.lower() if isinstance(status, str) else None priority_filter = priority.lower() if isinstance(priority, str) else None todos_list = [] for todo_id, todo in agent_todos.items(): if status_filter and todo.get("status") != status_filter: continue if priority_filter and todo.get("priority") != priority_filter: continue todo_with_id = todo.copy() todo_with_id["todo_id"] = todo_id todos_list.append(todo_with_id) priority_order = {"critical": 0, "high": 1, "normal": 2, "low": 3} status_order = {"done": 0, "in_progress": 1, "pending": 2} todos_list.sort( key=lambda x: ( status_order.get(x.get("status", "pending"), 99), priority_order.get(x.get("priority", "normal"), 99), x.get("created_at", ""), ) ) summary_counts = { "pending": 0, "in_progress": 0, "done": 0, } for todo in todos_list: status_value = todo.get("status", "pending") if status_value not in summary_counts: summary_counts[status_value] = 0 summary_counts[status_value] += 1 return { "success": True, "todos": todos_list, "total_count": len(todos_list), "summary": summary_counts, } except (ValueError, TypeError) as e: return { "success": False, "error": f"Failed to list todos: {e}", "todos": [], "total_count": 0, "summary": {"pending": 0, "in_progress": 0, "done": 0}, } def _apply_single_update( agent_todos: dict[str, dict[str, Any]], todo_id: str, title: str | None = None, description: str | None = None, priority: str | None = None, status: str | None = None, ) -> dict[str, Any] | None: if todo_id not in agent_todos: return {"todo_id": todo_id, "error": f"Todo with ID '{todo_id}' not found"} todo = agent_todos[todo_id] if title is not None: if not title.strip(): return {"todo_id": todo_id, "error": "Title cannot be empty"} todo["title"] = title.strip() if description is not None: todo["description"] = description.strip() if description else None if priority is not None: try: todo["priority"] = _normalize_priority(priority, str(todo.get("priority", "normal"))) except ValueError as exc: return {"todo_id": todo_id, "error": str(exc)} if status is not None: status_candidate = status.lower() if status_candidate not in VALID_STATUSES: return { "todo_id": todo_id, "error": f"Invalid status. Must be one of: {', '.join(VALID_STATUSES)}", } todo["status"] = status_candidate if status_candidate == "done": todo["completed_at"] = datetime.now(UTC).isoformat() else: todo["completed_at"] = None todo["updated_at"] = datetime.now(UTC).isoformat() return None @register_tool(sandbox_execution=False) def update_todo( agent_state: Any, todo_id: str | None = None, title: str | None = None, description: str | None = None, priority: str | None = None, status: str | None = None, updates: Any | None = None, ) -> dict[str, Any]: try: agent_id = agent_state.agent_id agent_todos = _get_agent_todos(agent_id) updates_to_apply: list[dict[str, Any]] = [] if updates is not None: updates_to_apply.extend(_normalize_bulk_updates(updates)) if todo_id is not None: updates_to_apply.append( { "todo_id": todo_id, "title": title, "description": description, "priority": priority, "status": status, } ) if not updates_to_apply: return { "success": False, "error": "Provide todo_id or 'updates' list to update.", } updated: list[str] = [] errors: list[dict[str, Any]] = [] for update in updates_to_apply: error = _apply_single_update( agent_todos, update["todo_id"], update.get("title"), update.get("description"), update.get("priority"), update.get("status"), ) if error: errors.append(error) else: updated.append(update["todo_id"]) todos_list = _sorted_todos(agent_id) response: dict[str, Any] = { "success": len(errors) == 0, "updated": updated, "updated_count": len(updated), "todos": todos_list, "total_count": len(todos_list), } if errors: response["errors"] = errors except (ValueError, TypeError) as e: return {"success": False, "error": str(e)} else: return response @register_tool(sandbox_execution=False) def mark_todo_done( agent_state: Any, todo_id: str | None = None, todo_ids: Any | None = None, ) -> dict[str, Any]: try: agent_id = agent_state.agent_id agent_todos = _get_agent_todos(agent_id) ids_to_mark: list[str] = [] if todo_ids is not None: ids_to_mark.extend(_normalize_todo_ids(todo_ids)) if todo_id is not None: ids_to_mark.append(todo_id) if not ids_to_mark: return {"success": False, "error": "Provide todo_id or todo_ids to mark as done."} marked: list[str] = [] errors: list[dict[str, Any]] = [] timestamp = datetime.now(UTC).isoformat() for tid in ids_to_mark: if tid not in agent_todos: errors.append({"todo_id": tid, "error": f"Todo with ID '{tid}' not found"}) continue todo = agent_todos[tid] todo["status"] = "done" todo["completed_at"] = timestamp todo["updated_at"] = timestamp marked.append(tid) todos_list = _sorted_todos(agent_id) response: dict[str, Any] = { "success": len(errors) == 0, "marked_done": marked, "marked_count": len(marked), "todos": todos_list, "total_count": len(todos_list), } if errors: response["errors"] = errors except (ValueError, TypeError) as e: return {"success": False, "error": str(e)} else: return response @register_tool(sandbox_execution=False) def mark_todo_pending( agent_state: Any, todo_id: str | None = None, todo_ids: Any | None = None, ) -> dict[str, Any]: try: agent_id = agent_state.agent_id agent_todos = _get_agent_todos(agent_id) ids_to_mark: list[str] = [] if todo_ids is not None: ids_to_mark.extend(_normalize_todo_ids(todo_ids)) if todo_id is not None: ids_to_mark.append(todo_id) if not ids_to_mark: return {"success": False, "error": "Provide todo_id or todo_ids to mark as pending."} marked: list[str] = [] errors: list[dict[str, Any]] = [] timestamp = datetime.now(UTC).isoformat() for tid in ids_to_mark: if tid not in agent_todos: errors.append({"todo_id": tid, "error": f"Todo with ID '{tid}' not found"}) continue todo = agent_todos[tid] todo["status"] = "pending" todo["completed_at"] = None todo["updated_at"] = timestamp marked.append(tid) todos_list = _sorted_todos(agent_id) response: dict[str, Any] = { "success": len(errors) == 0, "marked_pending": marked, "marked_count": len(marked), "todos": todos_list, "total_count": len(todos_list), } if errors: response["errors"] = errors except (ValueError, TypeError) as e: return {"success": False, "error": str(e)} else: return response @register_tool(sandbox_execution=False) def delete_todo( agent_state: Any, todo_id: str | None = None, todo_ids: Any | None = None, ) -> dict[str, Any]: try: agent_id = agent_state.agent_id agent_todos = _get_agent_todos(agent_id) ids_to_delete: list[str] = [] if todo_ids is not None: ids_to_delete.extend(_normalize_todo_ids(todo_ids)) if todo_id is not None: ids_to_delete.append(todo_id) if not ids_to_delete: return {"success": False, "error": "Provide todo_id or todo_ids to delete."} deleted: list[str] = [] errors: list[dict[str, Any]] = [] for tid in ids_to_delete: if tid not in agent_todos: errors.append({"todo_id": tid, "error": f"Todo with ID '{tid}' not found"}) continue del agent_todos[tid] deleted.append(tid) todos_list = _sorted_todos(agent_id) response: dict[str, Any] = { "success": len(errors) == 0, "deleted": deleted, "deleted_count": len(deleted), "todos": todos_list, "total_count": len(todos_list), } if errors: response["errors"] = errors except (ValueError, TypeError) as e: return {"success": False, "error": str(e)} else: return response
{ "repo_id": "usestrix/strix", "file_path": "strix/tools/todo/todo_actions.py", "license": "Apache License 2.0", "lines": 455, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/interface/utils.py
import ipaddress import json import re import secrets import shutil import subprocess import sys import tempfile from pathlib import Path from typing import Any from urllib.error import HTTPError, URLError from urllib.parse import urlparse from urllib.request import Request, urlopen import docker from docker.errors import DockerException, ImageNotFound from rich.console import Console from rich.panel import Panel from rich.text import Text # Token formatting utilities def format_token_count(count: float) -> str: count = int(count) if count >= 1_000_000: return f"{count / 1_000_000:.1f}M" if count >= 1_000: return f"{count / 1_000:.1f}K" return str(count) # Display utilities def get_severity_color(severity: str) -> str: severity_colors = { "critical": "#dc2626", "high": "#ea580c", "medium": "#d97706", "low": "#65a30d", "info": "#0284c7", } return severity_colors.get(severity, "#6b7280") def get_cvss_color(cvss_score: float) -> str: if cvss_score >= 9.0: return "#dc2626" if cvss_score >= 7.0: return "#ea580c" if cvss_score >= 4.0: return "#d97706" if cvss_score >= 0.1: return "#65a30d" return "#6b7280" def format_vulnerability_report(report: dict[str, Any]) -> Text: # noqa: PLR0912, PLR0915 """Format a vulnerability report for CLI display with all rich fields.""" field_style = "bold #4ade80" text = Text() title = report.get("title", "") if title: text.append("Vulnerability Report", style="bold #ea580c") text.append("\n\n") text.append("Title: ", style=field_style) text.append(title) severity = report.get("severity", "") if severity: text.append("\n\n") text.append("Severity: ", style=field_style) severity_color = get_severity_color(severity.lower()) text.append(severity.upper(), style=f"bold {severity_color}") cvss = report.get("cvss") if cvss is not None: text.append("\n\n") text.append("CVSS Score: ", style=field_style) cvss_color = get_cvss_color(cvss) text.append(f"{cvss:.1f}", style=f"bold {cvss_color}") target = report.get("target") if target: text.append("\n\n") text.append("Target: ", style=field_style) text.append(target) endpoint = report.get("endpoint") if endpoint: text.append("\n\n") text.append("Endpoint: ", style=field_style) text.append(endpoint) method = report.get("method") if method: text.append("\n\n") text.append("Method: ", style=field_style) text.append(method) cve = report.get("cve") if cve: text.append("\n\n") text.append("CVE: ", style=field_style) text.append(cve) cvss_breakdown = report.get("cvss_breakdown", {}) if cvss_breakdown: text.append("\n\n") cvss_parts = [] if cvss_breakdown.get("attack_vector"): cvss_parts.append(f"AV:{cvss_breakdown['attack_vector']}") if cvss_breakdown.get("attack_complexity"): cvss_parts.append(f"AC:{cvss_breakdown['attack_complexity']}") if cvss_breakdown.get("privileges_required"): cvss_parts.append(f"PR:{cvss_breakdown['privileges_required']}") if cvss_breakdown.get("user_interaction"): cvss_parts.append(f"UI:{cvss_breakdown['user_interaction']}") if cvss_breakdown.get("scope"): cvss_parts.append(f"S:{cvss_breakdown['scope']}") if cvss_breakdown.get("confidentiality"): cvss_parts.append(f"C:{cvss_breakdown['confidentiality']}") if cvss_breakdown.get("integrity"): cvss_parts.append(f"I:{cvss_breakdown['integrity']}") if cvss_breakdown.get("availability"): cvss_parts.append(f"A:{cvss_breakdown['availability']}") if cvss_parts: text.append("CVSS Vector: ", style=field_style) text.append("/".join(cvss_parts), style="dim") description = report.get("description") if description: text.append("\n\n") text.append("Description", style=field_style) text.append("\n") text.append(description) impact = report.get("impact") if impact: text.append("\n\n") text.append("Impact", style=field_style) text.append("\n") text.append(impact) technical_analysis = report.get("technical_analysis") if technical_analysis: text.append("\n\n") text.append("Technical Analysis", style=field_style) text.append("\n") text.append(technical_analysis) poc_description = report.get("poc_description") if poc_description: text.append("\n\n") text.append("PoC Description", style=field_style) text.append("\n") text.append(poc_description) poc_script_code = report.get("poc_script_code") if poc_script_code: text.append("\n\n") text.append("PoC Code", style=field_style) text.append("\n") text.append(poc_script_code, style="dim") code_locations = report.get("code_locations") if code_locations: text.append("\n\n") text.append("Code Locations", style=field_style) for i, loc in enumerate(code_locations): text.append("\n\n") text.append(f" Location {i + 1}: ", style="dim") text.append(loc.get("file", "unknown"), style="bold") start = loc.get("start_line") end = loc.get("end_line") if start is not None: if end and end != start: text.append(f":{start}-{end}") else: text.append(f":{start}") if loc.get("label"): text.append(f"\n {loc['label']}", style="italic dim") if loc.get("snippet"): text.append("\n ") text.append(loc["snippet"], style="dim") if loc.get("fix_before") or loc.get("fix_after"): text.append("\n Fix:") if loc.get("fix_before"): text.append("\n - ", style="dim") text.append(loc["fix_before"], style="dim") if loc.get("fix_after"): text.append("\n + ", style="dim") text.append(loc["fix_after"], style="dim") remediation_steps = report.get("remediation_steps") if remediation_steps: text.append("\n\n") text.append("Remediation", style=field_style) text.append("\n") text.append(remediation_steps) return text def _build_vulnerability_stats(stats_text: Text, tracer: Any) -> None: """Build vulnerability section of stats text.""" vuln_count = len(tracer.vulnerability_reports) if vuln_count > 0: severity_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0} for report in tracer.vulnerability_reports: severity = report.get("severity", "").lower() if severity in severity_counts: severity_counts[severity] += 1 stats_text.append("Vulnerabilities ", style="bold red") severity_parts = [] for severity in ["critical", "high", "medium", "low", "info"]: count = severity_counts[severity] if count > 0: severity_color = get_severity_color(severity) severity_text = Text() severity_text.append(f"{severity.upper()}: ", style=severity_color) severity_text.append(str(count), style=f"bold {severity_color}") severity_parts.append(severity_text) for i, part in enumerate(severity_parts): stats_text.append(part) if i < len(severity_parts) - 1: stats_text.append(" | ", style="dim white") stats_text.append(" (Total: ", style="dim white") stats_text.append(str(vuln_count), style="bold yellow") stats_text.append(")", style="dim white") stats_text.append("\n") else: stats_text.append("Vulnerabilities ", style="bold #22c55e") stats_text.append("0", style="bold white") stats_text.append(" (No exploitable vulnerabilities detected)", style="dim green") stats_text.append("\n") def _build_llm_stats(stats_text: Text, total_stats: dict[str, Any]) -> None: """Build LLM usage section of stats text.""" if total_stats["requests"] > 0: stats_text.append("\n") stats_text.append("Input Tokens ", style="dim") stats_text.append(format_token_count(total_stats["input_tokens"]), style="white") if total_stats["cached_tokens"] > 0: stats_text.append(" · ", style="dim white") stats_text.append("Cached Tokens ", style="dim") stats_text.append(format_token_count(total_stats["cached_tokens"]), style="white") stats_text.append(" · ", style="dim white") stats_text.append("Output Tokens ", style="dim") stats_text.append(format_token_count(total_stats["output_tokens"]), style="white") if total_stats["cost"] > 0: stats_text.append(" · ", style="dim white") stats_text.append("Cost ", style="dim") stats_text.append(f"${total_stats['cost']:.4f}", style="bold #fbbf24") else: stats_text.append("\n") stats_text.append("Cost ", style="dim") stats_text.append("$0.0000 ", style="#fbbf24") stats_text.append("· ", style="dim white") stats_text.append("Tokens ", style="dim") stats_text.append("0", style="white") def build_final_stats_text(tracer: Any) -> Text: """Build stats text for final output with detailed messages and LLM usage.""" stats_text = Text() if not tracer: return stats_text _build_vulnerability_stats(stats_text, tracer) tool_count = tracer.get_real_tool_count() agent_count = len(tracer.agents) stats_text.append("Agents", style="dim") stats_text.append(" ") stats_text.append(str(agent_count), style="bold white") stats_text.append(" · ", style="dim white") stats_text.append("Tools", style="dim") stats_text.append(" ") stats_text.append(str(tool_count), style="bold white") llm_stats = tracer.get_total_llm_stats() _build_llm_stats(stats_text, llm_stats["total"]) return stats_text def build_live_stats_text(tracer: Any, agent_config: dict[str, Any] | None = None) -> Text: stats_text = Text() if not tracer: return stats_text if agent_config: llm_config = agent_config["llm_config"] model = getattr(llm_config, "model_name", "Unknown") stats_text.append("Model ", style="dim") stats_text.append(model, style="white") stats_text.append("\n") vuln_count = len(tracer.vulnerability_reports) tool_count = tracer.get_real_tool_count() agent_count = len(tracer.agents) stats_text.append("Vulnerabilities ", style="dim") stats_text.append(f"{vuln_count}", style="white") stats_text.append("\n") if vuln_count > 0: severity_counts = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0} for report in tracer.vulnerability_reports: severity = report.get("severity", "").lower() if severity in severity_counts: severity_counts[severity] += 1 severity_parts = [] for severity in ["critical", "high", "medium", "low", "info"]: count = severity_counts[severity] if count > 0: severity_color = get_severity_color(severity) severity_text = Text() severity_text.append(f"{severity.upper()}: ", style=severity_color) severity_text.append(str(count), style=f"bold {severity_color}") severity_parts.append(severity_text) for i, part in enumerate(severity_parts): stats_text.append(part) if i < len(severity_parts) - 1: stats_text.append(" | ", style="dim white") stats_text.append("\n") stats_text.append("Agents ", style="dim") stats_text.append(str(agent_count), style="white") stats_text.append(" · ", style="dim white") stats_text.append("Tools ", style="dim") stats_text.append(str(tool_count), style="white") llm_stats = tracer.get_total_llm_stats() total_stats = llm_stats["total"] stats_text.append("\n") stats_text.append("Input Tokens ", style="dim") stats_text.append(format_token_count(total_stats["input_tokens"]), style="white") stats_text.append(" · ", style="dim white") stats_text.append("Cached Tokens ", style="dim") stats_text.append(format_token_count(total_stats["cached_tokens"]), style="white") stats_text.append("\n") stats_text.append("Output Tokens ", style="dim") stats_text.append(format_token_count(total_stats["output_tokens"]), style="white") stats_text.append(" · ", style="dim white") stats_text.append("Cost ", style="dim") stats_text.append(f"${total_stats['cost']:.4f}", style="#fbbf24") return stats_text def build_tui_stats_text(tracer: Any, agent_config: dict[str, Any] | None = None) -> Text: stats_text = Text() if not tracer: return stats_text if agent_config: llm_config = agent_config["llm_config"] model = getattr(llm_config, "model_name", "Unknown") stats_text.append(model, style="white") llm_stats = tracer.get_total_llm_stats() total_stats = llm_stats["total"] total_tokens = total_stats["input_tokens"] + total_stats["output_tokens"] if total_tokens > 0: stats_text.append("\n") stats_text.append(f"{format_token_count(total_tokens)} tokens", style="white") if total_stats["cost"] > 0: stats_text.append(" · ", style="white") stats_text.append(f"${total_stats['cost']:.2f}", style="white") caido_url = getattr(tracer, "caido_url", None) if caido_url: stats_text.append("\n") stats_text.append("Caido: ", style="bold white") stats_text.append(caido_url, style="white") return stats_text # Name generation utilities def _slugify_for_run_name(text: str, max_length: int = 32) -> str: text = text.lower().strip() text = re.sub(r"[^a-z0-9]+", "-", text) text = text.strip("-") if len(text) > max_length: text = text[:max_length].rstrip("-") return text or "pentest" def _derive_target_label_for_run_name(targets_info: list[dict[str, Any]] | None) -> str: # noqa: PLR0911 if not targets_info: return "pentest" first = targets_info[0] target_type = first.get("type") details = first.get("details", {}) or {} original = first.get("original", "") or "" if target_type == "web_application": url = details.get("target_url", original) try: parsed = urlparse(url) return str(parsed.netloc or parsed.path or url) except Exception: # noqa: BLE001 return str(url) if target_type == "repository": repo = details.get("target_repo", original) parsed = urlparse(repo) path = parsed.path or repo name = path.rstrip("/").split("/")[-1] or path if name.endswith(".git"): name = name[:-4] return str(name) if target_type == "local_code": path_str = details.get("target_path", original) try: return str(Path(path_str).name or path_str) except Exception: # noqa: BLE001 return str(path_str) if target_type == "ip_address": return str(details.get("target_ip", original) or original) return str(original or "pentest") def generate_run_name(targets_info: list[dict[str, Any]] | None = None) -> str: base_label = _derive_target_label_for_run_name(targets_info) slug = _slugify_for_run_name(base_label) random_suffix = secrets.token_hex(2) return f"{slug}_{random_suffix}" # Target processing utilities def _is_http_git_repo(url: str) -> bool: check_url = f"{url.rstrip('/')}/info/refs?service=git-upload-pack" try: req = Request(check_url, headers={"User-Agent": "git/strix"}) # noqa: S310 with urlopen(req, timeout=10) as resp: # noqa: S310 # nosec B310 return "x-git-upload-pack-advertisement" in resp.headers.get("Content-Type", "") except HTTPError as e: return e.code == 401 except (URLError, OSError, ValueError): return False def infer_target_type(target: str) -> tuple[str, dict[str, str]]: # noqa: PLR0911, PLR0912 if not target or not isinstance(target, str): raise ValueError("Target must be a non-empty string") target = target.strip() if target.startswith("git@"): return "repository", {"target_repo": target} if target.startswith("git://"): return "repository", {"target_repo": target} parsed = urlparse(target) if parsed.scheme in ("http", "https"): if parsed.username or parsed.password: return "repository", {"target_repo": target} if parsed.path.rstrip("/").endswith(".git"): return "repository", {"target_repo": target} if parsed.query or parsed.fragment: return "web_application", {"target_url": target} path_segments = [s for s in parsed.path.split("/") if s] if len(path_segments) >= 2 and _is_http_git_repo(target): return "repository", {"target_repo": target} return "web_application", {"target_url": target} try: ip_obj = ipaddress.ip_address(target) except ValueError: pass else: return "ip_address", {"target_ip": str(ip_obj)} path = Path(target).expanduser() try: if path.exists(): if path.is_dir(): return "local_code", {"target_path": str(path.resolve())} raise ValueError(f"Path exists but is not a directory: {target}") except (OSError, RuntimeError) as e: raise ValueError(f"Invalid path: {target} - {e!s}") from e if target.endswith(".git"): return "repository", {"target_repo": target} if "/" in target: host_part, _, path_part = target.partition("/") if "." in host_part and not host_part.startswith(".") and path_part: full_url = f"https://{target}" if _is_http_git_repo(full_url): return "repository", {"target_repo": full_url} return "web_application", {"target_url": full_url} if "." in target and "/" not in target and not target.startswith("."): parts = target.split(".") if len(parts) >= 2 and all(p and p.strip() for p in parts): return "web_application", {"target_url": f"https://{target}"} raise ValueError( f"Invalid target: {target}\n" "Target must be one of:\n" "- A valid URL (http:// or https://)\n" "- A Git repository URL (https://host/org/repo or git@host:org/repo.git)\n" "- A local directory path\n" "- A domain name (e.g., example.com)\n" "- An IP address (e.g., 192.168.1.10)" ) def sanitize_name(name: str) -> str: sanitized = re.sub(r"[^A-Za-z0-9._-]", "-", name.strip()) return sanitized or "target" def derive_repo_base_name(repo_url: str) -> str: if repo_url.endswith("/"): repo_url = repo_url[:-1] if ":" in repo_url and repo_url.startswith("git@"): path_part = repo_url.split(":", 1)[1] else: path_part = urlparse(repo_url).path or repo_url candidate = path_part.split("/")[-1] if candidate.endswith(".git"): candidate = candidate[:-4] return sanitize_name(candidate or "repository") def derive_local_base_name(path_str: str) -> str: try: base = Path(path_str).resolve().name except (OSError, RuntimeError): base = Path(path_str).name return sanitize_name(base or "workspace") def assign_workspace_subdirs(targets_info: list[dict[str, Any]]) -> None: name_counts: dict[str, int] = {} for target in targets_info: target_type = target["type"] details = target["details"] base_name: str | None = None if target_type == "repository": base_name = derive_repo_base_name(details["target_repo"]) elif target_type == "local_code": base_name = derive_local_base_name(details.get("target_path", "local")) if base_name is None: continue count = name_counts.get(base_name, 0) + 1 name_counts[base_name] = count workspace_subdir = base_name if count == 1 else f"{base_name}-{count}" details["workspace_subdir"] = workspace_subdir def collect_local_sources(targets_info: list[dict[str, Any]]) -> list[dict[str, str]]: local_sources: list[dict[str, str]] = [] for target_info in targets_info: details = target_info["details"] workspace_subdir = details.get("workspace_subdir") if target_info["type"] == "local_code" and "target_path" in details: local_sources.append( { "source_path": details["target_path"], "workspace_subdir": workspace_subdir, } ) elif target_info["type"] == "repository" and "cloned_repo_path" in details: local_sources.append( { "source_path": details["cloned_repo_path"], "workspace_subdir": workspace_subdir, } ) return local_sources def _is_localhost_host(host: str) -> bool: host_lower = host.lower().strip("[]") if host_lower in ("localhost", "0.0.0.0", "::1"): # nosec B104 return True try: ip = ipaddress.ip_address(host_lower) if isinstance(ip, ipaddress.IPv4Address): return ip.is_loopback # 127.0.0.0/8 if isinstance(ip, ipaddress.IPv6Address): return ip.is_loopback # ::1 except ValueError: pass return False def rewrite_localhost_targets(targets_info: list[dict[str, Any]], host_gateway: str) -> None: from yarl import URL # type: ignore[import-not-found] for target_info in targets_info: target_type = target_info.get("type") details = target_info.get("details", {}) if target_type == "web_application": target_url = details.get("target_url", "") try: url = URL(target_url) except (ValueError, TypeError): continue if url.host and _is_localhost_host(url.host): details["target_url"] = str(url.with_host(host_gateway)) elif target_type == "ip_address": target_ip = details.get("target_ip", "") if target_ip and _is_localhost_host(target_ip): details["target_ip"] = host_gateway # Repository utilities def clone_repository(repo_url: str, run_name: str, dest_name: str | None = None) -> str: console = Console() git_executable = shutil.which("git") if git_executable is None: raise FileNotFoundError("Git executable not found in PATH") temp_dir = Path(tempfile.gettempdir()) / "strix_repos" / run_name temp_dir.mkdir(parents=True, exist_ok=True) if dest_name: repo_name = dest_name else: repo_name = Path(repo_url).stem if repo_url.endswith(".git") else Path(repo_url).name clone_path = temp_dir / repo_name if clone_path.exists(): shutil.rmtree(clone_path) try: with console.status(f"[bold cyan]Cloning repository {repo_url}...", spinner="dots"): subprocess.run( # noqa: S603 [ git_executable, "clone", repo_url, str(clone_path), ], capture_output=True, text=True, check=True, ) return str(clone_path.absolute()) except subprocess.CalledProcessError as e: error_text = Text() error_text.append("REPOSITORY CLONE FAILED", style="bold red") error_text.append("\n\n", style="white") error_text.append(f"Could not clone repository: {repo_url}\n", style="white") error_text.append( f"Error: {e.stderr if hasattr(e, 'stderr') and e.stderr else str(e)}", style="dim red" ) panel = Panel( error_text, title="[bold white]STRIX", title_align="left", border_style="red", padding=(1, 2), ) console.print("\n") console.print(panel) console.print() sys.exit(1) except FileNotFoundError: error_text = Text() error_text.append("GIT NOT FOUND", style="bold red") error_text.append("\n\n", style="white") error_text.append("Git is not installed or not available in PATH.\n", style="white") error_text.append("Please install Git to clone repositories.\n", style="white") panel = Panel( error_text, title="[bold white]STRIX", title_align="left", border_style="red", padding=(1, 2), ) console.print("\n") console.print(panel) console.print() sys.exit(1) # Docker utilities def check_docker_connection() -> Any: try: return docker.from_env() except DockerException: console = Console() error_text = Text() error_text.append("DOCKER NOT AVAILABLE", style="bold red") error_text.append("\n\n", style="white") error_text.append("Cannot connect to Docker daemon.\n", style="white") error_text.append( "Please ensure Docker Desktop is installed and running, and try running strix again.\n", style="white", ) panel = Panel( error_text, title="[bold white]STRIX", title_align="left", border_style="red", padding=(1, 2), ) console.print("\n", panel, "\n") raise RuntimeError("Docker not available") from None def image_exists(client: Any, image_name: str) -> bool: try: client.images.get(image_name) except ImageNotFound: return False else: return True def update_layer_status(layers_info: dict[str, str], layer_id: str, layer_status: str) -> None: if "Pull complete" in layer_status or "Already exists" in layer_status: layers_info[layer_id] = "✓" elif "Downloading" in layer_status: layers_info[layer_id] = "↓" elif "Extracting" in layer_status: layers_info[layer_id] = "📦" elif "Waiting" in layer_status: layers_info[layer_id] = "⏳" else: layers_info[layer_id] = "•" def process_pull_line( line: dict[str, Any], layers_info: dict[str, str], status: Any, last_update: str ) -> str: if "id" in line and "status" in line: layer_id = line["id"] update_layer_status(layers_info, layer_id, line["status"]) completed = sum(1 for v in layers_info.values() if v == "✓") total = len(layers_info) if total > 0: update_msg = f"[bold cyan]Progress: {completed}/{total} layers complete" if update_msg != last_update: status.update(update_msg) return update_msg elif "status" in line and "id" not in line: global_status = line["status"] if "Pulling from" in global_status: status.update("[bold cyan]Fetching image manifest...") elif "Digest:" in global_status: status.update("[bold cyan]Verifying image...") elif "Status:" in global_status: status.update("[bold cyan]Finalizing...") return last_update # LLM utilities def validate_llm_response(response: Any) -> None: if not response or not response.choices or not response.choices[0].message.content: raise RuntimeError("Invalid response from LLM") def validate_config_file(config_path: str) -> Path: console = Console() path = Path(config_path) if not path.exists(): console.print(f"[bold red]Error:[/] Config file not found: {config_path}") sys.exit(1) if path.suffix != ".json": console.print("[bold red]Error:[/] Config file must be a .json file") sys.exit(1) try: with path.open("r", encoding="utf-8") as f: data = json.load(f) except json.JSONDecodeError as e: console.print(f"[bold red]Error:[/] Invalid JSON in config file: {e}") sys.exit(1) if not isinstance(data, dict): console.print("[bold red]Error:[/] Config file must contain a JSON object") sys.exit(1) if "env" not in data or not isinstance(data.get("env"), dict): console.print("[bold red]Error:[/] Config file must have an 'env' object") sys.exit(1) return path
{ "repo_id": "usestrix/strix", "file_path": "strix/interface/utils.py", "license": "Apache License 2.0", "lines": 680, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/interface/cli.py
import atexit import signal import sys import threading import time from typing import Any from rich.console import Console from rich.live import Live from rich.panel import Panel from rich.text import Text from strix.agents.StrixAgent import StrixAgent from strix.llm.config import LLMConfig from strix.telemetry.tracer import Tracer, set_global_tracer from .utils import ( build_live_stats_text, format_vulnerability_report, ) async def run_cli(args: Any) -> None: # noqa: PLR0915 console = Console() start_text = Text() start_text.append("Penetration test initiated", style="bold #22c55e") target_text = Text() target_text.append("Target", style="dim") target_text.append(" ") if len(args.targets_info) == 1: target_text.append(args.targets_info[0]["original"], style="bold white") else: target_text.append(f"{len(args.targets_info)} targets", style="bold white") for target_info in args.targets_info: target_text.append("\n ") target_text.append(target_info["original"], style="white") results_text = Text() results_text.append("Output", style="dim") results_text.append(" ") results_text.append(f"strix_runs/{args.run_name}", style="#60a5fa") note_text = Text() note_text.append("\n\n", style="dim") note_text.append("Vulnerabilities will be displayed in real-time.", style="dim") startup_panel = Panel( Text.assemble( start_text, "\n\n", target_text, "\n", results_text, note_text, ), title="[bold white]STRIX", title_align="left", border_style="#22c55e", padding=(1, 2), ) console.print("\n") console.print(startup_panel) console.print() scan_mode = getattr(args, "scan_mode", "deep") scan_config = { "scan_id": args.run_name, "targets": args.targets_info, "user_instructions": args.instruction or "", "run_name": args.run_name, } llm_config = LLMConfig(scan_mode=scan_mode) agent_config = { "llm_config": llm_config, "max_iterations": 300, "non_interactive": True, } if getattr(args, "local_sources", None): agent_config["local_sources"] = args.local_sources tracer = Tracer(args.run_name) tracer.set_scan_config(scan_config) def display_vulnerability(report: dict[str, Any]) -> None: report_id = report.get("id", "unknown") vuln_text = format_vulnerability_report(report) vuln_panel = Panel( vuln_text, title=f"[bold red]{report_id.upper()}", title_align="left", border_style="red", padding=(1, 2), ) console.print(vuln_panel) console.print() tracer.vulnerability_found_callback = display_vulnerability def cleanup_on_exit() -> None: from strix.runtime import cleanup_runtime tracer.cleanup() cleanup_runtime() def signal_handler(_signum: int, _frame: Any) -> None: tracer.cleanup() sys.exit(1) atexit.register(cleanup_on_exit) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) if hasattr(signal, "SIGHUP"): signal.signal(signal.SIGHUP, signal_handler) set_global_tracer(tracer) def create_live_status() -> Panel: status_text = Text() status_text.append("Penetration test in progress", style="bold #22c55e") status_text.append("\n\n") stats_text = build_live_stats_text(tracer, agent_config) if stats_text: status_text.append(stats_text) return Panel( status_text, title="[bold white]STRIX", title_align="left", border_style="#22c55e", padding=(1, 2), ) try: console.print() with Live( create_live_status(), console=console, refresh_per_second=2, transient=False ) as live: stop_updates = threading.Event() def update_status() -> None: while not stop_updates.is_set(): try: live.update(create_live_status()) time.sleep(2) except Exception: # noqa: BLE001 break update_thread = threading.Thread(target=update_status, daemon=True) update_thread.start() try: agent = StrixAgent(agent_config) result = await agent.execute_scan(scan_config) if isinstance(result, dict) and not result.get("success", True): error_msg = result.get("error", "Unknown error") error_details = result.get("details") console.print() console.print(f"[bold red]Penetration test failed:[/] {error_msg}") if error_details: console.print(f"[dim]{error_details}[/]") console.print() sys.exit(1) finally: stop_updates.set() update_thread.join(timeout=1) except Exception as e: console.print(f"[bold red]Error during penetration test:[/] {e}") raise if tracer.final_scan_result: console.print() final_report_text = Text() final_report_text.append("Penetration test summary", style="bold #60a5fa") final_report_panel = Panel( Text.assemble( final_report_text, "\n\n", tracer.final_scan_result, ), title="[bold white]STRIX", title_align="left", border_style="#60a5fa", padding=(1, 2), ) console.print(final_report_panel) console.print()
{ "repo_id": "usestrix/strix", "file_path": "strix/interface/cli.py", "license": "Apache License 2.0", "lines": 162, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/tools/terminal/terminal_session.py
import logging import re import time import uuid from enum import Enum from pathlib import Path from typing import Any import libtmux logger = logging.getLogger(__name__) class BashCommandStatus(Enum): CONTINUE = "continue" COMPLETED = "completed" NO_CHANGE_TIMEOUT = "no_change_timeout" HARD_TIMEOUT = "hard_timeout" def _remove_command_prefix(command_output: str, command: str) -> str: return command_output.lstrip().removeprefix(command.lstrip()).lstrip() class TerminalSession: POLL_INTERVAL = 0.5 HISTORY_LIMIT = 10_000 PS1_END = "]$ " def __init__(self, session_id: str, work_dir: str = "/workspace") -> None: self.session_id = session_id self.work_dir = str(Path(work_dir).resolve()) self._closed = False self._cwd = self.work_dir self.server: libtmux.Server | None = None self.session: libtmux.Session | None = None self.window: libtmux.Window | None = None self.pane: libtmux.Pane | None = None self.prev_status: BashCommandStatus | None = None self.prev_output: str = "" self._initialized = False self.initialize() @property def PS1(self) -> str: # noqa: N802 return r"[STRIX_$?]$ " @property def PS1_PATTERN(self) -> str: # noqa: N802 return r"\[STRIX_(\d+)\]" def initialize(self) -> None: self.server = libtmux.Server() session_name = f"strix-{self.session_id}-{uuid.uuid4()}" self.session = self.server.new_session( session_name=session_name, start_directory=self.work_dir, kill_session=True, x=120, y=30, ) self.session.set_option("history-limit", str(self.HISTORY_LIMIT)) self.session.history_limit = self.HISTORY_LIMIT _initial_window = self.session.active_window self.window = self.session.new_window( window_name="bash", window_shell="/bin/bash", start_directory=self.work_dir, ) self.pane = self.window.active_pane _initial_window.kill() self.pane.send_keys(f'export PROMPT_COMMAND=\'export PS1="{self.PS1}"\'; export PS2=""') time.sleep(0.1) self._clear_screen() self.prev_status = None self.prev_output = "" self._closed = False self._cwd = str(Path(self.work_dir).resolve()) self._initialized = True assert self.server is not None assert self.session is not None assert self.window is not None assert self.pane is not None def _get_pane_content(self) -> str: if not self.pane: raise RuntimeError("Terminal session not properly initialized") return "\n".join( line.rstrip() for line in self.pane.cmd("capture-pane", "-J", "-pS", "-").stdout ) def _clear_screen(self) -> None: if not self.pane: raise RuntimeError("Terminal session not properly initialized") self.pane.send_keys("C-l", enter=False) time.sleep(0.1) self.pane.cmd("clear-history") def _is_control_key(self, command: str) -> bool: return ( (command.startswith("C-") and len(command) >= 3) or (command.startswith("^") and len(command) >= 2) or (command.startswith("S-") and len(command) >= 3) or (command.startswith("M-") and len(command) >= 3) ) def _is_function_key(self, command: str) -> bool: if not command.startswith("F") or len(command) > 3: return False try: num_part = command[1:] return num_part.isdigit() and 1 <= int(num_part) <= 12 except (ValueError, IndexError): return False def _is_navigation_or_special_key(self, command: str) -> bool: navigation_keys = {"Up", "Down", "Left", "Right", "Home", "End"} special_keys = {"BSpace", "BTab", "DC", "Enter", "Escape", "IC", "Space", "Tab"} page_keys = {"NPage", "PageDown", "PgDn", "PPage", "PageUp", "PgUp"} return command in navigation_keys or command in special_keys or command in page_keys def _is_complex_modifier_key(self, command: str) -> bool: return "-" in command and any( command.startswith(prefix) for prefix in ["C-S-", "C-M-", "S-M-", "M-S-", "M-C-", "S-C-"] ) def _is_special_key(self, command: str) -> bool: _command = command.strip() if not _command: return False return ( self._is_control_key(_command) or self._is_function_key(_command) or self._is_navigation_or_special_key(_command) or self._is_complex_modifier_key(_command) ) def _matches_ps1_metadata(self, content: str) -> list[re.Match[str]]: return list(re.finditer(self.PS1_PATTERN + r"\]\$ ", content)) def _get_command_output( self, command: str, raw_command_output: str, continue_prefix: str = "", ) -> str: if self.prev_output: command_output = raw_command_output.removeprefix(self.prev_output) if continue_prefix: command_output = continue_prefix + command_output else: command_output = raw_command_output self.prev_output = raw_command_output command_output = _remove_command_prefix(command_output, command) return command_output.rstrip() def _combine_outputs_between_matches( self, pane_content: str, ps1_matches: list[re.Match[str]], get_content_before_last_match: bool = False, ) -> str: if len(ps1_matches) == 1: if get_content_before_last_match: return pane_content[: ps1_matches[0].start()] return pane_content[ps1_matches[0].end() + 1 :] if len(ps1_matches) == 0: return pane_content combined_output = "" for i in range(len(ps1_matches) - 1): output_segment = pane_content[ps1_matches[i].end() + 1 : ps1_matches[i + 1].start()] combined_output += output_segment + "\n" combined_output += pane_content[ps1_matches[-1].end() + 1 :] return combined_output def _extract_exit_code_from_matches(self, ps1_matches: list[re.Match[str]]) -> int | None: if not ps1_matches: return None last_match = ps1_matches[-1] try: return int(last_match.group(1)) except (ValueError, IndexError): return None def _handle_empty_command( self, cur_pane_output: str, ps1_matches: list[re.Match[str]], is_command_running: bool, timeout: float, ) -> dict[str, Any]: if not is_command_running: raw_command_output = self._combine_outputs_between_matches(cur_pane_output, ps1_matches) command_output = self._get_command_output("", raw_command_output) return { "content": command_output, "status": "completed", "exit_code": 0, "working_dir": self._cwd, } start_time = time.time() last_pane_output = cur_pane_output while True: cur_pane_output = self._get_pane_content() ps1_matches = self._matches_ps1_metadata(cur_pane_output) if cur_pane_output.rstrip().endswith(self.PS1_END.rstrip()) or len(ps1_matches) > 0: exit_code = self._extract_exit_code_from_matches(ps1_matches) raw_command_output = self._combine_outputs_between_matches( cur_pane_output, ps1_matches ) command_output = self._get_command_output("", raw_command_output) self.prev_status = BashCommandStatus.COMPLETED self.prev_output = "" self._ready_for_next_command() return { "content": command_output, "status": "completed", "exit_code": exit_code or 0, "working_dir": self._cwd, } elapsed_time = time.time() - start_time if elapsed_time >= timeout: raw_command_output = self._combine_outputs_between_matches( cur_pane_output, ps1_matches ) command_output = self._get_command_output("", raw_command_output) return { "content": command_output + f"\n[Command still running after {timeout}s - showing output so far]", "status": "running", "exit_code": None, "working_dir": self._cwd, } if cur_pane_output != last_pane_output: last_pane_output = cur_pane_output time.sleep(self.POLL_INTERVAL) def _handle_input_command( self, command: str, no_enter: bool, is_command_running: bool ) -> dict[str, Any]: if not is_command_running: return { "content": "No command is currently running. Cannot send input.", "status": "error", "exit_code": None, "working_dir": self._cwd, } if not self.pane: raise RuntimeError("Terminal session not properly initialized") is_special_key = self._is_special_key(command) should_add_enter = not is_special_key and not no_enter self.pane.send_keys(command, enter=should_add_enter) time.sleep(2) cur_pane_output = self._get_pane_content() ps1_matches = self._matches_ps1_metadata(cur_pane_output) raw_command_output = self._combine_outputs_between_matches(cur_pane_output, ps1_matches) command_output = self._get_command_output(command, raw_command_output) is_still_running = not ( cur_pane_output.rstrip().endswith(self.PS1_END.rstrip()) or len(ps1_matches) > 0 ) if is_still_running: return { "content": command_output, "status": "running", "exit_code": None, "working_dir": self._cwd, } exit_code = self._extract_exit_code_from_matches(ps1_matches) self.prev_status = BashCommandStatus.COMPLETED self.prev_output = "" self._ready_for_next_command() return { "content": command_output, "status": "completed", "exit_code": exit_code or 0, "working_dir": self._cwd, } def _execute_new_command(self, command: str, no_enter: bool, timeout: float) -> dict[str, Any]: if not self.pane: raise RuntimeError("Terminal session not properly initialized") initial_pane_output = self._get_pane_content() initial_ps1_matches = self._matches_ps1_metadata(initial_pane_output) initial_ps1_count = len(initial_ps1_matches) start_time = time.time() last_pane_output = initial_pane_output is_special_key = self._is_special_key(command) should_add_enter = not is_special_key and not no_enter self.pane.send_keys(command, enter=should_add_enter) while True: cur_pane_output = self._get_pane_content() ps1_matches = self._matches_ps1_metadata(cur_pane_output) current_ps1_count = len(ps1_matches) if cur_pane_output != last_pane_output: last_pane_output = cur_pane_output if current_ps1_count > initial_ps1_count or cur_pane_output.rstrip().endswith( self.PS1_END.rstrip() ): exit_code = self._extract_exit_code_from_matches(ps1_matches) get_content_before_last_match = bool(len(ps1_matches) == 1) raw_command_output = self._combine_outputs_between_matches( cur_pane_output, ps1_matches, get_content_before_last_match=get_content_before_last_match, ) command_output = self._get_command_output(command, raw_command_output) self.prev_status = BashCommandStatus.COMPLETED self.prev_output = "" self._ready_for_next_command() return { "content": command_output, "status": "completed", "exit_code": exit_code or 0, "working_dir": self._cwd, } elapsed_time = time.time() - start_time if elapsed_time >= timeout: raw_command_output = self._combine_outputs_between_matches( cur_pane_output, ps1_matches ) command_output = self._get_command_output( command, raw_command_output, continue_prefix="[Below is the output of the previous command.]\n", ) self.prev_status = BashCommandStatus.CONTINUE timeout_msg = ( f"\n[Command still running after {timeout}s - showing output so far. " "Use C-c to interrupt if needed.]" ) return { "content": command_output + timeout_msg, "status": "running", "exit_code": None, "working_dir": self._cwd, } time.sleep(self.POLL_INTERVAL) def execute( self, command: str, is_input: bool = False, timeout: float = 10.0, no_enter: bool = False ) -> dict[str, Any]: if not self._initialized: raise RuntimeError("Bash session is not initialized") cur_pane_output = self._get_pane_content() ps1_matches = self._matches_ps1_metadata(cur_pane_output) is_command_running = not ( cur_pane_output.rstrip().endswith(self.PS1_END.rstrip()) or len(ps1_matches) > 0 ) if command.strip() == "": return self._handle_empty_command( cur_pane_output, ps1_matches, is_command_running, timeout ) is_special_key = self._is_special_key(command) if is_input: return self._handle_input_command(command, no_enter, is_command_running) if is_special_key and is_command_running: return self._handle_input_command(command, no_enter, is_command_running) if is_command_running: return { "content": ( "A command is already running. Use is_input=true to send input to it, " "or interrupt it first (e.g., with C-c)." ), "status": "error", "exit_code": None, "working_dir": self._cwd, } return self._execute_new_command(command, no_enter, timeout) def _ready_for_next_command(self) -> None: self._clear_screen() def is_running(self) -> bool: if self._closed or not self.session: return False try: return self.session.id in [s.id for s in self.server.sessions] if self.server else False except (AttributeError, OSError) as e: logger.debug("Error checking if session is running: %s", e) return False def get_working_dir(self) -> str: return self._cwd def close(self) -> None: if self._closed: return if self.session: try: self.session.kill() except (AttributeError, OSError) as e: logger.debug("Error closing terminal session: %s", e) self._closed = True self.server = None self.session = None self.window = None self.pane = None
{ "repo_id": "usestrix/strix", "file_path": "strix/tools/terminal/terminal_session.py", "license": "Apache License 2.0", "lines": 367, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/agents/StrixAgent/strix_agent.py
from typing import Any from strix.agents.base_agent import BaseAgent from strix.llm.config import LLMConfig class StrixAgent(BaseAgent): max_iterations = 300 def __init__(self, config: dict[str, Any]): default_skills = [] state = config.get("state") if state is None or (hasattr(state, "parent_id") and state.parent_id is None): default_skills = ["root_agent"] self.default_llm_config = LLMConfig(skills=default_skills) super().__init__(config) async def execute_scan(self, scan_config: dict[str, Any]) -> dict[str, Any]: # noqa: PLR0912 user_instructions = scan_config.get("user_instructions", "") targets = scan_config.get("targets", []) repositories = [] local_code = [] urls = [] ip_addresses = [] for target in targets: target_type = target["type"] details = target["details"] workspace_subdir = details.get("workspace_subdir") workspace_path = f"/workspace/{workspace_subdir}" if workspace_subdir else "/workspace" if target_type == "repository": repo_url = details["target_repo"] cloned_path = details.get("cloned_repo_path") repositories.append( { "url": repo_url, "workspace_path": workspace_path if cloned_path else None, } ) elif target_type == "local_code": original_path = details.get("target_path", "unknown") local_code.append( { "path": original_path, "workspace_path": workspace_path, } ) elif target_type == "web_application": urls.append(details["target_url"]) elif target_type == "ip_address": ip_addresses.append(details["target_ip"]) task_parts = [] if repositories: task_parts.append("\n\nRepositories:") for repo in repositories: if repo["workspace_path"]: task_parts.append(f"- {repo['url']} (available at: {repo['workspace_path']})") else: task_parts.append(f"- {repo['url']}") if local_code: task_parts.append("\n\nLocal Codebases:") task_parts.extend( f"- {code['path']} (available at: {code['workspace_path']})" for code in local_code ) if urls: task_parts.append("\n\nURLs:") task_parts.extend(f"- {url}" for url in urls) if ip_addresses: task_parts.append("\n\nIP Addresses:") task_parts.extend(f"- {ip}" for ip in ip_addresses) task_description = " ".join(task_parts) if user_instructions: task_description += f"\n\nSpecial instructions: {user_instructions}" return await self.agent_loop(task=task_description)
{ "repo_id": "usestrix/strix", "file_path": "strix/agents/StrixAgent/strix_agent.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
usestrix/strix:strix/agents/base_agent.py
import asyncio import contextlib import logging from typing import TYPE_CHECKING, Any, Optional if TYPE_CHECKING: from strix.telemetry.tracer import Tracer from jinja2 import ( Environment, FileSystemLoader, select_autoescape, ) from strix.llm import LLM, LLMConfig, LLMRequestFailedError from strix.llm.utils import clean_content from strix.runtime import SandboxInitializationError from strix.tools import process_tool_invocations from strix.utils.resource_paths import get_strix_resource_path from .state import AgentState logger = logging.getLogger(__name__) class AgentMeta(type): agent_name: str jinja_env: Environment def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> type: new_cls = super().__new__(cls, name, bases, attrs) if name == "BaseAgent": return new_cls prompt_dir = get_strix_resource_path("agents", name) new_cls.agent_name = name new_cls.jinja_env = Environment( loader=FileSystemLoader(prompt_dir), autoescape=select_autoescape(enabled_extensions=(), default_for_string=False), ) return new_cls class BaseAgent(metaclass=AgentMeta): max_iterations = 300 agent_name: str = "" jinja_env: Environment default_llm_config: LLMConfig | None = None def __init__(self, config: dict[str, Any]): self.config = config self.local_sources = config.get("local_sources", []) self.non_interactive = config.get("non_interactive", False) if "max_iterations" in config: self.max_iterations = config["max_iterations"] self.llm_config_name = config.get("llm_config_name", "default") self.llm_config = config.get("llm_config", self.default_llm_config) if self.llm_config is None: raise ValueError("llm_config is required but not provided") state_from_config = config.get("state") if state_from_config is not None: self.state = state_from_config else: self.state = AgentState( agent_name="Root Agent", max_iterations=self.max_iterations, ) self.llm = LLM(self.llm_config, agent_name=self.agent_name) with contextlib.suppress(Exception): self.llm.set_agent_identity(self.state.agent_name, self.state.agent_id) self._current_task: asyncio.Task[Any] | None = None self._force_stop = False from strix.telemetry.tracer import get_global_tracer tracer = get_global_tracer() if tracer: tracer.log_agent_creation( agent_id=self.state.agent_id, name=self.state.agent_name, task=self.state.task, parent_id=self.state.parent_id, ) if self.state.parent_id is None: scan_config = tracer.scan_config or {} exec_id = tracer.log_tool_execution_start( agent_id=self.state.agent_id, tool_name="scan_start_info", args=scan_config, ) tracer.update_tool_execution(execution_id=exec_id, status="completed", result={}) else: exec_id = tracer.log_tool_execution_start( agent_id=self.state.agent_id, tool_name="subagent_start_info", args={ "name": self.state.agent_name, "task": self.state.task, "parent_id": self.state.parent_id, }, ) tracer.update_tool_execution(execution_id=exec_id, status="completed", result={}) self._add_to_agents_graph() def _add_to_agents_graph(self) -> None: from strix.tools.agents_graph import agents_graph_actions node = { "id": self.state.agent_id, "name": self.state.agent_name, "task": self.state.task, "status": "running", "parent_id": self.state.parent_id, "created_at": self.state.start_time, "finished_at": None, "result": None, "llm_config": self.llm_config_name, "agent_type": self.__class__.__name__, "state": self.state.model_dump(), } agents_graph_actions._agent_graph["nodes"][self.state.agent_id] = node agents_graph_actions._agent_instances[self.state.agent_id] = self agents_graph_actions._agent_states[self.state.agent_id] = self.state if self.state.parent_id: agents_graph_actions._agent_graph["edges"].append( {"from": self.state.parent_id, "to": self.state.agent_id, "type": "delegation"} ) if self.state.agent_id not in agents_graph_actions._agent_messages: agents_graph_actions._agent_messages[self.state.agent_id] = [] if self.state.parent_id is None and agents_graph_actions._root_agent_id is None: agents_graph_actions._root_agent_id = self.state.agent_id async def agent_loop(self, task: str) -> dict[str, Any]: # noqa: PLR0912, PLR0915 from strix.telemetry.tracer import get_global_tracer tracer = get_global_tracer() try: await self._initialize_sandbox_and_state(task) except SandboxInitializationError as e: return self._handle_sandbox_error(e, tracer) while True: if self._force_stop: self._force_stop = False await self._enter_waiting_state(tracer, was_cancelled=True) continue self._check_agent_messages(self.state) if self.state.is_waiting_for_input(): await self._wait_for_input() continue if self.state.should_stop(): if self.non_interactive: return self.state.final_result or {} await self._enter_waiting_state(tracer) continue if self.state.llm_failed: await self._wait_for_input() continue self.state.increment_iteration() if ( self.state.is_approaching_max_iterations() and not self.state.max_iterations_warning_sent ): self.state.max_iterations_warning_sent = True remaining = self.state.max_iterations - self.state.iteration warning_msg = ( f"URGENT: You are approaching the maximum iteration limit. " f"Current: {self.state.iteration}/{self.state.max_iterations} " f"({remaining} iterations remaining). " f"Please prioritize completing your required task(s) and calling " f"the appropriate finish tool (finish_scan for root agent, " f"agent_finish for sub-agents) as soon as possible." ) self.state.add_message("user", warning_msg) if self.state.iteration == self.state.max_iterations - 3: final_warning_msg = ( "CRITICAL: You have only 3 iterations left! " "Your next message MUST be the tool call to the appropriate " "finish tool: finish_scan if you are the root agent, or " "agent_finish if you are a sub-agent. " "No other actions should be taken except finishing your work " "immediately." ) self.state.add_message("user", final_warning_msg) try: iteration_task = asyncio.create_task(self._process_iteration(tracer)) self._current_task = iteration_task should_finish = await iteration_task self._current_task = None if should_finish: if self.non_interactive: self.state.set_completed({"success": True}) if tracer: tracer.update_agent_status(self.state.agent_id, "completed") return self.state.final_result or {} await self._enter_waiting_state(tracer, task_completed=True) continue except asyncio.CancelledError: self._current_task = None if tracer: partial_content = tracer.finalize_streaming_as_interrupted(self.state.agent_id) if partial_content and partial_content.strip(): self.state.add_message( "assistant", f"{partial_content}\n\n[ABORTED BY USER]" ) if self.non_interactive: raise await self._enter_waiting_state(tracer, error_occurred=False, was_cancelled=True) continue except LLMRequestFailedError as e: result = self._handle_llm_error(e, tracer) if result is not None: return result continue except (RuntimeError, ValueError, TypeError) as e: if not await self._handle_iteration_error(e, tracer): if self.non_interactive: self.state.set_completed({"success": False, "error": str(e)}) if tracer: tracer.update_agent_status(self.state.agent_id, "failed") raise await self._enter_waiting_state(tracer, error_occurred=True) continue async def _wait_for_input(self) -> None: if self._force_stop: return if self.state.has_waiting_timeout(): self.state.resume_from_waiting() self.state.add_message("user", "Waiting timeout reached. Resuming execution.") from strix.telemetry.tracer import get_global_tracer tracer = get_global_tracer() if tracer: tracer.update_agent_status(self.state.agent_id, "running") try: from strix.tools.agents_graph.agents_graph_actions import _agent_graph if self.state.agent_id in _agent_graph["nodes"]: _agent_graph["nodes"][self.state.agent_id]["status"] = "running" except (ImportError, KeyError): pass return await asyncio.sleep(0.5) async def _enter_waiting_state( self, tracer: Optional["Tracer"], task_completed: bool = False, error_occurred: bool = False, was_cancelled: bool = False, ) -> None: self.state.enter_waiting_state() if tracer: if task_completed: tracer.update_agent_status(self.state.agent_id, "completed") elif error_occurred: tracer.update_agent_status(self.state.agent_id, "error") elif was_cancelled: tracer.update_agent_status(self.state.agent_id, "stopped") else: tracer.update_agent_status(self.state.agent_id, "stopped") if task_completed: self.state.add_message( "assistant", "Task completed. I'm now waiting for follow-up instructions or new tasks.", ) elif error_occurred: self.state.add_message( "assistant", "An error occurred. I'm now waiting for new instructions." ) elif was_cancelled: self.state.add_message( "assistant", "Execution was cancelled. I'm now waiting for new instructions." ) else: self.state.add_message( "assistant", "Execution paused. I'm now waiting for new instructions or any updates.", ) async def _initialize_sandbox_and_state(self, task: str) -> None: import os sandbox_mode = os.getenv("STRIX_SANDBOX_MODE", "false").lower() == "true" if not sandbox_mode and self.state.sandbox_id is None: from strix.runtime import get_runtime try: runtime = get_runtime() sandbox_info = await runtime.create_sandbox( self.state.agent_id, self.state.sandbox_token, self.local_sources ) self.state.sandbox_id = sandbox_info["workspace_id"] self.state.sandbox_token = sandbox_info["auth_token"] self.state.sandbox_info = sandbox_info if "agent_id" in sandbox_info: self.state.sandbox_info["agent_id"] = sandbox_info["agent_id"] caido_port = sandbox_info.get("caido_port") if caido_port: from strix.telemetry.tracer import get_global_tracer tracer = get_global_tracer() if tracer: tracer.caido_url = f"localhost:{caido_port}" except Exception as e: from strix.telemetry import posthog posthog.error("sandbox_init_error", str(e)) raise if not self.state.task: self.state.task = task self.state.add_message("user", task) async def _process_iteration(self, tracer: Optional["Tracer"]) -> bool: final_response = None async for response in self.llm.generate(self.state.get_conversation_history()): final_response = response if tracer and response.content: tracer.update_streaming_content(self.state.agent_id, response.content) if final_response is None: return False content_stripped = (final_response.content or "").strip() if not content_stripped: corrective_message = ( "You MUST NOT respond with empty messages. " "If you currently have nothing to do or say, use an appropriate tool instead:\n" "- Use agents_graph_actions.wait_for_message to wait for messages " "from user or other agents\n" "- Use agents_graph_actions.agent_finish if you are a sub-agent " "and your task is complete\n" "- Use finish_actions.finish_scan if you are the root/main agent " "and the scan is complete" ) self.state.add_message("user", corrective_message) return False thinking_blocks = getattr(final_response, "thinking_blocks", None) self.state.add_message("assistant", final_response.content, thinking_blocks=thinking_blocks) if tracer: tracer.clear_streaming_content(self.state.agent_id) tracer.log_chat_message( content=clean_content(final_response.content), role="assistant", agent_id=self.state.agent_id, ) actions = ( final_response.tool_invocations if hasattr(final_response, "tool_invocations") and final_response.tool_invocations else [] ) if actions: return await self._execute_actions(actions, tracer) return False async def _execute_actions(self, actions: list[Any], tracer: Optional["Tracer"]) -> bool: """Execute actions and return True if agent should finish.""" for action in actions: self.state.add_action(action) conversation_history = self.state.get_conversation_history() tool_task = asyncio.create_task( process_tool_invocations(actions, conversation_history, self.state) ) self._current_task = tool_task try: should_agent_finish = await tool_task self._current_task = None except asyncio.CancelledError: self._current_task = None self.state.add_error("Tool execution cancelled by user") raise self.state.messages = conversation_history if should_agent_finish: self.state.set_completed({"success": True}) if tracer: tracer.update_agent_status(self.state.agent_id, "completed") if self.non_interactive and self.state.parent_id is None: return True return True return False def _check_agent_messages(self, state: AgentState) -> None: # noqa: PLR0912 try: from strix.tools.agents_graph.agents_graph_actions import _agent_graph, _agent_messages agent_id = state.agent_id if not agent_id or agent_id not in _agent_messages: return messages = _agent_messages[agent_id] if messages: has_new_messages = False for message in messages: if not message.get("read", False): sender_id = message.get("from") if state.is_waiting_for_input(): if state.llm_failed: if sender_id == "user": state.resume_from_waiting() has_new_messages = True from strix.telemetry.tracer import get_global_tracer tracer = get_global_tracer() if tracer: tracer.update_agent_status(state.agent_id, "running") else: state.resume_from_waiting() has_new_messages = True from strix.telemetry.tracer import get_global_tracer tracer = get_global_tracer() if tracer: tracer.update_agent_status(state.agent_id, "running") if sender_id == "user": sender_name = "User" state.add_message("user", message.get("content", "")) else: if sender_id and sender_id in _agent_graph.get("nodes", {}): sender_name = _agent_graph["nodes"][sender_id]["name"] message_content = f"""<inter_agent_message> <delivery_notice> <important>You have received a message from another agent. You should acknowledge this message and respond appropriately based on its content. However, DO NOT echo back or repeat the entire message structure in your response. Simply process the content and respond naturally as/if needed.</important> </delivery_notice> <sender> <agent_name>{sender_name}</agent_name> <agent_id>{sender_id}</agent_id> </sender> <message_metadata> <type>{message.get("message_type", "information")}</type> <priority>{message.get("priority", "normal")}</priority> <timestamp>{message.get("timestamp", "")}</timestamp> </message_metadata> <content> {message.get("content", "")} </content> <delivery_info> <note>This message was delivered during your task execution. Please acknowledge and respond if needed.</note> </delivery_info> </inter_agent_message>""" state.add_message("user", message_content.strip()) message["read"] = True if has_new_messages and not state.is_waiting_for_input(): from strix.telemetry.tracer import get_global_tracer tracer = get_global_tracer() if tracer: tracer.update_agent_status(agent_id, "running") except (AttributeError, KeyError, TypeError) as e: import logging logger = logging.getLogger(__name__) logger.warning(f"Error checking agent messages: {e}") return def _handle_sandbox_error( self, error: SandboxInitializationError, tracer: Optional["Tracer"], ) -> dict[str, Any]: error_msg = str(error.message) error_details = error.details self.state.add_error(error_msg) if self.non_interactive: self.state.set_completed({"success": False, "error": error_msg}) if tracer: tracer.update_agent_status(self.state.agent_id, "failed", error_msg) if error_details: exec_id = tracer.log_tool_execution_start( self.state.agent_id, "sandbox_error_details", {"error": error_msg, "details": error_details}, ) tracer.update_tool_execution(exec_id, "failed", {"details": error_details}) return {"success": False, "error": error_msg, "details": error_details} self.state.enter_waiting_state() if tracer: tracer.update_agent_status(self.state.agent_id, "sandbox_failed", error_msg) if error_details: exec_id = tracer.log_tool_execution_start( self.state.agent_id, "sandbox_error_details", {"error": error_msg, "details": error_details}, ) tracer.update_tool_execution(exec_id, "failed", {"details": error_details}) return {"success": False, "error": error_msg, "details": error_details} def _handle_llm_error( self, error: LLMRequestFailedError, tracer: Optional["Tracer"], ) -> dict[str, Any] | None: error_msg = str(error) error_details = getattr(error, "details", None) self.state.add_error(error_msg) if self.non_interactive: self.state.set_completed({"success": False, "error": error_msg}) if tracer: tracer.update_agent_status(self.state.agent_id, "failed", error_msg) if error_details: exec_id = tracer.log_tool_execution_start( self.state.agent_id, "llm_error_details", {"error": error_msg, "details": error_details}, ) tracer.update_tool_execution(exec_id, "failed", {"details": error_details}) return {"success": False, "error": error_msg} self.state.enter_waiting_state(llm_failed=True) if tracer: tracer.update_agent_status(self.state.agent_id, "llm_failed", error_msg) if error_details: exec_id = tracer.log_tool_execution_start( self.state.agent_id, "llm_error_details", {"error": error_msg, "details": error_details}, ) tracer.update_tool_execution(exec_id, "failed", {"details": error_details}) return None async def _handle_iteration_error( self, error: RuntimeError | ValueError | TypeError | asyncio.CancelledError, tracer: Optional["Tracer"], ) -> bool: error_msg = f"Error in iteration {self.state.iteration}: {error!s}" logger.exception(error_msg) self.state.add_error(error_msg) if tracer: tracer.update_agent_status(self.state.agent_id, "error") return True def cancel_current_execution(self) -> None: self._force_stop = True if self._current_task and not self._current_task.done(): try: loop = self._current_task.get_loop() loop.call_soon_threadsafe(self._current_task.cancel) except RuntimeError: self._current_task.cancel() self._current_task = None
{ "repo_id": "usestrix/strix", "file_path": "strix/agents/base_agent.py", "license": "Apache License 2.0", "lines": 501, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex