task.py 7.86 KB
Newer Older
1
2
3
4
5
6
"""
In the dynamic landscape of generative NLP, traditional text processing pipelines limit research flexibility and reproducibility, as they are tailored to specific dataset, task, and model combinations. The escalating complexity, involving system prompts, model-specific formats, instructions, and more, calls for a shift to a structured, modular, and customizable solution.

Addressing this need, we present Unitxt, an innovative library for customizable textual data preparation and evaluation tailored to generative language models. Unitxt natively integrates with common libraries like HuggingFace and LM-eval-harness and deconstructs processing flows into modular components, enabling easy customization and sharing between practitioners. These components encompass model-specific formats, task prompts, and many other comprehensive dataset processing definitions. The Unitxt-Catalog centralizes these components, fostering collaboration and exploration in modern textual data workflows. Beyond being a tool, Unitxt is a community-driven platform, empowering users to build, share, and advance their pipelines collaboratively.
"""

7
8
import importlib.util
import re
9
from functools import partial
10
from typing import Any, Dict, Optional
11

12
import datasets
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

from lm_eval.api.instance import Instance
from lm_eval.api.task import ConfigurableTask


_CITATION = """
@misc{bandel2024unitxt,
      title={Unitxt: Flexible, Shareable and Reusable Data Preparation and Evaluation for Generative AI},
      author={Elron Bandel and Yotam Perlitz and Elad Venezian and Roni Friedman-Melamed and Ofir Arviv and Matan Orbach and Shachar Don-Yehyia and Dafna Sheinwald and Ariel Gera and Leshem Choshen and Michal Shmueli-Scheuer and Yoav Katz},
      year={2024},
      eprint={2401.14019},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""


30
31
32
33
34
def assert_unitxt_installed():
    if importlib.util.find_spec("unitxt") is None:
        raise Exception(
            "Please install unitxt via 'pip install unitxt'. For more information see: https://www.unitxt.ai/"
        )
35

36
37
38
39
40
41
42
43
44
    from unitxt import __version__ as unitxt_version

    # Function argument change due to https://github.com/IBM/unitxt/pull/1564
    unitxt_version = tuple(map(int, (unitxt_version.split("."))))
    if unitxt_version < (1, 17, 2):
        raise Exception(
            "Please install a more recent version of unitxt via 'pip install --upgrade unitxt' to avoid errors due to breaking changes"
        )

45

46
47
def score(items, metric):
    predictions, references = zip(*items)
48
49
50
    assert_unitxt_installed()
    from unitxt import evaluate

51
52
    for reference in references:
        reference["metrics"] = [metric]
53
    results = evaluate(predictions, references)
54
55
56
57
58
59
60
61
62
63
    return results[0]["score"]["global"]["score"]


class Unitxt(ConfigurableTask):
    VERSION = 0

    def __init__(
        self,
        config: Optional[dict] = None,
    ) -> None:
64
65
        if config is None:
            config = {}
66
67
68
69
70
71
72
        assert "recipe" in config, "Unitxt task must have a 'recipe' string."
        super().__init__(
            config={
                "metadata": {"version": self.VERSION},
                "dataset_name": config["recipe"],
            }
        )
73
        self.image_decoder = datasets.Image()
74
75
        self.metrics = self.dataset["test"][0]["metrics"]

76
    def download(self, dataset_kwargs: Optional[Dict[str, Any]] = None) -> None:
77
78
        assert_unitxt_installed()
        from unitxt import load_dataset
79

80
        self.dataset = load_dataset(self.DATASET_NAME, use_cache=True)
81

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    def has_training_docs(self):
        return "train" in self.dataset

    def has_validation_docs(self):
        return "validation" in self.dataset

    def has_test_docs(self):
        return "test" in self.dataset

    def training_docs(self):
        return self.dataset["train"]

    def validation_docs(self):
        return self.dataset["validation"]

    def test_docs(self):
        return self.dataset["test"]

    def doc_to_text(self, doc):
        return doc["source"]

    def should_decontaminate(self):
        return False

    def doc_to_target(self, doc):
107
        return doc["target"]
108

109
110
111
    def get_arguments(self, doc, ctx):
        return (ctx, {"until": ["\n"]})

112
    def fewshot_context(self, doc, **kwargs) -> str:
113
        if isinstance(self.doc_to_text(doc), list):
114
115
            if kwargs.get("apply_chat_template"):
                chat_template = kwargs.get("chat_template")
116
117
118
119
120
121
122
                formated_source = chat_template(self.doc_to_text(doc))
                return formated_source
            else:
                raise Exception(
                    "Got chat template format from Unitxt, but apply_chat_template is false. Add '--apply_chat_template' to command line."
                )
        else:
123
            return super().fewshot_context(doc=doc, **kwargs)
124

125
126
127
128
129
130
131
132
133
134
135
    def construct_requests(self, doc, ctx, **kwargs):
        """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`.
        """
136
        kwargs.pop("apply_chat_template", False)  # Not used by unitxt
137
        kwargs.pop("chat_template", False)  # Not used by unitxt
138
139
140
141
        return [
            Instance(
                request_type="generate_until",
                doc=doc,
142
                arguments=self.get_arguments(doc, ctx),
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
                idx=0,
                **kwargs,
            )
        ]

    def process_results(self, doc, results):
        """Take a single document and the LM results and evaluates, returning a
        dict where keys are the names of submetrics and values are the values of
        the metric for that one document

        :param doc:
            The document as returned from training_docs, validation_docs, or test_docs.
        :param results:
            The results of the requests created in construct_requests.
        """

        continuation = results[0]

        predictions = continuation

        references = doc
        return {
            metric.replace("metrics.", ""): (predictions, references)
            for metric in self.metrics
        }

    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 {
            metric.replace("metrics.", ""): partial(score, metric=metric)
            for metric in self.metrics
        }

    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 {metric.replace("metrics.", ""): True for metric in self.metrics}
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217


images_regex = r'<img\s+src=["\'](.*?)["\']\s*/?>'
image_source_regex = r'<img\s+src=["\'](.*?)["\']'


def extract_images(text, instance):
    image_sources = re.findall(image_source_regex, text)
    images = []
    for image_source in image_sources:
        current = instance
        for key in image_source.split("/"):
            if key.isdigit():
                key = int(key)
            current = current[key]
        images.append(current)
    return images


class UnitxtMultiModal(Unitxt):
    MULTIMODAL = True

    def doc_to_text(self, doc):
        return re.sub(images_regex, "<image>", doc["source"])

    def doc_to_image(self, doc):
        images = extract_images(doc["source"], doc)
        return [self.image_decoder.decode_example(image) for image in images]

    def get_arguments(self, doc, ctx):
        return (ctx, {"until": ["\n"]}, {"visual": self.doc_to_image(doc)})