hendrycks_ethics.py 9.05 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
# 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"

Alain's avatar
Alain committed
44
45
46
47
# The authors declared that the dataset is not distributed under a copyright or intellectual property (https://arxiv.org/pdf/2008.02275.pdf)
# On Hugging Face, the dataset is distributed under the MIT license (https://huggingface.co/datasets/hendrycks/ethics)
# The common sense portion is from Reddit and might incur some licensing complications.
_LICENSE = "Ambiguous"
Jonathan Tow's avatar
Jonathan Tow committed
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

_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",
Fabrizio Milo's avatar
Fabrizio Milo committed
76
77
78
79
80
81
82
83
84
            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
85
86
87
88
        ),
        EthicsConfig(
            name="deontology",
            prefix="deontology",
Fabrizio Milo's avatar
Fabrizio Milo committed
89
90
91
92
93
94
95
96
            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
97
98
99
100
101
            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",
Fabrizio Milo's avatar
Fabrizio Milo committed
102
103
104
105
106
107
108
            features=datasets.Features(
                {
                    "group_id": datasets.Value("int32"),
                    "label": datasets.Value("int32"),
                    "scenario": datasets.Value("string"),
                }
            ),
Jonathan Tow's avatar
Jonathan Tow committed
109
110
111
112
113
            description="The Justice subset contains examples focusing on how a character treats another person",
        ),
        EthicsConfig(
            name="utilitarianism",
            prefix="util",
Fabrizio Milo's avatar
Fabrizio Milo committed
114
115
116
117
118
119
120
            features=datasets.Features(
                {
                    "activity": datasets.Value("string"),
                    "baseline": datasets.Value("string"),
                    "rating": datasets.Value("string"),  # Empty rating.
                }
            ),
Jonathan Tow's avatar
Jonathan Tow committed
121
122
123
124
125
            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",
Fabrizio Milo's avatar
Fabrizio Milo committed
126
127
128
129
130
131
132
133
            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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
            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={
Fabrizio Milo's avatar
Fabrizio Milo committed
155
156
157
158
159
160
                    "filepath": os.path.join(
                        data_dir,
                        "ethics",
                        self.config.name,
                        f"{self.config.prefix}_train.csv",
                    ),
Jonathan Tow's avatar
Jonathan Tow committed
161
162
163
164
165
166
167
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
Fabrizio Milo's avatar
Fabrizio Milo committed
168
169
170
171
172
173
174
                    "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
175
                },
Fabrizio Milo's avatar
Fabrizio Milo committed
176
            ),
Jonathan Tow's avatar
Jonathan Tow committed
177
178
179
180
        ]

    # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    def _generate_examples(self, filepath, split):
Fabrizio Milo's avatar
Fabrizio Milo committed
181
        with open(filepath, newline="") as f:
Jonathan Tow's avatar
Jonathan Tow committed
182
            if self.config.name == "utilitarianism":
Fabrizio Milo's avatar
Fabrizio Milo committed
183
                contents = csv.DictReader(f, fieldnames=["activity", "baseline"])
Jonathan Tow's avatar
Jonathan Tow committed
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
230
231
            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": "",
                    }