Spaces:
Runtime error
Runtime error
Marcus Vinicius Zerbini Canhaço
commited on
Commit
·
cd2dff3
1
Parent(s):
274148b
feat: atualização do detector com otimizações para GPU T4
Browse files- src/main.py +64 -16
src/main.py
CHANGED
|
@@ -13,32 +13,79 @@ logging.basicConfig(
|
|
| 13 |
)
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def setup_zero_gpu():
|
| 17 |
"""Configurações otimizadas para Zero-GPU."""
|
| 18 |
try:
|
| 19 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
if is_gpu_available():
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
torch.cuda.empty_cache()
|
| 24 |
gc.collect()
|
| 25 |
-
|
| 26 |
-
# Configurações
|
| 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
|
| 33 |
-
|
| 34 |
-
torch.cuda.set_per_process_memory_fraction(0.9) # Usar 90% da memória disponível
|
| 35 |
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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."""
|
|
@@ -50,19 +97,20 @@ def main():
|
|
| 50 |
if IS_HUGGINGFACE:
|
| 51 |
load_dotenv('.env.huggingface')
|
| 52 |
logger.info("Ambiente HuggingFace detectado")
|
| 53 |
-
setup_zero_gpu()
|
| 54 |
else:
|
| 55 |
load_dotenv('.env')
|
| 56 |
logger.info("Ambiente local detectado")
|
|
|
|
| 57 |
|
| 58 |
# Criar e configurar interface
|
| 59 |
interface = GradioInterface()
|
| 60 |
demo = interface.create_interface()
|
| 61 |
|
| 62 |
if IS_HUGGINGFACE:
|
| 63 |
-
#
|
| 64 |
-
if
|
| 65 |
-
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)
|
| 66 |
max_concurrent = 1 # Forçar single worker para Zero-GPU
|
| 67 |
logger.info(f"GPU Memory: {gpu_mem:.1f}GB, Max Concurrent: {max_concurrent}")
|
| 68 |
else:
|
|
@@ -70,13 +118,14 @@ def main():
|
|
| 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 |
-
#
|
| 74 |
demo = demo.queue(
|
| 75 |
api_open=False,
|
| 76 |
status_update_rate="auto",
|
| 77 |
max_size=5 # Reduzir tamanho da fila para economizar memória
|
| 78 |
)
|
| 79 |
-
|
|
|
|
| 80 |
demo.launch(
|
| 81 |
server_name="0.0.0.0",
|
| 82 |
server_port=7860,
|
|
@@ -84,7 +133,6 @@ def main():
|
|
| 84 |
max_threads=2 # Reduzir número de threads
|
| 85 |
)
|
| 86 |
else:
|
| 87 |
-
# Ambiente local - apenas launch direto
|
| 88 |
demo.launch(
|
| 89 |
server_name="0.0.0.0",
|
| 90 |
server_port=7860,
|
|
|
|
| 13 |
)
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
+
def check_cuda_environment():
|
| 17 |
+
"""Verifica e configura o ambiente CUDA."""
|
| 18 |
+
try:
|
| 19 |
+
# Verificar variáveis de ambiente CUDA
|
| 20 |
+
cuda_path = os.getenv('CUDA_HOME') or os.getenv('CUDA_PATH')
|
| 21 |
+
if not cuda_path:
|
| 22 |
+
logger.warning("Variáveis de ambiente CUDA não encontradas")
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
# Verificar se CUDA está disponível no PyTorch
|
| 26 |
+
if not torch.cuda.is_available():
|
| 27 |
+
logger.warning("PyTorch não detectou CUDA")
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
# Tentar obter informações da GPU
|
| 31 |
+
try:
|
| 32 |
+
device_count = torch.cuda.device_count()
|
| 33 |
+
if device_count > 0:
|
| 34 |
+
device_name = torch.cuda.get_device_name(0)
|
| 35 |
+
logger.info(f"GPU detectada: {device_name}")
|
| 36 |
+
return True
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.warning(f"Erro ao obter informações da GPU: {str(e)}")
|
| 39 |
+
|
| 40 |
+
return False
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logger.error(f"Erro ao verificar ambiente CUDA: {str(e)}")
|
| 43 |
+
return False
|
| 44 |
+
|
| 45 |
def setup_zero_gpu():
|
| 46 |
"""Configurações otimizadas para Zero-GPU."""
|
| 47 |
try:
|
| 48 |
+
# Verificar ambiente CUDA primeiro
|
| 49 |
+
if not check_cuda_environment():
|
| 50 |
+
logger.warning("Ambiente CUDA não está configurado corretamente")
|
| 51 |
+
return False
|
| 52 |
+
|
| 53 |
+
# Tentar inicializar GPU
|
| 54 |
if is_gpu_available():
|
| 55 |
+
# Configurar ambiente
|
| 56 |
+
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
|
| 57 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
|
| 58 |
+
|
| 59 |
+
# Limpar memória
|
| 60 |
torch.cuda.empty_cache()
|
| 61 |
gc.collect()
|
| 62 |
+
|
| 63 |
+
# Configurações de memória e performance
|
| 64 |
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
|
| 65 |
torch.backends.cuda.matmul.allow_tf32 = True
|
| 66 |
torch.backends.cudnn.benchmark = True
|
| 67 |
torch.backends.cudnn.allow_tf32 = True
|
| 68 |
|
| 69 |
+
# Configurar fração de memória
|
| 70 |
+
torch.cuda.set_per_process_memory_fraction(0.9)
|
|
|
|
| 71 |
|
| 72 |
+
# Verificar se a configuração foi bem sucedida
|
| 73 |
+
try:
|
| 74 |
+
device = torch.device('cuda')
|
| 75 |
+
dummy = torch.zeros(1, device=device)
|
| 76 |
+
del dummy
|
| 77 |
+
logger.info(f"Configurações Zero-GPU aplicadas com sucesso na GPU: {torch.cuda.get_device_name(0)}")
|
| 78 |
+
return True
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.error(f"Erro ao configurar GPU: {str(e)}")
|
| 81 |
+
return False
|
| 82 |
else:
|
| 83 |
logger.warning("GPU não disponível para configuração Zero-GPU. O sistema operará em modo CPU.")
|
| 84 |
+
return False
|
| 85 |
except Exception as e:
|
| 86 |
logger.error(f"Erro ao configurar Zero-GPU: {str(e)}")
|
| 87 |
logger.warning("Fallback para modo CPU devido a erro na configuração da GPU.")
|
| 88 |
+
return False
|
| 89 |
|
| 90 |
def main():
|
| 91 |
"""Função principal que inicia a aplicação."""
|
|
|
|
| 97 |
if IS_HUGGINGFACE:
|
| 98 |
load_dotenv('.env.huggingface')
|
| 99 |
logger.info("Ambiente HuggingFace detectado")
|
| 100 |
+
gpu_available = setup_zero_gpu()
|
| 101 |
else:
|
| 102 |
load_dotenv('.env')
|
| 103 |
logger.info("Ambiente local detectado")
|
| 104 |
+
gpu_available = False
|
| 105 |
|
| 106 |
# Criar e configurar interface
|
| 107 |
interface = GradioInterface()
|
| 108 |
demo = interface.create_interface()
|
| 109 |
|
| 110 |
if IS_HUGGINGFACE:
|
| 111 |
+
# Configurar com base na disponibilidade da GPU
|
| 112 |
+
if gpu_available:
|
| 113 |
+
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)
|
| 114 |
max_concurrent = 1 # Forçar single worker para Zero-GPU
|
| 115 |
logger.info(f"GPU Memory: {gpu_mem:.1f}GB, Max Concurrent: {max_concurrent}")
|
| 116 |
else:
|
|
|
|
| 118 |
logger.warning("GPU não disponível. O sistema está operando em modo CPU. " +
|
| 119 |
"Todas as funcionalidades estão disponíveis, mas o processamento será mais lento.")
|
| 120 |
|
| 121 |
+
# Configurar fila
|
| 122 |
demo = demo.queue(
|
| 123 |
api_open=False,
|
| 124 |
status_update_rate="auto",
|
| 125 |
max_size=5 # Reduzir tamanho da fila para economizar memória
|
| 126 |
)
|
| 127 |
+
|
| 128 |
+
# Launch
|
| 129 |
demo.launch(
|
| 130 |
server_name="0.0.0.0",
|
| 131 |
server_port=7860,
|
|
|
|
| 133 |
max_threads=2 # Reduzir número de threads
|
| 134 |
)
|
| 135 |
else:
|
|
|
|
| 136 |
demo.launch(
|
| 137 |
server_name="0.0.0.0",
|
| 138 |
server_port=7860,
|