Spaces:
Runtime error
Runtime error
Marcus Vinicius Zerbini Canhaço
commited on
Commit
·
534b64d
1
Parent(s):
9b6d2b8
force use GPU
Browse files- src/domain/factories/detector_factory.py +55 -1
- src/main.py +15 -8
src/domain/factories/detector_factory.py
CHANGED
|
@@ -31,6 +31,41 @@ load_dotenv()
|
|
| 31 |
logging.basicConfig(level=logging.INFO)
|
| 32 |
logger = logging.getLogger(__name__)
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
class BaseCache:
|
| 35 |
"""Cache base para armazenar resultados de detecção."""
|
| 36 |
def __init__(self, max_size: int = 1000):
|
|
@@ -293,4 +328,23 @@ class WeaponDetector:
|
|
| 293 |
# Forçar limpeza de memória
|
| 294 |
gc.collect()
|
| 295 |
if torch.cuda.is_available():
|
| 296 |
-
torch.cuda.empty_cache()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
logging.basicConfig(level=logging.INFO)
|
| 32 |
logger = logging.getLogger(__name__)
|
| 33 |
|
| 34 |
+
def force_gpu_init():
|
| 35 |
+
"""Força a inicialização da GPU."""
|
| 36 |
+
try:
|
| 37 |
+
# Forçar inicialização do CUDA
|
| 38 |
+
torch.cuda.init()
|
| 39 |
+
# Alocar e liberar um tensor pequeno para garantir que CUDA está funcionando
|
| 40 |
+
dummy = torch.cuda.FloatTensor(1)
|
| 41 |
+
del dummy
|
| 42 |
+
torch.cuda.empty_cache()
|
| 43 |
+
return True
|
| 44 |
+
except Exception as e:
|
| 45 |
+
logger.warning(f"Erro ao forçar inicialização da GPU: {str(e)}")
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
+
def is_gpu_available():
|
| 49 |
+
"""Verifica se a GPU está disponível de forma mais robusta."""
|
| 50 |
+
try:
|
| 51 |
+
if not torch.cuda.is_available():
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
# Tentar forçar inicialização
|
| 55 |
+
if not force_gpu_init():
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
# Verificar se há memória disponível
|
| 59 |
+
gpu_memory = torch.cuda.get_device_properties(0).total_memory
|
| 60 |
+
if gpu_memory < 4 * (1024**3): # Mínimo de 4GB
|
| 61 |
+
logger.warning("GPU encontrada mas com memória insuficiente")
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
return True
|
| 65 |
+
except Exception as e:
|
| 66 |
+
logger.warning(f"Erro ao verificar GPU: {str(e)}")
|
| 67 |
+
return False
|
| 68 |
+
|
| 69 |
class BaseCache:
|
| 70 |
"""Cache base para armazenar resultados de detecção."""
|
| 71 |
def __init__(self, max_size: int = 1000):
|
|
|
|
| 328 |
# Forçar limpeza de memória
|
| 329 |
gc.collect()
|
| 330 |
if torch.cuda.is_available():
|
| 331 |
+
torch.cuda.empty_cache()
|
| 332 |
+
|
| 333 |
+
class DetectorFactory:
|
| 334 |
+
"""Factory para criar a instância apropriada do detector."""
|
| 335 |
+
|
| 336 |
+
@staticmethod
|
| 337 |
+
def create_detector() -> BaseDetector:
|
| 338 |
+
"""Cria e retorna a instância apropriada do detector."""
|
| 339 |
+
try:
|
| 340 |
+
# Forçar verificação robusta de GPU
|
| 341 |
+
if is_gpu_available():
|
| 342 |
+
logger.info("GPU disponível e inicializada com sucesso")
|
| 343 |
+
return WeaponDetectorGPU()
|
| 344 |
+
else:
|
| 345 |
+
logger.warning("GPU não disponível ou com problemas, usando CPU")
|
| 346 |
+
return WeaponDetectorCPU()
|
| 347 |
+
except Exception as e:
|
| 348 |
+
logger.error(f"Erro ao criar detector: {str(e)}")
|
| 349 |
+
logger.warning("Fallback para CPU devido a erro")
|
| 350 |
+
return WeaponDetectorCPU()
|
src/main.py
CHANGED
|
@@ -4,6 +4,7 @@ from src.presentation.web.gradio_interface import GradioInterface
|
|
| 4 |
import logging
|
| 5 |
import torch
|
| 6 |
import gc
|
|
|
|
| 7 |
|
| 8 |
# Configurar logging
|
| 9 |
logging.basicConfig(
|
|
@@ -14,16 +15,21 @@ logger = logging.getLogger(__name__)
|
|
| 14 |
|
| 15 |
def setup_zero_gpu():
|
| 16 |
"""Configurações otimizadas para Zero-GPU."""
|
| 17 |
-
#
|
| 18 |
-
if
|
|
|
|
|
|
|
| 19 |
torch.cuda.empty_cache()
|
| 20 |
gc.collect()
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def main():
|
| 29 |
"""Função principal que inicia a aplicação."""
|
|
@@ -46,12 +52,13 @@ def main():
|
|
| 46 |
|
| 47 |
if IS_HUGGINGFACE:
|
| 48 |
# Calcular número ideal de workers baseado na GPU
|
| 49 |
-
if
|
| 50 |
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3) # em GB
|
| 51 |
max_concurrent = 1 # Forçar single worker para Zero-GPU
|
| 52 |
logger.info(f"GPU Memory: {gpu_mem:.1f}GB, Max Concurrent: {max_concurrent}")
|
| 53 |
else:
|
| 54 |
max_concurrent = 1
|
|
|
|
| 55 |
|
| 56 |
# Primeiro configurar a fila
|
| 57 |
demo = demo.queue(
|
|
|
|
| 4 |
import logging
|
| 5 |
import torch
|
| 6 |
import gc
|
| 7 |
+
from src.domain.factories.detector_factory import force_gpu_init, is_gpu_available
|
| 8 |
|
| 9 |
# Configurar logging
|
| 10 |
logging.basicConfig(
|
|
|
|
| 15 |
|
| 16 |
def setup_zero_gpu():
|
| 17 |
"""Configurações otimizadas para Zero-GPU."""
|
| 18 |
+
# Forçar inicialização da GPU
|
| 19 |
+
if is_gpu_available():
|
| 20 |
+
force_gpu_init()
|
| 21 |
+
# Limpar cache CUDA
|
| 22 |
torch.cuda.empty_cache()
|
| 23 |
gc.collect()
|
| 24 |
|
| 25 |
+
# Configurações para otimizar memória
|
| 26 |
+
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
|
| 27 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 28 |
+
torch.backends.cudnn.benchmark = True
|
| 29 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 30 |
+
logger.info("Configurações Zero-GPU aplicadas com sucesso")
|
| 31 |
+
else:
|
| 32 |
+
logger.warning("GPU não disponível para configuração Zero-GPU")
|
| 33 |
|
| 34 |
def main():
|
| 35 |
"""Função principal que inicia a aplicação."""
|
|
|
|
| 52 |
|
| 53 |
if IS_HUGGINGFACE:
|
| 54 |
# Calcular número ideal de workers baseado na GPU
|
| 55 |
+
if is_gpu_available():
|
| 56 |
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3) # em GB
|
| 57 |
max_concurrent = 1 # Forçar single worker para Zero-GPU
|
| 58 |
logger.info(f"GPU Memory: {gpu_mem:.1f}GB, Max Concurrent: {max_concurrent}")
|
| 59 |
else:
|
| 60 |
max_concurrent = 1
|
| 61 |
+
logger.warning("GPU não disponível, usando configuração mínima")
|
| 62 |
|
| 63 |
# Primeiro configurar a fila
|
| 64 |
demo = demo.queue(
|