Spaces:
Running
Running
fix: ensemble via set_adapter (elimina sobreposição de adapters) + Platt scaling com sinal correto
Browse files- inference.py +82 -90
inference.py
CHANGED
|
@@ -1,10 +1,7 @@
|
|
| 1 |
-
"""Carregamento do modelo e inferência (
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
inferência para cada uma e calcula a média das probabilidades.
|
| 6 |
-
As probabilidades brutas passam por uma transformação paramétrica
|
| 7 |
-
(Platt scaling / temperature scaling).
|
| 8 |
"""
|
| 9 |
from __future__ import annotations
|
| 10 |
|
|
@@ -20,34 +17,31 @@ from peft import PeftModel
|
|
| 20 |
from transformers import AutoModel, AutoTokenizer
|
| 21 |
|
| 22 |
from config import (
|
|
|
|
| 23 |
ARTIFACTS_DIR,
|
| 24 |
BATCH_SIZE,
|
| 25 |
CALIB_A,
|
| 26 |
CALIB_B,
|
| 27 |
HEAD_FILENAME,
|
| 28 |
-
MODEL_FOLDS,
|
| 29 |
-
ADAPTER_DIRNAME,
|
| 30 |
HF_TOKEN,
|
| 31 |
MAX_LENGTH,
|
|
|
|
| 32 |
MODEL_NAME,
|
| 33 |
TEMPERATURE,
|
| 34 |
)
|
| 35 |
|
| 36 |
logger = logging.getLogger(__name__)
|
| 37 |
|
| 38 |
-
# ---------------------------------------------------------------------------
|
| 39 |
-
# Dispositivo e dtype
|
| 40 |
-
# ---------------------------------------------------------------------------
|
| 41 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 42 |
-
|
| 43 |
-
if
|
| 44 |
-
|
| 45 |
-
else
|
| 46 |
-
|
| 47 |
|
| 48 |
|
| 49 |
def build_instruction_text(text: str) -> str:
|
| 50 |
-
"""
|
| 51 |
return text if isinstance(text, str) else ""
|
| 52 |
|
| 53 |
|
|
@@ -58,86 +52,95 @@ def mean_pool(last_hidden_states: torch.Tensor, attention_mask: torch.Tensor) ->
|
|
| 58 |
|
| 59 |
|
| 60 |
@lru_cache(maxsize=1)
|
| 61 |
-
def load_models() ->
|
| 62 |
-
"""
|
| 63 |
-
Carrega todas as combinações (tokenizer, encoder, head) definidas
|
| 64 |
-
em config.MODEL_FOLDS. Retorna uma lista de tuplas.
|
| 65 |
-
O tokenizer e o encoder base são compartilhados para economizar memória.
|
| 66 |
"""
|
| 67 |
-
|
|
|
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
logger.info("Carregando tokenizer de %s", MODEL_NAME)
|
| 70 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
|
|
|
|
|
|
| 71 |
if tokenizer.pad_token is None:
|
| 72 |
tokenizer.pad_token = tokenizer.eos_token
|
| 73 |
|
| 74 |
-
logger.info(
|
| 75 |
-
"Carregando encoder base %s (dtype=%s, device=%s)", MODEL_NAME, AMP_DTYPE, DEVICE
|
| 76 |
-
)
|
| 77 |
base_encoder = AutoModel.from_pretrained(
|
| 78 |
-
MODEL_NAME,
|
| 79 |
-
low_cpu_mem_usage=True,
|
| 80 |
-
torch_dtype=AMP_DTYPE,
|
| 81 |
-
token=HF_TOKEN,
|
| 82 |
).to(DEVICE)
|
| 83 |
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
adapter_dir = ARTIFACTS_DIR / ADAPTER_DIRNAME.format(fold=fold)
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
raise FileNotFoundError(
|
| 89 |
-
f"Artifacts do fold '{fold}' não encontrados em {adapter_dir} e {head_path}"
|
| 90 |
-
)
|
| 91 |
-
logger.info("Anexando adapter LoRA de %s", adapter_dir)
|
| 92 |
-
encoder = PeftModel.from_pretrained(base_encoder, str(adapter_dir), is_trainable=False).to(DEVICE)
|
| 93 |
-
encoder.eval()
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
head_state = head_payload.get("state_dict", head_payload) if isinstance(head_payload, dict) else head_payload
|
| 98 |
-
in_feat = int(head_state["weight"].shape[1])
|
| 99 |
-
head = nn.Linear(in_feat, 1)
|
| 100 |
-
head.load_state_dict(head_state)
|
| 101 |
-
head = head.to(DEVICE).eval()
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
return models
|
| 107 |
|
| 108 |
|
| 109 |
def warmup() -> None:
|
| 110 |
-
"""
|
| 111 |
load_models()
|
| 112 |
|
| 113 |
|
| 114 |
@torch.no_grad()
|
| 115 |
def predict_batch(texts: Iterable[str], batch_size: int = BATCH_SIZE) -> np.ndarray:
|
| 116 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
if isinstance(texts, str):
|
| 118 |
texts = [texts]
|
| 119 |
texts = list(texts)
|
| 120 |
if not texts:
|
| 121 |
return np.zeros(0, dtype=np.float64)
|
| 122 |
|
| 123 |
-
|
| 124 |
-
fold_preds: List[np.ndarray] = []
|
| 125 |
-
models = load_models()
|
| 126 |
-
# Determina dtype para autocast
|
| 127 |
autocast_device = "cuda" if DEVICE == "cuda" else "cpu"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
for tokenizer, encoder, head in models:
|
| 130 |
preds = []
|
| 131 |
for i in range(0, len(texts), batch_size):
|
| 132 |
-
batch = texts[i
|
| 133 |
instr = [build_instruction_text(t) for t in batch]
|
| 134 |
toks = tokenizer(
|
| 135 |
-
instr,
|
| 136 |
-
|
| 137 |
-
truncation=True,
|
| 138 |
-
max_length=MAX_LENGTH,
|
| 139 |
-
return_tensors="pt",
|
| 140 |
).to(DEVICE)
|
|
|
|
| 141 |
with torch.inference_mode(), torch.autocast(
|
| 142 |
device_type=autocast_device, dtype=AMP_DTYPE, enabled=(DEVICE == "cuda")
|
| 143 |
):
|
|
@@ -145,48 +148,37 @@ def predict_batch(texts: Iterable[str], batch_size: int = BATCH_SIZE) -> np.ndar
|
|
| 145 |
emb = mean_pool(out.last_hidden_state, toks["attention_mask"])
|
| 146 |
emb = F.normalize(emb, p=2, dim=1)
|
| 147 |
logits = head(emb.to(head.weight.dtype)).squeeze(-1)
|
| 148 |
-
# Temperature scaling (divide os logits por TEMPERATURE)
|
| 149 |
if TEMPERATURE != 1.0:
|
| 150 |
logits = logits / TEMPERATURE
|
| 151 |
-
# Calcula p via sigmóide nos logits (pré-calibração)
|
| 152 |
p = torch.sigmoid(logits).float().cpu().numpy()
|
| 153 |
preds.append(p)
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
#
|
|
|
|
| 158 |
if CALIB_A != 1.0 or CALIB_B != 0.0:
|
| 159 |
-
logits_np = np.log(
|
| 160 |
-
|
| 161 |
-
else:
|
| 162 |
-
calibrated = preds_full
|
| 163 |
-
fold_preds.append(calibrated)
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
else:
|
| 169 |
-
final = fold_preds[0]
|
| 170 |
-
return final
|
| 171 |
|
| 172 |
|
| 173 |
def predict_one(text: str) -> float:
|
| 174 |
-
"""
|
| 175 |
return float(predict_batch([text])[0])
|
| 176 |
|
| 177 |
|
| 178 |
def explain_occlusion(text: str, batch_size: int = BATCH_SIZE) -> dict:
|
| 179 |
-
"""
|
| 180 |
-
Explicação leave-one-out por palavra, usando a média do ensemble e aplicando calibração.
|
| 181 |
-
Δ = P(texto completo) − P(texto sem a palavra).
|
| 182 |
-
"""
|
| 183 |
words = text.split()
|
| 184 |
if not words:
|
| 185 |
p = predict_one(text)
|
| 186 |
return {"proba_full": p, "tokens": [], "contributions": []}
|
| 187 |
-
variants = [" ".join(words[:i] + words[i + 1
|
| 188 |
-
|
| 189 |
-
probs = predict_batch(all_texts, batch_size=batch_size)
|
| 190 |
p_full = float(probs[0])
|
| 191 |
-
|
| 192 |
-
|
|
|
|
| 1 |
+
"""Carregamento do modelo e inferência (ensemble multi-fold calibrado).
|
| 2 |
|
| 3 |
+
Usa o mecanismo nativo do PEFT (load_adapter / set_adapter) para trocar
|
| 4 |
+
adapters em um único encoder, evitando sobreposição de pesos entre folds.
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
|
|
|
|
| 17 |
from transformers import AutoModel, AutoTokenizer
|
| 18 |
|
| 19 |
from config import (
|
| 20 |
+
ADAPTER_DIRNAME,
|
| 21 |
ARTIFACTS_DIR,
|
| 22 |
BATCH_SIZE,
|
| 23 |
CALIB_A,
|
| 24 |
CALIB_B,
|
| 25 |
HEAD_FILENAME,
|
|
|
|
|
|
|
| 26 |
HF_TOKEN,
|
| 27 |
MAX_LENGTH,
|
| 28 |
+
MODEL_FOLDS,
|
| 29 |
MODEL_NAME,
|
| 30 |
TEMPERATURE,
|
| 31 |
)
|
| 32 |
|
| 33 |
logger = logging.getLogger(__name__)
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 36 |
+
AMP_DTYPE = (
|
| 37 |
+
(torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16)
|
| 38 |
+
if DEVICE == "cuda"
|
| 39 |
+
else torch.float16
|
| 40 |
+
)
|
| 41 |
|
| 42 |
|
| 43 |
def build_instruction_text(text: str) -> str:
|
| 44 |
+
"""bge-m3 não usa prompt de instrução — retorna o texto cru."""
|
| 45 |
return text if isinstance(text, str) else ""
|
| 46 |
|
| 47 |
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
@lru_cache(maxsize=1)
|
| 55 |
+
def load_models() -> Tuple[AutoTokenizer, PeftModel, List[nn.Module]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
"""
|
| 57 |
+
Carrega tokenizer, encoder com TODOS os adapters (via PEFT multi-adapter),
|
| 58 |
+
e lista de cabeças lineares, uma por fold.
|
| 59 |
|
| 60 |
+
O encoder base é carregado UMA VEZ. Cada adapter é adicionado com
|
| 61 |
+
`load_adapter(adapter_name=fold)` — sem sobreposição de pesos.
|
| 62 |
+
A troca de adapter em inferência usa `encoder.set_adapter(fold)`.
|
| 63 |
+
"""
|
| 64 |
logger.info("Carregando tokenizer de %s", MODEL_NAME)
|
| 65 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 66 |
+
MODEL_NAME, padding_side="right", token=HF_TOKEN
|
| 67 |
+
)
|
| 68 |
if tokenizer.pad_token is None:
|
| 69 |
tokenizer.pad_token = tokenizer.eos_token
|
| 70 |
|
| 71 |
+
logger.info("Carregando encoder base %s (dtype=%s)", MODEL_NAME, AMP_DTYPE)
|
|
|
|
|
|
|
| 72 |
base_encoder = AutoModel.from_pretrained(
|
| 73 |
+
MODEL_NAME, low_cpu_mem_usage=True, torch_dtype=AMP_DTYPE, token=HF_TOKEN
|
|
|
|
|
|
|
|
|
|
| 74 |
).to(DEVICE)
|
| 75 |
|
| 76 |
+
# Carrega o PRIMEIRO adapter — cria o PeftModel
|
| 77 |
+
first_fold = MODEL_FOLDS[0]
|
| 78 |
+
first_adapter_dir = ARTIFACTS_DIR / ADAPTER_DIRNAME.format(fold=first_fold)
|
| 79 |
+
assert first_adapter_dir.exists(), f"{first_adapter_dir} não encontrado"
|
| 80 |
+
encoder = PeftModel.from_pretrained(
|
| 81 |
+
base_encoder, str(first_adapter_dir),
|
| 82 |
+
adapter_name=first_fold, is_trainable=False,
|
| 83 |
+
).to(DEVICE)
|
| 84 |
+
|
| 85 |
+
# Carrega os DEMAIS adapters no mesmo PeftModel — sem modificar o base
|
| 86 |
+
for fold in MODEL_FOLDS[1:]:
|
| 87 |
adapter_dir = ARTIFACTS_DIR / ADAPTER_DIRNAME.format(fold=fold)
|
| 88 |
+
assert adapter_dir.exists(), f"{adapter_dir} não encontrado"
|
| 89 |
+
encoder.load_adapter(str(adapter_dir), adapter_name=fold)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
encoder.eval()
|
| 92 |
+
logger.info("%d adapters carregados: %s", len(MODEL_FOLDS), MODEL_FOLDS)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
# Carrega as cabeças lineares
|
| 95 |
+
heads: List[nn.Module] = []
|
| 96 |
+
for fold in MODEL_FOLDS:
|
| 97 |
+
head_path = ARTIFACTS_DIR / HEAD_FILENAME.format(fold=fold)
|
| 98 |
+
assert head_path.exists(), f"{head_path} não encontrada"
|
| 99 |
+
payload = torch.load(head_path, map_location="cpu")
|
| 100 |
+
state = payload.get("state_dict", payload) if isinstance(payload, dict) else payload
|
| 101 |
+
head = nn.Linear(int(state["weight"].shape[1]), 1)
|
| 102 |
+
head.load_state_dict(state)
|
| 103 |
+
heads.append(head.to(DEVICE).eval())
|
| 104 |
|
| 105 |
+
return tokenizer, encoder, heads
|
|
|
|
| 106 |
|
| 107 |
|
| 108 |
def warmup() -> None:
|
| 109 |
+
"""Força carregamento imediato para evitar cold-start no primeiro request."""
|
| 110 |
load_models()
|
| 111 |
|
| 112 |
|
| 113 |
@torch.no_grad()
|
| 114 |
def predict_batch(texts: Iterable[str], batch_size: int = BATCH_SIZE) -> np.ndarray:
|
| 115 |
+
"""
|
| 116 |
+
Probabilidade calibrada de 'útil', em média entre todos os folds.
|
| 117 |
+
|
| 118 |
+
Para cada fold: ativa o adapter com set_adapter(), roda o forward,
|
| 119 |
+
aplica Platt scaling se configurado, acumula. Depois tira a média.
|
| 120 |
+
"""
|
| 121 |
if isinstance(texts, str):
|
| 122 |
texts = [texts]
|
| 123 |
texts = list(texts)
|
| 124 |
if not texts:
|
| 125 |
return np.zeros(0, dtype=np.float64)
|
| 126 |
|
| 127 |
+
tokenizer, encoder, heads = load_models()
|
|
|
|
|
|
|
|
|
|
| 128 |
autocast_device = "cuda" if DEVICE == "cuda" else "cpu"
|
| 129 |
+
fold_preds: List[np.ndarray] = []
|
| 130 |
+
|
| 131 |
+
for fold, head in zip(MODEL_FOLDS, heads):
|
| 132 |
+
# Ativa SOMENTE o adapter deste fold; os demais ficam inativos
|
| 133 |
+
encoder.set_adapter(fold)
|
| 134 |
|
|
|
|
| 135 |
preds = []
|
| 136 |
for i in range(0, len(texts), batch_size):
|
| 137 |
+
batch = texts[i: i + batch_size]
|
| 138 |
instr = [build_instruction_text(t) for t in batch]
|
| 139 |
toks = tokenizer(
|
| 140 |
+
instr, padding=True, truncation=True,
|
| 141 |
+
max_length=MAX_LENGTH, return_tensors="pt",
|
|
|
|
|
|
|
|
|
|
| 142 |
).to(DEVICE)
|
| 143 |
+
|
| 144 |
with torch.inference_mode(), torch.autocast(
|
| 145 |
device_type=autocast_device, dtype=AMP_DTYPE, enabled=(DEVICE == "cuda")
|
| 146 |
):
|
|
|
|
| 148 |
emb = mean_pool(out.last_hidden_state, toks["attention_mask"])
|
| 149 |
emb = F.normalize(emb, p=2, dim=1)
|
| 150 |
logits = head(emb.to(head.weight.dtype)).squeeze(-1)
|
|
|
|
| 151 |
if TEMPERATURE != 1.0:
|
| 152 |
logits = logits / TEMPERATURE
|
|
|
|
| 153 |
p = torch.sigmoid(logits).float().cpu().numpy()
|
| 154 |
preds.append(p)
|
| 155 |
+
|
| 156 |
+
p_fold = np.clip(np.concatenate(preds).astype(np.float64), 1e-6, 1 - 1e-6)
|
| 157 |
+
|
| 158 |
+
# Platt scaling: P_calib = sigmoid(A * logit(p) + B)
|
| 159 |
+
# NOTA: sigmoid(x) = 1/(1+exp(-x)) — o sinal negativo é obrigatório
|
| 160 |
if CALIB_A != 1.0 or CALIB_B != 0.0:
|
| 161 |
+
logits_np = np.log(p_fold / (1.0 - p_fold))
|
| 162 |
+
p_fold = 1.0 / (1.0 + np.exp(-(CALIB_A * logits_np + CALIB_B)))
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
+
fold_preds.append(p_fold)
|
| 165 |
+
|
| 166 |
+
return np.mean(fold_preds, axis=0) if len(fold_preds) > 1 else fold_preds[0]
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
def predict_one(text: str) -> float:
|
| 170 |
+
"""Probabilidade calibrada para um único texto."""
|
| 171 |
return float(predict_batch([text])[0])
|
| 172 |
|
| 173 |
|
| 174 |
def explain_occlusion(text: str, batch_size: int = BATCH_SIZE) -> dict:
|
| 175 |
+
"""Leave-one-out usando o ensemble completo com calibração."""
|
|
|
|
|
|
|
|
|
|
| 176 |
words = text.split()
|
| 177 |
if not words:
|
| 178 |
p = predict_one(text)
|
| 179 |
return {"proba_full": p, "tokens": [], "contributions": []}
|
| 180 |
+
variants = [" ".join(words[:i] + words[i + 1:]) for i in range(len(words))]
|
| 181 |
+
probs = predict_batch([text] + variants, batch_size=batch_size)
|
|
|
|
| 182 |
p_full = float(probs[0])
|
| 183 |
+
return {"proba_full": p_full, "tokens": words,
|
| 184 |
+
"contributions": (p_full - probs[1:]).tolist()}
|