Akahsizrr commited on
Commit
d33338a
·
verified ·
1 Parent(s): 15a2901

Upload alea/gen_hf3.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. alea/gen_hf3.py +431 -0
alea/gen_hf3.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gen_hf3: second wave of real HF data — legal/policy/multi-hop/social.
2
+
3
+ Targets the skills JevBench-hard actually tests: apply a long document's
4
+ rules to a concrete case (contract-nli, casehold, ledgar), multi-hop
5
+ retrieval (hotpot, 2wiki), algebra MCQ (aqua), commonsense/social
6
+ (cosmos, siqa, swag, medmcqa), answerability (squad_v2).
7
+ """
8
+ import argparse
9
+ import json
10
+ import random
11
+
12
+ from datasets import load_dataset
13
+
14
+ rng = random.Random(555)
15
+
16
+
17
+ def choice_row(state, instructions, options_texts, correct_idx, family,
18
+ meta=None):
19
+ n = len(options_texts)
20
+ keys = ["opt_%d" % i for i in range(n)]
21
+ seen, fo, fk, ni = {}, [], [], None
22
+ for i, t in enumerate(options_texts):
23
+ t = str(t).strip()
24
+ if not t:
25
+ t = "(empty %d)" % i
26
+ if t in seen:
27
+ if i == correct_idx:
28
+ ni = seen[t]
29
+ continue
30
+ seen[t] = len(fo)
31
+ fo.append(t); fk.append(keys[i])
32
+ if i == correct_idx:
33
+ ni = len(fo) - 1
34
+ if ni is None or len(fo) < 2:
35
+ return None
36
+ tgt = [0.0] * len(fo); tgt[ni] = 1.0
37
+ return {"state": str(state)[:20000],
38
+ "questions": {"q0": {"type": "choice", "instructions": instructions,
39
+ "criteria": dict(zip(fk, fo))}},
40
+ "targets": {"q0": tgt}, "family": family, "meta": meta or {}}
41
+
42
+
43
+ def noul_row(state, instructions, val, family, meta=None):
44
+ return {"state": str(state)[:20000],
45
+ "questions": {"q0": {"type": "noul", "instructions": instructions}},
46
+ "targets": {"q0": float(val)}, "family": family, "meta": meta or {}}
47
+
48
+
49
+ def gen_contractnli(n, rng):
50
+ """Contract + hypothesis -> entailment/contradiction/neutral (3-way)."""
51
+ ds = None
52
+ for repo, cfg in (("coastalcph/lex_glue", "contract_nli"),
53
+ ("jonathanli/lex-glue", "contract_nli")):
54
+ try:
55
+ ds = load_dataset(repo, cfg, split="train")
56
+ break
57
+ except Exception:
58
+ continue
59
+ if ds is None:
60
+ return []
61
+ out = []
62
+ label_names = ["entailment", "neutral", "contradiction"]
63
+ feats = ds.features.get("label")
64
+ if feats is not None and hasattr(feats, "names"):
65
+ label_names = feats.names
66
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
67
+ for i in idxs:
68
+ if len(out) >= n:
69
+ break
70
+ r = ds[i]
71
+ doc = (r.get("contract_text") or r.get("document") or "")[:9000]
72
+ hyp = r.get("hypothesis") or r.get("premise") or ""
73
+ lab = r.get("label")
74
+ if not doc or not hyp or lab is None:
75
+ continue
76
+ ci = int(lab)
77
+ if ci >= len(label_names):
78
+ continue
79
+ st = ("CONTRACT EXCERPT:\n%s\n\nHYPOTHESIS UNDER REVIEW:\n%s"
80
+ % (doc, hyp))
81
+ row = choice_row(st, "Decide the relationship between the contract "
82
+ "text and the hypothesis.",
83
+ ["the contract entails the hypothesis",
84
+ "the contract neither entails nor contradicts it",
85
+ "the contract contradicts the hypothesis"],
86
+ {"entailment": 0, "neutral": 1,
87
+ "contradiction": 2}.get(label_names[ci].lower(), 1),
88
+ "hf_contractnli", meta={"src": "contract_nli"})
89
+ if row:
90
+ out.append(row)
91
+ return out
92
+
93
+
94
+ def gen_casehold(n, rng):
95
+ ds = None
96
+ for repo in ("coastalcph/lex_glue", "jonathanli/lex-glue"):
97
+ try:
98
+ ds = load_dataset(repo, "case_hold", split="train")
99
+ break
100
+ except Exception:
101
+ continue
102
+ if ds is None:
103
+ return []
104
+ out = []
105
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
106
+ for i in idxs:
107
+ if len(out) >= n:
108
+ break
109
+ r = ds[i]
110
+ ctx = str(r.get("context") or "")[:6000]
111
+ endings = [str(e) for e in (r.get("endings") or [])]
112
+ lab = int(r.get("label", -1))
113
+ if not ctx or len(endings) < 2 or lab < 0 or lab >= len(endings):
114
+ continue
115
+ row = choice_row("Case context:\n%s" % ctx,
116
+ "Choose the holding that correctly completes the "
117
+ "legal reasoning.", endings, lab, "hf_casehold",
118
+ meta={"src": "lex_glue_case_hold"})
119
+ if row:
120
+ out.append(row)
121
+ return out
122
+
123
+
124
+ def gen_ledgar(n, rng):
125
+ """Contract clause -> provision type among sampled options."""
126
+ ds = None
127
+ for repo in ("coastalcph/lex_glue", "jonathanli/lex-glue"):
128
+ try:
129
+ ds = load_dataset(repo, "ledgar", split="train")
130
+ break
131
+ except Exception:
132
+ continue
133
+ if ds is None:
134
+ return []
135
+ names = ds.features["label"].names
136
+ out = []
137
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
138
+ for i in idxs:
139
+ if len(out) >= n:
140
+ break
141
+ r = ds[i]
142
+ true_name = names[int(r["label"])].replace("_", " ").lower()
143
+ k = rng.randint(3, 6)
144
+ others = rng.sample([x.replace("_", " ").lower() for x in names
145
+ if x != names[int(r["label"])]], k)
146
+ opts = [true_name] + others
147
+ order = list(range(len(opts))); rng.shuffle(order)
148
+ shuffled = [opts[j] for j in order]
149
+ ci = shuffled.index(true_name)
150
+ st = "Contract clause:\n%s" % str(r.get("text") or "")[:3000]
151
+ row = choice_row(st, "Classify the provision type of this clause.",
152
+ shuffled, ci, "hf_ledgar", meta={"src": "ledgar"})
153
+ if row:
154
+ out.append(row)
155
+ return out
156
+
157
+
158
+ def gen_unfair_tos(n, rng):
159
+ """ToS clause -> unfairness category."""
160
+ ds = None
161
+ for repo in ("coastalcph/lex_glue", "jonathanli/lex-glue"):
162
+ try:
163
+ ds = load_dataset(repo, "unfair_tos", split="train")
164
+ break
165
+ except Exception:
166
+ continue
167
+ if ds is None:
168
+ return []
169
+ names = ds.features["label"].names
170
+ out = []
171
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
172
+ for i in idxs:
173
+ if len(out) >= n:
174
+ break
175
+ r = ds[i]
176
+ lab = int(r["label"])
177
+ txt = str(r.get("text") or "")[:3000]
178
+ if not txt:
179
+ continue
180
+ opts = [x.replace("_", " ") for x in names]
181
+ row = choice_row("Terms-of-service clause:\n%s" % txt,
182
+ "Classify the unfairness category of this clause.",
183
+ opts, lab, "hf_unfair_tos", meta={"src": "unfair_tos"})
184
+ if row:
185
+ out.append(row)
186
+ return out
187
+
188
+
189
+ def gen_hotpot(n, rng):
190
+ try:
191
+ ds = load_dataset("hotpotqa/hotpot_qa", "distractor", split="train")
192
+ except Exception:
193
+ try:
194
+ ds = load_dataset("hotpot_qa", "distractor", split="train",
195
+ trust_remote_code=True)
196
+ except Exception:
197
+ return []
198
+ out = []
199
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
200
+ for i in idxs:
201
+ if len(out) >= n:
202
+ break
203
+ r = ds[i]
204
+ # build a passage bundle from context titles/sentences
205
+ ctx = r.get("context") or {}
206
+ titles = ctx.get("title") or []
207
+ sents = ctx.get("sentences") or []
208
+ parts = []
209
+ for t, ss in zip(titles[:8], sents[:8]):
210
+ parts.append("%s: %s" % (t, " ".join(ss[:4])))
211
+ st = ("Passages:\n%s\n\nQuestion: %s" % ("\n".join(parts),
212
+ r["question"]))
213
+ ans = r.get("answer", "")
214
+ if not ans or len(ans) > 120:
215
+ continue
216
+ # distractors from other answers
217
+ oi = idxs[rng.randint(0, len(idxs) - 1)]
218
+ wrong = []
219
+ while len(wrong) < 3:
220
+ w = ds[oi].get("answer", "")
221
+ if w and w != ans and len(w) < 120 and w not in wrong:
222
+ wrong.append(w)
223
+ oi = idxs[rng.randint(0, len(idxs) - 1)]
224
+ opts = [ans] + wrong
225
+ order = list(range(4)); rng.shuffle(order)
226
+ shuffled = [opts[j] for j in order]
227
+ ci = shuffled.index(ans)
228
+ row = choice_row(st, "Choose the answer that the passages jointly "
229
+ "support.", shuffled, ci, "hf_hotpot",
230
+ meta={"src": "hotpot"})
231
+ if row:
232
+ out.append(row)
233
+ return out
234
+
235
+
236
+ def gen_aqua(n, rng):
237
+ try:
238
+ ds = load_dataset("deepmind/aqua_rat", "raw", split="train")
239
+ except Exception:
240
+ try:
241
+ ds = load_dataset("aqua_rat", split="train",
242
+ trust_remote_code=True)
243
+ except Exception:
244
+ return []
245
+ out = []
246
+ letter = "abcde"
247
+ for r in ds:
248
+ if len(out) >= n:
249
+ break
250
+ opts = r.get("options") or []
251
+ opts = [o[2:].strip() if len(o) > 2 and o[1] == ")" else o.strip()
252
+ for o in opts]
253
+ if len(opts) != 5:
254
+ continue
255
+ ci = letter.find(str(r.get("correct", "")).lower())
256
+ if ci < 0:
257
+ continue
258
+ row = choice_row("Problem:\n%s" % r["question"].strip(),
259
+ "Solve and choose the correct answer.", opts, ci,
260
+ "hf_aqua", meta={"src": "aqua_rat"})
261
+ if row:
262
+ out.append(row)
263
+ return out
264
+
265
+
266
+ def gen_medmcqa(n, rng):
267
+ try:
268
+ ds = load_dataset("openlifescienceai/medmcqa", split="train")
269
+ except Exception:
270
+ try:
271
+ ds = load_dataset("medmcqa", split="train", trust_remote_code=True)
272
+ except Exception:
273
+ return []
274
+ out = []
275
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
276
+ for i in idxs:
277
+ if len(out) >= n:
278
+ break
279
+ r = ds[i]
280
+ opts = [r.get(k, "") for k in ("opa", "opb", "opc", "opd")]
281
+ cop = r.get("cop")
282
+ if not all(opts) or cop is None or int(cop) > 3:
283
+ continue
284
+ st = "Clinical question:\n%s" % (r.get("question") or "")
285
+ row = choice_row(st, "Choose the best answer.", opts, int(cop),
286
+ "hf_medmcqa", meta={"src": "medmcqa"})
287
+ if row:
288
+ out.append(row)
289
+ return out
290
+
291
+
292
+ def gen_cosmos(n, rng):
293
+ try:
294
+ ds = load_dataset("allenai/cosmos_qa", split="train")
295
+ except Exception:
296
+ try:
297
+ ds = load_dataset("cosmos_qa", split="train",
298
+ trust_remote_code=True)
299
+ except Exception:
300
+ return []
301
+ out = []
302
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
303
+ for i in idxs:
304
+ if len(out) >= n:
305
+ break
306
+ r = ds[i]
307
+ opts = [r.get("answer%d" % k, "") for k in range(4)]
308
+ lab = r.get("label")
309
+ if not all(opts) or lab is None:
310
+ continue
311
+ st = "Context:\n%s\n\nQuestion:\n%s" % (r.get("context", ""),
312
+ r.get("question", ""))
313
+ row = choice_row(st, "Choose the most plausible answer.", opts,
314
+ int(lab), "hf_cosmos", meta={"src": "cosmos_qa"})
315
+ if row:
316
+ out.append(row)
317
+ return out
318
+
319
+
320
+ def gen_squad2(n, rng):
321
+ """Answerable vs unanswerable -> noul (abstention signal)."""
322
+ try:
323
+ ds = load_dataset("rajpurkar/squad_v2", split="train")
324
+ except Exception:
325
+ return []
326
+ out = []
327
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
328
+ for i in idxs:
329
+ if len(out) >= n:
330
+ break
331
+ r = ds[i]
332
+ ans = r.get("answers", {}).get("text") or []
333
+ st = "Passage:\n%s\n\nQuestion:\n%s" % (r["context"][:5000],
334
+ r["question"])
335
+ out.append(noul_row(st, "Is the question answerable from the "
336
+ "passage?", len(ans) > 0, "hf_squad2_answerable",
337
+ meta={"src": "squad_v2"}))
338
+ return out
339
+
340
+
341
+ def gen_siqa(n, rng):
342
+ try:
343
+ ds = load_dataset("allenai/social_i_qa", split="train")
344
+ except Exception:
345
+ try:
346
+ ds = load_dataset("social_i_qa", split="train",
347
+ trust_remote_code=True)
348
+ except Exception:
349
+ return []
350
+ out = []
351
+ for r in ds:
352
+ if len(out) >= n:
353
+ break
354
+ opts = [r.get("answerA", ""), r.get("answerB", ""), r.get("answerC", "")]
355
+ lab = r.get("label")
356
+ if not all(opts) or lab is None:
357
+ continue
358
+ st = "Situation:\n%s\n\nQuestion:\n%s" % (r.get("context", ""),
359
+ r.get("question", ""))
360
+ row = choice_row(st, "Choose the best answer.", opts,
361
+ int(lab) - 1, "hf_siqa", meta={"src": "siqa"})
362
+ if row:
363
+ out.append(row)
364
+ return out
365
+
366
+
367
+ def gen_swag(n, rng):
368
+ try:
369
+ ds = load_dataset("allenai/swag", "regular", split="train")
370
+ except Exception:
371
+ try:
372
+ ds = load_dataset("swag", split="train", trust_remote_code=True)
373
+ except Exception:
374
+ return []
375
+ out = []
376
+ idxs = list(range(len(ds))); rng.shuffle(idxs)
377
+ for i in idxs:
378
+ if len(out) >= n:
379
+ break
380
+ r = ds[i]
381
+ opts = [r.get("ending%d" % k, "") for k in range(4)]
382
+ lab = r.get("label")
383
+ if not all(opts) or lab is None:
384
+ continue
385
+ st = "%s %s" % (r.get("startphrase", ""), r.get("sent1", ""))
386
+ row = choice_row(st, "Choose the most plausible continuation.", opts,
387
+ int(lab), "hf_swag", meta={"src": "swag"})
388
+ if row:
389
+ out.append(row)
390
+ return out
391
+
392
+
393
+ GENS = {
394
+ "ledgar": gen_ledgar,
395
+ "unfair_tos": gen_unfair_tos,
396
+ "casehold": gen_casehold,
397
+ "hotpot": gen_hotpot,
398
+ "aqua": gen_aqua,
399
+ "medmcqa": gen_medmcqa,
400
+ "squad2": gen_squad2,
401
+ "swag": gen_swag,
402
+ }
403
+
404
+
405
+ def main():
406
+ ap = argparse.ArgumentParser()
407
+ ap.add_argument("--out", default="data/hf3.jsonl")
408
+ ap.add_argument("--per", type=int, default=5000)
409
+ ap.add_argument("--only", default="")
410
+ args = ap.parse_args()
411
+ rows = []
412
+ only = set(args.only.split(",")) if args.only else None
413
+ for name, fn in GENS.items():
414
+ if only and name not in only:
415
+ continue
416
+ try:
417
+ got = fn(args.per, rng)
418
+ except Exception as e:
419
+ print(name, "FAILED", type(e).__name__, str(e)[:120])
420
+ continue
421
+ print(name, len(got))
422
+ rows += got
423
+ rng.shuffle(rows)
424
+ with open(args.out, "w") as f:
425
+ for r in rows:
426
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
427
+ print("TOTAL", len(rows), "->", args.out)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()