""" UKS Seed Dataset Generator Generates preprocessed training data from FineWeb dataset using: - spaCy for linguistic features (POS, dependencies, lemmas, entities) - XLNetTokenizer for subword tokenization Outputs: - pre_tokenized.jsonl.gz: Ready for model training - intermediate.parquet: For exploration and custom tokenization """ import gzip import hashlib import json from dataclasses import dataclass, field from pathlib import Path from typing import Dict, Iterator, List, Optional import spacy from datasets import load_dataset from transformers import XLNetTokenizer from tqdm import tqdm @dataclass class SEEDConfig: max_samples: int = 10000 batch_size: int = 100 min_sentence_len: int = 5 max_sentence_len: int = 512 output_dir: Path = Path(__file__).parent / "train" cache_dir: Path = Path(__file__).parent / ".cache" hf_dataset_name: str = "HuggingFaceFW/fineweb" hf_dataset_split: str = "train" spacy_model: str = "en_core_web_sm" xlnet_model: str = "xlnet/xlnet-base-cased" class SEEDDatasetGenerator: def __init__(self, config: Optional[SEEDConfig] = None): self.config = config or SEEDConfig() self._nlp = None self._tokenizer = None self._processed_ids: set = set() @property def nlp(self): if self._nlp is None: try: self._nlp = spacy.load(self.config.spacy_model) except OSError: import subprocess import sys print(f"Downloading spaCy model: {self.config.spacy_model}") subprocess.run( [ sys.executable, "-m", "spacy", "download", self.config.spacy_model, ], check=True, ) self._nlp = spacy.load(self.config.spacy_model) return self._nlp @property def tokenizer(self): if self._tokenizer is None: self._tokenizer = XLNetTokenizer.from_pretrained(self.config.xlnet_model) return self._tokenizer def _load_processed_ids(self) -> set: cache_file = self.config.cache_dir / "processed_ids.json" if cache_file.exists(): with open(cache_file, "r") as f: return set(json.load(f)) return set() def _save_processed_ids(self): cache_file = self.config.cache_dir / "processed_ids.json" cache_file.parent.mkdir(parents=True, exist_ok=True) with open(cache_file, "w") as f: json.dump(list(self._processed_ids), f) def _get_sample_id(self, text: str) -> str: return hashlib.sha256(text.encode()).hexdigest()[:16] def _load_fineweb(self) -> Iterator[Dict]: dataset = load_dataset( self.config.hf_dataset_name, split=self.config.hf_dataset_split, streaming=True, ) for sample in dataset: text = sample.get("text", "") if text and len(text.strip()) > 0: yield { "id": sample.get("id", ""), "text": text, } def _process_document(self, text: str) -> List[Dict]: doc = self.nlp(text) records = [] for sent in doc.sents: sent_text = sent.text.strip() if len(sent_text) < self.config.min_sentence_len: continue if len(sent_text) > self.config.max_sentence_len: sent_text = sent_text[: self.config.max_sentence_len] tokens = [] pos_tags = [] dep_tags = [] lemmas = [] ent_types = [] head_dists = [] for token in sent: tokens.append(token.text) pos_tags.append(token.pos_) dep_tags.append(token.dep_) lemmas.append(token.lemma_ if token.lemma_ else token.text) ent_types.append(token.ent_type_ if token.ent_type_ else "O") head_dists.append(token.head.i - token.i) enc = self.tokenizer( sent_text, add_special_tokens=False, truncation=True, max_length=self.config.max_sentence_len, ) token_ids = enc["input_ids"] record = { "id": self._get_sample_id(sent_text), "text": sent_text, "tokens": json.dumps(tokens), "token_ids": json.dumps(token_ids), "pos": json.dumps(pos_tags), "dep": json.dumps(dep_tags), "lemma": json.dumps(lemmas), "ent_type": json.dumps(ent_types), "head_dist": json.dumps(head_dists), } records.append(record) return records def generate(self) -> Dict[str, Path]: self.config.output_dir.mkdir(parents=True, exist_ok=True) self.config.cache_dir.mkdir(parents=True, exist_ok=True) self._processed_ids = self._load_processed_ids() jsonl_path = self.config.output_dir / "pre_tokenized.jsonl.gz" parquet_path = self.config.output_dir / "intermediate.parquet" jsonl_records: List[Dict] = [] all_records: List[Dict] = [] try: import pyarrow as pa import pyarrow.parquet as pq has_pyarrow = True except ImportError: has_pyarrow = False print("Warning: pyarrow not installed. Parquet output will be skipped.") print("Install with: pip install pyarrow") batch_buffer: List[str] = [] sample_count = 0 skipped_count = 0 print(f"Loading FineWeb from: {self.config.hf_dataset_name}") print(f"Target samples: {self.config.max_samples}") dataset = self._load_fineweb() for sample in tqdm(dataset, desc="Processing documents"): if sample_count >= self.config.max_samples: break sample_text = sample["text"] if not sample_text: continue batch_buffer.append(sample_text) if len(batch_buffer) >= self.config.batch_size: texts = batch_buffer batch_buffer = [] docs = list(self.nlp.pipe(texts, batch_size=len(texts))) for doc in docs: for sent in doc.sents: sent_text = sent.text.strip() if len(sent_text) < self.config.min_sentence_len: continue if len(sent_text) > self.config.max_sentence_len: sent_text = sent_text[: self.config.max_sentence_len] sample_id = self._get_sample_id(sent_text) if sample_id in self._processed_ids: skipped_count += 1 continue self._processed_ids.add(sample_id) sample_count += 1 tokens = [] pos_tags = [] dep_tags = [] lemmas = [] ent_types = [] head_dists = [] for token in sent: tokens.append(token.text) pos_tags.append(token.pos_) dep_tags.append(token.dep_) lemmas.append(token.lemma_ if token.lemma_ else token.text) ent_types.append( token.ent_type_ if token.ent_type_ else "O" ) head_dists.append(token.head.i - token.i) enc = self.tokenizer( sent_text, add_special_tokens=False, truncation=True, max_length=self.config.max_sentence_len, ) token_ids = enc["input_ids"] record = { "id": sample_id, "text": sent_text, "tokens": json.dumps(tokens), "token_ids": json.dumps(token_ids), "pos": json.dumps(pos_tags), "dep": json.dumps(dep_tags), "lemma": json.dumps(lemmas), "ent_type": json.dumps(ent_types), "head_dist": json.dumps(head_dists), } jsonl_records.append(record) all_records.append(record) if sample_count >= self.config.max_samples: break if sample_count >= self.config.max_samples: break if sample_count % 1000 == 0 and jsonl_records: self._write_jsonl(jsonl_records, jsonl_path, append=True) jsonl_records = [] self._save_processed_ids() if jsonl_records: self._write_jsonl(jsonl_records, jsonl_path, append=True) if has_pyarrow and all_records: self._write_parquet(all_records, parquet_path) self._save_processed_ids() print(f"\n=== Generation Complete ===") print(f"Total samples: {sample_count}") print(f"Skipped (duplicates): {skipped_count}") print(f"Output files:") print(f" - {jsonl_path}") if has_pyarrow: print(f" - {parquet_path}") return { "jsonl": jsonl_path, "parquet": parquet_path if has_pyarrow else None, } def _write_jsonl(self, records: List[Dict], path: Path, append: bool = False): mode = "ab" if append else "wb" with gzip.open(path, mode) as f: for record in records: f.write((json.dumps(record) + "\n").encode()) def _write_parquet(self, records: List[Dict], path: Path): try: import pyarrow as pa import pyarrow.parquet as pq if not records: return keys = list(records[0].keys()) arrays = [] for key in keys: arrays.append( pa.array([r.get(key, "") for r in records], type=pa.string()) ) schema = pa.schema(zip(keys, [pa.string() for _ in keys])) table = pa.table(dict(zip(keys, arrays)), schema=schema) pq.write_table(table, path) except ImportError: print("Skipping parquet output (pyarrow not available)") def main(): import argparse parser = argparse.ArgumentParser(description="Generate UKS Seed Dataset") parser.add_argument( "--max-samples", type=int, default=10000, help="Maximum number of samples" ) parser.add_argument( "--batch-size", type=int, default=100, help="Batch size for processing" ) parser.add_argument("--output-dir", type=str, default=None, help="Output directory") parser.add_argument("--cache-dir", type=str, default=None, help="Cache directory") args = parser.parse_args() config = SEEDConfig( max_samples=args.max_samples, batch_size=args.batch_size, ) if args.output_dir: config.output_dir = Path(args.output_dir) if args.cache_dir: config.cache_dir = Path(args.cache_dir) generator = SEEDDatasetGenerator(config) generator.generate() if __name__ == "__main__": main()