hendrycks_ethics.py 8.76 KB
Newer Older
Jonathan Tow's avatar
Jonathan Tow committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Jon Tow's avatar
Jon Tow committed
14
"""ETHICS dataset."""
Jonathan Tow's avatar
Jonathan Tow committed
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
# TODO: Add the `hard` dataset splits.


import csv
import os

import datasets


_CITATION = """\
@article{hendrycks2021ethics
    title={Aligning AI With Shared Human Values},
    author={Dan Hendrycks and Collin Burns and Steven Basart and Andrew Critch and Jerry Li and Dawn Song and Jacob Steinhardt},
    journal={Proceedings of the International Conference on Learning Representations (ICLR)},
    year={2021}
}
"""

_DESCRIPTION = """\
The ETHICS dataset is a benchmark that spans concepts in justice, well-being,
duties, virtues, and commonsense morality. Models predict widespread moral
judgments about diverse text scenarios. This requires connecting physical and
social world knowledge to value judgements, a capability that may enable us
to steer chatbot outputs or eventually regularize open-ended reinforcement
learning agents.
"""

_HOMEPAGE = "https://github.com/hendrycks/ethics"

# TODO: Add the licence for the dataset here if you can find it
_LICENSE = ""

_URLS = "https://people.eecs.berkeley.edu/~hendrycks/ethics.tar"


class EthicsConfig(datasets.BuilderConfig):
    """BuilderConfig for Hendrycks ETHICS."""

    def __init__(self, prefix, features, **kwargs):
        """BuilderConfig for Hendrycks ETHICS.

        Args:
        prefix: *string*, prefix to add to the dataset name for path location.
        features: *list[string]*, list of the features that will appear in the
            feature dict.
        """
        # Version history:
        super().__init__(version=datasets.Version("0.0.1"), **kwargs)
        self.prefix = prefix
        self.features = features


class HendrycksEthics(datasets.GeneratorBasedBuilder):
    """The ETHICS dataset is a benchmark that spans concepts in justice, well-being, duties, virtues, and commonsense morality."""

    BUILDER_CONFIGS = [
        EthicsConfig(
            name="commonsense",
            prefix="cm",
bzantium's avatar
bzantium committed
74
75
76
77
78
79
80
81
82
            features=datasets.Features(
                {
                    "label": datasets.Value("int32"),
                    "input": datasets.Value("string"),
                    "is_short": datasets.Value("bool"),
                    "edited": datasets.Value("bool"),
                }
            ),
            description="The Commonsense subset contains examples focusing on moral standards and principles that most people intuitively accept.",
Jonathan Tow's avatar
Jonathan Tow committed
83
84
85
86
        ),
        EthicsConfig(
            name="deontology",
            prefix="deontology",
bzantium's avatar
bzantium committed
87
88
89
90
91
92
93
94
            features=datasets.Features(
                {
                    "group_id": datasets.Value("int32"),
                    "label": datasets.Value("int32"),
                    "scenario": datasets.Value("string"),
                    "excuse": datasets.Value("string"),
                }
            ),
Jonathan Tow's avatar
Jonathan Tow committed
95
96
97
98
99
            description="The Deontology subset contains examples focusing on whether an act is required, permitted, or forbidden according to a set of rules or constraints",
        ),
        EthicsConfig(
            name="justice",
            prefix="justice",
bzantium's avatar
bzantium committed
100
101
102
103
104
105
106
            features=datasets.Features(
                {
                    "group_id": datasets.Value("int32"),
                    "label": datasets.Value("int32"),
                    "scenario": datasets.Value("string"),
                }
            ),
Jonathan Tow's avatar
Jonathan Tow committed
107
108
109
110
111
            description="The Justice subset contains examples focusing on how a character treats another person",
        ),
        EthicsConfig(
            name="utilitarianism",
            prefix="util",
bzantium's avatar
bzantium committed
112
113
114
115
116
117
118
            features=datasets.Features(
                {
                    "activity": datasets.Value("string"),
                    "baseline": datasets.Value("string"),
                    "rating": datasets.Value("string"),  # Empty rating.
                }
            ),
Jonathan Tow's avatar
Jonathan Tow committed
119
120
121
122
123
            description="The Utilitarianism subset contains scenarios that should be ranked from most pleasant to least pleasant for the person in the scenario",
        ),
        EthicsConfig(
            name="virtue",
            prefix="virtue",
bzantium's avatar
bzantium committed
124
125
126
127
128
129
130
131
            features=datasets.Features(
                {
                    "group_id": datasets.Value("int32"),
                    "label": datasets.Value("int32"),
                    "scenario": datasets.Value("string"),
                    "trait": datasets.Value("string"),
                }
            ),
Jonathan Tow's avatar
Jonathan Tow committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
            description="The Virtue subset contains scenarios focusing on whether virtues or vices are being exemplified",
        ),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            description=f"{_DESCRIPTION}\n{self.config.description}",
            features=self.config.features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        urls = _URLS
        data_dir = dl_manager.download_and_extract(urls)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
bzantium's avatar
bzantium committed
153
154
155
156
157
158
                    "filepath": os.path.join(
                        data_dir,
                        "ethics",
                        self.config.name,
                        f"{self.config.prefix}_train.csv",
                    ),
Jonathan Tow's avatar
Jonathan Tow committed
159
160
161
162
163
164
165
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
bzantium's avatar
bzantium committed
166
167
168
169
170
171
172
                    "filepath": os.path.join(
                        data_dir,
                        "ethics",
                        self.config.name,
                        f"{self.config.prefix}_test.csv",
                    ),
                    "split": "test",
Jonathan Tow's avatar
Jonathan Tow committed
173
                },
bzantium's avatar
bzantium committed
174
            ),
Jonathan Tow's avatar
Jonathan Tow committed
175
176
177
178
        ]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, filepath, split):
bzantium's avatar
bzantium committed
179
        with open(filepath, newline="") as f:
Jonathan Tow's avatar
Jonathan Tow committed
180
            if self.config.name == "utilitarianism":
bzantium's avatar
bzantium committed
181
                contents = csv.DictReader(f, fieldnames=["activity", "baseline"])
Jonathan Tow's avatar
Jonathan Tow committed
182
183
184
185
186
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
218
219
220
221
222
223
224
225
226
227
228
229
            else:
                contents = csv.DictReader(f)
            # For subsets with grouped scenarios, tag them with an id.
            group_id = 0
            for key, row in enumerate(contents):
                if self.config.name == "deontology":
                    # Scenarios come in groups of 4.
                    if key % 4 == 0 and key != 0:
                        group_id += 1
                    yield key, {
                        "group_id": group_id,
                        "label": row["label"],
                        "scenario": row["scenario"],
                        "excuse": row["excuse"],
                    }
                elif self.config.name == "justice":
                    # Scenarios come in groups of 4.
                    if key % 4 == 0 and key != 0:
                        group_id += 1
                    yield key, {
                        "group_id": group_id,
                        "label": row["label"],
                        "scenario": row["scenario"],
                    }
                elif self.config.name == "commonsense":
                    yield key, {
                        "label": row["label"],
                        "input": row["input"],
                        "is_short": row["is_short"],
                        "edited": row["edited"],
                    }
                elif self.config.name == "virtue":
                    # Scenarios come in groups of 5.
                    if key % 5 == 0 and key != 0:
                        group_id += 1
                    scenario, trait = row["scenario"].split(" [SEP] ")
                    yield key, {
                        "group_id": group_id,
                        "label": row["label"],
                        "scenario": scenario,
                        "trait": trait,
                    }
                elif self.config.name == "utilitarianism":
                    yield key, {
                        "activity": row["activity"],
                        "baseline": row["baseline"],
                        "rating": "",
                    }