File size: 6,866 Bytes
aa6da07
 
 
a15c41a
 
cda1138
 
 
 
 
 
 
 
 
 
 
aa6da07
a15c41a
cda1138
a15c41a
 
3988dcb
c99583c
3988dcb
a15c41a
cda1138
 
 
 
 
8efc71c
 
cda1138
 
 
2c0cc11
cda1138
 
99ff4e1
2c0cc11
cda1138
a15c41a
cda1138
 
99ff4e1
cda1138
2c0cc11
3988dcb
2c0cc11
cda1138
 
 
 
 
 
 
 
 
 
 
 
 
8efc71c
cda1138
2c0cc11
cda1138
 
 
 
 
 
a15c41a
2c0cc11
3988dcb
2c0cc11
3988dcb
aa6da07
 
 
 
99ff4e1
aa6da07
cda1138
99ff4e1
88103b2
 
cda1138
 
88103b2
 
cda1138
3988dcb
a15c41a
cda1138
 
2c0cc11
a15c41a
2c0cc11
 
cda1138
 
 
2c0cc11
cda1138
 
 
 
 
99ff4e1
cda1138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3988dcb
a15c41a
cda1138
88103b2
cda1138
99ff4e1
a15c41a
cda1138
88103b2
 
 
 
3988dcb
cda1138
 
 
 
 
 
99ff4e1
3988dcb
cda1138
 
 
16079ad
aa6da07
88103b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3988dcb
aa6da07
 
3988dcb
 
aa6da07
 
99ff4e1
2560f7d
88103b2
 
 
 
 
 
 
 
 
 
 
 
16079ad
cda1138
aa6da07
3988dcb
88103b2
cda1138
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
from fastapi import FastAPI, Query, HTTPException
import torch
import re
import time
import logging
import os
from transformers import AutoTokenizer, LlamaForCausalLM, GenerationConfig
from peft import AutoPeftModelForCausalLM
import gc

# -------- CONFIGURAÇÕES DE OTIMIZAÇÃO --------
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["OMP_NUM_THREADS"] = "2"  # Ajuste para seus 2 vcpus
os.environ["MKL_NUM_THREADS"] = "2"
torch.set_num_threads(2)
torch.set_num_interop_threads(1)

# -------- LOGGING CONFIG --------
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger("news-filter")

# -------- LOAD MODEL --------
model_name = "habulaj/filter"
log.info("🚀 Carregando modelo e tokenizer...")

# Tokenizer otimizado
tokenizer = AutoTokenizer.from_pretrained(
    model_name,
    use_fast=True,  # Usa tokenizer fast se disponível
    padding_side="left"  # Padding à esquerda para melhor performance
)

# Configurar pad_token se não existir
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

# Modelo otimizado
model = AutoPeftModelForCausalLM.from_pretrained(
    model_name,
    device_map="cpu",
    torch_dtype=torch.bfloat16,  # bfloat16 é mais rápido que float32 em CPU moderna
    low_cpu_mem_usage=True,
    use_cache=True,  # Cache interno do modelo
    trust_remote_code=True
)

model.eval()
log.info("✅ Modelo carregado (eval mode).")

# Configuração de geração otimizada
generation_config = GenerationConfig(
    max_new_tokens=100,
    temperature=1.0,
    do_sample=False,
    num_beams=1,
    use_cache=True,
    eos_token_id=tokenizer.eos_token_id,
    pad_token_id=tokenizer.eos_token_id,
    no_repeat_ngram_size=2,
    repetition_penalty=1.1,
    length_penalty=1.0
)

# Torch compile com configurações otimizadas
try:
    model = torch.compile(
        model, 
        mode="reduce-overhead",
        fullgraph=True,
        dynamic=False
    )
    log.info("✅ Modelo compilado com torch.compile.")
except Exception as e:
    log.warning(f"⚠️ torch.compile não disponível: {e}")

# -------- FASTAPI INIT --------
app = FastAPI(title="News Filter JSON API")

@app.get("/")
def read_root():
    return {"message": "News Filter JSON API is running!", "docs": "/docs"}

# -------- INFERENCE OTIMIZADA --------
def infer_filter(title, content):
    # Prompt mais específico para JSON válido
    prompt = f"""Analyze the news and return a valid JSON object with double quotes for all keys and string values.
Title: "{title}"
Content: "{content}"

Return only valid JSON:"""
    
    log.info(f"🧠 Inferência iniciada para: {title}")
    start_time = time.time()
    
    # Tokenização otimizada
    inputs = tokenizer(
        prompt,
        return_tensors="pt",
        truncation=True,
        max_length=384,  # Reduzido de 512 para acelerar
        padding=False,   # Sem padding desnecessário
        add_special_tokens=True,
    )
    
    input_ids = inputs.input_ids
    attention_mask = inputs.attention_mask
    
    # Geração otimizada
    with torch.no_grad():
        with torch.inference_mode():  # Modo de inferência mais rápido
            outputs = model.generate(
                input_ids=input_ids,
                attention_mask=attention_mask,
                generation_config=generation_config,
                # Parâmetros adicionais de otimização
                num_return_sequences=1,
                output_scores=False,
                return_dict_in_generate=False,
            )
    
    # Decodificação otimizada
    generated_tokens = outputs[0][len(input_ids[0]):]
    generated = tokenizer.decode(
        generated_tokens, 
        skip_special_tokens=True,
        clean_up_tokenization_spaces=True
    )
    
    log.info("📤 Resultado gerado:")
    log.info(generated)
    
    # Extração e limpeza de JSON
    match = re.search(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', generated, re.DOTALL)
    if match:
        duration = time.time() - start_time
        json_result = match.group(0)
        
        # Limpeza do JSON para corrigir formatação
        json_result = fix_json_format(json_result)
        
        log.info(f"✅ JSON extraído em {duration:.2f}s")
        
        # Limpeza de memória
        del outputs, generated_tokens, inputs
        gc.collect()
        
        return json_result
    else:
        log.warning("⚠️ Falha ao extrair JSON.")
        # Limpeza de memória mesmo em caso de erro
        del outputs, generated_tokens, inputs
        gc.collect()
        raise HTTPException(status_code=404, detail="Unable to extract JSON from model output.")

def fix_json_format(json_str):
    """Corrige formatação comum de JSON gerado por LLMs"""
    # Remove quebras de linha dentro do JSON
    json_str = re.sub(r'\n\s*', ' ', json_str)
    
    # Corrige aspas simples para duplas
    json_str = re.sub(r"'([^']*)':", r'"\1":', json_str)  # Chaves
    json_str = re.sub(r":\s*'([^']*)'", r': "\1"', json_str)  # Valores string
    
    # Corrige valores booleanos
    json_str = re.sub(r':\s*True\b', ': true', json_str)
    json_str = re.sub(r':\s*False\b', ': false', json_str)
    
    # Remove vírgulas extras
    json_str = re.sub(r',\s*}', '}', json_str)
    json_str = re.sub(r',\s*]', ']', json_str)
    
    # Remove espaços extras
    json_str = re.sub(r'\s+', ' ', json_str)
    
    return json_str.strip()

# -------- API --------
@app.get("/filter")
def get_filter(
    title: str = Query(..., description="News title"),
    content: str = Query(..., description="News content")
):
    try:
        json_output = infer_filter(title, content)
        import json
        
        # Tenta fazer parse do JSON
        try:
            parsed_result = json.loads(json_output)
            return {"result": parsed_result}
        except json.JSONDecodeError as je:
            log.error(f"❌ Erro ao parsear JSON: {je}")
            log.error(f"JSON problemático: {json_output}")
            
            # Fallback: retorna JSON como string se não conseguir parsear
            return {"result": json_output, "warning": "JSON returned as string due to parsing error"}
            
    except HTTPException as he:
        raise he
    except Exception as e:
        log.exception("❌ Erro inesperado:")
        raise HTTPException(status_code=500, detail="Internal server error during inference.")

# -------- WARMUP (OPCIONAL) --------
@app.on_event("startup")
async def warmup():
    """Faz um warmup do modelo para otimizar as primeiras execuções"""
    log.info("🔥 Executando warmup...")
    try:
        # Exemplo simples para warmup
        infer_filter("Test title", "Test content")
        log.info("✅ Warmup concluído.")
    except Exception as e:
        log.warning(f"⚠️ Warmup falhou: {e}")