translation.py 6.32 KB
Newer Older
1
import pycountry
2
from pprint import pprint
3
4
5
from sacrebleu import sacrebleu
from lm_eval import metrics
from lm_eval.base import Task, rf
Muennighoff's avatar
Muennighoff committed
6
7
8
9
10
from typing import List

import jieba
import nagisa

11
12
13
14
15
16
17
18
19
20

"""
This file implements translation tasks using datasets from WMT conferences, provided by sacrebleu.
Traditionally they are evaluated with BLEU scores. TER and CHRF are other options.

See sacrebleu.DATASETS for all available datasets. There are a lot!
"""
sacrebleu_datasets = sacrebleu.DATASETS


&'s avatar
& committed
21
def create_tasks_from_benchmarks(benchmark_dict):
&'s avatar
& committed
22
    """Creates a dictionary of tasks from a dict
&'s avatar
& committed
23
    :param benchmark_dict: { dataset: [lang_pair, ...], }
&'s avatar
& committed
24
25
26
    :return: {task_name: task}
        e.g. {wmt14-fr-en: Task, wmt16-de-en: Task}
    """
&'s avatar
& committed
27
28
29
30
31
32
    return {
        f"{dataset}-{language_pair}": create_translation_task(dataset, language_pair)
        for dataset, language_pairs in benchmark_dict.items()
        for language_pair in language_pairs
    }

Muennighoff's avatar
Muennighoff committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
########################################
# Language Specifics
########################################

def zh_split(zh_text: List[str]) -> List[str]:
    """Chinese splitting"""
    return [" ".join(jieba.cut(txt.strip())) for txt in zh_text]

def ja_split(ja_text: List[str]) -> List[str]:
    """Japanese splitting"""
    return [" ".join(nagisa.tagging(txt.strip()).words) for txt in ja_text]

NO_SPACE_LANG = {"zh": zh_split, "ja": ja_split}

&'s avatar
& committed
47
48
49
50
########################################
# Tasks
########################################

51
52
53
54
55
56
57
def create_translation_task(dataset, language_pair):
    class TranslationTask(GeneralTranslationTask):
        def __init__(self):
            super().__init__(dataset, language_pair)
    return TranslationTask

class GeneralTranslationTask(Task):
Leo Gao's avatar
Leo Gao committed
58
    VERSION = 0
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
93
94
95
96
97
98
99
100

    # e.g. ("wmt14", "fr-en")
    def __init__(self, sacrebleu_dataset, sacrebleu_language_pair=None):
        self.sacrebleu_dataset = sacrebleu_dataset
        self.sacrebleu_language_pair = sacrebleu_language_pair
        self.src_file = self.ref_file = self.src_data = self.ref_data = None

        super().__init__()

    def download(self):
        # This caches in the users home dir automatically
        self.src_file, self.ref_file = \
            sacrebleu.download_test_set(self.sacrebleu_dataset, self.sacrebleu_language_pair)
        self.src_data, self.ref_data = [
            [line.rstrip() for line in sacrebleu.smart_open(file)]
            for file in (self.src_file, self.ref_file)
        ]

    def has_training_docs(self):
        """Whether the task has a training set"""
        # TODO In the future we could be more discerning. Some more recent tests have train and dev sets
        return False

    def has_validation_docs(self):
        """Whether the task has a validation set"""
        return False

    def has_test_docs(self):
        """Whether the task has a test set"""
        return True

    def test_docs(self):
        """
        :return: Iterable[obj]
            A iterable of any object, that doc_to_text can handle
        """
        return [{
            "src": src,
            "ref": ref
        } for src, ref in zip(self.src_data, self.ref_data)]

    def doc_to_text(self, doc):
Leo Gao's avatar
Leo Gao committed
101
102
103
104
        language_codes = self.sacrebleu_language_pair.split("-")
        src_lang = code_to_language(language_codes[0])
        tar_lang = code_to_language(language_codes[1])
        return f"{src_lang} phrase: " + doc["src"] + f"\n{tar_lang} phrase:"
105
106

    def doc_to_target(self, doc):
&'s avatar
& committed
107
        # This shows a single target, though there may be multiple targets in a lang test
Leo Gao's avatar
Leo Gao committed
108
        return " " + doc["ref"] if isinstance(doc["ref"], str) else doc["ref"][0]
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

    def construct_requests(self, doc, ctx):
        """ Uses RequestFactory to construct Requests and returns an iterable of
        Requests which will be sent to the LM.

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param ctx: str
            The context string, generated by fewshot_context. This includes the natural
            language description, as well as the few shot examples, and the question
            part of the document for `doc`.
        """
        return rf.greedy_until(ctx, ["\n"])

    def process_results(self, doc, results):
Muennighoff's avatar
Muennighoff committed
124
125
126
127
128
129
        # Add spaces between words for BLEU score calculation of target languages like Chinese
        tar_lang_code = self.sacrebleu_language_pair.split("-")[-1]
        if tar_lang_code in NO_SPACE_LANG:
            doc["ref"] = NO_SPACE_LANG[tar_lang_code]([doc["ref"]])[0]
            results = NO_SPACE_LANG[tar_lang_code](results)

130
131
        # These metrics are corpus-level not sentence level, so we'll hide the
        # results in this dict and compute the corpus score in the aggregate method
&'s avatar
& committed
132
        ref_pred = (doc["ref"], results)
133
        return {
&'s avatar
& committed
134
135
136
            "bleu": ref_pred,
            "chrf": ref_pred,
            "ter": ref_pred,
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        }

    def aggregation(self):
        """
        :returns: {str: [float] -> float}
            A dictionary where keys are the names of submetrics and values are
            functions that aggregate a list of metrics
        """
        return {
            "bleu": metrics.bleu,
            "chrf": metrics.chrf,
            "ter": metrics.ter,
        }

    def higher_is_better(self):
        """
        :returns: {str: bool}
            A dictionary where keys are the names of submetrics and values are
            whether a higher value of the submetric is better
        """
        return {
            "bleu": True,
            "chrf": True,
            "ter": False,
        }

    def fewshot_description(self):
        language_codes = self.sacrebleu_language_pair.split("-")
&'s avatar
& committed
165
166
167
        src_lang = code_to_language(language_codes[0])
        tar_lang = code_to_language(language_codes[1])
        return f"Translate these {src_lang} phrases to {tar_lang}."
168

&'s avatar
& committed
169
170
171
172
173
174
    def __str__(self):
        language_codes = self.sacrebleu_language_pair.split("-")
        src_lang = code_to_language(language_codes[0])
        tar_lang = code_to_language(language_codes[1])
        return f"{self.sacrebleu_dataset.upper()} {src_lang} to {tar_lang} Task"

175
176
177
178
179
180
181
182

########################################
# Util
########################################


def code_to_language(code):
    # key is alpha_2 or alpha_3 depending on the code length
&'s avatar
& committed
183
    language_tuple = pycountry.languages.get(**{f"alpha_{len(code)}": code})
184
    return language_tuple.name