Jon Gauthier
commited on
Commit
·
535608c
1
Parent(s):
9d3d980
Implementation nice and clean, but need to verify results w/ reference syntaxgym-core still
Browse files- syntaxgym.py +86 -57
- test.py +6 -39
syntaxgym.py
CHANGED
@@ -13,8 +13,10 @@ import re
|
|
13 |
from typing import List, Tuple
|
14 |
|
15 |
import datasets
|
|
|
16 |
import numpy as np
|
17 |
import torch
|
|
|
18 |
|
19 |
from .prediction import Prediction
|
20 |
|
@@ -64,26 +66,28 @@ class SyntaxGymSuiteConfig(datasets.BuilderConfig):
|
|
64 |
self.features = list(suite_json["region_meta"].values())
|
65 |
|
66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
class SyntaxGym(datasets.GeneratorBasedBuilder):
|
68 |
|
69 |
BUILDER_CONFIGS = [SyntaxGymSuiteConfig(suite_json)
|
70 |
for suite_json in SUITE_JSONS.values()]
|
71 |
|
72 |
def _info(self):
|
73 |
-
condition_spec = {
|
74 |
-
"condition_name": datasets.Value("string"),
|
75 |
-
"content": datasets.Value("string"),
|
76 |
-
"regions": datasets.Sequence({
|
77 |
-
"region_number": datasets.Value("int32"),
|
78 |
-
"content": datasets.Value("string")
|
79 |
-
})
|
80 |
-
}
|
81 |
-
|
82 |
-
features = {
|
83 |
-
"item_number": datasets.Value("int32"),
|
84 |
-
"conditions": datasets.Sequence(condition_spec)
|
85 |
-
}
|
86 |
-
|
87 |
citation = ""
|
88 |
if self.config.meta["reference"]:
|
89 |
citation = f"Test suite citation: {self.meta['reference']}\n"
|
@@ -91,7 +95,7 @@ class SyntaxGym(datasets.GeneratorBasedBuilder):
|
|
91 |
|
92 |
return datasets.DatasetInfo(
|
93 |
description=_DESCRIPTION,
|
94 |
-
features=datasets.Features(
|
95 |
homepage=_PROJECT_URL,
|
96 |
citation=citation,
|
97 |
)
|
@@ -103,12 +107,15 @@ class SyntaxGym(datasets.GeneratorBasedBuilder):
|
|
103 |
def _generate_examples(self, name):
|
104 |
# DEV: NB suite jsons already loaded because BUILDER_CONFIGS is static
|
105 |
suite_json = SUITE_JSONS[name]
|
|
|
106 |
|
107 |
for item in suite_json["items"]:
|
108 |
# Convert to sentence input.
|
109 |
for cond in item["conditions"]:
|
110 |
cond["content"] = condition_to_string(cond)
|
111 |
|
|
|
|
|
112 |
yield item["item_number"], item
|
113 |
|
114 |
|
@@ -117,27 +124,10 @@ class SyntaxGymMetric(datasets.Metric):
|
|
117 |
SyntaxGym prediction evaluation metric.
|
118 |
"""
|
119 |
|
120 |
-
def __init__(self, *args, **kwargs):
|
121 |
-
super().__init__(*args, **kwargs)
|
122 |
-
self.suite = SUITE_JSONS[self.config_name]
|
123 |
-
self.predictions = [
|
124 |
-
Prediction(idx, p["formula"], "sum")
|
125 |
-
for idx, p in enumerate(self.suite["predictions"])
|
126 |
-
]
|
127 |
-
|
128 |
def _info(self):
|
129 |
seq = datasets.Sequence
|
130 |
features = datasets.Features({
|
131 |
-
|
132 |
-
"surprisals": seq(seq(datasets.Value("float"))),
|
133 |
-
|
134 |
-
# TODO necessary? can assume it remains sorted?
|
135 |
-
"condition_names": datasets.Value("string"),
|
136 |
-
|
137 |
-
"input_ids": seq(datasets.Value("int32")),
|
138 |
-
|
139 |
-
# offset mapping: 3d int array
|
140 |
-
"offset_mapping": seq(seq(datasets.Value("int32"))),
|
141 |
})
|
142 |
return datasets.MetricInfo(
|
143 |
description="TODO",
|
@@ -146,16 +136,53 @@ class SyntaxGymMetric(datasets.Metric):
|
|
146 |
features=features,
|
147 |
)
|
148 |
|
149 |
-
def _compute(self,
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
|
155 |
# input_ids: B * T
|
156 |
-
input_ids =
|
157 |
assert input_ids.ndim == 2
|
158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
# Get surprisals of expected words.
|
160 |
surps_shifted = surprisals[:, :-1, :]
|
161 |
expected_ids = input_ids[:, 1:]
|
@@ -170,10 +197,11 @@ class SyntaxGymMetric(datasets.Metric):
|
|
170 |
# surprisals is now B * (T - 1)
|
171 |
|
172 |
#### aggregate
|
|
|
173 |
region_totals = {condition_name: defaultdict(float)
|
174 |
for condition_name in condition_names}
|
175 |
region2tokens = self.compute_region_token_mapping(
|
176 |
-
|
177 |
|
178 |
for i, (i_cond, i_inputs) in enumerate(zip(condition_names, input_ids)):
|
179 |
for region_number, region_tokens in region2tokens[i_cond].items():
|
@@ -183,7 +211,8 @@ class SyntaxGymMetric(datasets.Metric):
|
|
183 |
else:
|
184 |
# TODO don't think this is an issue, just should clean
|
185 |
# up the aggregation output
|
186 |
-
|
|
|
187 |
|
188 |
region_totals = {(condition_name, region_number): float(total)
|
189 |
for condition_name, totals in region_totals.items()
|
@@ -191,33 +220,29 @@ class SyntaxGymMetric(datasets.Metric):
|
|
191 |
|
192 |
results = {
|
193 |
"prediction_results": [
|
194 |
-
|
|
|
195 |
],
|
196 |
|
197 |
"region_totals": region_totals
|
198 |
}
|
199 |
return results
|
200 |
|
201 |
-
def get_region_edges(self,
|
202 |
"""
|
203 |
Get left edge of each region as a character index.
|
204 |
"""
|
205 |
# NB this is coupled with `condition_to_string` logic of course
|
206 |
|
207 |
-
|
208 |
-
item = next(item for item in self.suite["items"]
|
209 |
-
if item["item_number"] == item_number)
|
210 |
-
cond = next(cond for cond in item["conditions"]
|
211 |
-
if cond["condition_name"] == condition_name)
|
212 |
|
213 |
idx = 0
|
214 |
ret = []
|
215 |
-
for r_idx,
|
216 |
ret.append(idx)
|
217 |
|
218 |
-
|
219 |
-
|
220 |
-
if content.strip() != "" and r_idx != 0 and not content.startswith(","):
|
221 |
# Add joining space
|
222 |
region_size += 1
|
223 |
|
@@ -225,16 +250,20 @@ class SyntaxGymMetric(datasets.Metric):
|
|
225 |
|
226 |
return ret
|
227 |
|
228 |
-
def compute_region_token_mapping(self,
|
229 |
offset_mapping: List[Tuple[int, int]]):
|
230 |
# input_ids: B * T
|
231 |
# offset_mapping: B * T * 2
|
|
|
232 |
|
|
|
233 |
region2tokens = {cond: defaultdict(list) for cond in condition_names}
|
234 |
|
|
|
|
|
235 |
input_ids = input_ids.detach()
|
236 |
-
for i_cond, i_tokens, i_offsets in zip(
|
237 |
-
region_edges = self.get_region_edges(
|
238 |
|
239 |
t_cursor, r_cursor = 0, 0
|
240 |
while t_cursor < i_tokens.shape[0]:
|
@@ -243,14 +272,14 @@ class SyntaxGymMetric(datasets.Metric):
|
|
243 |
|
244 |
region_start = region_edges[r_cursor]
|
245 |
region_end = region_edges[r_cursor + 1] \
|
246 |
-
if r_cursor + 1 < len(region_edges) else
|
247 |
|
248 |
# NB region boundaries are left edges, hence the >= here.
|
249 |
if token_char_start >= region_end:
|
250 |
r_cursor += 1
|
251 |
continue
|
252 |
|
253 |
-
region2tokens[i_cond][r_cursor + 1].append(t_cursor)
|
254 |
t_cursor += 1
|
255 |
|
256 |
return region2tokens
|
|
|
13 |
from typing import List, Tuple
|
14 |
|
15 |
import datasets
|
16 |
+
from datasets import logging
|
17 |
import numpy as np
|
18 |
import torch
|
19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
20 |
|
21 |
from .prediction import Prediction
|
22 |
|
|
|
66 |
self.features = list(suite_json["region_meta"].values())
|
67 |
|
68 |
|
69 |
+
SUITE_DATASET_CONDITION_SPEC = {
|
70 |
+
"condition_name": datasets.Value("string"),
|
71 |
+
"content": datasets.Value("string"),
|
72 |
+
"regions": datasets.Sequence({
|
73 |
+
"region_number": datasets.Value("int32"),
|
74 |
+
"content": datasets.Value("string")
|
75 |
+
})
|
76 |
+
}
|
77 |
+
|
78 |
+
SUITE_DATASET_SPEC = {
|
79 |
+
"item_number": datasets.Value("int32"),
|
80 |
+
"conditions": datasets.Sequence(SUITE_DATASET_CONDITION_SPEC),
|
81 |
+
"predictions": datasets.Sequence(datasets.Value("string")),
|
82 |
+
}
|
83 |
+
|
84 |
+
|
85 |
class SyntaxGym(datasets.GeneratorBasedBuilder):
|
86 |
|
87 |
BUILDER_CONFIGS = [SyntaxGymSuiteConfig(suite_json)
|
88 |
for suite_json in SUITE_JSONS.values()]
|
89 |
|
90 |
def _info(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
citation = ""
|
92 |
if self.config.meta["reference"]:
|
93 |
citation = f"Test suite citation: {self.meta['reference']}\n"
|
|
|
95 |
|
96 |
return datasets.DatasetInfo(
|
97 |
description=_DESCRIPTION,
|
98 |
+
features=datasets.Features(SUITE_DATASET_SPEC),
|
99 |
homepage=_PROJECT_URL,
|
100 |
citation=citation,
|
101 |
)
|
|
|
107 |
def _generate_examples(self, name):
|
108 |
# DEV: NB suite jsons already loaded because BUILDER_CONFIGS is static
|
109 |
suite_json = SUITE_JSONS[name]
|
110 |
+
predictions = [p["formula"] for p in suite_json["predictions"]]
|
111 |
|
112 |
for item in suite_json["items"]:
|
113 |
# Convert to sentence input.
|
114 |
for cond in item["conditions"]:
|
115 |
cond["content"] = condition_to_string(cond)
|
116 |
|
117 |
+
item["predictions"] = predictions
|
118 |
+
|
119 |
yield item["item_number"], item
|
120 |
|
121 |
|
|
|
124 |
SyntaxGym prediction evaluation metric.
|
125 |
"""
|
126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
def _info(self):
|
128 |
seq = datasets.Sequence
|
129 |
features = datasets.Features({
|
130 |
+
"suite": SUITE_DATASET_SPEC
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
})
|
132 |
return datasets.MetricInfo(
|
133 |
description="TODO",
|
|
|
136 |
features=features,
|
137 |
)
|
138 |
|
139 |
+
def _compute(self, suite, model_id, batch_size: int = 16,
|
140 |
+
add_start_token=True, device=None):
|
141 |
+
if device is not None:
|
142 |
+
assert device in ["gpu", "cpu", "cuda"]
|
143 |
+
if device == "gpu":
|
144 |
+
device = "cuda"
|
145 |
+
else:
|
146 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
147 |
+
|
148 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
149 |
+
model = model.to(device)
|
150 |
+
model.eval()
|
151 |
+
|
152 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
153 |
+
# TODO copy from perplexity metric
|
154 |
+
tokenizer.pad_token = tokenizer.eos_token
|
155 |
+
|
156 |
+
results = {"prediction_results": [], "region_totals": []}
|
157 |
+
# TODO batch all items together
|
158 |
+
for item in logging.tqdm(suite):
|
159 |
+
result_single = self._compute_single(item, tokenizer, model, device)
|
160 |
+
|
161 |
+
for k in ["prediction_results", "region_totals"]:
|
162 |
+
results[k].append(result_single[k])
|
163 |
+
|
164 |
+
return results
|
165 |
+
|
166 |
+
|
167 |
+
def _compute_single(self, item, tokenizer, model, device):
|
168 |
+
tokenized = tokenizer(item["conditions"]["content"],
|
169 |
+
padding=True,
|
170 |
+
return_tensors="pt",
|
171 |
+
return_offsets_mapping=True).to(device)
|
172 |
|
173 |
# input_ids: B * T
|
174 |
+
input_ids = tokenized["input_ids"]
|
175 |
assert input_ids.ndim == 2
|
176 |
|
177 |
+
# Compute sentence level surprisals.
|
178 |
+
with torch.no_grad():
|
179 |
+
# Pre-softmax predictive distribution B * T * V
|
180 |
+
logits = model(input_ids).logits
|
181 |
+
surprisals = -logits.log_softmax(dim=2) / np.log(2)
|
182 |
+
|
183 |
+
# surprisals: B * T * V
|
184 |
+
assert surprisals.ndim == 3
|
185 |
+
|
186 |
# Get surprisals of expected words.
|
187 |
surps_shifted = surprisals[:, :-1, :]
|
188 |
expected_ids = input_ids[:, 1:]
|
|
|
197 |
# surprisals is now B * (T - 1)
|
198 |
|
199 |
#### aggregate
|
200 |
+
condition_names = item["conditions"]["condition_name"]
|
201 |
region_totals = {condition_name: defaultdict(float)
|
202 |
for condition_name in condition_names}
|
203 |
region2tokens = self.compute_region_token_mapping(
|
204 |
+
item, input_ids, tokenized["offset_mapping"])
|
205 |
|
206 |
for i, (i_cond, i_inputs) in enumerate(zip(condition_names, input_ids)):
|
207 |
for region_number, region_tokens in region2tokens[i_cond].items():
|
|
|
211 |
else:
|
212 |
# TODO don't think this is an issue, just should clean
|
213 |
# up the aggregation output
|
214 |
+
assert token == surprisals.shape[1], \
|
215 |
+
"%s %s" % (token, surprisals.shape[1])
|
216 |
|
217 |
region_totals = {(condition_name, region_number): float(total)
|
218 |
for condition_name, totals in region_totals.items()
|
|
|
220 |
|
221 |
results = {
|
222 |
"prediction_results": [
|
223 |
+
Prediction(i, formula, "sum").formula(region_totals)
|
224 |
+
for i, formula in enumerate(item["predictions"])
|
225 |
],
|
226 |
|
227 |
"region_totals": region_totals
|
228 |
}
|
229 |
return results
|
230 |
|
231 |
+
def get_region_edges(self, item, condition_idx):
|
232 |
"""
|
233 |
Get left edge of each region as a character index.
|
234 |
"""
|
235 |
# NB this is coupled with `condition_to_string` logic of course
|
236 |
|
237 |
+
regions = item["conditions"]["regions"][condition_idx]
|
|
|
|
|
|
|
|
|
238 |
|
239 |
idx = 0
|
240 |
ret = []
|
241 |
+
for r_idx, region_content in enumerate(regions["content"]):
|
242 |
ret.append(idx)
|
243 |
|
244 |
+
region_size = len(region_content)
|
245 |
+
if region_content.strip() != "" and r_idx != 0 and not region_content.startswith(","):
|
|
|
246 |
# Add joining space
|
247 |
region_size += 1
|
248 |
|
|
|
250 |
|
251 |
return ret
|
252 |
|
253 |
+
def compute_region_token_mapping(self, item, input_ids: torch.LongTensor,
|
254 |
offset_mapping: List[Tuple[int, int]]):
|
255 |
# input_ids: B * T
|
256 |
# offset_mapping: B * T * 2
|
257 |
+
# assumes batch is sorted according to item's condition_name order
|
258 |
|
259 |
+
condition_names = item["conditions"]["condition_name"]
|
260 |
region2tokens = {cond: defaultdict(list) for cond in condition_names}
|
261 |
|
262 |
+
max_long = torch.iinfo(torch.int64).max
|
263 |
+
|
264 |
input_ids = input_ids.detach()
|
265 |
+
for i_cond, (i_tokens, i_offsets) in enumerate(zip(input_ids, offset_mapping)):
|
266 |
+
region_edges = self.get_region_edges(item, i_cond)
|
267 |
|
268 |
t_cursor, r_cursor = 0, 0
|
269 |
while t_cursor < i_tokens.shape[0]:
|
|
|
272 |
|
273 |
region_start = region_edges[r_cursor]
|
274 |
region_end = region_edges[r_cursor + 1] \
|
275 |
+
if r_cursor + 1 < len(region_edges) else max_long
|
276 |
|
277 |
# NB region boundaries are left edges, hence the >= here.
|
278 |
if token_char_start >= region_end:
|
279 |
r_cursor += 1
|
280 |
continue
|
281 |
|
282 |
+
region2tokens[condition_names[i_cond]][r_cursor + 1].append(t_cursor)
|
283 |
t_cursor += 1
|
284 |
|
285 |
return region2tokens
|
test.py
CHANGED
@@ -7,44 +7,11 @@ import transformers
|
|
7 |
import torch
|
8 |
|
9 |
|
10 |
-
dataset = datasets.load_dataset("syntaxgym.py", "
|
11 |
-
metric = datasets.load_metric("syntaxgym.py"
|
12 |
|
13 |
-
|
14 |
-
model_ref = "hf-internal-testing/tiny-random-gpt_neo"
|
15 |
|
16 |
-
|
17 |
-
|
18 |
-
tokenizer.pad_token = tokenizer.eos_token
|
19 |
-
|
20 |
-
model = transformers.AutoModelForCausalLM.from_pretrained(model_ref)
|
21 |
-
model.eval()
|
22 |
-
|
23 |
-
|
24 |
-
# all_sentences: List[List[str]] = [item["conditions"]["content"] for item in dataset["test"]]
|
25 |
-
# all_sentences_flat = list(itertools.chain.from_iterable(all_sentences))
|
26 |
-
|
27 |
-
tokenized = tokenizer(all_sentences_flat,
|
28 |
-
return_tensors="pt", padding=True, return_offsets_mapping=True)
|
29 |
-
for item in dataset["test"]:
|
30 |
-
# TODO full preprocessing setup
|
31 |
-
condition_names = item["conditions"]["condition_name"]
|
32 |
-
tokenized = tokenizer(item["conditions"]["content"], return_tensors="pt",
|
33 |
-
padding=True, return_offsets_mapping=True)
|
34 |
-
|
35 |
-
print(item)
|
36 |
-
print(tokenized)
|
37 |
-
print(tokenized["offset_mapping"].shape)
|
38 |
-
|
39 |
-
with torch.no_grad():
|
40 |
-
# Pre-softmax predictive distribution (shape B * T * V)
|
41 |
-
output = model(tokenized["input_ids"])[0]
|
42 |
-
surprisals = -output.log_softmax(dim=2) / np.log(2)
|
43 |
-
|
44 |
-
result = metric.compute(surprisals=surprisals,
|
45 |
-
item_number=item["item_number"],
|
46 |
-
condition_names=condition_names,
|
47 |
-
input_ids=tokenized["input_ids"],
|
48 |
-
offset_mapping=tokenized["offset_mapping"])
|
49 |
-
|
50 |
-
break
|
|
|
7 |
import torch
|
8 |
|
9 |
|
10 |
+
dataset = datasets.load_dataset("syntaxgym.py", "subordination_src-src")
|
11 |
+
metric = datasets.load_metric("syntaxgym.py")
|
12 |
|
13 |
+
model_ref = "gpt2"
|
14 |
+
# model_ref = "hf-internal-testing/tiny-random-gpt_neo"
|
15 |
|
16 |
+
result = metric.compute(suite=dataset["test"], model_id=model_ref)
|
17 |
+
print(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|