Spaces:
Runtime error
Runtime error
Marcus Vinicius Zerbini Canhaço
commited on
Commit
·
274148b
1
Parent(s):
534b64d
feat: atualização do detector com otimizações para GPU T4
Browse files- src/domain/factories/detector_factory.py +39 -15
- src/main.py +26 -16
src/domain/factories/detector_factory.py
CHANGED
|
@@ -34,13 +34,19 @@ logger = logging.getLogger(__name__)
|
|
| 34 |
def force_gpu_init():
|
| 35 |
"""Força a inicialização da GPU."""
|
| 36 |
try:
|
| 37 |
-
#
|
| 38 |
-
torch.cuda.
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
except Exception as e:
|
| 45 |
logger.warning(f"Erro ao forçar inicialização da GPU: {str(e)}")
|
| 46 |
return False
|
|
@@ -48,22 +54,38 @@ def force_gpu_init():
|
|
| 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 |
-
#
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
|
@@ -342,9 +364,11 @@ class DetectorFactory:
|
|
| 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
|
|
|
|
| 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()
|
|
|
|
| 34 |
def force_gpu_init():
|
| 35 |
"""Força a inicialização da GPU."""
|
| 36 |
try:
|
| 37 |
+
# Verificar se CUDA está disponível
|
| 38 |
+
if not torch.cuda.is_available():
|
| 39 |
+
return False
|
| 40 |
+
|
| 41 |
+
# Tentar alocar um tensor na GPU
|
| 42 |
+
try:
|
| 43 |
+
dummy = torch.cuda.FloatTensor(1)
|
| 44 |
+
del dummy
|
| 45 |
+
torch.cuda.empty_cache()
|
| 46 |
+
return True
|
| 47 |
+
except RuntimeError:
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
except Exception as e:
|
| 51 |
logger.warning(f"Erro ao forçar inicialização da GPU: {str(e)}")
|
| 52 |
return False
|
|
|
|
| 54 |
def is_gpu_available():
|
| 55 |
"""Verifica se a GPU está disponível de forma mais robusta."""
|
| 56 |
try:
|
| 57 |
+
# Verificar CUDA primeiro
|
| 58 |
if not torch.cuda.is_available():
|
| 59 |
+
logger.warning("CUDA não está disponível")
|
| 60 |
return False
|
| 61 |
|
| 62 |
# Tentar forçar inicialização
|
| 63 |
if not force_gpu_init():
|
| 64 |
+
logger.warning("Não foi possível inicializar a GPU")
|
| 65 |
return False
|
| 66 |
|
| 67 |
+
# Tentar obter informações da GPU
|
| 68 |
+
try:
|
| 69 |
+
device_count = torch.cuda.device_count()
|
| 70 |
+
if device_count == 0:
|
| 71 |
+
logger.warning("Nenhuma GPU encontrada")
|
| 72 |
+
return False
|
| 73 |
+
|
| 74 |
+
# Verificar se podemos realmente usar a GPU
|
| 75 |
+
device = torch.device('cuda')
|
| 76 |
+
dummy_tensor = torch.zeros(1, device=device)
|
| 77 |
+
del dummy_tensor
|
| 78 |
+
torch.cuda.empty_cache()
|
| 79 |
+
|
| 80 |
+
logger.info(f"GPU disponível: {torch.cuda.get_device_name(0)}")
|
| 81 |
+
return True
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
logger.warning(f"Erro ao verificar GPU: {str(e)}")
|
| 85 |
return False
|
| 86 |
|
|
|
|
| 87 |
except Exception as e:
|
| 88 |
+
logger.warning(f"Erro ao verificar disponibilidade da GPU: {str(e)}")
|
| 89 |
return False
|
| 90 |
|
| 91 |
class BaseCache:
|
|
|
|
| 364 |
logger.info("GPU disponível e inicializada com sucesso")
|
| 365 |
return WeaponDetectorGPU()
|
| 366 |
else:
|
| 367 |
+
logger.warning("GPU não disponível ou com problemas. ATENÇÃO: O sistema funcionará em modo CPU, " +
|
| 368 |
+
"que é mais lento mas igualmente funcional. Performance será reduzida.")
|
| 369 |
return WeaponDetectorCPU()
|
| 370 |
except Exception as e:
|
| 371 |
logger.error(f"Erro ao criar detector: {str(e)}")
|
| 372 |
+
logger.warning("Fallback para CPU devido a erro. O sistema continuará funcionando, " +
|
| 373 |
+
"mas com performance reduzida.")
|
| 374 |
return WeaponDetectorCPU()
|
src/main.py
CHANGED
|
@@ -15,21 +15,30 @@ logger = logging.getLogger(__name__)
|
|
| 15 |
|
| 16 |
def setup_zero_gpu():
|
| 17 |
"""Configurações otimizadas para Zero-GPU."""
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
def main():
|
| 35 |
"""Função principal que inicia a aplicação."""
|
|
@@ -58,7 +67,8 @@ def main():
|
|
| 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
|
|
|
|
| 62 |
|
| 63 |
# Primeiro configurar a fila
|
| 64 |
demo = demo.queue(
|
|
|
|
| 15 |
|
| 16 |
def setup_zero_gpu():
|
| 17 |
"""Configurações otimizadas para Zero-GPU."""
|
| 18 |
+
try:
|
| 19 |
+
# Forçar inicialização da GPU
|
| 20 |
+
if is_gpu_available():
|
| 21 |
+
force_gpu_init()
|
| 22 |
+
# Limpar cache CUDA
|
| 23 |
+
torch.cuda.empty_cache()
|
| 24 |
+
gc.collect()
|
| 25 |
+
|
| 26 |
+
# Configurações para otimizar memória
|
| 27 |
+
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
|
| 28 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 29 |
+
torch.backends.cudnn.benchmark = True
|
| 30 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 31 |
+
|
| 32 |
+
# Configurar device map para melhor utilização da memória
|
| 33 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 34 |
+
torch.cuda.set_per_process_memory_fraction(0.9) # Usar 90% da memória disponível
|
| 35 |
+
|
| 36 |
+
logger.info(f"Configurações Zero-GPU aplicadas com sucesso na GPU: {torch.cuda.get_device_name(0)}")
|
| 37 |
+
else:
|
| 38 |
+
logger.warning("GPU não disponível para configuração Zero-GPU. O sistema operará em modo CPU.")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"Erro ao configurar Zero-GPU: {str(e)}")
|
| 41 |
+
logger.warning("Fallback para modo CPU devido a erro na configuração da GPU.")
|
| 42 |
|
| 43 |
def main():
|
| 44 |
"""Função principal que inicia a aplicação."""
|
|
|
|
| 67 |
logger.info(f"GPU Memory: {gpu_mem:.1f}GB, Max Concurrent: {max_concurrent}")
|
| 68 |
else:
|
| 69 |
max_concurrent = 1
|
| 70 |
+
logger.warning("GPU não disponível. O sistema está operando em modo CPU. " +
|
| 71 |
+
"Todas as funcionalidades estão disponíveis, mas o processamento será mais lento.")
|
| 72 |
|
| 73 |
# Primeiro configurar a fila
|
| 74 |
demo = demo.queue(
|