Download modules/local_gpu_llm.py from akra35567/Akiragpu: direct link, hf CLI and curl.
- Browser
- Download file 21.3 kB
-
https://huggingface.co/spaces/akra35567/Akiragpu/resolve/main/modules/local_gpu_llm.py
- Command line
-
hf download hf://spaces/akra35567/Akiragpu/modules/local_gpu_llm.py
-
curl -L -o local_gpu_llm.py https://huggingface.co/spaces/akra35567/Akiragpu/resolve/main/modules/local_gpu_llm.py
21.3 kB
| # type: ignore | |
| """ | |
| modules/local_gpu_llm.py | |
| ================================================================================ | |
| LLM LOCAL GPU - PRIMEIRA PRIORIDADE DA CHAIN (Space Akiragpu / NVIDIA L4) | |
| ================================================================================ | |
| Modelo local 4-bit (bitsandbytes) carregado de forma LAZY em CUDA. | |
| Hierarquia nova (AKIRA GPU): | |
| 1. Este módulo (inferência local, sem custo de API) | |
| 2. HF Router / Mistral / Gemini ... (cloud, apenas se o local falhar) | |
| Configuração via env: | |
| AKIRA_LOCAL_MODEL modelo HF (default: Qwen/Qwen2.5-7B-Instruct) | |
| LOCAL_GPU_ENABLED "true"/"false" (default: true) | |
| AKIRA_LOCAL_MAX_NEW máx. tokens gerados (default: 1024) | |
| Notas: | |
| - Import de torch/transformers é LAZY (só na 1ª chamada) → cold start rápido. | |
| - OOM é apanhado: limpa cache CUDA e devolve None → cloud assume. | |
| - Singleton + lock de geração (FastAPI e Gradio podem pedir em paralelo). | |
| ================================================================================ | |
| """ | |
| import os | |
| import threading | |
| import time | |
| from typing import Optional, List, Dict, Any | |
| try: | |
| from loguru import logger # type: ignore | |
| LOGURU_AVAILABLE = True | |
| except Exception: | |
| LOGURU_AVAILABLE = False | |
| class _DummyLogger: | |
| def info(self, *a, **k): pass | |
| def success(self, *a, **k): pass | |
| def warning(self, *a, **k): pass | |
| def error(self, *a, **k): pass | |
| def debug(self, *a, **k): pass | |
| logger = _DummyLogger() # type: ignore | |
| # 7B 4-bit (~5GB bitsandbytes) em vez de 3B bf16 (~7GB): mais inteligente e carrega | |
| # mais rápido. Override: AKIRA_LOCAL_MODEL. Quantização: AKIRA_QUANT (default=4bit). | |
| DEFAULT_MODEL = os.getenv("AKIRA_LOCAL_MODEL", "Qwen/Qwen2.5-7B-Instruct") | |
| def _hf_cache_dir() -> Optional[str]: | |
| """Cache HF EXPLÍCITO e persistente. | |
| O env HF_HOME não chega se huggingface_hub já tiver sido importado (as | |
| constantes são calculadas à importação) — e foi exatamente isso que fez o | |
| 1º load baixar os pesos DENTRO da janela GPU (86s). Cache_dir explícito | |
| em prefetch() e from_pretrained() garante que leem do volume /data. | |
| """ | |
| explicit = os.getenv("AKIRA_HF_CACHE") | |
| if explicit: | |
| return explicit | |
| if os.path.isdir("/data") and os.access("/data", os.W_OK): | |
| return "/data/hf_cache/hub" | |
| return None | |
| def _env_flag(name: str, default: bool = True) -> bool: | |
| raw = os.getenv(name) | |
| if raw is None or raw.strip() == "": | |
| return default | |
| return raw.strip().lower() in ("1", "true", "yes", "on") | |
| class LocalGPUModel: | |
| """Singleton com modelo causal 4-bit residente na GPU.""" | |
| _instance = None | |
| def __new__(cls): | |
| if cls._instance is None: | |
| cls._instance = super().__new__(cls) | |
| cls._instance._initialized = False | |
| return cls._instance | |
| def __init__(self): | |
| if getattr(self, "_initialized", False): | |
| return | |
| self._initialized = True | |
| self._model_name: str = DEFAULT_MODEL | |
| self._model = None | |
| self._tokenizer = None | |
| self._loaded: bool = False | |
| self._load_failed: bool = False | |
| self._load_attempts: int = 0 | |
| self._prefetched: bool = False | |
| self._load_error: Optional[str] = None | |
| self._last_error: Optional[str] = None | |
| self._load_lock = threading.Lock() | |
| self._gen_lock = threading.Lock() | |
| self._max_new_tokens: int = int(os.getenv("AKIRA_LOCAL_MAX_NEW", "1024")) | |
| self._temperature: float = 0.7 | |
| self._top_p: float = 0.9 | |
| self._repetition_penalty: float = 1.12 | |
| self._stats: Dict[str, Any] = { | |
| "total_calls": 0, | |
| "successful_calls": 0, | |
| "failed_calls": 0, | |
| "oom_events": 0, | |
| "load_seconds": None, | |
| "last_used": None, | |
| "model_name": self._model_name, | |
| } | |
| # ------------------------------------------------------------------ | |
| # Disponibilidade / carga | |
| # ------------------------------------------------------------------ | |
| def enabled(self) -> bool: | |
| return _env_flag("LOCAL_GPU_ENABLED", True) | |
| def cuda_available(self) -> bool: | |
| """CUDA real e utilizável. | |
| Em ZeroGPU, `torch.cuda.is_available()` devolve True FORA dos | |
| decorators @spaces.GPU, mas qualquer operação CUDA levanta | |
| "Low-level CUDA init ... did not intercept a CUDA operation". | |
| Prova com uma operação mínima para não tentar carregar o modelo à toa. | |
| """ | |
| try: | |
| import torch # type: ignore | |
| if not torch.cuda.is_available(): | |
| return False | |
| torch.zeros(1, device="cuda") | |
| return True | |
| except Exception: | |
| return False | |
| def is_available(self) -> bool: | |
| """Pronto a ser usado (env ligada + CUDA presente).""" | |
| return self.enabled and self.cuda_available() | |
| def is_loaded(self) -> bool: | |
| return self._loaded | |
| def _retry_allowed(self) -> bool: | |
| """LOCAL_GPU_RETRY_ON_FAIL explícito > senão orçamento de tentativas. | |
| Em ZeroGPU uma falha de load costuma ser quota/timeout (transitória), | |
| por isso não travamos o local à primeira — mas também não re-tentamos | |
| para sempre dentro da janela GPU. | |
| """ | |
| raw = os.getenv("LOCAL_GPU_RETRY_ON_FAIL") | |
| if raw is not None and raw.strip() != "": | |
| return _env_flag("LOCAL_GPU_RETRY_ON_FAIL", True) | |
| try: | |
| max_attempts = int(os.getenv("LOCAL_GPU_MAX_LOAD_RETRIES", "3") or 3) | |
| except ValueError: | |
| max_attempts = 3 | |
| return self._load_attempts < max_attempts | |
| def prefetch(self) -> bool: | |
| """Descarrega os pesos para o cache HF — SEM GPU (corre no arranque). | |
| Fazê-lo aqui significa que o load dentro do @spaces.GPU é só leitura | |
| de disco local: cabe na janela de 60s do tier FREE e não gasta quota. | |
| """ | |
| if self._prefetched: | |
| return True | |
| if not self.enabled: | |
| return False | |
| try: | |
| from .hf_auth import snapshot_cached # type: ignore | |
| t0 = time.time() | |
| ok = snapshot_cached(self._model_name, cache_dir=_hf_cache_dir()) | |
| if not ok: | |
| return False | |
| self._prefetched = True | |
| logger.info( | |
| f"[LOCAL-GPU] Pesos pré-descarregados em {time.time() - t0:.0f}s " | |
| f"({self._model_name} → {_hf_cache_dir() or 'cache HF default'})" | |
| ) | |
| return True | |
| except Exception as e: | |
| logger.warning(f"[LOCAL-GPU] Pré-download falhou ({self._model_name}): {e}") | |
| return False | |
| def _gpu_still_holds_model(self) -> bool: | |
| """Os tensores continuam válidos na GPU? Em ZeroGPU a VRAM é libertada no | |
| fim de cada chamada decorada — ficam órfãos e a geração rebentaria.""" | |
| if self._model is None: | |
| return False | |
| try: | |
| import torch # type: ignore | |
| torch.zeros(1, device="cuda") # prova que o contexto responde | |
| return torch.cuda.memory_allocated(0) >= 512 * 1024 * 1024 | |
| except Exception: | |
| return False | |
| def ensure_loaded(self) -> bool: | |
| """Carrega tokenizer+modelo 4-bit na GPU (lazy, thread-safe).""" | |
| if self._loaded: | |
| if not self.cuda_available(): | |
| # Sem contexto GPU (quota esgotada / fora do decorator): mantém | |
| # o estado como está e deixa a cloud assumir. | |
| return False | |
| if self._gpu_still_holds_model(): | |
| return True | |
| logger.warning("[LOCAL-GPU] VRAM libertada entre chamadas — a recarregar o modelo") | |
| self._free_cuda() | |
| self._loaded = False | |
| if self._load_failed and not self._retry_allowed(): | |
| return False | |
| if not self.is_available(): | |
| return False | |
| with self._load_lock: | |
| if self._loaded: | |
| return True | |
| if self._load_failed and not self._retry_allowed(): | |
| return False | |
| t0 = time.time() | |
| try: | |
| self._load_attempts += 1 | |
| import torch # type: ignore | |
| from transformers import ( # type: ignore | |
| AutoTokenizer, | |
| AutoModelForCausalLM, | |
| ) | |
| logger.info(f"[LOCAL-GPU] A carregar modelo local: {self._model_name}") | |
| # 7B 4-bit (~5GB bitsandbytes) em vez de 3B bf16 (~7GB): | |
| # mais inteligente, mais leve, carrega mais rápido. | |
| # AKIRA_QUANT=bf16 força bf16 (apenas GPUs grandes). | |
| quant_mode = os.getenv("AKIRA_QUANT", "4bit").strip().lower() | |
| quant = None | |
| if quant_mode == "4bit": | |
| from transformers import BitsAndBytesConfig # type: ignore | |
| quant = BitsAndBytesConfig( | |
| load_in_4bit=True, bnb_4bit_quant_type="nf4", | |
| bnb_4bit_compute_dtype=torch.bfloat16, | |
| bnb_4bit_use_double_quant=True, | |
| ) | |
| logger.info("[LOCAL-GPU] Modo 4-bit (GPUs 16GB: T4 Kaggle/Lightning)") | |
| cache_dir = _hf_cache_dir() | |
| self._tokenizer = AutoTokenizer.from_pretrained( | |
| self._model_name, | |
| trust_remote_code=True, | |
| padding_side="left", | |
| cache_dir=cache_dir, | |
| ) | |
| if self._tokenizer.pad_token is None: | |
| self._tokenizer.pad_token = self._tokenizer.eos_token | |
| if quant is not None: | |
| self._model = AutoModelForCausalLM.from_pretrained( | |
| self._model_name, | |
| quantization_config=quant, | |
| device_map="cuda:0", | |
| dtype=torch.bfloat16, | |
| trust_remote_code=True, | |
| cache_dir=cache_dir, | |
| low_cpu_mem_usage=True, | |
| ) | |
| else: | |
| self._model = AutoModelForCausalLM.from_pretrained( | |
| self._model_name, | |
| torch_dtype=torch.bfloat16, | |
| trust_remote_code=True, | |
| cache_dir=cache_dir, | |
| low_cpu_mem_usage=True, | |
| ) | |
| self._model.to("cuda") | |
| self._model.eval() | |
| assert next(self._model.parameters()).device.type == "cuda", "LLM carregado fora da GPU" | |
| self._loaded = True | |
| self._load_failed = False | |
| self._load_attempts = 0 | |
| self._load_error = None | |
| self._stats["load_seconds"] = round(time.time() - t0, 1) | |
| try: | |
| self.gpu_info(probe=True) # dentro do contexto GPU → cache p/ Status | |
| except Exception: | |
| pass | |
| logger.success( | |
| f"[LOCAL-GPU] Modelo pronto em {self._stats['load_seconds']}s " | |
| f"({self._model_name}) | VRAM: {self.vram_used_mb():.0f} MB" | |
| ) | |
| return True | |
| except Exception as e: | |
| self._load_failed = True | |
| self._load_error = str(e) | |
| self._model = None | |
| self._tokenizer = None | |
| logger.error(f"[LOCAL-GPU] Falha ao carregar {self._model_name}: {e}") | |
| self._free_cuda() | |
| return False | |
| def _free_cuda(self): | |
| try: | |
| import torch # type: ignore | |
| self._model = None | |
| self._tokenizer = None | |
| import gc | |
| gc.collect() | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| torch.cuda.ipc_collect() | |
| except Exception: | |
| pass | |
| # ------------------------------------------------------------------ | |
| # Geração | |
| # ------------------------------------------------------------------ | |
| def generate( | |
| self, | |
| prompt: str, | |
| system_prompt: Optional[str] = None, | |
| context_history: Optional[List[dict]] = None, | |
| max_tokens: Optional[int] = None, | |
| temperature: Optional[float] = None, | |
| ) -> Optional[str]: | |
| """ | |
| Gera resposta com o modelo local. Devolve None em qualquer falha | |
| (CUDA ausente, OOM, erro de template) para a chain cair na cloud. | |
| """ | |
| self._stats["total_calls"] += 1 | |
| if not self.ensure_loaded(): | |
| self._stats["failed_calls"] += 1 | |
| return None | |
| import torch # type: ignore | |
| messages: List[Dict[str, str]] = [] | |
| if system_prompt: | |
| messages.append({"role": "system", "content": system_prompt}) | |
| for turn in (context_history or []): | |
| role = turn.get("role", "user") | |
| content = turn.get("content", "") | |
| if role in ("user", "assistant") and content: | |
| messages.append({"role": role, "content": str(content)}) | |
| messages.append({"role": "user", "content": prompt}) | |
| try: | |
| # apply_chat_template c/ return_tensors devolve BatchEncoding | |
| # (não tensor) — extrair input_ids/attention_mask explicitamente. | |
| enc = self._tokenizer.apply_chat_template( | |
| messages, | |
| tokenize=True, | |
| add_generation_prompt=True, | |
| return_tensors="pt", | |
| ) | |
| input_ids = enc["input_ids"].to("cuda:0") | |
| _attn = enc.get("attention_mask") | |
| if _attn is not None: | |
| _attn = _attn.to("cuda:0") | |
| input_len = input_ids.shape[1] | |
| new_tokens = int(max_tokens or self._max_new_tokens) | |
| # Proteção: nunca gerar mais que o contexto do modelo | |
| try: | |
| ctx = getattr(self._model.config, "max_position_embeddings", 8192) or 8192 | |
| new_tokens = min(new_tokens, max(64, ctx - input_len - 8)) | |
| except Exception: | |
| pass | |
| temp = self._temperature if temperature is None else float(temperature) | |
| do_sample = temp > 0.05 | |
| with self._gen_lock: | |
| with torch.inference_mode(): | |
| output_ids = self._model.generate( | |
| input_ids, | |
| attention_mask=_attn, | |
| max_new_tokens=new_tokens, | |
| do_sample=do_sample, | |
| temperature=max(temp, 0.05) if do_sample else None, | |
| top_p=self._top_p if do_sample else None, | |
| repetition_penalty=self._repetition_penalty, | |
| pad_token_id=self._tokenizer.pad_token_id, | |
| eos_token_id=self._tokenizer.eos_token_id, | |
| ) | |
| generated = output_ids[0][input_len:] | |
| text = self._tokenizer.decode(generated, skip_special_tokens=True).strip() | |
| if not text: | |
| self._stats["failed_calls"] += 1 | |
| return None | |
| self._stats["successful_calls"] += 1 | |
| self._stats["last_used"] = time.time() | |
| return text | |
| except Exception as e: | |
| err = str(e) | |
| is_oom = "out of memory" in err.lower() or "cuda" in err.lower() and "alloc" in err.lower() | |
| if is_oom: | |
| self._stats["oom_events"] += 1 | |
| logger.warning(f"[LOCAL-GPU] OOM — a libertar cache e a cair para cloud: {e}") | |
| self._free_cuda() | |
| else: | |
| logger.error(f"[LOCAL-GPU] Erro de geração: {e}") | |
| self._last_error = err | |
| self._stats["failed_calls"] += 1 | |
| return None | |
| # ------------------------------------------------------------------ | |
| # Status (aba Gradio) | |
| # ------------------------------------------------------------------ | |
| def vram_used_mb(self) -> float: | |
| try: | |
| import torch # type: ignore | |
| if torch.cuda.is_available(): | |
| return torch.cuda.memory_allocated(0) / (1024 * 1024) | |
| except Exception: | |
| pass | |
| return 0.0 | |
| def _probe_nvidia_smi(self, info: Dict[str, Any]) -> None: | |
| """Device via NVML/nvidia-smi — NÃO cria contexto CUDA, pelo que é seguro | |
| FORA do @spaces.GPU (a queries via torch penduravam o arranque). | |
| Timeout de 5s para nunca atrasar o startup.""" | |
| import subprocess # noqa: WPS433 (local: só aqui) | |
| try: | |
| out = subprocess.run( | |
| ["nvidia-smi", "--query-gpu=name,memory.total,compute_cap", | |
| "--format=csv,noheader"], | |
| capture_output=True, text=True, timeout=5, | |
| ) | |
| if out.returncode != 0 or not (out.stdout or "").strip(): | |
| info["nvidia_smi"] = (out.stderr or "").strip()[:120] or "sem saída" | |
| return | |
| parts = [p.strip() for p in out.stdout.strip().splitlines()[0].split(",")] | |
| if parts and parts[0]: | |
| info["device"] = parts[0] | |
| if len(parts) > 1 and parts[1]: | |
| try: | |
| info["vram_gb"] = round(float(parts[1].replace("MiB", "").replace("MB", "").strip()) / 1024, 1) | |
| except ValueError: | |
| pass | |
| if len(parts) > 2 and parts[2]: | |
| info["capability"] = parts[2] | |
| except Exception as e: | |
| info["nvidia_smi"] = str(e)[:120] | |
| if info.get("device"): | |
| self._gpu_info_cache = dict(info) | |
| def gpu_info(self, probe: bool = False) -> Dict[str, Any]: | |
| """Identificação do dispositivo que o ZeroGPU nos dá. | |
| O pool ZeroGPU é migrado pelo HF (A10G → H200 → RTX Pro 6000 Blackwell) | |
| sem mudar o nosso código, por isso reportamos device/capability e as | |
| versões de torch/bitsandbytes — é isso que decide se o 4-bit nf4 tem | |
| kernels para a arquitectura. | |
| ATENÇÃO: `probe=True` só pode ser chamado DENTRO de um @spaces.GPU: | |
| fora do contexto o ZeroGPU intercepta as queries de dispositivo e o | |
| arranque fica pendurado (blocker confirmado em 729353d). | |
| """ | |
| info: Dict[str, Any] = dict(getattr(self, "_gpu_info_cache", None) or {}) | |
| try: | |
| import torch # type: ignore | |
| info["torch"] = getattr(torch, "__version__", "?") | |
| info["cuda"] = str(getattr(getattr(torch, "version", None), "cuda", "") or "") | |
| except Exception: | |
| pass | |
| if not probe: | |
| if not info.get("bitsandbytes"): | |
| info["bitsandbytes"] = "(versão só dentro do contexto GPU)" | |
| if not info.get("device"): | |
| self._probe_nvidia_smi(info) | |
| return info | |
| try: | |
| import torch # type: ignore | |
| if torch.cuda.is_available(): | |
| props = torch.cuda.get_device_properties(0) | |
| info["device"] = torch.cuda.get_device_name(0) | |
| info["vram_gb"] = round(props.total_memory / (1024 ** 3), 1) | |
| info["capability"] = f"{props.major}.{props.minor}" | |
| except Exception as e: | |
| info["error"] = str(e)[:200] | |
| try: | |
| import bitsandbytes as bnb # type: ignore | |
| info["bitsandbytes"] = getattr(bnb, "__version__", "?") | |
| except Exception as e: | |
| info["bitsandbytes"] = f"indisponível: {str(e)[:80]}" | |
| if info.get("device"): | |
| self._gpu_info_cache = info | |
| return info | |
| def get_status(self, probe_gpu: bool = False) -> Dict[str, Any]: | |
| return { | |
| "enabled": self.enabled, | |
| "cuda_available": self.cuda_available(), | |
| "loaded": self._loaded, | |
| "load_failed": self._load_failed, | |
| "model_name": self._model_name, | |
| "vram_used_mb": round(self.vram_used_mb(), 1), | |
| "load_error": self._load_error, | |
| "last_error": self._last_error, | |
| "gpu": self.gpu_info(probe=probe_gpu), | |
| "stats": dict(self._stats), | |
| } | |
| # ---------------------------------------------------------------------- | |
| # API pública | |
| # ---------------------------------------------------------------------- | |
| def get_local_gpu() -> LocalGPUModel: | |
| """Instância singleton do modelo local GPU.""" | |
| return LocalGPUModel() | |
| def generate_local_gpu( | |
| prompt: str, | |
| system_prompt: Optional[str] = None, | |
| context_history: Optional[List[dict]] = None, | |
| max_tokens: Optional[int] = None, | |
| temperature: Optional[float] = None, | |
| ) -> Optional[str]: | |
| """Atalho: gera com o modelo local (None = usar cloud).""" | |
| return get_local_gpu().generate( | |
| prompt=prompt, | |
| system_prompt=system_prompt, | |
| context_history=context_history, | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| ) | |
| __all__ = [ | |
| "LocalGPUModel", | |
| "get_local_gpu", | |
| "generate_local_gpu", | |
| ] | |