| """ |
| Reservoir-sample random documents from FineWeb-Edu sample-100BT. |
| |
| Usage: |
| python sample_random.py --output audit_output/random_100k.csv --sample 100000 |
| """ |
| import csv |
| import random |
| import argparse |
|
|
| from datasets import load_dataset |
|
|
| SEED = 42 |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--output", default="audit_output/random_100k.csv") |
| parser.add_argument("--sample", type=int, default=100_000) |
| args = parser.parse_args() |
|
|
| random.seed(SEED) |
|
|
| ds = load_dataset("HuggingFaceFW/fineweb-edu", name="sample-100BT", split="train", streaming=True) |
|
|
| reservoir = [] |
| n = 0 |
|
|
| for doc in ds: |
| n += 1 |
| if n <= args.sample: |
| reservoir.append(doc) |
| else: |
| j = random.randint(0, n - 1) |
| if j < args.sample: |
| reservoir[j] = doc |
| if n % 1_000_000 == 0: |
| print(f"{n:,} docs scanned...", flush=True) |
|
|
| print(f"\nTotal docs: {n:,}") |
| print(f"Sampled: {len(reservoir):,}") |
|
|
| with open(args.output, "w", newline="") as f: |
| writer = csv.DictWriter(f, fieldnames=["url", "score", "int_score", "dump", "full_text"]) |
| writer.writeheader() |
| for doc in reservoir: |
| writer.writerow({ |
| "url": doc["url"], |
| "score": doc["score"], |
| "int_score": doc["int_score"], |
| "dump": doc["dump"], |
| "full_text": doc["text"], |
| }) |
|
|
| print(f"Written to {args.output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|