Spaces:
Sleeping
Sleeping
Marcus Vinicius Zerbini Canhaço
commited on
Commit
·
3374810
1
Parent(s):
178f6aa
feat: atualização do detector com otimizações para GPU T4
Browse files- src/domain/detectors/gpu.py +11 -8
- src/main.py +20 -4
src/domain/detectors/gpu.py
CHANGED
@@ -21,10 +21,13 @@ torch.backends.cudnn.benchmark = True
|
|
21 |
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = True
|
22 |
torch._dynamo.config.suppress_errors = True
|
23 |
|
|
|
|
|
|
|
24 |
|
25 |
class GPUCache(BaseCache):
|
26 |
"""Cache otimizado para GPU."""
|
27 |
-
def __init__(self, max_size: int =
|
28 |
super().__init__(max_size)
|
29 |
self.device = torch.device('cuda')
|
30 |
|
@@ -35,12 +38,12 @@ class WeaponDetectorGPU(BaseDetector):
|
|
35 |
def __init__(self):
|
36 |
"""Inicializa variáveis básicas."""
|
37 |
super().__init__()
|
38 |
-
self.default_resolution =
|
39 |
self.amp_dtype = torch.float16
|
40 |
self.preprocess_stream = torch.cuda.Stream()
|
41 |
-
self.max_batch_size =
|
42 |
-
self.current_batch_size =
|
43 |
-
self.min_batch_size =
|
44 |
|
45 |
def _initialize(self):
|
46 |
"""Inicializa o modelo e o processador para execução exclusiva em GPU."""
|
@@ -64,18 +67,18 @@ class WeaponDetectorGPU(BaseDetector):
|
|
64 |
cache_dir=cache_dir
|
65 |
)
|
66 |
|
67 |
-
# Configurações otimizadas para
|
68 |
self.owlv2_model = Owlv2ForObjectDetection.from_pretrained(
|
69 |
model_name,
|
70 |
cache_dir=cache_dir,
|
71 |
torch_dtype=self.amp_dtype,
|
72 |
device_map="auto",
|
73 |
-
low_cpu_mem_usage=True
|
|
|
74 |
).to(self.device)
|
75 |
|
76 |
# Otimizar modelo para inferência
|
77 |
self.owlv2_model.eval()
|
78 |
-
torch.compile(self.owlv2_model) # Usar torch.compile para otimização
|
79 |
|
80 |
# Usar queries do método base
|
81 |
self.text_queries = self._get_detection_queries()
|
|
|
21 |
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = True
|
22 |
torch._dynamo.config.suppress_errors = True
|
23 |
|
24 |
+
# Configurações para Zero-GPU
|
25 |
+
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
|
26 |
+
|
27 |
|
28 |
class GPUCache(BaseCache):
|
29 |
"""Cache otimizado para GPU."""
|
30 |
+
def __init__(self, max_size: int = 100): # Reduzido para economizar memória
|
31 |
super().__init__(max_size)
|
32 |
self.device = torch.device('cuda')
|
33 |
|
|
|
38 |
def __init__(self):
|
39 |
"""Inicializa variáveis básicas."""
|
40 |
super().__init__()
|
41 |
+
self.default_resolution = 512 # Reduzido para economizar memória
|
42 |
self.amp_dtype = torch.float16
|
43 |
self.preprocess_stream = torch.cuda.Stream()
|
44 |
+
self.max_batch_size = 4 # Reduzido para Zero-GPU
|
45 |
+
self.current_batch_size = 2 # Reduzido para Zero-GPU
|
46 |
+
self.min_batch_size = 1
|
47 |
|
48 |
def _initialize(self):
|
49 |
"""Inicializa o modelo e o processador para execução exclusiva em GPU."""
|
|
|
67 |
cache_dir=cache_dir
|
68 |
)
|
69 |
|
70 |
+
# Configurações otimizadas para Zero-GPU
|
71 |
self.owlv2_model = Owlv2ForObjectDetection.from_pretrained(
|
72 |
model_name,
|
73 |
cache_dir=cache_dir,
|
74 |
torch_dtype=self.amp_dtype,
|
75 |
device_map="auto",
|
76 |
+
low_cpu_mem_usage=True,
|
77 |
+
max_memory={'cuda:0': '10GB'} # Limitar uso de memória
|
78 |
).to(self.device)
|
79 |
|
80 |
# Otimizar modelo para inferência
|
81 |
self.owlv2_model.eval()
|
|
|
82 |
|
83 |
# Usar queries do método base
|
84 |
self.text_queries = self._get_detection_queries()
|
src/main.py
CHANGED
@@ -3,6 +3,7 @@ from dotenv import load_dotenv
|
|
3 |
from src.presentation.web.gradio_interface import GradioInterface
|
4 |
import logging
|
5 |
import torch
|
|
|
6 |
|
7 |
# Configurar logging
|
8 |
logging.basicConfig(
|
@@ -11,6 +12,19 @@ logging.basicConfig(
|
|
11 |
)
|
12 |
logger = logging.getLogger(__name__)
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
def main():
|
15 |
"""Função principal que inicia a aplicação."""
|
16 |
try:
|
@@ -21,6 +35,7 @@ def main():
|
|
21 |
if IS_HUGGINGFACE:
|
22 |
load_dotenv('.env.huggingface')
|
23 |
logger.info("Ambiente HuggingFace detectado")
|
|
|
24 |
else:
|
25 |
load_dotenv('.env')
|
26 |
logger.info("Ambiente local detectado")
|
@@ -33,22 +48,23 @@ def main():
|
|
33 |
# Calcular número ideal de workers baseado na GPU
|
34 |
if torch.cuda.is_available():
|
35 |
gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3) # em GB
|
36 |
-
max_concurrent =
|
37 |
logger.info(f"GPU Memory: {gpu_mem:.1f}GB, Max Concurrent: {max_concurrent}")
|
38 |
else:
|
39 |
max_concurrent = 1
|
40 |
|
41 |
# Primeiro configurar a fila
|
42 |
demo = demo.queue(
|
43 |
-
concurrency_limit=max_concurrent, # Simplificando para um worker
|
44 |
api_open=False,
|
45 |
-
status_update_rate="auto"
|
|
|
46 |
)
|
47 |
# Depois fazer o launch
|
48 |
demo.launch(
|
49 |
server_name="0.0.0.0",
|
50 |
server_port=7860,
|
51 |
-
share=False
|
|
|
52 |
)
|
53 |
else:
|
54 |
# Ambiente local - apenas launch direto
|
|
|
3 |
from src.presentation.web.gradio_interface import GradioInterface
|
4 |
import logging
|
5 |
import torch
|
6 |
+
import gc
|
7 |
|
8 |
# Configurar logging
|
9 |
logging.basicConfig(
|
|
|
12 |
)
|
13 |
logger = logging.getLogger(__name__)
|
14 |
|
15 |
+
def setup_zero_gpu():
|
16 |
+
"""Configurações otimizadas para Zero-GPU."""
|
17 |
+
# Limpar cache CUDA
|
18 |
+
if torch.cuda.is_available():
|
19 |
+
torch.cuda.empty_cache()
|
20 |
+
gc.collect()
|
21 |
+
|
22 |
+
# Configurações para otimizar memória
|
23 |
+
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
|
24 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
25 |
+
torch.backends.cudnn.benchmark = True
|
26 |
+
torch.backends.cudnn.allow_tf32 = True
|
27 |
+
|
28 |
def main():
|
29 |
"""Função principal que inicia a aplicação."""
|
30 |
try:
|
|
|
35 |
if IS_HUGGINGFACE:
|
36 |
load_dotenv('.env.huggingface')
|
37 |
logger.info("Ambiente HuggingFace detectado")
|
38 |
+
setup_zero_gpu()
|
39 |
else:
|
40 |
load_dotenv('.env')
|
41 |
logger.info("Ambiente local detectado")
|
|
|
48 |
# Calcular número ideal de workers baseado na GPU
|
49 |
if torch.cuda.is_available():
|
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(
|
|
|
58 |
api_open=False,
|
59 |
+
status_update_rate="auto",
|
60 |
+
max_size=5 # Reduzir tamanho da fila para economizar memória
|
61 |
)
|
62 |
# Depois fazer o launch
|
63 |
demo.launch(
|
64 |
server_name="0.0.0.0",
|
65 |
server_port=7860,
|
66 |
+
share=False,
|
67 |
+
max_threads=2 # Reduzir número de threads
|
68 |
)
|
69 |
else:
|
70 |
# Ambiente local - apenas launch direto
|