Datasets:

Modalities:
Text
Libraries:
Datasets
Jon Gauthier commited on
Commit
2b2f744
·
1 Parent(s): d254185

stage working data loader, no metric/eval

Browse files
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pyparsing
syntaxgym/__init__.py ADDED
File without changes
syntaxgym/prediction.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Optional as TOptional, List as TList
2
+
3
+
4
+ from pyparsing import *
5
+ import numpy as np
6
+
7
+ from syntaxgym.utils import METRICS
8
+
9
+
10
+ # Enable parser packrat (caching)
11
+ ParserElement.enablePackrat()
12
+
13
+ # Relative and absolute tolerance thresholds for surprisal equality
14
+ EQUALITY_RTOL = 1e-5
15
+ EQUALITY_ATOL = 1e-3
16
+
17
+
18
+ #######
19
+ # Define a grammar for prediction formulae.
20
+
21
+ # References a surprisal region
22
+ lpar = Suppress("(")
23
+ rpar = Suppress(")")
24
+ region = lpar + (Word(nums) | "*") + Suppress(";%") + Word(alphanums + "_-") + Suppress("%") + rpar
25
+ literal_float = pyparsing_common.number
26
+
27
+ class Region(object):
28
+ def __init__(self, tokens):
29
+ self.region_number = tokens[0]
30
+ self.condition_name = tokens[1]
31
+
32
+ def __str__(self):
33
+ return "(%s;%%%s%%)" % (self.region_number, self.condition_name)
34
+
35
+ def __repr__(self):
36
+ return "Region(%s,%s)" % (self.condition_name, self.region_number)
37
+
38
+ def __call__(self, surprisal_dict):
39
+ if self.region_number == "*":
40
+ return sum(value for (condition, region), value in surprisal_dict.items()
41
+ if condition == self.condition_name)
42
+
43
+ return surprisal_dict[self.condition_name, int(self.region_number)]
44
+
45
+ class LiteralFloat(object):
46
+ def __init__(self, tokens):
47
+ self.value = float(tokens[0])
48
+
49
+ def __str__(self):
50
+ return "%f" % (self.value,)
51
+
52
+ def __repr__(self):
53
+ return "LiteralFloat(%f)" % (self.value,)
54
+
55
+ def __call__(self, surprisal_dict):
56
+ return self.value
57
+
58
+ class BinaryOp(object):
59
+ operators: TOptional[TList[str]]
60
+
61
+ def __init__(self, tokens):
62
+ self.operator = tokens[0][1]
63
+ if self.operators is not None and self.operator not in self.operators:
64
+ raise ValueError("Invalid %s operator %s" % (self.__class__.__name__,
65
+ self.operator))
66
+ self.operands = [tokens[0][0], tokens[0][2]]
67
+
68
+ def __str__(self):
69
+ return "(%s %s %s)" % (self.operands[0], self.operator, self.operands[1])
70
+
71
+ def __repr__(self):
72
+ return "%s(%s)(%s)" % (self.__class__.__name__, self.operator, ",".join(map(repr, self.operands)))
73
+
74
+ def __call__(self, surprisal_dict):
75
+ op_vals = [op(surprisal_dict) for op in self.operands]
76
+ return self._evaluate(op_vals, surprisal_dict)
77
+
78
+ def _evaluate(self, evaluated_operands, surprisal_dict):
79
+ raise NotImplementedError()
80
+
81
+ class BoolOp(BinaryOp):
82
+ operators = ["&", "|"]
83
+ def _evaluate(self, op_vals, surprisal_dict):
84
+ if self.operator == "&":
85
+ return op_vals[0] and op_vals[1]
86
+ elif self.operator == "|":
87
+ return op_vals[0] or op_vals[1]
88
+
89
+ class FloatOp(BinaryOp):
90
+ operators = ["-", "+"]
91
+ def _evaluate(self, op_vals, surprisal_dict):
92
+ if self.operator == "-":
93
+ return op_vals[0] - op_vals[1]
94
+ elif self.operator == "+":
95
+ return op_vals[0] + op_vals[1]
96
+
97
+ class ComparatorOp(BinaryOp):
98
+ operators = ["<", ">", "="]
99
+ def _evaluate(self, op_vals, surprisal_dict):
100
+ if self.operator == "<":
101
+ return op_vals[0] < op_vals[1]
102
+ elif self.operator == ">":
103
+ return op_vals[0] > op_vals[1]
104
+ elif self.operator == "=":
105
+ return np.isclose(op_vals[0], op_vals[1],
106
+ rtol=EQUALITY_RTOL,
107
+ atol=EQUALITY_ATOL)
108
+
109
+ def Chain(op_cls, left_assoc=True):
110
+ def chainer(tokens):
111
+ """
112
+ Create a binary tree of BinaryOps from the given repeated application
113
+ of the op.
114
+ """
115
+ operators = tokens[0][1::2]
116
+ args = tokens[0][0::2]
117
+ if not left_assoc:
118
+ raise NotImplementedError
119
+
120
+ arg1 = args.pop(0)
121
+ while len(args) > 0:
122
+ operator = operators.pop(0)
123
+ arg2 = args.pop(0)
124
+ arg1 = op_cls([[arg1, operator, arg2]])
125
+
126
+ return arg1
127
+
128
+ return chainer
129
+
130
+ atom = region.setParseAction(Region) | literal_float.setParseAction(LiteralFloat)
131
+
132
+ prediction_expr = infixNotation(
133
+ atom,
134
+ [
135
+ (oneOf("- +"), 2, opAssoc.LEFT, Chain(FloatOp)),
136
+ (oneOf("< > ="), 2, opAssoc.LEFT, ComparatorOp),
137
+ (oneOf("& |"), 2, opAssoc.LEFT, Chain(BoolOp)),
138
+ ],
139
+ lpar=lpar, rpar=rpar
140
+ )
141
+
142
+
143
+ class Prediction(object):
144
+ """
145
+ Predictions state expected relations between language model surprisal
146
+ measures in different regions and conditions of a test suite. For more
147
+ information, see :ref:`architecture`.
148
+ """
149
+
150
+ def __init__(self, idx: int, formula: Union[str, BinaryOp], metric: str):
151
+ """
152
+ Args:
153
+ idx: A unique prediction ID. This is only relevant for
154
+ serialization.
155
+ formula: A string representation of the prediction formula, or an
156
+ already parsed formula. For more information, see
157
+ :ref:`architecture`.
158
+ metric: Metric for aggregating surprisals within regions.
159
+ """
160
+ if isinstance(formula, str):
161
+ try:
162
+ formula = prediction_expr.parseString(formula, parseAll=True)[0]
163
+ except ParseException as e:
164
+ raise ValueError("Invalid formula expression %r" % (formula,)) from e
165
+
166
+ self.idx = idx
167
+ self.formula = formula
168
+
169
+ if metric not in METRICS.keys():
170
+ raise ValueError("Unknown metric %s. Supported metrics: %s" %
171
+ (metric, " ".join(METRICS.keys())))
172
+ self.metric = metric
173
+
174
+ def __call__(self, item):
175
+ """
176
+ Evaluate the prediction on the given item dict representation. For more
177
+ information on item representations, see :ref:`suite_json`.
178
+ """
179
+ # Prepare relevant surprisal dict
180
+ surps = {(c["condition_name"], r["region_number"]): r["metric_value"][self.metric]
181
+ for c in item["conditions"]
182
+ for r in c["regions"]}
183
+ return self.formula(surps)
184
+
185
+ @classmethod
186
+ def from_dict(cls, pred_dict, idx: int, metric: str):
187
+ """
188
+ Parse from a prediction dictionary representation (see
189
+ :ref:`suite_json`).
190
+ """
191
+ if not pred_dict["type"] == "formula":
192
+ raise ValueError("Unknown prediction type %s" % (pred_dict["type"],))
193
+
194
+ return cls(formula=pred_dict["formula"], idx=idx, metric=metric)
195
+
196
+ @property
197
+ def referenced_regions(self):
198
+ """
199
+ Get a set of the regions referenced by this formula.
200
+ Each item is a tuple of the form ``(condition_name, region_number)``.
201
+ """
202
+ def traverse(x, acc):
203
+ if isinstance(x, BinaryOp):
204
+ for val in x.operands:
205
+ traverse(val, acc)
206
+ elif isinstance(x, Region):
207
+ acc.add((x.condition_name, int(x.region_number)))
208
+
209
+ return acc
210
+
211
+ return traverse(self.formula, set())
212
+
213
+ def as_dict(self):
214
+ """
215
+ Serialize as a prediction dictionary representation (see
216
+ :ref:`suite_json`).
217
+ """
218
+ return dict(type="formula", formula=str(self.formula))
219
+
220
+ def __str__(self):
221
+ return "Prediction(%s)" % (self.formula,)
222
+ __repr__ = __str__
223
+
224
+ def __hash__(self):
225
+ return hash(self.formula)
226
+
227
+ def __eq__(self, other):
228
+ return isinstance(other, Prediction) and hash(self) == hash(other)
syntaxgym/syntaxgym.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ """
4
+ SyntaxGym dataset as used in Hu et al. (2020).
5
+ """
6
+
7
+
8
+ import json
9
+ from pathlib import Path
10
+ from typing import List
11
+
12
+ import datasets
13
+
14
+
15
+ _CITATION = """
16
+ @inproceedings{Hu:et-al:2020,
17
+ author = {Hu, Jennifer and Gauthier, Jon and Qian, Peng and Wilcox, Ethan and Levy, Roger},
18
+ title = {A systematic assessment of syntactic generalization in neural language models},
19
+ booktitle = {Proceedings of the Association of Computational Linguistics},
20
+ year = {2020}
21
+ }
22
+ """
23
+
24
+ _DESCRIPTION = "" # TODO
25
+
26
+
27
+ _PROJECT_URL = "https://syntaxgym.org"
28
+ _DOWNLOAD_URL = "https://github.com/cpllab/syntactic-generalization"
29
+
30
+
31
+ print("_____HERE")
32
+ SUITE_JSONS = []
33
+ for suite_f in Path("test_suites").glob("*.json"):
34
+ with suite_f.open() as f:
35
+ SUITE_JSONS.append(json.load(f))
36
+
37
+
38
+ class SyntaxGymSuiteConfig(datasets.BuilderConfig):
39
+
40
+ def __init__(self, suite_json, version=datasets.Version("1.0.0"), **kwargs):
41
+ self.meta = suite_json["meta"]
42
+ name = self.meta["name"]
43
+ description = f"SyntaxGym test suite {name}.\n" + _DESCRIPTION
44
+
45
+ super().__init__(name=name, description=description, version=version,
46
+ **kwargs)
47
+
48
+ self.features = list(suite_json["region_meta"].values())
49
+
50
+
51
+ class SyntaxGym(datasets.GeneratorBasedBuilder):
52
+
53
+ BUILDER_CONFIGS = [SyntaxGymSuiteConfig(suite_json)
54
+ for suite_json in SUITE_JSONS]
55
+
56
+ def _info(self):
57
+ condition_spec = {
58
+ "condition_name": datasets.Value("string"),
59
+ "regions": datasets.Sequence({
60
+ "region_number": datasets.Value("int32"),
61
+ "content": datasets.Value("string")
62
+ })
63
+ }
64
+
65
+ features = {
66
+ "item_number": datasets.Value("string"),
67
+ "conditions": datasets.Sequence(condition_spec)
68
+ }
69
+
70
+ citation = ""
71
+ if self.config.meta["reference"]:
72
+ citation = f"Test suite citation: {self.meta['reference']}\n"
73
+ citation += f"SyntaxGym citation:\n{_CITATION}"
74
+
75
+ return datasets.DatasetInfo(
76
+ description=_DESCRIPTION,
77
+ features=datasets.Features(features),
78
+ homepage=_PROJECT_URL,
79
+ citation=citation,
80
+ )
81
+
82
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
83
+ return [datasets.SplitGenerator(name=datasets.Split.TEST,
84
+ gen_kwargs={"name": self.config.name})]
85
+
86
+ def _generate_examples(self, name):
87
+ # DEV: NB suite jsons already loaded because BUILDER_CONFIGS is static
88
+ suite_jsons = SUITE_JSONS
89
+
90
+ suite_json = next(suite for suite in SUITE_JSONS
91
+ if suite["meta"]["name"] == name)
92
+
93
+ for item in suite_json["items"]:
94
+ yield item["item_number"], item
test.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import datasets
2
+
3
+
4
+ dataset = datasets.load_dataset("syntaxgym", "mvrr_mod")