Seeds / src /04_evaluate_nllb.py
BeaMorais's picture
Update src/04_evaluate_nllb.py
16e30bd verified
Raw History Blame Contribute Delete
15.4 kB
import json
import csv
import gc
import torch
from pathlib import Path
from datetime import datetime
from transformers import (
AutoTokenizer,
AutoModelForSeq2SeqLM
)
from peft import PeftModel
from sacrebleu import corpus_bleu, corpus_chrf
from tqdm.auto import tqdm
# ============================================================
# 1. CONFIGURAÇÕES
# ============================================================
BASE_MODEL_ID = "facebook/nllb-200-distilled-600M"
# Diretório raiz do projeto (um nível acima de src/)
ROOT_DIR = Path(__file__).resolve().parent.parent
# Caminho local do adaptador LoRA
LORA_MODEL_DIR = (
ROOT_DIR / "models" / "seeds-nllb-lora-final"
)
SOURCE_LANG = "eng_Latn"
TARGET_MARKER = "por_Latn"
# Arquivos de entrada e saída
TEST_FILE = ROOT_DIR / "data" / "test.jsonl"
OUTPUT_DIR = ROOT_DIR / "evaluation"
MAX_SOURCE_LENGTH = 128
MAX_GENERATION_LENGTH = 256
BATCH_SIZE = 1
DEVICE = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
RANDOM_SEED = 42
torch.manual_seed(RANDOM_SEED)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(RANDOM_SEED)
else:
torch.set_num_threads(2)
# ============================================================
# 2. VERIFICAÇÃO DO AMBIENTE
# ============================================================
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print("=" * 60)
print("SEEDS — AVALIAÇÃO DO MODELO NLLB")
print("=" * 60)
print(f"Dispositivo: {DEVICE}")
print(f"Modelo base: {BASE_MODEL_ID}")
print(f"Adaptador local: {LORA_MODEL_DIR}")
print(f"Conjunto de teste: {TEST_FILE}")
# Verifica o conjunto de teste.
if not TEST_FILE.exists():
raise FileNotFoundError(
f"Arquivo de teste não encontrado: {TEST_FILE}"
)
# Verifica se o diretório do adaptador existe.
if not LORA_MODEL_DIR.is_dir():
raise FileNotFoundError(
"\nAdaptador LoRA não encontrado!\n"
f"Caminho esperado: {LORA_MODEL_DIR}\n"
"Verifique se o treinamento foi preservado."
)
# Verifica os arquivos essenciais do adaptador.
adapter_config = LORA_MODEL_DIR / "adapter_config.json"
adapter_weights = [
LORA_MODEL_DIR / "adapter_model.safetensors",
LORA_MODEL_DIR / "adapter_model.bin"
]
if not adapter_config.exists():
raise FileNotFoundError(
"adapter_config.json não encontrado no diretório LoRA."
)
if not any(path.exists() for path in adapter_weights):
raise FileNotFoundError(
"Pesos do adaptador não encontrados. "
"Esperado adapter_model.safetensors ou adapter_model.bin."
)
print("\nArquivos do adaptador encontrados.")
print("Verificações iniciais concluídas.")
# ============================================================
# 3. CARREGAMENTO DO CONJUNTO DE TESTE
# ============================================================
def load_test_data(file_path):
examples = []
with open(file_path, "r", encoding="utf-8") as file:
for line_number, line in enumerate(file, start=1):
if not line.strip():
continue
item = json.loads(line)
source = next(
(
item[key]
for key in [
"source",
"english",
"eng",
"eng-web",
"source_text",
"input"
]
if key in item and item[key]
),
None
)
target = next(
(
item[key]
for key in [
"target",
"macushi",
"macuxi",
"mbcNT",
"target_text",
"reference"
]
if key in item and item[key]
),
None
)
if source is None or target is None:
raise ValueError(
f"Campos de origem/destino não encontrados "
f"na linha {line_number}. "
f"Campos disponíveis: {list(item.keys())}"
)
examples.append({
"source": str(source),
"reference": str(target),
"book": item.get("book", ""),
"chapter": item.get("chapter", ""),
"verse": item.get("verse", "")
})
if not examples:
raise ValueError("O conjunto de teste está vazio.")
return examples
test_data = load_test_data(TEST_FILE)
print(f"\nExemplos carregados: {len(test_data)}")
# ============================================================
# 4. CARREGAMENTO DO TOKENIZER
# ============================================================
print("\nCarregando tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(
BASE_MODEL_ID,
src_lang=SOURCE_LANG,
tgt_lang=TARGET_MARKER
)
target_id = tokenizer.convert_tokens_to_ids(
TARGET_MARKER
)
if target_id == tokenizer.unk_token_id:
raise RuntimeError(
f"Marcador de idioma não reconhecido: {TARGET_MARKER}"
)
print("Tokenizer carregado com sucesso.")
# ============================================================
# 5. CARREGAMENTO DO MODELO BASE
# ============================================================
def load_base_model():
print("\nCarregando modelo NLLB original...")
model = AutoModelForSeq2SeqLM.from_pretrained(
BASE_MODEL_ID
)
model.config.use_cache = True
model.to(DEVICE)
model.eval()
return model
# ============================================================
# 6. CARREGAMENTO DO MODELO COM LORA
# ============================================================
def load_lora_model():
print("\nCarregando modelo NLLB com adaptador LoRA...")
# Carrega o modelo base.
base_model = AutoModelForSeq2SeqLM.from_pretrained(
BASE_MODEL_ID
)
# Aplica o adaptador salvo localmente.
model = PeftModel.from_pretrained(
base_model,
str(LORA_MODEL_DIR),
is_trainable=False
)
model.config.use_cache = True
model.to(DEVICE)
model.eval()
print("Modelo NLLB + LoRA carregado com sucesso.")
return model
# ============================================================
# 7. GERAÇÃO DAS TRADUÇÕES
# ============================================================
def generate_translations(model, examples, model_name):
predictions = []
print(f"\nIniciando avaliação: {model_name}")
progress = tqdm(
range(0, len(examples), BATCH_SIZE),
desc=f"Gerando traduções ({model_name})",
unit="lote"
)
for start in progress:
batch = examples[
start:start + BATCH_SIZE
]
sources = [
item["source"]
for item in batch
]
inputs = tokenizer(
sources,
return_tensors="pt",
padding=True,
truncation=True,
max_length=MAX_SOURCE_LENGTH
)
inputs = {
key: value.to(DEVICE)
for key, value in inputs.items()
}
with torch.inference_mode():
generated = model.generate(
**inputs,
max_length=MAX_GENERATION_LENGTH,
num_beams=1,
do_sample=False,
forced_bos_token_id=target_id,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id
)
decoded = tokenizer.batch_decode(
generated,
skip_special_tokens=True
)
predictions.extend(decoded)
del inputs
del generated
print(f"\nTraduções geradas: {len(predictions)}")
return predictions
# ============================================================
# 8. CÁLCULO DAS MÉTRICAS
# ============================================================
def calculate_metrics(predictions, references):
if len(predictions) != len(references):
raise ValueError(
"A quantidade de predições não corresponde "
"à quantidade de referências."
)
bleu = corpus_bleu(
predictions,
[references]
)
chrf = corpus_chrf(
predictions,
[references]
)
return {
"bleu": round(bleu.score, 4),
"chrf": round(chrf.score, 4)
}
# ============================================================
# 9. SALVAMENTO DAS PREDIÇÕES
# ============================================================
def save_predictions(examples, predictions, filename):
output_file = OUTPUT_DIR / filename
with open(
output_file,
"w",
encoding="utf-8-sig",
newline=""
) as file:
writer = csv.DictWriter(
file,
fieldnames=[
"book",
"chapter",
"verse",
"source",
"reference",
"prediction"
]
)
writer.writeheader()
for item, prediction in zip(
examples,
predictions
):
writer.writerow({
"book": item["book"],
"chapter": item["chapter"],
"verse": item["verse"],
"source": item["source"],
"reference": item["reference"],
"prediction": prediction
})
print(f"Predições salvas em: {output_file}")
# ============================================================
# 10. REAPROVEITAMENTO DA AVALIAÇÃO BASELINE
# ============================================================
def load_cached_baseline(examples):
baseline_file = OUTPUT_DIR / "predictions_baseline.csv"
if not baseline_file.exists():
print("\nResultado baseline não encontrado.")
return None
print("\nVerificando resultado baseline existente...")
cached_predictions = []
try:
with open(
baseline_file,
"r",
encoding="utf-8-sig",
newline=""
) as file:
reader = csv.DictReader(file)
required_columns = {
"source",
"reference",
"prediction"
}
if not required_columns.issubset(
set(reader.fieldnames or [])
):
print("CSV baseline possui estrutura inválida.")
return None
rows = list(reader)
if len(rows) != len(examples):
print("Quantidade de registros diferente. Recalculando baseline.")
return None
for row, example in zip(rows, examples):
# Confirma que o CSV corresponde exatamente
# ao conjunto de teste atual e à mesma ordem.
if (
row["source"] != example["source"]
or row["reference"] != example["reference"]
):
print("CSV baseline não corresponde ao teste atual.")
return None
cached_predictions.append(
row["prediction"]
)
print("Baseline anterior validada com sucesso.")
print("As traduções existentes serão reutilizadas.")
return cached_predictions
except Exception as error:
print(f"Não foi possível reutilizar baseline: {error}")
return None
# ============================================================
# 11. AVALIAÇÃO DO MODELO BASELINE
# ============================================================
print("\n" + "=" * 60)
print("ETAPA 1 — NLLB ORIGINAL (BASELINE)")
print("=" * 60)
baseline_predictions = load_cached_baseline(test_data)
if baseline_predictions is None:
baseline_model = load_base_model()
baseline_predictions = generate_translations(
baseline_model,
test_data,
"NLLB Baseline"
)
save_predictions(
test_data,
baseline_predictions,
"predictions_baseline.csv"
)
del baseline_model
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
else:
print("Execução da baseline ignorada.")
baseline_results = calculate_metrics(
baseline_predictions,
[
item["reference"]
for item in test_data
]
)
print("\nResultados do baseline:")
print(json.dumps(baseline_results, indent=4))
# ============================================================
# 12. AVALIAÇÃO DO MODELO COM LORA
# ============================================================
print("\n" + "=" * 60)
print("ETAPA 2 — NLLB + LORA")
print("=" * 60)
lora_model = load_lora_model()
lora_predictions = generate_translations(
lora_model,
test_data,
"NLLB + LoRA"
)
lora_results = calculate_metrics(
lora_predictions,
[
item["reference"]
for item in test_data
]
)
save_predictions(
test_data,
lora_predictions,
"predictions_nllb_lora.csv"
)
print("\nResultados do NLLB + LoRA:")
print(json.dumps(lora_results, indent=4))
del lora_model
del lora_predictions
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
# ============================================================
# 13. RELATÓRIO FINAL
# ============================================================
report = {
"project": "SEEDS",
"evaluation_date": datetime.now().isoformat(),
"base_model": BASE_MODEL_ID,
"adapter_path": str(LORA_MODEL_DIR),
"source_language": SOURCE_LANG,
"target_marker": TARGET_MARKER,
"device": str(DEVICE),
"test_samples": len(test_data),
"generation_configuration": {
"max_source_length": MAX_SOURCE_LENGTH,
"max_generation_length": MAX_GENERATION_LENGTH,
"batch_size": BATCH_SIZE,
"num_beams": 1,
"do_sample": False
},
"baseline": baseline_results,
"nllb_lora": lora_results,
"limitations": [
"O NLLB-200 não oferece suporte nativo à língua Macuxi.",
"O marcador por_Latn foi utilizado como estratégia experimental.",
"Os resultados devem ser interpretados como exploratórios.",
"BLEU e chrF não substituem uma avaliação humana da qualidade das traduções."
]
}
report_path = OUTPUT_DIR / "evaluation_report.json"
with open(
report_path,
"w",
encoding="utf-8"
) as file:
json.dump(
report,
file,
ensure_ascii=False,
indent=4
)
# ============================================================
# 14. RESUMO
# ============================================================
print("\n" + "=" * 60)
print("AVALIAÇÃO FINALIZADA")
print("=" * 60)
print(f"Exemplos avaliados: {len(test_data)}")
print("\nNLLB Baseline:")
print(f"BLEU: {baseline_results['bleu']}")
print(f"chrF: {baseline_results['chrf']}")
print("\nNLLB + LoRA:")
print(f"BLEU: {lora_results['bleu']}")
print(f"chrF: {lora_results['chrf']}")
print("\nArquivos gerados:")
print("- evaluation/predictions_baseline.csv")
print("- evaluation/predictions_nllb_lora.csv")
print("- evaluation/evaluation_report.json")
print("\nEtapa de avaliação concluída!")