skyzhou06 commited on
Commit
d8291a1
·
verified ·
1 Parent(s): 8a50304

Delete scripts/apply_v041_quality_patch.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/apply_v041_quality_patch.py +0 -522
scripts/apply_v041_quality_patch.py DELETED
@@ -1,522 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import json
5
- import re
6
- import shutil
7
- import statistics
8
- from collections import Counter, defaultdict
9
- from pathlib import Path
10
- from typing import Any
11
-
12
- import pandas as pd
13
-
14
-
15
- ROOT = Path("life_streaming_cot_dataset")
16
- DATA_DIR = ROOT / "data"
17
- VERSION = "v0.4.1"
18
- GENERATION_METHOD = "source_grounded_rule_based_v0.4.1_quality_patch"
19
- REFINEMENT_METHOD = "rule_based_quality_patch_v0.4.1"
20
- REPO_ID = "skyzhou06/LifeTextSingleTurnStreamingCoT"
21
- EXCLUDED_HQ_FLAGS = {
22
- "copied_source_response",
23
- "awkward_answer",
24
- "keyword_stitching",
25
- "repeated_context_chunks",
26
- "weak_high_quality_candidate",
27
- "generic_reasoning",
28
- "closing_mishandled",
29
- "possible_slot_error",
30
- "excessive_chunking",
31
- "fragment_chunk",
32
- "low_specificity",
33
- }
34
- SEVERE_FLAGS = {
35
- "generic_reasoning",
36
- "closing_mishandled",
37
- "possible_slot_error",
38
- "excessive_chunking",
39
- "fragment_chunk",
40
- "low_specificity",
41
- }
42
- BASE_FIELDS = [
43
- "id",
44
- "domain",
45
- "source_dataset",
46
- "instruction",
47
- "context",
48
- "context_chunks",
49
- "streaming_reasoning",
50
- "deep_reasoning",
51
- "answer",
52
- "response",
53
- "messages",
54
- "text",
55
- "num_chunks",
56
- "language",
57
- "split",
58
- "generation_method",
59
- "quality_flags",
60
- "version",
61
- "reasoning_policy",
62
- "chunking_method",
63
- "chunk_labels",
64
- "skip_chunks",
65
- "skip_reasons",
66
- "reasoning_token_budget",
67
- "original_num_chunks",
68
- "chunk_split_count",
69
- "quality_score",
70
- "is_high_quality",
71
- "refinement_method",
72
- "llm_augmented",
73
- "llm_augmentation_model",
74
- "rejected_reason",
75
- "state_tracking_confidence",
76
- ]
77
-
78
-
79
- def read_jsonl(path: Path) -> list[dict[str, Any]]:
80
- rows: list[dict[str, Any]] = []
81
- with path.open("r", encoding="utf-8") as handle:
82
- for line in handle:
83
- line = line.strip()
84
- if line:
85
- rows.append(json.loads(line))
86
- return rows
87
-
88
-
89
- def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
90
- path.parent.mkdir(parents=True, exist_ok=True)
91
- with path.open("w", encoding="utf-8") as handle:
92
- for row in rows:
93
- handle.write(json.dumps(row, ensure_ascii=False) + "\n")
94
-
95
-
96
- def write_parquet(path: Path, rows: list[dict[str, Any]]) -> None:
97
- pd.DataFrame(rows, columns=BASE_FIELDS).to_parquet(path, index=False)
98
-
99
-
100
- def word_count(text: Any) -> int:
101
- return len(re.findall(r"\b[\w'-]+\b", str(text)))
102
-
103
-
104
- def normalize(text: Any) -> str:
105
- return re.sub(r"\W+", " ", str(text).lower()).strip()
106
-
107
-
108
- def avg(values: list[float]) -> float:
109
- return statistics.mean(values) if values else 0.0
110
-
111
-
112
- def repeated_chunk_ratio(row: dict[str, Any]) -> tuple[int, float]:
113
- chunks = [normalize(chunk) for chunk in row.get("context_chunks", []) if normalize(chunk)]
114
- counts = Counter(chunks)
115
- repeated = sum(count - 1 for count in counts.values() if count > 1)
116
- return repeated, repeated / len(chunks) if chunks else 0.0
117
-
118
-
119
- def hard_fragment(chunk: str) -> bool:
120
- text = str(chunk or "").strip()
121
- normalized = normalize(text)
122
- if not text or not normalized:
123
- return True
124
- if normalized in {"mr", "mrs", "ms", "dr", "prof", "macmillan"}:
125
- return True
126
- if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\.?", text):
127
- return True
128
- if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\s+\.", text):
129
- return True
130
- return word_count(text) <= 2 and bool(re.fullmatch(r"[\W_]+", text))
131
-
132
-
133
- def short_fragmentish(chunk: str) -> bool:
134
- text = str(chunk or "").strip()
135
- if hard_fragment(text):
136
- return True
137
- if word_count(text) >= 4:
138
- return False
139
- safe_short = re.search(
140
- r"\b(hi|hello|thanks|thank|yes|no|ok|okay|bye|goodbye|wow|well|sure|certainly|yeah|yep|nope|sorry|wait|listen|right|exactly|perfect|interesting|tomorrow|monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b",
141
- text,
142
- flags=re.IGNORECASE,
143
- )
144
- meaningful_short = re.search(
145
- r"\b(book|leave|go|wait|stop|help|call|turn|tap|click|wipe|wash|unplug|rinse)\b",
146
- text,
147
- flags=re.IGNORECASE,
148
- )
149
- return not (safe_short or meaningful_short)
150
-
151
-
152
- def keyword_list_style(text: str) -> bool:
153
- lower = str(text).lower()
154
- if re.search(r"\b(main topic is|especially with|after|because|around)\s+[a-z][a-z'-]+,\s+[a-z][a-z'-]+", lower):
155
- return True
156
- if re.search(r"\b[a-z][a-z'-]+,\s+[a-z][a-z'-]+,\s+[a-z][a-z'-]+(?:,\s+[a-z][a-z'-]+)?\b", lower):
157
- return any(marker in lower for marker in ["user feels", "user is processing", "main topic", "especially with", "dialogue state"])
158
- return False
159
-
160
-
161
- def awkward_answer(row: dict[str, Any]) -> bool:
162
- answer = str(row.get("answer", ""))
163
- lower = answer.lower()
164
- return (
165
- "especially with" in lower
166
- or "the main topic is" in lower
167
- or "certainly," in lower
168
- or keyword_list_style(answer)
169
- )
170
-
171
-
172
- def emotional_keyword_stitching(row: dict[str, Any]) -> bool:
173
- if row.get("domain") != "emotional_support":
174
- return False
175
- stream = str(row.get("streaming_reasoning", ""))
176
- deep = str(row.get("deep_reasoning", ""))
177
- answer = str(row.get("answer", ""))
178
- support_signals = stream.count("support_signal=received")
179
- chunks = max(1, int(row.get("num_chunks", 1)))
180
- return (
181
- support_signals >= 3
182
- or support_signals / chunks > 0.35
183
- or "especially with" in answer.lower()
184
- or keyword_list_style(deep)
185
- or keyword_list_style(answer)
186
- )
187
-
188
-
189
- def task_closing_mishandled(row: dict[str, Any]) -> bool:
190
- if row.get("domain") != "task_oriented_assistant":
191
- return False
192
- context = " ".join(row.get("context_chunks", []))
193
- closing = re.search(
194
- r"\b(thanks|thank you|goodbye|bye|that'?s all|that is all|all i need|all i needed|all set|take care|good bye)\b",
195
- context,
196
- flags=re.IGNORECASE,
197
- )
198
- asks = re.search(r"\?|what .*(should|would)|please (provide|confirm|tell)|which .* should|share .*", str(row.get("answer", "")), flags=re.IGNORECASE)
199
- return bool(closing and asks)
200
-
201
-
202
- def recompute_flags(row: dict[str, Any]) -> list[str]:
203
- flags = list(dict.fromkeys(row.get("quality_flags", [])))
204
- chunks = row.get("context_chunks", [])
205
- repeated, ratio = repeated_chunk_ratio(row)
206
- if repeated:
207
- flags.append("repeated_context_chunks")
208
- if any(hard_fragment(chunk) for chunk in chunks):
209
- flags.append("fragment_chunk")
210
- if any(short_fragmentish(chunk) for chunk in chunks):
211
- flags.append("weak_high_quality_candidate")
212
- avg_chunk_words = avg([word_count(chunk) for chunk in chunks])
213
- if avg_chunk_words < 4 or row.get("num_chunks", 0) > 12:
214
- flags.append("excessive_chunking")
215
- if awkward_answer(row):
216
- flags.append("awkward_answer")
217
- if emotional_keyword_stitching(row):
218
- flags.append("keyword_stitching")
219
- if "Dialogue state:" in str(row.get("deep_reasoning", "")):
220
- flags.append("weak_high_quality_candidate")
221
- if task_closing_mishandled(row):
222
- flags.append("closing_mishandled")
223
- if ratio > 0.30:
224
- flags.append("weak_high_quality_candidate")
225
- return list(dict.fromkeys(flags))
226
-
227
-
228
- def recompute_quality_score(row: dict[str, Any], flags: list[str]) -> float:
229
- penalties = {
230
- "generic_reasoning": 0.20,
231
- "copied_source_response": 0.20,
232
- "awkward_answer": 0.25,
233
- "keyword_stitching": 0.25,
234
- "weak_high_quality_candidate": 0.20,
235
- "repeated_context_chunks": 0.10,
236
- "fragment_chunk": 0.20,
237
- "excessive_chunking": 0.15,
238
- "closing_mishandled": 0.20,
239
- "possible_slot_error": 0.15,
240
- "low_specificity": 0.15,
241
- "long_streaming_reasoning": 0.05,
242
- "long_deep_reasoning": 0.05,
243
- "too_many_skips": 0.05,
244
- "weak_context": 0.05,
245
- }
246
- score = 1.0 - sum(penalties.get(flag, 0.0) for flag in set(flags))
247
- if repeated_chunk_ratio(row)[1] > 0.30:
248
- score -= 0.10
249
- if word_count(row.get("streaming_reasoning", "")) > 120:
250
- score -= 0.05
251
- if word_count(row.get("deep_reasoning", "")) > 45:
252
- score -= 0.05
253
- return round(max(0.0, min(1.0, score)), 3)
254
-
255
-
256
- def is_high_quality(row: dict[str, Any]) -> bool:
257
- flags = set(row.get("quality_flags", []))
258
- if row.get("quality_score", 0) < 0.85:
259
- return False
260
- if flags & EXCLUDED_HQ_FLAGS:
261
- return False
262
- if repeated_chunk_ratio(row)[1] > 0:
263
- return False
264
- if word_count(row.get("streaming_reasoning", "")) > 120 or word_count(row.get("deep_reasoning", "")) > 45:
265
- return False
266
- return True
267
-
268
-
269
- def update_row(row: dict[str, Any]) -> dict[str, Any]:
270
- row = dict(row)
271
- row["version"] = VERSION
272
- row["generation_method"] = GENERATION_METHOD
273
- row["refinement_method"] = REFINEMENT_METHOD
274
- flags = recompute_flags(row)
275
- row["quality_flags"] = flags
276
- row["quality_score"] = recompute_quality_score(row, flags)
277
- row["is_high_quality"] = is_high_quality(row)
278
- return row
279
-
280
-
281
- def quality_counts(rows: list[dict[str, Any]]) -> dict[str, int]:
282
- return dict(sorted(Counter(flag for row in rows for flag in row.get("quality_flags", [])).items()))
283
-
284
-
285
- def source_summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
286
- counts = Counter(row["source_dataset"] for row in rows)
287
- domains: dict[str, set[str]] = defaultdict(set)
288
- for row in rows:
289
- domains[row["source_dataset"]].add(row["domain"])
290
- return [{"name": source, "domain": ",".join(sorted(domains[source])), "rows": count} for source, count in sorted(counts.items())]
291
-
292
-
293
- def metrics(rows: list[dict[str, Any]]) -> dict[str, Any]:
294
- total_chunks = sum(row.get("num_chunks", 0) for row in rows)
295
- skip_chunks = sum(len(row.get("skip_chunks", [])) for row in rows)
296
- severe = sum(1 for row in rows if set(row.get("quality_flags", [])) & SEVERE_FLAGS)
297
- return {
298
- "rows": len(rows),
299
- "average_quality_score": avg([float(row.get("quality_score", 0)) for row in rows]),
300
- "average_streaming_reasoning_words": avg([word_count(row.get("streaming_reasoning", "")) for row in rows]),
301
- "average_deep_reasoning_words": avg([word_count(row.get("deep_reasoning", "")) for row in rows]),
302
- "average_num_chunks": avg([row.get("num_chunks", 0) for row in rows]),
303
- "average_chunk_length": avg([word_count(chunk) for row in rows for chunk in row.get("context_chunks", [])]),
304
- "skip_chunk_ratio": skip_chunks / total_chunks if total_chunks else 0,
305
- "severe_flag_percentage": severe / len(rows) if rows else 0,
306
- "quality_flags_distribution": quality_counts(rows),
307
- }
308
-
309
-
310
- def select_review_samples(rows: list[dict[str, Any]], hq_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
311
- fields = [
312
- "id",
313
- "domain",
314
- "context_chunks",
315
- "chunk_labels",
316
- "skip_reasons",
317
- "streaming_reasoning",
318
- "deep_reasoning",
319
- "answer",
320
- "quality_flags",
321
- "quality_score",
322
- "is_high_quality",
323
- "refinement_method",
324
- "split",
325
- ]
326
- selected: list[dict[str, Any]] = []
327
- seen: set[str] = set()
328
- by_domain: dict[str, list[dict[str, Any]]] = defaultdict(list)
329
- for row in hq_rows + rows:
330
- by_domain[row["domain"]].append(row)
331
- for domain in ["task_oriented_assistant", "emotional_support", "daily_dialogue", "how_to_guidance"]:
332
- for row in by_domain.get(domain, [])[:30]:
333
- if row["id"] in seen:
334
- continue
335
- selected.append({field: row.get(field) for field in fields})
336
- seen.add(row["id"])
337
- for row in rows:
338
- if len(selected) >= 120:
339
- break
340
- if row["id"] not in seen:
341
- selected.append({field: row.get(field) for field in fields})
342
- seen.add(row["id"])
343
- return selected[:120]
344
-
345
-
346
- def update_dataset_info(
347
- train_rows: list[dict[str, Any]],
348
- eval_rows: list[dict[str, Any]],
349
- hq_train: list[dict[str, Any]],
350
- hq_eval: list[dict[str, Any]],
351
- old_info: dict[str, Any],
352
- ) -> dict[str, Any]:
353
- rows = train_rows + eval_rows
354
- hq_rows = hq_train + hq_eval
355
- full_metrics = metrics(rows)
356
- hq_metrics = metrics(hq_rows)
357
- return {
358
- **old_info,
359
- "version": VERSION,
360
- "repo_id": REPO_ID,
361
- "generation_method": GENERATION_METHOD,
362
- "refinement_method": REFINEMENT_METHOD,
363
- "patch_name": "v0.4.1 loading config and high-quality subset patch",
364
- "patch_notes": [
365
- "Adds explicit Hugging Face dataset card configs so default loading uses only data/train.parquet and data/eval.parquet.",
366
- "Adds a separate high_quality config backed by data/train_high_quality.parquet and data/eval_high_quality.parquet.",
367
- "Tightens high-quality subset filtering to remove copied-source responses, awkward answer templates, keyword-stitching, repeated chunks, and weak candidates.",
368
- ],
369
- "hf_config_fixed": True,
370
- "old_v0_4_counts": {
371
- "train_rows": old_info.get("train_rows"),
372
- "eval_rows": old_info.get("eval_rows"),
373
- "high_quality_train_rows": old_info.get("high_quality_train_rows"),
374
- "high_quality_eval_rows": old_info.get("high_quality_eval_rows"),
375
- "hf_auto_detected_total_rows": 18336,
376
- },
377
- "total_rows": len(rows),
378
- "train_rows": len(train_rows),
379
- "eval_rows": len(eval_rows),
380
- "high_quality_train_rows": len(hq_train),
381
- "high_quality_eval_rows": len(hq_eval),
382
- "domains": dict(sorted(Counter(row["domain"] for row in rows).items())),
383
- "source_datasets_used": source_summary(rows),
384
- "average_streaming_reasoning_words": full_metrics["average_streaming_reasoning_words"],
385
- "average_deep_reasoning_words": full_metrics["average_deep_reasoning_words"],
386
- "average_quality_score": full_metrics["average_quality_score"],
387
- "high_quality_percentage": len(hq_rows) / len(rows) if rows else 0,
388
- "skip_chunk_ratio": full_metrics["skip_chunk_ratio"],
389
- "quality_flags_distribution": full_metrics["quality_flags_distribution"],
390
- "high_quality_metrics": hq_metrics,
391
- "high_quality_filtering_rules": sorted(EXCLUDED_HQ_FLAGS | {"quality_score >= 0.85", "no repeated context chunks", "streaming/deep length limits"}),
392
- "llm_augmented_count": sum(1 for row in rows if row.get("llm_augmented")),
393
- }
394
-
395
-
396
- def yaml_front_matter() -> str:
397
- return f"""---
398
- pretty_name: LifeTextSingleTurnStreamingCoT
399
- language:
400
- - en
401
- license: apache-2.0
402
- version: "{VERSION}"
403
- configs:
404
- - config_name: default
405
- data_files:
406
- - split: train
407
- path: data/train.parquet
408
- - split: test
409
- path: data/eval.parquet
410
- - config_name: high_quality
411
- data_files:
412
- - split: train
413
- path: data/train_high_quality.parquet
414
- - split: test
415
- path: data/eval_high_quality.parquet
416
- task_categories:
417
- - text-generation
418
- tags:
419
- - streaming-reasoning
420
- - selective-reasoning
421
- - quality-refined
422
- - supervised-fine-tuning
423
- - sft
424
- - dialogue
425
- - task-oriented-dialogue
426
- - life-assistant
427
- - streamingthinker
428
- size_categories:
429
- - 1K<n<10K
430
- ---
431
- """
432
-
433
-
434
- def update_readme(info: dict[str, Any]) -> None:
435
- path = ROOT / "README.md"
436
- text = path.read_text(encoding="utf-8")
437
- body = re.sub(r"\A---.*?---\s*", "", text, flags=re.DOTALL)
438
- body = body.replace(
439
- "Current version: v0.4: Quality-Refined Selective Streaming Reasoning",
440
- "Current version: v0.4.1: Loading Config and High-Quality Subset Patch",
441
- )
442
- body = body.replace(
443
- "| v0.4 | Quality refinement, quality scores, high-quality subset |",
444
- "| v0.4 | Quality refinement, quality scores, high-quality subset |\n| v0.4.1 | HF loading config fix, stricter high-quality filtering |",
445
- )
446
- if "## Version 0.4.1: Loading Config and High-Quality Subset Patch" not in body:
447
- section = f"""
448
- ## Version 0.4.1: Loading Config and High-Quality Subset Patch
449
-
450
- v0.4.1 is a patch over v0.4. It fixes Hugging Face loading behavior by adding explicit dataset card configs. The default config now points only to the full dataset files, while the `high_quality` config points only to the stricter high-quality subset files.
451
-
452
- ```python
453
- from datasets import load_dataset
454
-
455
- full = load_dataset("skyzhou06/LifeTextSingleTurnStreamingCoT", "default")
456
- hq = load_dataset("skyzhou06/LifeTextSingleTurnStreamingCoT", "high_quality")
457
- ```
458
-
459
- Expected split sizes for v0.4.1:
460
-
461
- - `default/train`: {info['train_rows']}
462
- - `default/test`: {info['eval_rows']}
463
- - `high_quality/train`: {info['high_quality_train_rows']}
464
- - `high_quality/test`: {info['high_quality_eval_rows']}
465
-
466
- The high-quality subset excludes copied-source responses, awkward answer templates, keyword-stitching, repeated context chunks, weak candidates, and severe quality flags.
467
- """
468
- body = body.replace("## Version History\n", section + "\n## Version History\n")
469
- body = re.sub(r"- Train: \d+", f"- Train: {info['train_rows']}", body)
470
- body = re.sub(r"- Eval: \d+", f"- Eval: {info['eval_rows']}", body)
471
- body = re.sub(r"- Total: \d+", f"- Total: {info['total_rows']}", body)
472
- body = re.sub(r"- High-quality train: \d+", f"- High-quality train: {info['high_quality_train_rows']}", body)
473
- body = re.sub(r"- High-quality eval: \d+", f"- High-quality eval: {info['high_quality_eval_rows']}", body)
474
- body = body.replace("v0.4 improves quality", "v0.4 improved quality")
475
- path.write_text(yaml_front_matter() + body, encoding="utf-8")
476
-
477
-
478
- def sync_scripts() -> None:
479
- target = ROOT / "scripts"
480
- target.mkdir(parents=True, exist_ok=True)
481
- for src in Path("scripts").glob("*.py"):
482
- shutil.copy2(src, target / src.name)
483
-
484
-
485
- def main() -> None:
486
- old_info = json.loads((ROOT / "dataset_info.json").read_text(encoding="utf-8"))
487
- train_rows = [update_row(row) for row in read_jsonl(DATA_DIR / "train.jsonl")]
488
- eval_rows = [update_row(row) for row in read_jsonl(DATA_DIR / "eval.jsonl")]
489
- hq_train = [row for row in train_rows if row["is_high_quality"]]
490
- hq_eval = [row for row in eval_rows if row["is_high_quality"]]
491
- if len(hq_train) + len(hq_eval) < 1000:
492
- raise RuntimeError("v0.4.1 high-quality filtering produced fewer than 1000 rows.")
493
-
494
- write_jsonl(DATA_DIR / "train.jsonl", train_rows)
495
- write_jsonl(DATA_DIR / "eval.jsonl", eval_rows)
496
- write_jsonl(DATA_DIR / "train_high_quality.jsonl", hq_train)
497
- write_jsonl(DATA_DIR / "eval_high_quality.jsonl", hq_eval)
498
- write_parquet(DATA_DIR / "train.parquet", train_rows)
499
- write_parquet(DATA_DIR / "eval.parquet", eval_rows)
500
- write_parquet(DATA_DIR / "train_high_quality.parquet", hq_train)
501
- write_parquet(DATA_DIR / "eval_high_quality.parquet", hq_eval)
502
-
503
- info = update_dataset_info(train_rows, eval_rows, hq_train, hq_eval, old_info)
504
- (ROOT / "dataset_info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
505
- write_jsonl(ROOT / "samples_for_review.jsonl", select_review_samples(train_rows + eval_rows, hq_train + hq_eval))
506
- update_readme(info)
507
- sync_scripts()
508
-
509
- print(json.dumps({
510
- "version": VERSION,
511
- "train_rows": len(train_rows),
512
- "eval_rows": len(eval_rows),
513
- "high_quality_train_rows": len(hq_train),
514
- "high_quality_eval_rows": len(hq_eval),
515
- "high_quality_total": len(hq_train) + len(hq_eval),
516
- "full_quality_flags": quality_counts(train_rows + eval_rows),
517
- "high_quality_flags": quality_counts(hq_train + hq_eval),
518
- }, ensure_ascii=False, indent=2))
519
-
520
-
521
- if __name__ == "__main__":
522
- main()