ali5341 commited on
Commit
a5381d1
·
verified ·
1 Parent(s): b19449e

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -58,3 +58,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ train.jsonl filter=lfs diff=lfs merge=lfs -text
62
+ validation.jsonl filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # QASPER (Chat-Format Preparation)
2
+
3
+ This dataset is a chat-format preparation of QASPER for supervised fine-tuning (SFT).
4
+
5
+ ## Format
6
+
7
+ This format is commonly referred to as:
8
+
9
+ - chat-format SFT data
10
+ - instruction-tuning conversations
11
+ - OpenAI-style `messages` format
12
+
13
+ ## Included files
14
+
15
+ - `train.jsonl`
16
+ - `validation.jsonl`
17
+ - `stats.json`
18
+ - `prepare_qasper_unsloth.py`
19
+
20
+ ## Source
21
+
22
+ - Base dataset: `allenai/qasper`
23
+
24
+ ## Preparation summary
25
+
26
+ - One row per `(paper, question)` using the best available annotation.
27
+ - Answer normalization priority:
28
+ 1. free-form
29
+ 2. yes/no
30
+ 3. extractive spans
31
+ 4. unanswerable
32
+ - Context mode is mixed between:
33
+ - evidence-only
34
+ - full-text
35
+ - User prompt follows a question-first structure.
36
+
37
+ Assistant target is the normalized answer text.
38
+
39
+ ## Schema
40
+
41
+ Each JSONL row contains:
42
+
43
+ - `messages`
44
+ - `user`: text instruction + question + title + abstract + context
45
+ - `assistant`: text answer
46
+ - `meta`: ids, answer type, context mode, evidence count
47
+
48
+ ## Reproduction
49
+
50
+ ```bash
51
+ python prepare_qasper_unsloth.py
52
+ ```
__pycache__/prepare_qasper_unsloth.cpython-313.pyc ADDED
Binary file (17.2 kB). View file
 
prepare_qasper_unsloth.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ import random
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Dict, List, Optional, Tuple
8
+
9
+
10
+ USER_INSTRUCTION = (
11
+ "Answer the question using the provided scientific paper context. "
12
+ "Use only the given context, and if the answer is not supported, "
13
+ 'reply with "Unanswerable".'
14
+ )
15
+
16
+
17
+ @dataclass
18
+ class Example:
19
+ split: str
20
+ paper_id: str
21
+ title: str
22
+ abstract: str
23
+ question: str
24
+ question_id: str
25
+ answer_text: str
26
+ answer_type: str
27
+ evidence_list: List[str]
28
+ full_text_sections: List[Dict]
29
+ annotation_id: str
30
+ worker_id: str
31
+
32
+
33
+ def parse_args() -> argparse.Namespace:
34
+ parser = argparse.ArgumentParser(
35
+ description="Prepare QASPER Unsloth chat-format datasets (train/validation)."
36
+ )
37
+ parser.add_argument(
38
+ "--train-json",
39
+ type=Path,
40
+ default=Path("/d/hpc/projects/FRI/DL/Scholar/raw_downloads/qasper/qasper-train-v0.3.json"),
41
+ )
42
+ parser.add_argument(
43
+ "--dev-json",
44
+ type=Path,
45
+ default=Path("/d/hpc/projects/FRI/DL/Scholar/raw_downloads/qasper/qasper-dev-v0.3.json"),
46
+ )
47
+ parser.add_argument(
48
+ "--output-dir",
49
+ type=Path,
50
+ default=Path("/d/hpc/projects/FRI/DL/Scholar/prepared_datasets/qasper_unsloth"),
51
+ )
52
+ parser.add_argument(
53
+ "--evidence-context-ratio",
54
+ type=float,
55
+ default=0.5,
56
+ help="Fraction of examples using evidence-only context. Remaining use full-text context.",
57
+ )
58
+ parser.add_argument(
59
+ "--fulltext-max-chars",
60
+ type=int,
61
+ default=None,
62
+ help="Character cap for full-text context mode. Use None or <=0 for no truncation.",
63
+ )
64
+ parser.add_argument("--seed", type=int, default=42)
65
+ parser.add_argument(
66
+ "--max-train-examples",
67
+ type=int,
68
+ default=None,
69
+ help="Optional cap for smoke tests.",
70
+ )
71
+ return parser.parse_args()
72
+
73
+
74
+ def load_json(path: Path) -> Dict:
75
+ with path.open("r", encoding="utf-8") as f:
76
+ return json.load(f)
77
+
78
+
79
+ def normalize_answer(answer_obj: Dict) -> Optional[Tuple[str, str]]:
80
+ if answer_obj.get("unanswerable") is True:
81
+ return "Unanswerable", "unanswerable"
82
+
83
+ yes_no = answer_obj.get("yes_no")
84
+ if isinstance(yes_no, bool):
85
+ return ("Yes" if yes_no else "No"), "yes_no"
86
+
87
+ free = (answer_obj.get("free_form_answer") or "").strip()
88
+ if free:
89
+ return free, "free_form"
90
+
91
+ spans = [s.strip() for s in (answer_obj.get("extractive_spans") or []) if s and s.strip()]
92
+ if spans:
93
+ unique_spans = list(dict.fromkeys(spans))
94
+ return " ; ".join(unique_spans), "extractive"
95
+
96
+ return None
97
+
98
+
99
+ def answer_rank(answer_obj: Dict, evidence_count: int) -> Tuple[int, int]:
100
+ normalized = normalize_answer(answer_obj)
101
+ if normalized is None:
102
+ return 100, -evidence_count
103
+ _, kind = normalized
104
+ rank_map = {
105
+ "free_form": 0,
106
+ "yes_no": 1,
107
+ "extractive": 2,
108
+ "unanswerable": 3,
109
+ }
110
+ return rank_map[kind], -evidence_count
111
+
112
+
113
+ def pick_best_annotation(annotations: List[Dict]) -> Optional[Tuple[Dict, str, str]]:
114
+ best = None
115
+ best_key = None
116
+ for ann in annotations:
117
+ answer_obj = ann.get("answer", {})
118
+ evidence = answer_obj.get("evidence") or []
119
+ key = answer_rank(answer_obj, len([e for e in evidence if e and e.strip()]))
120
+ normalized = normalize_answer(answer_obj)
121
+ if normalized is None:
122
+ continue
123
+ if best is None or key < best_key:
124
+ best = ann
125
+ best_key = key
126
+ if best is None:
127
+ return None
128
+ text, kind = normalize_answer(best["answer"])
129
+ return best, text, kind
130
+
131
+
132
+ def convert_float_evidence(evidence_text: str) -> str:
133
+ prefix = "FLOAT SELECTED:"
134
+ if evidence_text.startswith(prefix):
135
+ payload = evidence_text[len(prefix):].strip()
136
+ return f"[Figure/Table: {payload}]"
137
+ return evidence_text
138
+
139
+
140
+ def build_fulltext_context(full_text_sections: List[Dict], max_chars: Optional[int]) -> str:
141
+ blocks: List[str] = []
142
+ for section in full_text_sections:
143
+ section_name = (section.get("section_name") or "").strip()
144
+ paragraphs = section.get("paragraphs") or []
145
+ cleaned = [p.strip() for p in paragraphs if isinstance(p, str) and p.strip()]
146
+ if not cleaned:
147
+ continue
148
+ joined = "\n".join(cleaned)
149
+ if section_name:
150
+ blocks.append(f"## {section_name}\n{joined}")
151
+ else:
152
+ blocks.append(joined)
153
+ context = "\n\n".join(blocks)
154
+ if max_chars is not None and max_chars > 0 and len(context) > max_chars:
155
+ context = context[:max_chars].rstrip() + "\n\n[TRUNCATED]"
156
+ return context
157
+
158
+
159
+ def build_evidence_context(evidence_list: List[str]) -> str:
160
+ seen = set()
161
+ out = []
162
+ for raw in evidence_list:
163
+ if not isinstance(raw, str):
164
+ continue
165
+ text = convert_float_evidence(raw.strip())
166
+ if not text:
167
+ continue
168
+ if text in seen:
169
+ continue
170
+ seen.add(text)
171
+ out.append(text)
172
+ return "\n".join(f"- {e}" for e in out)
173
+
174
+
175
+ def to_example_rows(split: str, papers: Dict) -> List[Example]:
176
+ rows: List[Example] = []
177
+ for paper_id in sorted(papers.keys()):
178
+ paper = papers[paper_id]
179
+ title = (paper.get("title") or "").strip()
180
+ abstract = (paper.get("abstract") or "").strip()
181
+ full_text_sections = paper.get("full_text") or []
182
+ qas = paper.get("qas") or []
183
+ for qa in qas:
184
+ question = (qa.get("question") or "").strip()
185
+ question_id = (qa.get("question_id") or "").strip()
186
+ picked = pick_best_annotation(qa.get("answers") or [])
187
+ if not question or not question_id or picked is None:
188
+ continue
189
+ ann, answer_text, answer_type = picked
190
+ answer_obj = ann.get("answer") or {}
191
+ evidence_list = [e for e in (answer_obj.get("evidence") or []) if isinstance(e, str)]
192
+ rows.append(
193
+ Example(
194
+ split=split,
195
+ paper_id=paper_id,
196
+ title=title,
197
+ abstract=abstract,
198
+ question=question,
199
+ question_id=question_id,
200
+ answer_text=answer_text,
201
+ answer_type=answer_type,
202
+ evidence_list=evidence_list,
203
+ full_text_sections=full_text_sections,
204
+ annotation_id=str(ann.get("annotation_id") or ""),
205
+ worker_id=str(ann.get("worker_id") or ""),
206
+ )
207
+ )
208
+ return rows
209
+
210
+
211
+ def build_user_text(ex: Example, context_mode: str, fulltext_max_chars: int) -> str:
212
+ if context_mode == "evidence":
213
+ context_text = build_evidence_context(ex.evidence_list)
214
+ if not context_text:
215
+ context_text = "[No evidence provided]"
216
+ context_header = "Relevant passages"
217
+ else:
218
+ context_text = build_fulltext_context(ex.full_text_sections, max_chars=fulltext_max_chars)
219
+ context_header = "Paper context"
220
+
221
+ return (
222
+ f"{USER_INSTRUCTION}\n\n"
223
+ f"Question: {ex.question}\n\n"
224
+ f"Paper title: {ex.title}\n\n"
225
+ f"Abstract: {ex.abstract}\n\n"
226
+ f"{context_header}:\n{context_text}"
227
+ )
228
+
229
+
230
+ def build_row(ex: Example, context_mode: str, fulltext_max_chars: int) -> Dict:
231
+ user_text = build_user_text(ex=ex, context_mode=context_mode, fulltext_max_chars=fulltext_max_chars)
232
+ return {
233
+ "messages": [
234
+ {
235
+ "role": "user",
236
+ "content": [{"type": "text", "text": user_text}],
237
+ },
238
+ {
239
+ "role": "assistant",
240
+ "content": [{"type": "text", "text": ex.answer_text}],
241
+ },
242
+ ],
243
+ "meta": {
244
+ "dataset": "qasper",
245
+ "split": ex.split,
246
+ "paper_id": ex.paper_id,
247
+ "question_id": ex.question_id,
248
+ "annotation_id": ex.annotation_id,
249
+ "worker_id": ex.worker_id,
250
+ "answer_type": ex.answer_type,
251
+ "context_mode": context_mode,
252
+ "evidence_count": len(ex.evidence_list),
253
+ },
254
+ }
255
+
256
+
257
+ def assign_modes(examples: List[Example], evidence_ratio: float, rng: random.Random) -> Dict[str, str]:
258
+ ids = [f"{e.paper_id}::{e.question_id}" for e in examples]
259
+ shuffled = ids[:]
260
+ rng.shuffle(shuffled)
261
+ n_evidence = int(round(len(shuffled) * evidence_ratio))
262
+ evidence_ids = set(shuffled[:n_evidence])
263
+ mode_map = {}
264
+ for e in examples:
265
+ key = f"{e.paper_id}::{e.question_id}"
266
+ mode_map[key] = "evidence" if key in evidence_ids else "full_text"
267
+ return mode_map
268
+
269
+
270
+ def write_jsonl(path: Path, rows: List[Dict]) -> None:
271
+ with path.open("w", encoding="utf-8") as f:
272
+ for row in rows:
273
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
274
+
275
+
276
+ def main() -> None:
277
+ args = parse_args()
278
+ if not (0.0 <= args.evidence_context_ratio <= 1.0):
279
+ raise ValueError("--evidence-context-ratio must be in [0,1]")
280
+
281
+ args.output_dir.mkdir(parents=True, exist_ok=True)
282
+ train_data = load_json(args.train_json)
283
+ dev_data = load_json(args.dev_json)
284
+
285
+ train_examples = to_example_rows("train", train_data)
286
+ dev_examples = to_example_rows("validation", dev_data)
287
+ if args.max_train_examples is not None:
288
+ train_examples = train_examples[: args.max_train_examples]
289
+
290
+ rng = random.Random(args.seed)
291
+ train_modes = assign_modes(train_examples, args.evidence_context_ratio, rng)
292
+ dev_modes = assign_modes(dev_examples, args.evidence_context_ratio, rng)
293
+
294
+ train_rows = [
295
+ build_row(
296
+ ex,
297
+ context_mode=train_modes[f"{ex.paper_id}::{ex.question_id}"],
298
+ fulltext_max_chars=args.fulltext_max_chars,
299
+ )
300
+ for ex in train_examples
301
+ ]
302
+ dev_rows = [
303
+ build_row(
304
+ ex,
305
+ context_mode=dev_modes[f"{ex.paper_id}::{ex.question_id}"],
306
+ fulltext_max_chars=args.fulltext_max_chars,
307
+ )
308
+ for ex in dev_examples
309
+ ]
310
+
311
+ train_out = args.output_dir / "train.jsonl"
312
+ val_out = args.output_dir / "validation.jsonl"
313
+ stats_out = args.output_dir / "stats.json"
314
+ write_jsonl(train_out, train_rows)
315
+ write_jsonl(val_out, dev_rows)
316
+
317
+ def mode_counts(rows: List[Dict]) -> Dict[str, int]:
318
+ return {
319
+ "evidence": sum(1 for r in rows if r["meta"]["context_mode"] == "evidence"),
320
+ "full_text": sum(1 for r in rows if r["meta"]["context_mode"] == "full_text"),
321
+ }
322
+
323
+ def answer_counts(rows: List[Dict]) -> Dict[str, int]:
324
+ kinds = ["free_form", "extractive", "yes_no", "unanswerable"]
325
+ return {k: sum(1 for r in rows if r["meta"]["answer_type"] == k) for k in kinds}
326
+
327
+ stats = {
328
+ "seed": args.seed,
329
+ "evidence_context_ratio": args.evidence_context_ratio,
330
+ "fulltext_max_chars": args.fulltext_max_chars,
331
+ "train": {
332
+ "rows": len(train_rows),
333
+ "context_mode_counts": mode_counts(train_rows),
334
+ "answer_type_counts": answer_counts(train_rows),
335
+ },
336
+ "validation": {
337
+ "rows": len(dev_rows),
338
+ "context_mode_counts": mode_counts(dev_rows),
339
+ "answer_type_counts": answer_counts(dev_rows),
340
+ },
341
+ "paths": {
342
+ "train_jsonl": str(train_out),
343
+ "validation_jsonl": str(val_out),
344
+ "stats_json": str(stats_out),
345
+ },
346
+ }
347
+ with stats_out.open("w", encoding="utf-8") as f:
348
+ json.dump(stats, f, ensure_ascii=False, indent=2)
349
+ print(json.dumps(stats, ensure_ascii=False, indent=2))
350
+
351
+
352
+ if __name__ == "__main__":
353
+ main()
stats.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "seed": 42,
3
+ "evidence_context_ratio": 0.5,
4
+ "fulltext_max_chars": null,
5
+ "train": {
6
+ "rows": 2593,
7
+ "context_mode_counts": {
8
+ "evidence": 1296,
9
+ "full_text": 1297
10
+ },
11
+ "answer_type_counts": {
12
+ "free_form": 615,
13
+ "extractive": 1311,
14
+ "yes_no": 396,
15
+ "unanswerable": 271
16
+ }
17
+ },
18
+ "validation": {
19
+ "rows": 1005,
20
+ "context_mode_counts": {
21
+ "evidence": 502,
22
+ "full_text": 503
23
+ },
24
+ "answer_type_counts": {
25
+ "free_form": 355,
26
+ "extractive": 463,
27
+ "yes_no": 127,
28
+ "unanswerable": 60
29
+ }
30
+ },
31
+ "paths": {
32
+ "train_jsonl": "/d/hpc/projects/FRI/DL/Scholar/prepared_datasets/qasper_unsloth/train.jsonl",
33
+ "validation_jsonl": "/d/hpc/projects/FRI/DL/Scholar/prepared_datasets/qasper_unsloth/validation.jsonl",
34
+ "stats_json": "/d/hpc/projects/FRI/DL/Scholar/prepared_datasets/qasper_unsloth/stats.json"
35
+ }
36
+ }
train.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:91e0495cb1f747b635ef29aa08a61dcd4b04f09c3afe2484d1bf08cbb2fb3d0d
3
+ size 37840587
validation.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c072f49bb7d0971acac46099076dbaf4c965711ec60fe428d847eae2b7e8907
3
+ size 13893259