kevinwang676 commited on
Commit
c2e4b4e
·
verified ·
1 Parent(s): 79b741c

Create mcqa_dataset.py

Browse files
Files changed (1) hide show
  1. mcqa_dataset.py +55 -0
mcqa_dataset.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mcqa_dataset.py
2
+ # --------------------------------------------------
3
+ # Pre‑tokenised dataset for 4‑choice MCQA
4
+ # --------------------------------------------------
5
+ import json
6
+ import torch
7
+ from torch.utils.data import Dataset
8
+
9
+
10
+ class MCQADataset(Dataset):
11
+ """
12
+ Each item returns:
13
+ input_ids, attention_mask : LongTensor (max_len)
14
+ label : 0/1 (1 → correct choice)
15
+ qid, cid : strings (question id, choice id)
16
+ """
17
+ def __init__(self, path: str, tokenizer, max_len: int = 128):
18
+ self.encodings, self.labels, self.qids, self.cids = [], [], [], []
19
+
20
+ with open(path, encoding="utf-8") as f:
21
+ for line in f:
22
+ obj = json.loads(line)
23
+ stem = obj["question"]["stem"]
24
+ fact = obj["fact1"]
25
+ gold = obj["answerKey"]
26
+
27
+ for ch in obj["question"]["choices"]:
28
+ text = f"{fact} {stem} {ch['text']}"
29
+ enc = tokenizer(
30
+ text,
31
+ max_length=max_len,
32
+ truncation=True,
33
+ padding="max_length",
34
+ )
35
+ self.encodings.append(enc)
36
+ self.labels.append(1 if ch["label"] == gold else 0)
37
+ self.qids.append(obj["id"])
38
+ self.cids.append(ch["label"])
39
+
40
+ # Convert lists of dicts → dict of lists for cheaper indexing
41
+ self.encodings = {
42
+ k: [d[k] for d in self.encodings] for k in self.encodings[0]
43
+ }
44
+
45
+ # --------------------------------------------------
46
+
47
+ def __len__(self):
48
+ return len(self.labels)
49
+
50
+ def __getitem__(self, idx):
51
+ item = {k: torch.tensor(v[idx]) for k, v in self.encodings.items()}
52
+ item["label"] = torch.tensor(self.labels[idx], dtype=torch.long)
53
+ item["qid"] = self.qids[idx]
54
+ item["cid"] = self.cids[idx]
55
+ return item