Spaces:
Sleeping
Sleeping
fix: ensemble via set_adapter (elimina sobreposição de adapters) + Platt scaling com sinal correto
Browse files123456789109 unmodified lines202122232425262728293031323334353637383940414243444546474849505152534 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431 unmodified line145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""Carregamento do modelo e inferência (calibrado e ensemblado).Serve o ensemble calibrado com base BAAI/bge-m3 + LoRA.Carrega todas as combinações definidas em config.MODEL_FOLDS, roda ainferência para cada uma e calcula a média das probabilidades.As probabilidades brutas passam por uma transformação paramétrica(Platt scaling / temperature scaling)."""from __future__ import annotations9 unmodified linesfrom transformers import AutoModel, AutoTokenizerfrom config import (ARTIFACTS_DIR,BATCH_SIZE,CALIB_A,CALIB_B,HEAD_FILENAME,MODEL_FOLDS,ADAPTER_DIRNAME,HF_TOKEN,MAX_LENGTH,MODEL_NAME,TEMPERATURE,)logger = logging.getLogger(__name__)# ---------------------------------------------------------------------------# Dispositivo e dtype# ---------------------------------------------------------------------------DEVICE = "cuda" if torch.cuda.is_available() else "cpu"if DEVICE == "cuda":AMP_DTYPE = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16else:AMP_DTYPE = torch.float16def build_instruction_text(text: str) -> str:"""Retorna o texto sem prompt de instrução (bge-m3 não usa prompts)."""return text if isinstance(text, str) else ""4 unmodified lines@lru_cache(maxsize=1)def load_models() -> List[Tuple[AutoTokenizer, PeftModel, nn.Module]]:"""Carrega todas as combinações (tokenizer, encoder, head) definidasem config.MODEL_FOLDS. Retorna uma lista de tuplas.O tokenizer e o encoder base são compartilhados para economizar memória."""models = []logger.info("Carregando tokenizer de %s", MODEL_NAME)tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, padding_side="right", token=HF_TOKEN)if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_tokenlogger.info("Carregando encoder base %s (dtype=%s, device=%s)", MODEL_NAME, AMP_DTYPE, DEVICE)base_encoder = AutoModel.from_pretrained(MODEL_NAME,low_cpu_mem_usage=True,torch_dtype=AMP_DTYPE,token=HF_TOKEN,).to(DEVICE)for fold in MODEL_FOLDS:adapter_dir = ARTIFACTS_DIR / ADAPTER_DIRNAME.format(fold=fold)head_path = ARTIFACTS_DIR / HEAD_FILENAME.format(fold=fold)if not adapter_dir.exists() or not head_path.exists():raise FileNotFoundError(f"Artifacts do fold '{fold}' não encontrados em {adapter_dir} e {head_path}")logger.info("Anexando adapter LoRA de %s", adapter_dir)encoder = PeftModel.from_pretrained(base_encoder, str(adapter_dir), is_trainable=False).to(DEVICE)encoder.eval()logger.info("Carregando cabeça linear de %s", head_path)head_payload = torch.load(head_path, map_location="cpu")head_state = head_payload.get("state_dict", head_payload) if isinstance(head_payload, dict) else head_payloadin_feat = int(head_state["weight"].shape[1])head = nn.Linear(in_feat, 1)head.load_state_dict(head_state)head = head.to(DEVICE).eval()models.append((tokenizer, encoder, head))logger.info("%d modelos de ensemble carregados.", len(models))return modelsdef warmup() -> None:"""Carrega todos os modelos imediatamente para evitar cold-start."""load_models()@torch.no_grad()def predict_batch(texts: Iterable[str], batch_size: int = BATCH_SIZE) -> np.ndarray:"""Retorna a probabilidade calibrada de 'útil' para cada texto, em média entre folds."""if isinstance(texts, str):texts = [texts]texts = list(texts)if not texts:return np.zeros(0, dtype=np.float64)# Coleção de predições por foldfold_preds: List[np.ndarray] = []models = load_models()# Determina dtype para autocastautocast_device = "cuda" if DEVICE == "cuda" else "cpu"for tokenizer, encoder, head in models:preds = []for i in range(0, len(texts), batch_size):batch = texts[i : i + batch_size]instr = [build_instruction_text(t) for t in batch]toks = tokenizer(instr,padding=True,truncation=True,max_length=MAX_LENGTH,return_tensors="pt",).to(DEVICE)with torch.inference_mode(), torch.autocast(device_type=autocast_device, dtype=AMP_DTYPE, enabled=(DEVICE == "cuda")):1 unmodified lineemb = mean_pool(out.last_hidden_state, toks["attention_mask"])emb = F.normalize(emb, p=2, dim=1)logits = head(emb.to(head.weight.dtype)).squeeze(-1)# Temperature scaling (divide os logits por TEMPERATURE)if TEMPERATURE != 1.0:logits = logits / TEMPERATURE# Calcula p via sigmóide nos logits (pré-calibração)p = torch.sigmoid(logits).float().cpu().numpy()preds.append(p)preds_full = np.concatenate(preds).astype(np.float64)# Clip para evitar 0 ou 1 exatospreds_full = np.clip(preds_full, 1e-6, 1 - 1e-6)# Converte p em logit para aplicar calibração Platt: z = log(p/(1-p))if CALIB_A != 1.0 or CALIB_B != 0.0:logits_np = np.log(preds_full / (1.0 - preds_full))calibrated = 1.0 / (1.0 + np.exp(CALIB_A * logits_np + CALIB_B))else:calibrated = preds_fullfold_preds.append(calibrated)# Média do Ensembleif len(fold_preds) > 1:final = np.mean(fold_preds, axis=0)else:final = fold_preds[0]return finaldef predict_one(text: str) -> float:"""Retorna a probabilidade calibrada para um único texto."""return float(predict_batch([text])[0])def explain_occlusion(text: str, batch_size: int = BATCH_SIZE) -> dict:"""Explicação leave-one-out por palavra, usando a média do ensemble e aplicando calibração.Δ = P(texto completo) − P(texto sem a palavra)."""words = text.split()if not words:p = predict_one(text)return {"proba_full": p, "tokens": [], "contributions": []}variants = [" ".join(words[:i] + words[i + 1 :]) for i in range(len(words))]all_texts = [text] + variantsprobs = predict_batch(all_texts, batch_size=batch_size)p_full = float(probs[0])contribs = (p_full - probs[1:]).tolist()return {"proba_full": p_full, "tokens": words, "contributions": contribs}12345679 unmodified lines171819202122232425262728293031323334353637383940414243444546474 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461 unmodified line148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""Carregamento do modelo e inferência (ensemble multi-fold calibrado).Usa o mecanismo nativo do PEFT (load_adapter / set_adapter) para trocaradapters em um único encoder, evitando sobreposição de pesos entre folds."""from __future__ import annotations9 unmodified linesfrom transformers import AutoModel, AutoTokenizerfrom config import (ADAPTER_DIRNAME,ARTIFACTS_DIR,BATCH_SIZE,CALIB_A,CALIB_B,HEAD_FILENAME,HF_TOKEN,MAX_LENGTH,MODEL_FOLDS,MODEL_NAME,TEMPERATURE,)logger = logging.getLogger(__name__)DEVICE = "cuda" if torch.cuda.is_available() else "cpu"AMP_DTYPE = ((torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16)if DEVICE == "cuda"else torch.float16)def build_instruction_text(text: str) -> str:"""bge-m3 não usa prompt de instrução — retorna o texto cru."""return text if isinstance(text, str) else ""4 unmodified lines@lru_cache(maxsize=1)def load_models() -> Tuple[AutoTokenizer, PeftModel, List[nn.Module]]:"""Carrega tokenizer, encoder com TODOS os adapters (via PEFT multi-adapter),e lista de cabeças lineares, uma por fold.O encoder base é carregado UMA VEZ. Cada adapter é adicionado com`load_adapter(adapter_name=fold)` — sem sobreposição de pesos.A troca de adapter em inferência usa `encoder.set_adapter(fold)`."""logger.info("Carregando tokenizer de %s", MODEL_NAME)tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, padding_side="right", token=HF_TOKEN)if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_tokenlogger.info("Carregando encoder base %s (dtype=%s)", MODEL_NAME, AMP_DTYPE)base_encoder = AutoModel.from_pretrained(MODEL_NAME, low_cpu_mem_usage=True, torch_dtype=AMP_DTYPE, token=HF_TOKEN).to(DEVICE)# Carrega o PRIMEIRO adapter — cria o PeftModelfirst_fold = MODEL_FOLDS[0]first_adapter_dir = ARTIFACTS_DIR / ADAPTER_DIRNAME.format(fold=first_fold)assert first_adapter_dir.exists(), f"{first_adapter_dir} não encontrado"encoder = PeftModel.from_pretrained(base_encoder, str(first_adapter_dir),adapter_name=first_fold, is_trainable=False,).to(DEVICE)# Carrega os DEMAIS adapters no mesmo PeftModel — sem modificar o basefor fold in MODEL_FOLDS[1:]:adapter_dir = ARTIFACTS_DIR / ADAPTER_DIRNAME.format(fold=fold)assert adapter_dir.exists(), f"{adapter_dir} não encontrado"encoder.load_adapter(str(adapter_dir), adapter_name=fold)encoder.eval()logger.info("%d adapters carregados: %s", len(MODEL_FOLDS), MODEL_FOLDS)# Carrega as cabeças linearesheads: List[nn.Module] = []for fold in MODEL_FOLDS:head_path = ARTIFACTS_DIR / HEAD_FILENAME.format(fold=fold)assert head_path.exists(), f"{head_path} não encontrada"payload = torch.load(head_path, map_location="cpu")state = payload.get("state_dict", payload) if isinstance(payload, dict) else payloadhead = nn.Linear(int(state["weight"].shape[1]), 1)head.load_state_dict(state)heads.append(head.to(DEVICE).eval())return tokenizer, encoder, headsdef warmup() -> None:"""Força carregamento imediato para evitar cold-start no primeiro request."""load_models()@torch.no_grad()def predict_batch(texts: Iterable[str], batch_size: int = BATCH_SIZE) -> np.ndarray:"""Probabilidade calibrada de 'útil', em média entre todos os folds.Para cada fold: ativa o adapter com set_adapter(), roda o forward,aplica Platt scaling se configurado, acumula. Depois tira a média."""if isinstance(texts, str):texts = [texts]texts = list(texts)if not texts:return np.zeros(0, dtype=np.float64)tokenizer, encoder, heads = load_models()autocast_device = "cuda" if DEVICE == "cuda" else "cpu"fold_preds: List[np.ndarray] = []for fold, head in zip(MODEL_FOLDS, heads):# Ativa SOMENTE o adapter deste fold; os demais ficam inativosencoder.set_adapter(fold)preds = []for i in range(0, len(texts), batch_size):batch = texts[i: i + batch_size]instr = [build_instruction_text(t) for t in batch]toks = tokenizer(instr, padding=True, truncation=True,max_length=MAX_LENGTH, return_tensors="pt",).to(DEVICE)with torch.inference_mode(), torch.autocast(device_type=autocast_device, dtype=AMP_DTYPE, enabled=(DEVICE == "cuda")):1 unmodified lineemb = mean_pool(out.last_hidden_state, toks["attention_mask"])emb = F.normalize(emb, p=2, dim=1)logits = head(emb.to(head.weight.dtype)).squeeze(-1)if TEMPERATURE != 1.0:logits = logits / TEMPERATUREp = torch.sigmoid(logits).float().cpu().numpy()preds.append(p)p_fold = np.clip(np.concatenate(preds).astype(np.float64), 1e-6, 1 - 1e-6)# Platt scaling: P_calib = sigmoid(A * logit(p) + B)# NOTA: sigmoid(x) = 1/(1+exp(-x)) — o sinal negativo é obrigatórioif CALIB_A != 1.0 or CALIB_B != 0.0:logits_np = np.log(p_fold / (1.0 - p_fold))p_fold = 1.0 / (1.0 + np.exp(-(CALIB_A * logits_np + CALIB_B)))fold_preds.append(p_fold)return np.mean(fold_preds, axis=0) if len(fold_preds) > 1 else fold_preds[0]def predict_one(text: str) -> float:"""Probabilidade calibrada para um único texto."""return float(predict_batch([text])[0])def explain_occlusion(text: str, batch_size: int = BATCH_SIZE) -> dict:"""Leave-one-out usando o ensemble completo com calibração."""words = text.split()if not words:p = predict_one(text)return {"proba_full": p, "tokens": [], "contributions": []}variants = [" ".join(words[:i] + words[i + 1:]) for i in range(len(words))]probs = predict_batch([text] + variants, batch_size=batch_size)p_full = float(probs[0])return {"proba_full": p_full, "tokens": words,"contributions": (p_full - probs[1:]).tolist()}
inference.py+82-90