Datasets:
Download eval_choice.py from Synth-NLP/massive-pt-br-dedup: direct link, hf CLI and curl.
- Browser
- Download file 6.4 kB
-
https://huggingface.co/datasets/Synth-NLP/massive-pt-br-dedup/resolve/main/eval_choice.py
- Command line
-
hf download hf://datasets/Synth-NLP/massive-pt-br-dedup/eval_choice.py
-
curl -L -o eval_choice.py https://huggingface.co/datasets/Synth-NLP/massive-pt-br-dedup/resolve/main/eval_choice.py
6.4 kB
| """Avalia o Laya sem fine-tuning na escolha de intenção do massive-pt-br. | |
| Só aceita a validação: o teste fica de fora até os rótulos estarem congelados. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import random | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import huggingface_hub | |
| import numpy as np | |
| import torch | |
| import laya | |
| from laya.common import build_head | |
| from laya.train import to_internal | |
| REPO = "Magurofg/massive-pt-br" | |
| REVISAO = "1356d116fe64d9a2bd796857b88679e21992b86a" | |
| PERGUNTA = "O que o usuário está pedindo?" | |
| N_BOOTSTRAP = 1000 | |
| def carregar_dados(split, limite): | |
| caminho = huggingface_hub.hf_hub_download(REPO, f"{split}.jsonl", repo_type="dataset", revision=REVISAO) | |
| conteudo = Path(caminho).read_bytes() | |
| linhas = [json.loads(l) for l in conteudo.decode("utf-8").splitlines() if l.strip()] | |
| if limite: | |
| # Amostra fixa, para o teste rápido não pegar só o começo do arquivo | |
| linhas = random.Random(0).sample(linhas, min(limite, len(linhas))) | |
| return linhas, hashlib.sha256(conteudo).hexdigest() | |
| def montar_pergunta(rotulos, ids): | |
| # None é a forma nativa de "sem descrição": a opção vira só a tradução | |
| criteria = {rotulos[i]["traducao"]: None for i in ids} | |
| return {"type": "choice", "instructions": PERGUNTA, "criteria": criteria} | |
| def sortear_opcoes(id_frase, ouro, n_rotulos, n_opcoes, seed): | |
| # A seed combina com o id da frase: cada frase tem seu sorteio, reproduzível entre rodadas | |
| rng = random.Random(f"{seed}-{id_frase}") | |
| outros = [i for i in range(n_rotulos) if i != ouro] | |
| ids = [ouro] + rng.sample(outros, n_opcoes - 1) | |
| rng.shuffle(ids) | |
| return ids | |
| def medir_cabecalho(tok, rotulos, n_opcoes, head_max_len): | |
| q = to_internal("intent", montar_pergunta(rotulos, list(range(n_opcoes)))) | |
| ids, _, stats = build_head(tok, q, head_max_len) | |
| return {"tokens": len(ids), **stats} | |
| def f1_macro(ouro, pred): | |
| f1s = [] | |
| # Só as classes presentes no ouro: uma classe sem exemplos não tem F1 definido | |
| for c in np.unique(ouro): | |
| vp = np.sum((ouro == c) & (pred == c)) | |
| denominador = np.sum(ouro == c) + np.sum(pred == c) | |
| f1s.append(2 * vp / denominador) | |
| return float(np.mean(f1s)) | |
| def metricas(ouro, pred): | |
| ouro, pred = np.array(ouro), np.array(pred) | |
| rng = np.random.default_rng(0) | |
| acc, f1 = [], [] | |
| for _ in range(N_BOOTSTRAP): | |
| a = rng.integers(0, len(ouro), len(ouro)) | |
| acc.append(np.mean(ouro[a] == pred[a])) | |
| f1.append(f1_macro(ouro[a], pred[a])) | |
| return { | |
| "n": len(ouro), | |
| "acuracia": float(np.mean(ouro == pred)), | |
| "acuracia_ic95": [float(x) for x in np.percentile(acc, [2.5, 97.5])], | |
| "f1_macro": f1_macro(ouro, pred), | |
| "f1_macro_ic95": [float(x) for x in np.percentile(f1, [2.5, 97.5])], | |
| } | |
| def main() -> int: | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--split", choices=["validation"], default="validation") | |
| p.add_argument("--opcoes", type=int, nargs="+", default=[20, 60]) | |
| p.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2]) | |
| p.add_argument("--limite", type=int, default=0, help="número de frases; 0 usa todas") | |
| p.add_argument("--head-max-len", type=int, default=None) | |
| p.add_argument("--rotulos", default="labels/massive_intents_ptbr.json") | |
| p.add_argument("--saida", required=True) | |
| args = p.parse_args() | |
| rotulos = json.loads(Path(args.rotulos).read_text(encoding="utf-8")) | |
| assert [r["id"] for r in rotulos] == list(range(60)), "rótulos fora de ordem" | |
| assert len({r["traducao"] for r in rotulos}) == 60, "traduções repetidas" | |
| frases, sha = carregar_dados(args.split, args.limite) | |
| agente = laya.load("convaiinnovations/laya", subfolder="multilingual") | |
| head_max_len = args.head_max_len or agente.cfg.get("head_max_len", 192) | |
| print(f"max_len={agente.cfg.get('max_len', 512)} head_max_len={head_max_len} | {len(frases)} frases") | |
| resultado = { | |
| "repo": REPO, "revisao": REVISAO, "split": args.split, "sha256": sha, "pergunta": PERGUNTA, | |
| "laya": laya.__version__, "torch": torch.__version__, "limite": args.limite, | |
| "head_max_len": head_max_len, "seeds": args.seeds, "cabecalho": {}, "configuracoes": {}, | |
| } | |
| previsoes = [] | |
| for n_opcoes in args.opcoes: | |
| nome = f"{n_opcoes}_opcoes" | |
| resultado["cabecalho"][nome] = medir_cabecalho(agente.tok, rotulos, n_opcoes, head_max_len) | |
| print(nome, resultado["cabecalho"][nome]) | |
| por_seed = {} | |
| for seed in args.seeds: | |
| ouro, pred, ouro_sem_groq, pred_sem_groq = [], [], [], [] | |
| t0 = time.perf_counter() | |
| for f in frases: | |
| ids = sortear_opcoes(f["id"], f["intent"], len(rotulos), n_opcoes, seed) | |
| pergunta = montar_pergunta(rotulos, ids) | |
| resposta = agente.predict(f["utt_br"], {"intent": pergunta}, | |
| head_max_len=head_max_len)["answers"]["intent"] | |
| previsto = next(r["id"] for r in rotulos if r["traducao"] == resposta["choice"]) | |
| ouro.append(f["intent"]) | |
| pred.append(previsto) | |
| if f["professor"] != "groq": | |
| ouro_sem_groq.append(f["intent"]) | |
| pred_sem_groq.append(previsto) | |
| previsoes.append({"config": nome, "seed": seed, "id": f["id"], "ouro": f["intent"], | |
| "previsto": previsto, "confianca": resposta.get("confidence")}) | |
| ms = (time.perf_counter() - t0) * 1000 / len(frases) | |
| por_seed[seed] = {"ms_por_frase": ms, "geral": metricas(ouro, pred), | |
| "sem_groq": metricas(ouro_sem_groq, pred_sem_groq)} | |
| print(f" seed {seed}: acc={por_seed[seed]['geral']['acuracia']:.3f} " | |
| f"f1={por_seed[seed]['geral']['f1_macro']:.3f} {ms:.0f} ms/frase") | |
| resultado["configuracoes"][nome] = por_seed | |
| saida = Path(args.saida) | |
| saida.parent.mkdir(parents=True, exist_ok=True) | |
| saida.write_text(json.dumps(resultado, ensure_ascii=False, indent=1), encoding="utf-8") | |
| saida.with_suffix(".previsoes.jsonl").write_text( | |
| "\n".join(json.dumps(x, ensure_ascii=False) for x in previsoes) + "\n", encoding="utf-8") | |
| print(f"salvo em {saida}") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |