Spaces:
Sleeping
Sleeping
Commit Β·
efb4fe4
1
Parent(s): 6e467d1
feat: Add 3-tier quantization with auto hardware detection
Browse files- Tier 1: Qwen2.5-7B with 4-bit NF4 quantization (needs GPU 5.5GB+)
- Tier 2: Qwen2.5-1.5B with 8-bit quantization (GPU or CPU)
- Tier 3: Qwen2.5-0.5B bfloat16 fallback (CPU, default)
- Auto-detect GPU/CPU and select optimal quantization
- Auto-fallback: 7Bβ1.5B if GPU VRAM insufficient
- Configurable via .env: QUANTIZATION=auto/4bit/8bit/none
- Graceful fallback if bitsandbytes not installed
- Update requirements.txt with bitsandbytes>=0.43.0
- Update Dockerfile with GPU base image option
Files changed (4)
3 unmodified lines4563 unmodified lines# Qwen/Qwen2.5-1.5B-Instruct (Goldilocks - ~3GB, recommended for GPU)# Qwen/Qwen2.5-7B-Instruct (Smartest - needs 4-bit quantization + GPU)MODEL_ID=Qwen/Qwen2.5-0.5B-Instruct3 unmodified lines456789101112131415163 unmodified lines# Qwen/Qwen2.5-1.5B-Instruct (Goldilocks - ~3GB, recommended for GPU)# Qwen/Qwen2.5-7B-Instruct (Smartest - needs 4-bit quantization + GPU)MODEL_ID=Qwen/Qwen2.5-0.5B-Instruct# Quantization mode: auto, 4bit, 8bit, none# auto = 4-bit on GPU for 7B, 8-bit on GPU for 1.5B, bf16 on CPU# 4bit = force 4-bit quantization (requires GPU + bitsandbytes)# 8bit = force 8-bit quantization# none = disable quantization, uses bfloat16QUANTIZATION=auto# Double quantization for 4-bit (saves ~10% more memory)USE_DOUBLE_QUANT=true
12345FROM python:3.9RUN useradd -m -u 1000 userUSER userENV PATH="/home/user/.local/bin:$PATH"12345678910# CPU-optimized default image (works on HuggingFace free tier)FROM python:3.9# For GPU support (uncomment to use):# FROM pytorch/pytorch:2.1.0-cuda12.1-cudnn8-runtime# RUN pip install bitsandbytes>=0.43.0RUN useradd -m -u 1000 userUSER userENV PATH="/home/user/.local/bin:$PATH"
6 unmodified lines7896 unmodified linestransformersacceleratesentencepiece6 unmodified lines789106 unmodified linestransformersacceleratesentencepiecebitsandbytes>=0.43.0
1234561 unmodified line891011121314151617181920212223242526272829303132import osimport torchfrom transformers import pipelinefrom dotenv import load_dotenvfrom pathlib import Path1 unmodified lineload_dotenv(dotenv_path=env_path)MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")_pipe = Nonedef get_pipe():global _pipeif _pipe is None:print(f"β³ Loading Local Model {MODEL_ID}...")try:_pipe = pipeline("text-generation",model=MODEL_ID,torch_dtype=torch.bfloat16,device_map="auto",trust_remote_code=True)print("β Model Loaded Successfully!")except Exception as e:print(f"β Model Load Failed: {e}")_pipe = Nonereturn _pipedef generate_text(messages, temperature=0.3, max_new_tokens=2000):1234561 unmodified line89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import osimport torchfrom transformers import pipeline, BitsAndBytesConfigfrom dotenv import load_dotenvfrom pathlib import Path1 unmodified lineload_dotenv(dotenv_path=env_path)MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")QUANTIZATION = os.getenv("QUANTIZATION", "auto")USE_DOUBLE_QUANT = os.getenv("USE_DOUBLE_QUANT", "true").lower() == "true"_pipe = None_current_model = Nonedef _log(msg: str):print(f"[ModelLoader] {msg}")def _has_gpu() -> bool:return torch.cuda.is_available()def _gpu_name() -> str:if _has_gpu():return torch.cuda.get_device_name(0)return "None"def _gpu_memory_gb() -> float:if _has_gpu():try:return torch.cuda.get_device_properties(0).total_mem / 1e9except:return 0return 0def _select_quantization() -> str:"""Auto-select quantization tier based on MODEL_ID and hardware."""user_mode = QUANTIZATION.lower()if user_mode == "none":return "none"if user_mode != "auto":return user_mode# Auto-detect: GPU with enough VRAM for requested modelif "7B" in MODEL_ID:if _has_gpu() and _gpu_memory_gb() >= 5.5:_log(f"7B model detected, GPU {_gpu_name()} ({_gpu_memory_gb():.1f}GB) β using 4-bit")return "4bit"_log("7B model requested but no GPU with 5.5GB+ VRAM β falling back to 1.5B 8-bit")return "cpu_fallback_8bit"if "1.5B" in MODEL_ID:if _has_gpu():_log(f"1.5B model detected, GPU available β using 8-bit")return "8bit"_log("1.5B model detected, CPU only β using bfloat16")return "none"return "none"def _build_model_kwargs(quant_mode: str) -> dict:"""Build pipeline kwargs based on quantization mode."""kwargs = {"trust_remote_code": True,}if quant_mode == "4bit":kwargs["device_map"] = "auto"kwargs["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_compute_dtype=torch.bfloat16,bnb_4bit_use_double_quant=USE_DOUBLE_QUANT,bnb_4bit_quant_type="nf4",)_log("β‘ 4-bit quantization enabled (NF4, double quant)")elif quant_mode == "8bit":kwargs["device_map"] = "auto"kwargs["quantization_config"] = BitsAndBytesConfig(load_in_8bit=True,)_log("β‘ 8-bit quantization enabled")elif quant_mode == "cpu_fallback_8bit":kwargs["device_map"] = "auto"kwargs["quantization_config"] = BitsAndBytesConfig(load_in_8bit=True,)_log("β‘ CPU fallback 8-bit for 1.5B model")else:kwargs["torch_dtype"] = torch.bfloat16kwargs["device_map"] = "auto"_log(f"π¦ Loading {MODEL_ID} in bfloat16 (CPU-friendly)")return kwargsdef get_pipe():global _pipe, _current_modelif _pipe is not None:return _pipeactual_model_id = MODEL_IDquant_mode = _select_quantization()# Handle CPU fallback for 7B β 1.5Bif quant_mode == "cpu_fallback_8bit":actual_model_id = "Qwen/Qwen2.5-1.5B-Instruct"_log(f"π Fallback: loading {actual_model_id} instead of {MODEL_ID}")_log(f"π Loading {actual_model_id} (quantization: {quant_mode})")_log(f" Hardware: GPU={_gpu_name()}, VRAM={_gpu_memory_gb():.1f}GB, CUDA={_has_gpu()}")try:kwargs = _build_model_kwargs(quant_mode)_pipe = pipeline("text-generation",model=actual_model_id,**kwargs)_current_model = actual_model_id_log("β Model loaded successfully!")except ImportError as e:if "bitsandbytes" in str(e):_log("β bitsandbytes not installed. Falling back to CPU bfloat16.")_pipe = pipeline("text-generation",model=actual_model_id,torch_dtype=torch.bfloat16,device_map="auto",trust_remote_code=True,)_current_model = actual_model_id_log("β Model loaded with CPU fallback")else:_log(f"β Model load failed: {e}")_pipe = Noneexcept Exception as e:_log(f"β Model load failed: {e}")_pipe = Nonereturn _pipedef generate_text(messages, temperature=0.3, max_new_tokens=2000):
.env.example+10
Dockerfile+5
requirements.txt+1
services/model_loader.py+125-10