from __future__ import annotations from dataclasses import dataclass from typing import Optional @dataclass class LoRAConfigSpec: r: int = 16 alpha: int = 32 dropout: float = 0.05 target_modules: Optional[list[str]] = None def build_lora_model( model_name: str, lora_cfg: LoRAConfigSpec, load_in_4bit: bool = True, device_map: str = "auto", ): import warnings import os # Suppress bitsandbytes warnings if it fails os.environ.setdefault('BITSANDBYTES_NOWELCOME', '1') from transformers import AutoModelForCausalLM from peft import LoraConfig, get_peft_model kwargs = {"device_map": device_map} if load_in_4bit: # Check if bitsandbytes is available and working bitsandbytes_available = False try: # Try to import bitsandbytes (this may raise RuntimeError if CUDA setup fails) import bitsandbytes as bnb # If import succeeds, try to use BitsAndBytesConfig try: from transformers import BitsAndBytesConfig # Create config to test if it works test_config = BitsAndBytesConfig(load_in_4bit=True) bitsandbytes_available = True except Exception as e: print(f"⚠️ Warning: bitsandbytes configuration failed: {str(e)[:100]}") print(" Falling back to full precision training.") bitsandbytes_available = False except (ImportError, RuntimeError, Exception) as e: error_msg = str(e) if "CUDA Setup failed" in error_msg or "libcudart" in error_msg or "libstdc++" in error_msg: print("⚠️ Warning: bitsandbytes CUDA setup failed (missing CUDA libraries).") print(" Falling back to full precision training.") print(" To fix: Install CUDA libraries or use full precision (remove --load-in-4bit)") else: print(f"⚠️ Warning: bitsandbytes not available: {error_msg[:100]}") print(" Falling back to full precision training.") bitsandbytes_available = False if bitsandbytes_available: try: from transformers import BitsAndBytesConfig # Use BitsAndBytesConfig for better control quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", # Use NF4 for training (recommended by QLoRA paper) bnb_4bit_compute_dtype="float16", bnb_4bit_use_double_quant=True, # Double quantization for better memory efficiency ) kwargs["quantization_config"] = quantization_config print("✓ Using 4-bit quantization with bitsandbytes") except Exception as e: print(f"⚠️ Warning: Failed to configure 4-bit quantization: {str(e)[:100]}") print(" Falling back to full precision training.") load_in_4bit = False else: load_in_4bit = False if not load_in_4bit: print("ℹ️ Training in full precision (FP16/BF16). This requires more GPU memory.") print(" If you run out of memory, try reducing --batch-size or install/fix bitsandbytes.") # Suppress bitsandbytes warnings during model loading import warnings import torch # Set default torch_dtype to float16 or bfloat16 for memory efficiency kwargs.setdefault("torch_dtype", torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=UserWarning, module="bitsandbytes") model = AutoModelForCausalLM.from_pretrained(model_name, **kwargs) target_modules = lora_cfg.target_modules or ["q_proj", "k_proj", "v_proj", "o_proj"] peft_cfg = LoraConfig( r=lora_cfg.r, lora_alpha=lora_cfg.alpha, lora_dropout=lora_cfg.dropout, bias="none", task_type="CAUSAL_LM", target_modules=target_modules, ) try: return get_peft_model(model, peft_cfg) except Exception as e: print(f"⚠️ Error creating PEFT model: {e}") print(" This might be due to bitsandbytes issues. Try removing --load-in-4bit.") raise