Update src/04_evaluate.py
Browse files- src/04_evaluate.py +268 -475
src/04_evaluate.py
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
import json
|
| 2 |
-
import
|
| 3 |
-
import subprocess
|
| 4 |
-
import sys
|
| 5 |
|
| 6 |
-
import evaluate
|
| 7 |
import torch
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
from transformers import (
|
| 10 |
-
|
| 11 |
-
|
| 12 |
)
|
| 13 |
|
| 14 |
|
|
@@ -16,347 +16,133 @@ from transformers import (
|
|
| 16 |
# CONFIGURAÇÕES
|
| 17 |
# ============================================================
|
| 18 |
|
| 19 |
-
|
| 20 |
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
| 27 |
|
| 28 |
MAX_SOURCE_LENGTH = 128
|
| 29 |
MAX_TARGET_LENGTH = 128
|
| 30 |
|
| 31 |
-
|
| 32 |
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
# CABEÇALHO
|
| 36 |
-
# ============================================================
|
| 37 |
-
|
| 38 |
-
print("=" * 70)
|
| 39 |
-
print("SEEDS - AVALIAÇÃO DO MODELO")
|
| 40 |
-
print("English → Macushi")
|
| 41 |
-
print("=" * 70)
|
| 42 |
-
|
| 43 |
-
print()
|
| 44 |
-
print(
|
| 45 |
-
f"Modelo: {MODEL_PATH}"
|
| 46 |
-
)
|
| 47 |
-
print(
|
| 48 |
-
f"Arquivo de teste: {TEST_FILE}"
|
| 49 |
-
)
|
| 50 |
-
print(
|
| 51 |
-
f"Máximo de exemplos: "
|
| 52 |
-
f"{MAX_TEST_EXAMPLES}"
|
| 53 |
-
)
|
| 54 |
-
print(
|
| 55 |
-
f"Comprimento source: "
|
| 56 |
-
f"{MAX_SOURCE_LENGTH}"
|
| 57 |
-
)
|
| 58 |
-
print(
|
| 59 |
-
f"Comprimento target: "
|
| 60 |
-
f"{MAX_TARGET_LENGTH}"
|
| 61 |
-
)
|
| 62 |
-
print()
|
| 63 |
|
| 64 |
|
| 65 |
# ============================================================
|
| 66 |
-
#
|
| 67 |
# ============================================================
|
| 68 |
|
| 69 |
-
def
|
| 70 |
-
|
| 71 |
-
return (
|
| 72 |
-
os.path.exists(TEST_FILE)
|
| 73 |
-
and os.path.getsize(TEST_FILE) > 0
|
| 74 |
-
)
|
| 75 |
-
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
)
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
)
|
| 94 |
-
print(
|
| 95 |
-
" src/02_prepare_dataset.py"
|
| 96 |
-
)
|
| 97 |
-
print()
|
| 98 |
-
|
| 99 |
-
subprocess.run(
|
| 100 |
-
[
|
| 101 |
-
sys.executable,
|
| 102 |
-
"src/02_prepare_dataset.py"
|
| 103 |
-
],
|
| 104 |
-
check=True
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
if not test_file_exists():
|
| 108 |
-
|
| 109 |
-
raise RuntimeError(
|
| 110 |
-
"O arquivo de teste não foi "
|
| 111 |
-
"criado após a execução de "
|
| 112 |
-
"02_prepare_dataset.py."
|
| 113 |
)
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
"✅ Dataset de teste preparado."
|
| 118 |
-
)
|
| 119 |
-
print()
|
| 120 |
-
|
| 121 |
|
| 122 |
-
|
| 123 |
|
| 124 |
|
| 125 |
# ============================================================
|
| 126 |
-
#
|
| 127 |
# ============================================================
|
| 128 |
|
| 129 |
-
def
|
| 130 |
-
|
| 131 |
-
required_files = [
|
| 132 |
-
"config.json"
|
| 133 |
-
]
|
| 134 |
-
|
| 135 |
-
if not os.path.isdir(MODEL_PATH):
|
| 136 |
-
return False
|
| 137 |
-
|
| 138 |
-
for filename in required_files:
|
| 139 |
-
|
| 140 |
-
if not os.path.exists(
|
| 141 |
-
os.path.join(
|
| 142 |
-
MODEL_PATH,
|
| 143 |
-
filename
|
| 144 |
-
)
|
| 145 |
-
):
|
| 146 |
-
return False
|
| 147 |
-
|
| 148 |
-
return True
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
print(
|
| 156 |
-
"✅ Modelo encontrado."
|
| 157 |
)
|
| 158 |
-
print()
|
| 159 |
-
|
| 160 |
-
return
|
| 161 |
|
| 162 |
-
print(
|
| 163 |
-
"⚠️ Modelo treinado não encontrado."
|
| 164 |
-
)
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
print(
|
| 171 |
-
" src/03_train.py"
|
| 172 |
-
)
|
| 173 |
-
print()
|
| 174 |
-
|
| 175 |
-
subprocess.run(
|
| 176 |
-
[
|
| 177 |
-
sys.executable,
|
| 178 |
-
"src/03_train.py"
|
| 179 |
-
],
|
| 180 |
-
check=True
|
| 181 |
)
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
raise RuntimeError(
|
| 186 |
-
"O modelo não foi encontrado "
|
| 187 |
-
"após a execução de "
|
| 188 |
-
"03_train.py."
|
| 189 |
-
)
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
"✅ Modelo preparado para avaliação."
|
| 194 |
)
|
| 195 |
-
print()
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
train_model_if_needed()
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
# ============================================================
|
| 202 |
-
# CARREGAR DATASET
|
| 203 |
-
# ============================================================
|
| 204 |
-
|
| 205 |
-
print("Carregando dataset de teste...")
|
| 206 |
-
|
| 207 |
-
with open(
|
| 208 |
-
TEST_FILE,
|
| 209 |
-
"r",
|
| 210 |
-
encoding="utf-8"
|
| 211 |
-
) as f:
|
| 212 |
-
|
| 213 |
-
test_data = [
|
| 214 |
-
json.loads(linha)
|
| 215 |
-
for linha in f
|
| 216 |
-
if linha.strip()
|
| 217 |
-
]
|
| 218 |
-
|
| 219 |
-
print(
|
| 220 |
-
f"Dataset completo: "
|
| 221 |
-
f"{len(test_data)} exemplos"
|
| 222 |
-
)
|
| 223 |
-
|
| 224 |
-
if MAX_TEST_EXAMPLES is not None:
|
| 225 |
-
|
| 226 |
-
test_data = test_data[
|
| 227 |
-
:MAX_TEST_EXAMPLES
|
| 228 |
-
]
|
| 229 |
-
|
| 230 |
-
print(
|
| 231 |
-
f"Dataset utilizado: "
|
| 232 |
-
f"{len(test_data)} exemplos"
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
print()
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
# ============================================================
|
| 239 |
-
# DATASET HUGGING FACE
|
| 240 |
-
# ============================================================
|
| 241 |
-
|
| 242 |
-
dataset = Dataset.from_list(
|
| 243 |
-
test_data
|
| 244 |
-
)
|
| 245 |
|
| 246 |
-
print("
|
| 247 |
-
print(dataset.column_names)
|
| 248 |
-
print()
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
# ============================================================
|
| 254 |
-
|
| 255 |
-
print("Carregando tokenizer...")
|
| 256 |
-
|
| 257 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 258 |
-
MODEL_PATH
|
| 259 |
-
)
|
| 260 |
-
|
| 261 |
-
print("Tokenizer carregado.")
|
| 262 |
-
print()
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
# ============================================================
|
| 266 |
-
# MODELO
|
| 267 |
-
# ============================================================
|
| 268 |
-
|
| 269 |
-
print("Carregando modelo...")
|
| 270 |
-
|
| 271 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 272 |
-
MODEL_PATH
|
| 273 |
-
)
|
| 274 |
-
|
| 275 |
-
model.config.use_cache = True
|
| 276 |
-
|
| 277 |
-
model.eval()
|
| 278 |
-
|
| 279 |
-
device = torch.device("cpu")
|
| 280 |
-
|
| 281 |
-
model.to(device)
|
| 282 |
-
|
| 283 |
-
print(
|
| 284 |
-
f"Modelo carregado em: {device}"
|
| 285 |
-
)
|
| 286 |
-
|
| 287 |
-
print()
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
# ============================================================
|
| 291 |
-
# PREPARAR TEXTOS
|
| 292 |
-
# ============================================================
|
| 293 |
-
|
| 294 |
-
sources = []
|
| 295 |
-
|
| 296 |
-
references = []
|
| 297 |
-
|
| 298 |
-
for exemplo in test_data:
|
| 299 |
-
|
| 300 |
-
source = exemplo["source"]
|
| 301 |
-
|
| 302 |
-
target = exemplo["target"]
|
| 303 |
-
|
| 304 |
-
prompt = (
|
| 305 |
-
f"translate English to Macushi: "
|
| 306 |
-
f"{source}"
|
| 307 |
)
|
| 308 |
|
| 309 |
-
|
| 310 |
|
| 311 |
-
|
| 312 |
|
|
|
|
| 313 |
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
print("Carregando métricas...")
|
| 319 |
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
|
|
|
| 323 |
|
| 324 |
-
|
| 325 |
-
"chrf"
|
| 326 |
-
)
|
| 327 |
|
| 328 |
-
|
| 329 |
-
print()
|
| 330 |
|
| 331 |
|
| 332 |
# ============================================================
|
| 333 |
# GERAÇÃO
|
| 334 |
# ============================================================
|
| 335 |
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
predictions = []
|
| 343 |
-
|
| 344 |
-
for i in range(
|
| 345 |
-
0,
|
| 346 |
-
len(sources),
|
| 347 |
-
BATCH_SIZE
|
| 348 |
):
|
| 349 |
|
| 350 |
-
batch_sources = sources[
|
| 351 |
-
i:i + BATCH_SIZE
|
| 352 |
-
]
|
| 353 |
-
|
| 354 |
inputs = tokenizer(
|
| 355 |
-
|
| 356 |
-
|
| 357 |
truncation=True,
|
| 358 |
-
|
| 359 |
-
return_tensors="pt"
|
| 360 |
)
|
| 361 |
|
| 362 |
inputs = {
|
|
@@ -369,267 +155,274 @@ for i in range(
|
|
| 369 |
generated = model.generate(
|
| 370 |
**inputs,
|
| 371 |
max_length=MAX_TARGET_LENGTH,
|
| 372 |
-
num_beams=
|
|
|
|
|
|
|
|
|
|
| 373 |
early_stopping=True
|
| 374 |
)
|
| 375 |
|
| 376 |
-
|
| 377 |
-
generated,
|
| 378 |
skip_special_tokens=True
|
| 379 |
)
|
| 380 |
|
| 381 |
-
|
| 382 |
-
decoded
|
| 383 |
-
)
|
| 384 |
|
| 385 |
-
if (
|
| 386 |
-
(i + BATCH_SIZE) % 10 == 0
|
| 387 |
-
or
|
| 388 |
-
i + BATCH_SIZE >= len(sources)
|
| 389 |
-
):
|
| 390 |
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
)
|
| 395 |
|
| 396 |
-
|
| 397 |
-
f"Traduções geradas: "
|
| 398 |
-
f"{processados}/{len(sources)}"
|
| 399 |
-
)
|
| 400 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
|
|
|
| 405 |
|
| 406 |
|
| 407 |
# ============================================================
|
| 408 |
-
#
|
| 409 |
# ============================================================
|
| 410 |
|
| 411 |
-
|
| 412 |
-
prediction.strip()
|
| 413 |
-
for prediction in predictions
|
| 414 |
-
]
|
| 415 |
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
]
|
| 420 |
|
|
|
|
| 421 |
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
|
| 426 |
-
print(
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
-
|
| 429 |
-
predictions=predictions,
|
| 430 |
-
references=[
|
| 431 |
-
[reference]
|
| 432 |
-
for reference in references
|
| 433 |
-
]
|
| 434 |
-
)
|
| 435 |
|
| 436 |
-
|
|
|
|
|
|
|
| 437 |
|
| 438 |
-
|
| 439 |
-
f"BLEU: {bleu_score:.4f}"
|
| 440 |
-
)
|
| 441 |
|
| 442 |
-
print()
|
| 443 |
|
|
|
|
| 444 |
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
# ============================================================
|
| 448 |
|
| 449 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
references=references
|
| 454 |
-
)
|
| 455 |
|
| 456 |
-
|
|
|
|
| 457 |
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
|
| 462 |
-
|
| 463 |
|
|
|
|
|
|
|
|
|
|
| 464 |
|
| 465 |
-
#
|
| 466 |
-
#
|
| 467 |
-
#
|
| 468 |
|
| 469 |
-
print("
|
| 470 |
-
print("EXEMPLOS DE TRADUÇÃO")
|
| 471 |
-
print("=" * 70)
|
| 472 |
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
)
|
| 477 |
|
| 478 |
-
|
|
|
|
|
|
|
| 479 |
|
| 480 |
-
print()
|
| 481 |
-
|
| 482 |
-
|
|
|
|
|
|
|
| 483 |
)
|
| 484 |
|
| 485 |
-
|
|
|
|
|
|
|
| 486 |
|
| 487 |
-
|
| 488 |
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
|
|
|
| 492 |
|
| 493 |
-
|
| 494 |
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
|
|
|
| 498 |
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
|
| 503 |
-
|
|
|
|
|
|
|
| 504 |
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
|
|
|
|
| 513 |
|
| 514 |
-
|
| 515 |
-
# SALVAR RESULTADOS
|
| 516 |
-
# ============================================================
|
| 517 |
|
| 518 |
-
|
| 519 |
-
OUTPUT_DIR,
|
| 520 |
-
exist_ok=True
|
| 521 |
-
)
|
| 522 |
|
| 523 |
-
|
| 524 |
|
| 525 |
-
|
| 526 |
|
| 527 |
-
|
| 528 |
-
test_data
|
| 529 |
-
),
|
| 530 |
|
| 531 |
-
|
| 532 |
-
MAX_SOURCE_LENGTH
|
| 533 |
-
),
|
| 534 |
|
| 535 |
-
|
| 536 |
-
MAX_TARGET_LENGTH
|
| 537 |
-
),
|
| 538 |
|
| 539 |
-
|
| 540 |
|
| 541 |
-
|
| 542 |
|
| 543 |
-
|
| 544 |
-
}
|
| 545 |
|
|
|
|
| 546 |
|
| 547 |
-
|
| 548 |
-
len(test_data)
|
| 549 |
-
):
|
| 550 |
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
"
|
| 554 |
-
|
| 555 |
-
|
|
|
|
|
|
|
| 556 |
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
|
|
|
| 560 |
|
| 561 |
-
|
| 562 |
-
"verse"
|
| 563 |
-
),
|
| 564 |
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
|
|
|
|
|
|
| 568 |
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
|
|
|
|
|
|
|
|
|
|
| 575 |
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
"
|
| 579 |
-
)
|
| 580 |
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
"
|
| 584 |
-
encoding="utf-8"
|
| 585 |
-
) as f:
|
| 586 |
-
|
| 587 |
-
json.dump(
|
| 588 |
-
results,
|
| 589 |
-
f,
|
| 590 |
-
ensure_ascii=False,
|
| 591 |
-
indent=2
|
| 592 |
-
)
|
| 593 |
|
|
|
|
| 594 |
|
| 595 |
-
|
| 596 |
-
# RESULTADO
|
| 597 |
-
# ============================================================
|
| 598 |
|
| 599 |
-
print(
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
|
|
|
|
|
|
| 603 |
|
| 604 |
-
print()
|
| 605 |
|
| 606 |
-
|
| 607 |
-
f"Exemplos avaliados: "
|
| 608 |
-
f"{len(test_data)}"
|
| 609 |
-
)
|
| 610 |
|
| 611 |
-
print(
|
| 612 |
-
f"BLEU: "
|
| 613 |
-
f"{bleu_score:.4f}"
|
| 614 |
-
)
|
| 615 |
|
| 616 |
-
print(
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
)
|
| 620 |
|
| 621 |
-
print(
|
|
|
|
|
|
|
| 622 |
|
| 623 |
-
print(
|
| 624 |
-
|
| 625 |
-
)
|
| 626 |
|
| 627 |
-
print(
|
| 628 |
-
|
| 629 |
-
)
|
|
|
|
|
|
|
|
|
|
| 630 |
|
| 631 |
-
print()
|
| 632 |
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
print("=" * 70)
|
|
|
|
| 1 |
import json
|
| 2 |
+
from pathlib import Path
|
|
|
|
|
|
|
| 3 |
|
|
|
|
| 4 |
import torch
|
| 5 |
+
import sacrebleu
|
| 6 |
+
|
| 7 |
+
from peft import PeftModel
|
| 8 |
+
|
| 9 |
from transformers import (
|
| 10 |
+
AutoModelForSeq2SeqLM,
|
| 11 |
+
AutoTokenizer
|
| 12 |
)
|
| 13 |
|
| 14 |
|
|
|
|
| 16 |
# CONFIGURAÇÕES
|
| 17 |
# ============================================================
|
| 18 |
|
| 19 |
+
BASE_MODEL = "facebook/nllb-200-distilled-600M"
|
| 20 |
|
| 21 |
+
ADAPTER_DIR = Path("models/seeds-nllb-lora-final")
|
| 22 |
|
| 23 |
+
TEST_FILE = Path("data/test.jsonl")
|
| 24 |
|
| 25 |
+
OUTPUT_DIR = Path("outputs")
|
| 26 |
+
|
| 27 |
+
SOURCE_LANG = "eng_Latn"
|
| 28 |
+
TARGET_MARKER = "por_Latn"
|
| 29 |
|
| 30 |
MAX_SOURCE_LENGTH = 128
|
| 31 |
MAX_TARGET_LENGTH = 128
|
| 32 |
|
| 33 |
+
NUM_BEAMS = 4
|
| 34 |
|
| 35 |
+
# 100 para teste rápido.
|
| 36 |
+
# None para avaliar todo o conjunto de teste.
|
| 37 |
+
MAX_TEST_EXAMPLES = 100
|
| 38 |
|
| 39 |
+
torch.set_num_threads(2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
# ============================================================
|
| 43 |
+
# CARREGAMENTO DO DATASET
|
| 44 |
# ============================================================
|
| 45 |
|
| 46 |
+
def load_test_data():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
if not TEST_FILE.exists():
|
| 49 |
+
raise FileNotFoundError(
|
| 50 |
+
f"Arquivo não encontrado: {TEST_FILE}"
|
| 51 |
+
)
|
| 52 |
|
| 53 |
+
rows = []
|
| 54 |
|
| 55 |
+
with open(
|
| 56 |
+
TEST_FILE,
|
| 57 |
+
"r",
|
| 58 |
+
encoding="utf-8"
|
| 59 |
+
) as file:
|
| 60 |
|
| 61 |
+
for line in file:
|
| 62 |
|
| 63 |
+
if line.strip():
|
| 64 |
+
rows.append(json.loads(line))
|
|
|
|
| 65 |
|
| 66 |
+
if not rows:
|
| 67 |
+
raise ValueError(
|
| 68 |
+
"O conjunto de teste está vazio."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
)
|
| 70 |
|
| 71 |
+
if MAX_TEST_EXAMPLES is not None:
|
| 72 |
+
rows = rows[:MAX_TEST_EXAMPLES]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
return rows
|
| 75 |
|
| 76 |
|
| 77 |
# ============================================================
|
| 78 |
+
# CARREGAMENTO DO MODELO + LoRA
|
| 79 |
# ============================================================
|
| 80 |
|
| 81 |
+
def load_model():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
if not ADAPTER_DIR.exists():
|
| 84 |
+
raise FileNotFoundError(
|
| 85 |
+
f"Adaptador não encontrado: {ADAPTER_DIR}. "
|
| 86 |
+
"Execute 03_train_nllb.py."
|
|
|
|
|
|
|
|
|
|
| 87 |
)
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
print("Carregando tokenizer...")
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 92 |
+
ADAPTER_DIR,
|
| 93 |
+
src_lang=SOURCE_LANG,
|
| 94 |
+
tgt_lang=TARGET_MARKER
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
)
|
| 96 |
|
| 97 |
+
print("Carregando modelo-base...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 100 |
+
BASE_MODEL
|
|
|
|
| 101 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
print("Carregando adaptador LoRA...")
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
model = PeftModel.from_pretrained(
|
| 106 |
+
base_model,
|
| 107 |
+
ADAPTER_DIR
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
)
|
| 109 |
|
| 110 |
+
model.eval()
|
| 111 |
|
| 112 |
+
device = torch.device("cpu")
|
| 113 |
|
| 114 |
+
model.to(device)
|
| 115 |
|
| 116 |
+
target_id = tokenizer.convert_tokens_to_ids(
|
| 117 |
+
TARGET_MARKER
|
| 118 |
+
)
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
if target_id is None or target_id == tokenizer.unk_token_id:
|
| 121 |
+
raise RuntimeError(
|
| 122 |
+
f"Marcador experimental não reconhecido: {TARGET_MARKER}"
|
| 123 |
+
)
|
| 124 |
|
| 125 |
+
model.generation_config.forced_bos_token_id = target_id
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
return tokenizer, model, device
|
|
|
|
| 128 |
|
| 129 |
|
| 130 |
# ============================================================
|
| 131 |
# GERAÇÃO
|
| 132 |
# ============================================================
|
| 133 |
|
| 134 |
+
def generate_translation(
|
| 135 |
+
source,
|
| 136 |
+
tokenizer,
|
| 137 |
+
model,
|
| 138 |
+
device
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
):
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
inputs = tokenizer(
|
| 142 |
+
source,
|
| 143 |
+
return_tensors="pt",
|
| 144 |
truncation=True,
|
| 145 |
+
max_length=MAX_SOURCE_LENGTH
|
|
|
|
| 146 |
)
|
| 147 |
|
| 148 |
inputs = {
|
|
|
|
| 155 |
generated = model.generate(
|
| 156 |
**inputs,
|
| 157 |
max_length=MAX_TARGET_LENGTH,
|
| 158 |
+
num_beams=NUM_BEAMS,
|
| 159 |
+
forced_bos_token_id=tokenizer.convert_tokens_to_ids(
|
| 160 |
+
TARGET_MARKER
|
| 161 |
+
),
|
| 162 |
early_stopping=True
|
| 163 |
)
|
| 164 |
|
| 165 |
+
prediction = tokenizer.decode(
|
| 166 |
+
generated[0],
|
| 167 |
skip_special_tokens=True
|
| 168 |
)
|
| 169 |
|
| 170 |
+
return prediction.strip()
|
|
|
|
|
|
|
| 171 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
+
# ============================================================
|
| 174 |
+
# MÉTRICAS
|
| 175 |
+
# ============================================================
|
|
|
|
| 176 |
|
| 177 |
+
def calculate_metrics(predictions, references):
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
bleu = sacrebleu.corpus_bleu(
|
| 180 |
+
predictions,
|
| 181 |
+
[references]
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
chrf = sacrebleu.corpus_chrf(
|
| 185 |
+
predictions,
|
| 186 |
+
[references]
|
| 187 |
+
)
|
| 188 |
|
| 189 |
+
return {
|
| 190 |
+
"bleu": bleu.score,
|
| 191 |
+
"chrf": chrf.score
|
| 192 |
+
}
|
| 193 |
|
| 194 |
|
| 195 |
# ============================================================
|
| 196 |
+
# MAIN
|
| 197 |
# ============================================================
|
| 198 |
|
| 199 |
+
def main():
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
+
print("=" * 70)
|
| 202 |
+
print("SEEDS — AVALIAÇÃO NLLB + LoRA")
|
| 203 |
+
print("=" * 70)
|
|
|
|
| 204 |
|
| 205 |
+
test_data = load_test_data()
|
| 206 |
|
| 207 |
+
print(
|
| 208 |
+
f"Exemplos selecionados: {len(test_data)}"
|
| 209 |
+
)
|
| 210 |
|
| 211 |
+
print(
|
| 212 |
+
f"Exemplos disponíveis no teste: "
|
| 213 |
+
f"{sum(1 for _ in open(TEST_FILE, encoding='utf-8'))}"
|
| 214 |
+
)
|
| 215 |
|
| 216 |
+
tokenizer, model, device = load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
+
predictions = []
|
| 219 |
+
references = []
|
| 220 |
+
baseline_predictions = []
|
| 221 |
|
| 222 |
+
examples = []
|
|
|
|
|
|
|
| 223 |
|
| 224 |
+
print("\nIniciando geração...")
|
| 225 |
|
| 226 |
+
for index, item in enumerate(test_data, start=1):
|
| 227 |
|
| 228 |
+
source = item["source"].strip()
|
| 229 |
+
reference = item["target"].strip()
|
|
|
|
| 230 |
|
| 231 |
+
prediction = generate_translation(
|
| 232 |
+
source,
|
| 233 |
+
tokenizer,
|
| 234 |
+
model,
|
| 235 |
+
device
|
| 236 |
+
)
|
| 237 |
|
| 238 |
+
predictions.append(prediction)
|
| 239 |
+
references.append(reference)
|
|
|
|
|
|
|
| 240 |
|
| 241 |
+
# Baseline simples: saída igual ao texto de entrada.
|
| 242 |
+
baseline_predictions.append(source)
|
| 243 |
|
| 244 |
+
examples.append({
|
| 245 |
+
"reference_id": item.get("reference"),
|
| 246 |
+
"book": item.get("book"),
|
| 247 |
+
"chapter": item.get("chapter"),
|
| 248 |
+
"verse": item.get("verse"),
|
| 249 |
+
"source": source,
|
| 250 |
+
"reference": reference,
|
| 251 |
+
"prediction": prediction
|
| 252 |
+
})
|
| 253 |
|
| 254 |
+
if index % 10 == 0 or index == len(test_data):
|
| 255 |
|
| 256 |
+
print(
|
| 257 |
+
f"Processados: {index}/{len(test_data)}"
|
| 258 |
+
)
|
| 259 |
|
| 260 |
+
# --------------------------------------------------------
|
| 261 |
+
# MÉTRICAS DO MODELO
|
| 262 |
+
# --------------------------------------------------------
|
| 263 |
|
| 264 |
+
print("\nCalculando métricas do NLLB...")
|
|
|
|
|
|
|
| 265 |
|
| 266 |
+
model_metrics = calculate_metrics(
|
| 267 |
+
predictions,
|
| 268 |
+
references
|
| 269 |
+
)
|
| 270 |
|
| 271 |
+
# --------------------------------------------------------
|
| 272 |
+
# MÉTRICAS DO BASELINE
|
| 273 |
+
# --------------------------------------------------------
|
| 274 |
|
| 275 |
+
print("Calculando métricas do baseline...")
|
| 276 |
+
|
| 277 |
+
baseline_metrics = calculate_metrics(
|
| 278 |
+
baseline_predictions,
|
| 279 |
+
references
|
| 280 |
)
|
| 281 |
|
| 282 |
+
# --------------------------------------------------------
|
| 283 |
+
# MÉTRICAS POR LIVRO
|
| 284 |
+
# --------------------------------------------------------
|
| 285 |
|
| 286 |
+
per_book = {}
|
| 287 |
|
| 288 |
+
books = sorted({
|
| 289 |
+
item.get("book", "UNKNOWN")
|
| 290 |
+
for item in examples
|
| 291 |
+
})
|
| 292 |
|
| 293 |
+
for book in books:
|
| 294 |
|
| 295 |
+
indexes = [
|
| 296 |
+
i for i, item in enumerate(examples)
|
| 297 |
+
if item.get("book", "UNKNOWN") == book
|
| 298 |
+
]
|
| 299 |
|
| 300 |
+
book_predictions = [
|
| 301 |
+
predictions[i] for i in indexes
|
| 302 |
+
]
|
| 303 |
|
| 304 |
+
book_references = [
|
| 305 |
+
references[i] for i in indexes
|
| 306 |
+
]
|
| 307 |
|
| 308 |
+
per_book[book] = {
|
| 309 |
+
"examples": len(indexes),
|
| 310 |
+
**calculate_metrics(
|
| 311 |
+
book_predictions,
|
| 312 |
+
book_references
|
| 313 |
+
)
|
| 314 |
+
}
|
| 315 |
|
| 316 |
+
# --------------------------------------------------------
|
| 317 |
+
# RESULTADO
|
| 318 |
+
# --------------------------------------------------------
|
| 319 |
|
| 320 |
+
results = {
|
| 321 |
|
| 322 |
+
"base_model": BASE_MODEL,
|
|
|
|
|
|
|
| 323 |
|
| 324 |
+
"adapter": str(ADAPTER_DIR),
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
+
"method": "NLLB-200 + LoRA",
|
| 327 |
|
| 328 |
+
"source_language": "English",
|
| 329 |
|
| 330 |
+
"target_language": "Macuxi",
|
|
|
|
|
|
|
| 331 |
|
| 332 |
+
"experimental_target_marker": TARGET_MARKER,
|
|
|
|
|
|
|
| 333 |
|
| 334 |
+
"test_examples": len(test_data),
|
|
|
|
|
|
|
| 335 |
|
| 336 |
+
"test_limit": MAX_TEST_EXAMPLES,
|
| 337 |
|
| 338 |
+
"model_metrics": model_metrics,
|
| 339 |
|
| 340 |
+
"baseline_metrics": baseline_metrics,
|
|
|
|
| 341 |
|
| 342 |
+
"metrics_by_book": per_book,
|
| 343 |
|
| 344 |
+
"examples": examples,
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
"limitation": (
|
| 347 |
+
"Avaliação exploratória. O NLLB não possui suporte "
|
| 348 |
+
"nativo ao Macuxi; por_Latn foi utilizado como marcador "
|
| 349 |
+
"experimental de destino. Os resultados não devem ser "
|
| 350 |
+
"interpretados como validação de tradução em produção."
|
| 351 |
+
)
|
| 352 |
+
}
|
| 353 |
|
| 354 |
+
OUTPUT_DIR.mkdir(
|
| 355 |
+
parents=True,
|
| 356 |
+
exist_ok=True
|
| 357 |
+
)
|
| 358 |
|
| 359 |
+
output_file = OUTPUT_DIR / "nllb_lora_evaluation.json"
|
|
|
|
|
|
|
| 360 |
|
| 361 |
+
with open(
|
| 362 |
+
output_file,
|
| 363 |
+
"w",
|
| 364 |
+
encoding="utf-8"
|
| 365 |
+
) as file:
|
| 366 |
|
| 367 |
+
json.dump(
|
| 368 |
+
results,
|
| 369 |
+
file,
|
| 370 |
+
ensure_ascii=False,
|
| 371 |
+
indent=2
|
| 372 |
+
)
|
| 373 |
|
| 374 |
+
# --------------------------------------------------------
|
| 375 |
+
# EXIBIÇÃO
|
| 376 |
+
# --------------------------------------------------------
|
| 377 |
|
| 378 |
+
print("\n" + "=" * 70)
|
| 379 |
+
print("RESULTADO DA AVALIAÇÃO")
|
| 380 |
+
print("=" * 70)
|
| 381 |
|
| 382 |
+
print("\nNLLB + LoRA")
|
| 383 |
+
print(f"BLEU: {model_metrics['bleu']:.4f}")
|
| 384 |
+
print(f"chrF: {model_metrics['chrf']:.4f}")
|
|
|
|
| 385 |
|
| 386 |
+
print("\nBaseline — cópia do inglês")
|
| 387 |
+
print(f"BLEU: {baseline_metrics['bleu']:.4f}")
|
| 388 |
+
print(f"chrF: {baseline_metrics['chrf']:.4f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
+
print("\nMétricas por livro:")
|
| 391 |
|
| 392 |
+
for book, metrics in per_book.items():
|
|
|
|
|
|
|
| 393 |
|
| 394 |
+
print(
|
| 395 |
+
f"{book}: "
|
| 396 |
+
f"BLEU={metrics['bleu']:.4f} | "
|
| 397 |
+
f"chrF={metrics['chrf']:.4f} | "
|
| 398 |
+
f"n={metrics['examples']}"
|
| 399 |
+
)
|
| 400 |
|
| 401 |
+
print("\nExemplos de tradução:")
|
| 402 |
|
| 403 |
+
for item in examples[:10]:
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
+
print("\n" + "-" * 70)
|
|
|
|
|
|
|
|
|
|
| 406 |
|
| 407 |
+
print(
|
| 408 |
+
f"Referência: {item['reference_id']}"
|
| 409 |
+
)
|
|
|
|
| 410 |
|
| 411 |
+
print(
|
| 412 |
+
f"English: {item['source']}"
|
| 413 |
+
)
|
| 414 |
|
| 415 |
+
print(
|
| 416 |
+
f"Macuxi referência: {item['reference']}"
|
| 417 |
+
)
|
| 418 |
|
| 419 |
+
print(
|
| 420 |
+
f"Macuxi modelo: {item['prediction']}"
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
print("\nRelatório salvo em:")
|
| 424 |
+
print(output_file)
|
| 425 |
|
|
|
|
| 426 |
|
| 427 |
+
if __name__ == "__main__":
|
| 428 |
+
main()
|
|
|