Spaces:
Running

File size: 4,003 Bytes
f2f9311
8f3b9c2
f2f9311
8f3b9c2
 
 
f2f9311
8f3b9c2
 
f2f9311
8f3b9c2
 
f2f9311
 
 
 
 
 
 
 
 
8f3b9c2
f2f9311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f3b9c2
 
f2f9311
8f3b9c2
f2f9311
 
 
 
 
 
 
 
 
 
 
8f3b9c2
f2f9311
 
 
 
 
 
 
 
8f3b9c2
f2f9311
 
8f3b9c2
f2f9311
 
 
8f3b9c2
f2f9311
 
 
 
 
 
 
 
 
 
 
8f3b9c2
f2f9311
 
 
8f3b9c2
 
f2f9311
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Empirical benchmark of a zero-shot classifier for misplaced-field detection (Field-Fit ML).

Goal: measure whether `MoritzLaurer/mDeBERTa-v3-base-mnli-xnli` (multilingual
zero-shot, already cached) reliably classifies a field's content into its proper
field category so misplaced-field detection does not flood false positives.

Output: top predicted label + score for each case, match status against the
expected field, plus overall accuracy and latency summary.

Run:
    python scripts/experiments/test_fieldfit_ml.py
"""
from __future__ import annotations

import time

from transformers import pipeline

MODEL = "MoritzLaurer/mDeBERTa-v3-base-mnli-xnli"

# Indonesian field descriptions used as candidate zero-shot labels.
FIELD_LABELS = {
    "task":         "tugas atau perintah utama yang harus dikerjakan AI",
    "context":      "konteks, latar belakang, atau situasi",
    "references":   "sumber rujukan, materi, atau referensi yang dipakai",
    "role":         "peran atau persona yang harus diperankan AI",
    "audience":     "target audiens atau pembaca hasil",
    "tone":         "gaya bahasa atau nada penulisan",
    "constraints":  "batasan, larangan, atau aturan yang harus dipatuhi",
    "outputFormat": "format atau struktur keluaran yang diinginkan",
    "example":      "contoh hasil atau referensi keluaran",
}
LABELS = list(FIELD_LABELS.values())
DESC_TO_ID = {v: k for k, v in FIELD_LABELS.items()}
HYP = "Bagian prompt ini berisi {}."

# Test cases: (text, expected_field), covering well-placed fields and
# misplaced examples that should be detected.
CASES = [
    # Well-placed examples (model should predict the same field)
    ("Buatkan rencana pelaksanaan pembelajaran tentang fotosintesis", "task"),
    ("Rangkum perbedaan sel hewan dan sel tumbuhan", "task"),
    ("Untuk kelas 7 SMP dengan durasi 80 menit, siswa belum pernah belajar topik ini", "context"),
    ("Gunakan buku paket IPA kelas 7 halaman 20 sampai 35 dan kurikulum merdeka", "references"),
    ("Kamu adalah seorang guru IPA yang berpengalaman mengajar SMP", "role"),
    ("Bertindaklah sebagai dokter spesialis anak", "role"),
    ("Ditujukan untuk siswa kelas 3 SD yang baru belajar membaca", "audience"),
    ("Gunakan bahasa yang ramah, santai, dan mudah dipahami", "tone"),
    ("Jangan lebih dari 500 kata dan hindari istilah teknis yang rumit", "constraints"),
    ("Sajikan dalam bentuk tabel dengan kolom tujuan, kegiatan, dan penilaian", "outputFormat"),
    ("Contoh: 1. Pendahuluan sepuluh menit berisi apersepsi tentang tumbuhan", "example"),
    # Misplaced examples (tested against the intended target field)
    ("Kamu adalah seorang ahli sejarah Indonesia", "role"),
    ("Tampilkan hasilnya sebagai poin-poin bernomor", "outputFormat"),
    ("Khusus untuk mahasiswa tingkat akhir", "audience"),
    ("Maksimal tiga paragraf saja", "constraints"),
]


def main() -> None:
    print(f"Loading zero-shot model: {MODEL} (CPU) ...")
    t0 = time.time()
    clf = pipeline("zero-shot-classification", model=MODEL)
    print(f"  model ready in {time.time()-t0:.1f}s\n")

    correct = 0
    lat = []
    print(f"{'EXPECTED':12} {'PRED':12} {'score':>5} {'margin':>6}  match  text")
    print("-" * 100)
    for text, expected in CASES:
        t1 = time.time()
        out = clf(text, LABELS, hypothesis_template=HYP, multi_label=False)
        lat.append(time.time() - t1)
        top_id = DESC_TO_ID[out["labels"][0]]
        top_score = out["scores"][0]
        margin = out["scores"][0] - out["scores"][1]
        ok = top_id == expected
        correct += ok
        print(f"{expected:12} {top_id:12} {top_score:5.2f} {margin:6.2f}  "
              f"{'  OK ' if ok else 'MISS '}  {text[:48]}")

    n = len(CASES)
    print("-" * 100)
    print(f"Field accuracy: {correct}/{n} = {correct/n*100:.0f}%")
    print(f"Latency per field: avg {sum(lat)/len(lat)*1000:.0f} ms "
          f"(min {min(lat)*1000:.0f}, max {max(lat)*1000:.0f})")


if __name__ == "__main__":
    main()