SPOOKEXE commited on
Commit
afecc1c
·
verified ·
1 Parent(s): ef4fdd6

root-files

Browse files

essential files

Files changed (3) hide show
  1. .gitignore +3 -0
  2. README.md +173 -13
  3. generate.py +344 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .cache/
2
+ __pycache__/
3
+ *.pyc
README.md CHANGED
@@ -1,13 +1,173 @@
1
- ---
2
- license: mit
3
- task_categories:
4
- - text-generation
5
- - text-classification
6
- language:
7
- - en
8
- tags:
9
- - spaCy
10
- - text
11
- size_categories:
12
- - 100K<n<1M
13
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UKS Seed Dataset Generator
2
+
3
+ Generates preprocessed training data for the UKS Energy System from the FineWeb dataset.
4
+
5
+ ## Overview
6
+
7
+ This pipeline processes text from HuggingFace's FineWeb dataset and produces two output formats:
8
+
9
+ 1. **pre_tokenized.jsonl.gz**: Ready for direct model training
10
+ 2. **intermediate.parquet**: For exploration and custom tokenization workflows
11
+
12
+ ## Dependencies
13
+
14
+ ```bash
15
+ pip install spacy transformers datasets tqdm
16
+ python -m spacy download en_core_web_sm
17
+ pip install pyarrow # for parquet output
18
+ ```
19
+
20
+ ## Tokenizer
21
+
22
+ ### XLNetTokenizer
23
+
24
+ Preprocessed data uses **[XLNetTokenizer](https://huggingface.co/xlnet/xlnet-base-cased)** for subword tokenization.
25
+
26
+ **Model**: `xlnet/xlnet-base-cased`
27
+ **Vocab size**: 32,000 tokens
28
+ **Features**:
29
+ - SentencePiece subword tokenization
30
+ - Punctuation-aware splitting
31
+ - Multilingual support built-in
32
+
33
+ **Example tokenization**:
34
+ ```python
35
+ from transformers import XLNetTokenizer
36
+
37
+ tokenizer = XLNetTokenizer.from_pretrained("xlnet/xlnet-base-cased")
38
+ text = "Don't forget the meeting at 5pm."
39
+
40
+ ids = tokenizer.encode(text, add_special_tokens=False)
41
+ tokens = tokenizer.convert_ids_to_tokens(ids)
42
+ # tokens: ["Don", "'", "t", "forget", "the", "meeting", "at", "5", "pm", "."]
43
+ # ids: [13645, 9, 24, 12087, 5, 4857, 19, 821, 131, 10]
44
+ ```
45
+
46
+ ### spaCy Features
47
+
48
+ Linguistic annotations are extracted using **spaCy** (`en_core_web_sm`):
49
+
50
+ | Feature | Description |
51
+ |---------|-------------|
52
+ | `pos` | Part-of-speech tags (NOUN, VERB, ADJ, etc.) |
53
+ | `dep` | Dependency relations (nsubj, dobj, prep, etc.) |
54
+ | `lemma` | Lemmatized forms |
55
+ | `ent_type` | Named entity types (PERSON, ORG, DATE, etc.) |
56
+ | `head_dist` | Distance to head token in dependency tree |
57
+
58
+ ## Output Schema
59
+
60
+ Both output files contain the following columns:
61
+
62
+ | Column | Type | Description | Example |
63
+ |--------|------|-------------|---------|
64
+ | `id` | string | SHA256 hash (first 16 chars) | `"a1b2c3d4e5f6g7h8"` |
65
+ | `text` | string | Original sentence | `"The cat sat on the mat."` |
66
+ | `tokens` | string (JSON list) | XLNet token strings | `["The", "cat", "sat", ...]` |
67
+ | `token_ids` | string (JSON list) | XLNet integer IDs | `[44, 245, 1234, ...]` |
68
+ | `pos` | string (JSON list) | spaCy POS tags | `["DET", "NOUN", "VERB", ...]` |
69
+ | `dep` | string (JSON list) | Dependency labels | `["det", "nsubj", "ROOT", ...]` |
70
+ | `lemma` | string (JSON list) | Lemmas | `["the", "cat", "sit", ...]` |
71
+ | `ent_type` | string (JSON list) | Entity types | `["O", "O", "O", "DATE"]` |
72
+ | `head_dist` | string (JSON list) | Head distances | `[1, -2, 0, ...]` |
73
+
74
+ ### JSON List Format
75
+
76
+ All list columns are stored as JSON strings for compatibility:
77
+
78
+ ```python
79
+ import json
80
+
81
+ # Loading tokens from file
82
+ record = json.loads(line)
83
+ tokens = json.loads(record["tokens"]) # ["The", "cat", "sat", ...]
84
+ ```
85
+
86
+ ## Output Files
87
+
88
+ ### pre_tokenized.jsonl.gz
89
+
90
+ Gzipped JSON Lines format for direct training consumption:
91
+
92
+ ```python
93
+ import gzip
94
+ import json
95
+
96
+ with gzip.open("output/pre_tokenized.jsonl.gz", "rt") as f:
97
+ for line in f:
98
+ record = json.loads(line)
99
+ # Use directly in training
100
+ ```
101
+
102
+ ### intermediate.parquet
103
+
104
+ Apache Parquet for data exploration:
105
+
106
+ ```python
107
+ import pyarrow.parquet as pq
108
+
109
+ table = pq.read_table("output/intermediate.parquet")
110
+ df = table.to_pandas()
111
+ # Explore with pandas
112
+ ```
113
+
114
+ ## Usage
115
+
116
+ ### Basic Generation
117
+
118
+ ```bash
119
+ cd hf_dataset
120
+ python generate.py
121
+ ```
122
+
123
+ ### Custom Options
124
+
125
+ ```bash
126
+ python generate.py \
127
+ --max-samples 50000 \
128
+ --batch-size 200 \
129
+ --output-dir ./my_output \
130
+ --cache-dir ./my_cache
131
+ ```
132
+
133
+ ### Python API
134
+
135
+ ```python
136
+ from generate import SEEDDatasetGenerator, SEEDConfig
137
+
138
+ config = SEEDConfig(
139
+ max_samples=10000,
140
+ batch_size=100,
141
+ output_dir=Path("output"),
142
+ )
143
+
144
+ generator = SEEDDatasetGenerator(config)
145
+ paths = generator.generate()
146
+
147
+ print(f"Generated: {paths}")
148
+ ```
149
+
150
+ ## Configuration
151
+
152
+ | Parameter | Default | Description |
153
+ |-----------|---------|-------------|
154
+ | `max_samples` | 10,000 | Maximum sentences to process |
155
+ | `batch_size` | 100 | Documents per spaCy batch |
156
+ | `min_sentence_len` | 5 | Minimum sentence characters |
157
+ | `max_sentence_len` | 512 | Maximum sentence characters |
158
+ | `output_dir` | `hf_dataset/output` | Output directory |
159
+ | `cache_dir` | `hf_dataset/.cache` | Cache directory |
160
+ | `hf_dataset_name` | `HuggingFaceFW/fineweb` | Source dataset |
161
+ | `spacy_model` | `en_core_web_sm` | spaCy model name |
162
+ | `xlnet_model` | `xlnet/xlnet-base-cased` | HuggingFace model path |
163
+
164
+ ## Cache
165
+
166
+ The generator tracks processed samples in `cache_dir/processed_ids.json` to avoid duplicates and enable resuming interrupted runs.
167
+
168
+ ## Notes
169
+
170
+ - Sentences shorter than 5 characters are skipped
171
+ - Sentences longer than 512 characters are truncated
172
+ - Duplicates are detected via SHA256 hash
173
+ - Processsing is streamed from HuggingFace (memory efficient)
generate.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ UKS Seed Dataset Generator
3
+
4
+ Generates preprocessed training data from FineWeb dataset using:
5
+ - spaCy for linguistic features (POS, dependencies, lemmas, entities)
6
+ - XLNetTokenizer for subword tokenization
7
+
8
+ Outputs:
9
+ - pre_tokenized.jsonl.gz: Ready for model training
10
+ - intermediate.parquet: For exploration and custom tokenization
11
+ """
12
+
13
+ import gzip
14
+ import hashlib
15
+ import json
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Dict, Iterator, List, Optional
19
+
20
+ import spacy
21
+ from datasets import load_dataset
22
+ from transformers import XLNetTokenizer
23
+ from tqdm import tqdm
24
+
25
+
26
+ @dataclass
27
+ class SEEDConfig:
28
+ max_samples: int = 10000
29
+ batch_size: int = 100
30
+ min_sentence_len: int = 5
31
+ max_sentence_len: int = 512
32
+ output_dir: Path = Path(__file__).parent / "train"
33
+ cache_dir: Path = Path(__file__).parent / ".cache"
34
+ hf_dataset_name: str = "HuggingFaceFW/fineweb"
35
+ hf_dataset_split: str = "train"
36
+ spacy_model: str = "en_core_web_sm"
37
+ xlnet_model: str = "xlnet/xlnet-base-cased"
38
+
39
+
40
+ class SEEDDatasetGenerator:
41
+ def __init__(self, config: Optional[SEEDConfig] = None):
42
+ self.config = config or SEEDConfig()
43
+ self._nlp = None
44
+ self._tokenizer = None
45
+ self._processed_ids: set = set()
46
+
47
+ @property
48
+ def nlp(self):
49
+ if self._nlp is None:
50
+ try:
51
+ self._nlp = spacy.load(self.config.spacy_model)
52
+ except OSError:
53
+ import subprocess
54
+ import sys
55
+
56
+ print(f"Downloading spaCy model: {self.config.spacy_model}")
57
+ subprocess.run(
58
+ [
59
+ sys.executable,
60
+ "-m",
61
+ "spacy",
62
+ "download",
63
+ self.config.spacy_model,
64
+ ],
65
+ check=True,
66
+ )
67
+ self._nlp = spacy.load(self.config.spacy_model)
68
+ return self._nlp
69
+
70
+ @property
71
+ def tokenizer(self):
72
+ if self._tokenizer is None:
73
+ self._tokenizer = XLNetTokenizer.from_pretrained(self.config.xlnet_model)
74
+ return self._tokenizer
75
+
76
+ def _load_processed_ids(self) -> set:
77
+ cache_file = self.config.cache_dir / "processed_ids.json"
78
+ if cache_file.exists():
79
+ with open(cache_file, "r") as f:
80
+ return set(json.load(f))
81
+ return set()
82
+
83
+ def _save_processed_ids(self):
84
+ cache_file = self.config.cache_dir / "processed_ids.json"
85
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
86
+ with open(cache_file, "w") as f:
87
+ json.dump(list(self._processed_ids), f)
88
+
89
+ def _get_sample_id(self, text: str) -> str:
90
+ return hashlib.sha256(text.encode()).hexdigest()[:16]
91
+
92
+ def _load_fineweb(self) -> Iterator[Dict]:
93
+ dataset = load_dataset(
94
+ self.config.hf_dataset_name,
95
+ split=self.config.hf_dataset_split,
96
+ streaming=True,
97
+ )
98
+ for sample in dataset:
99
+ text = sample.get("text", "")
100
+ if text and len(text.strip()) > 0:
101
+ yield {
102
+ "id": sample.get("id", ""),
103
+ "text": text,
104
+ }
105
+
106
+ def _process_document(self, text: str) -> List[Dict]:
107
+ doc = self.nlp(text)
108
+ records = []
109
+
110
+ for sent in doc.sents:
111
+ sent_text = sent.text.strip()
112
+ if len(sent_text) < self.config.min_sentence_len:
113
+ continue
114
+ if len(sent_text) > self.config.max_sentence_len:
115
+ sent_text = sent_text[: self.config.max_sentence_len]
116
+
117
+ tokens = []
118
+ pos_tags = []
119
+ dep_tags = []
120
+ lemmas = []
121
+ ent_types = []
122
+ head_dists = []
123
+
124
+ for token in sent:
125
+ tokens.append(token.text)
126
+ pos_tags.append(token.pos_)
127
+ dep_tags.append(token.dep_)
128
+ lemmas.append(token.lemma_ if token.lemma_ else token.text)
129
+ ent_types.append(token.ent_type_ if token.ent_type_ else "O")
130
+ head_dists.append(token.head.i - token.i)
131
+
132
+ enc = self.tokenizer(
133
+ sent_text,
134
+ add_special_tokens=False,
135
+ truncation=True,
136
+ max_length=self.config.max_sentence_len,
137
+ )
138
+ token_ids = enc["input_ids"]
139
+
140
+ record = {
141
+ "id": self._get_sample_id(sent_text),
142
+ "text": sent_text,
143
+ "tokens": json.dumps(tokens),
144
+ "token_ids": json.dumps(token_ids),
145
+ "pos": json.dumps(pos_tags),
146
+ "dep": json.dumps(dep_tags),
147
+ "lemma": json.dumps(lemmas),
148
+ "ent_type": json.dumps(ent_types),
149
+ "head_dist": json.dumps(head_dists),
150
+ }
151
+ records.append(record)
152
+
153
+ return records
154
+
155
+ def generate(self) -> Dict[str, Path]:
156
+ self.config.output_dir.mkdir(parents=True, exist_ok=True)
157
+ self.config.cache_dir.mkdir(parents=True, exist_ok=True)
158
+ self._processed_ids = self._load_processed_ids()
159
+
160
+ jsonl_path = self.config.output_dir / "pre_tokenized.jsonl.gz"
161
+ parquet_path = self.config.output_dir / "intermediate.parquet"
162
+
163
+ jsonl_records: List[Dict] = []
164
+ all_records: List[Dict] = []
165
+
166
+ try:
167
+ import pyarrow as pa
168
+ import pyarrow.parquet as pq
169
+
170
+ has_pyarrow = True
171
+ except ImportError:
172
+ has_pyarrow = False
173
+ print("Warning: pyarrow not installed. Parquet output will be skipped.")
174
+ print("Install with: pip install pyarrow")
175
+
176
+ batch_buffer: List[str] = []
177
+ sample_count = 0
178
+ skipped_count = 0
179
+
180
+ print(f"Loading FineWeb from: {self.config.hf_dataset_name}")
181
+ print(f"Target samples: {self.config.max_samples}")
182
+
183
+ dataset = self._load_fineweb()
184
+
185
+ for sample in tqdm(dataset, desc="Processing documents"):
186
+ if sample_count >= self.config.max_samples:
187
+ break
188
+
189
+ sample_text = sample["text"]
190
+ if not sample_text:
191
+ continue
192
+
193
+ batch_buffer.append(sample_text)
194
+
195
+ if len(batch_buffer) >= self.config.batch_size:
196
+ texts = batch_buffer
197
+ batch_buffer = []
198
+
199
+ docs = list(self.nlp.pipe(texts, batch_size=len(texts)))
200
+
201
+ for doc in docs:
202
+ for sent in doc.sents:
203
+ sent_text = sent.text.strip()
204
+ if len(sent_text) < self.config.min_sentence_len:
205
+ continue
206
+ if len(sent_text) > self.config.max_sentence_len:
207
+ sent_text = sent_text[: self.config.max_sentence_len]
208
+
209
+ sample_id = self._get_sample_id(sent_text)
210
+ if sample_id in self._processed_ids:
211
+ skipped_count += 1
212
+ continue
213
+
214
+ self._processed_ids.add(sample_id)
215
+ sample_count += 1
216
+
217
+ tokens = []
218
+ pos_tags = []
219
+ dep_tags = []
220
+ lemmas = []
221
+ ent_types = []
222
+ head_dists = []
223
+
224
+ for token in sent:
225
+ tokens.append(token.text)
226
+ pos_tags.append(token.pos_)
227
+ dep_tags.append(token.dep_)
228
+ lemmas.append(token.lemma_ if token.lemma_ else token.text)
229
+ ent_types.append(
230
+ token.ent_type_ if token.ent_type_ else "O"
231
+ )
232
+ head_dists.append(token.head.i - token.i)
233
+
234
+ enc = self.tokenizer(
235
+ sent_text,
236
+ add_special_tokens=False,
237
+ truncation=True,
238
+ max_length=self.config.max_sentence_len,
239
+ )
240
+ token_ids = enc["input_ids"]
241
+
242
+ record = {
243
+ "id": sample_id,
244
+ "text": sent_text,
245
+ "tokens": json.dumps(tokens),
246
+ "token_ids": json.dumps(token_ids),
247
+ "pos": json.dumps(pos_tags),
248
+ "dep": json.dumps(dep_tags),
249
+ "lemma": json.dumps(lemmas),
250
+ "ent_type": json.dumps(ent_types),
251
+ "head_dist": json.dumps(head_dists),
252
+ }
253
+
254
+ jsonl_records.append(record)
255
+ all_records.append(record)
256
+
257
+ if sample_count >= self.config.max_samples:
258
+ break
259
+ if sample_count >= self.config.max_samples:
260
+ break
261
+
262
+ if sample_count % 1000 == 0 and jsonl_records:
263
+ self._write_jsonl(jsonl_records, jsonl_path, append=True)
264
+ jsonl_records = []
265
+ self._save_processed_ids()
266
+
267
+ if jsonl_records:
268
+ self._write_jsonl(jsonl_records, jsonl_path, append=True)
269
+
270
+ if has_pyarrow and all_records:
271
+ self._write_parquet(all_records, parquet_path)
272
+
273
+ self._save_processed_ids()
274
+
275
+ print(f"\n=== Generation Complete ===")
276
+ print(f"Total samples: {sample_count}")
277
+ print(f"Skipped (duplicates): {skipped_count}")
278
+ print(f"Output files:")
279
+ print(f" - {jsonl_path}")
280
+ if has_pyarrow:
281
+ print(f" - {parquet_path}")
282
+
283
+ return {
284
+ "jsonl": jsonl_path,
285
+ "parquet": parquet_path if has_pyarrow else None,
286
+ }
287
+
288
+ def _write_jsonl(self, records: List[Dict], path: Path, append: bool = False):
289
+ mode = "ab" if append else "wb"
290
+ with gzip.open(path, mode) as f:
291
+ for record in records:
292
+ f.write((json.dumps(record) + "\n").encode())
293
+
294
+ def _write_parquet(self, records: List[Dict], path: Path):
295
+ try:
296
+ import pyarrow as pa
297
+ import pyarrow.parquet as pq
298
+
299
+ if not records:
300
+ return
301
+
302
+ keys = list(records[0].keys())
303
+ arrays = []
304
+ for key in keys:
305
+ arrays.append(
306
+ pa.array([r.get(key, "") for r in records], type=pa.string())
307
+ )
308
+
309
+ schema = pa.schema(zip(keys, [pa.string() for _ in keys]))
310
+ table = pa.table(dict(zip(keys, arrays)), schema=schema)
311
+ pq.write_table(table, path)
312
+ except ImportError:
313
+ print("Skipping parquet output (pyarrow not available)")
314
+
315
+
316
+ def main():
317
+ import argparse
318
+
319
+ parser = argparse.ArgumentParser(description="Generate UKS Seed Dataset")
320
+ parser.add_argument(
321
+ "--max-samples", type=int, default=10000, help="Maximum number of samples"
322
+ )
323
+ parser.add_argument(
324
+ "--batch-size", type=int, default=100, help="Batch size for processing"
325
+ )
326
+ parser.add_argument("--output-dir", type=str, default=None, help="Output directory")
327
+ parser.add_argument("--cache-dir", type=str, default=None, help="Cache directory")
328
+ args = parser.parse_args()
329
+
330
+ config = SEEDConfig(
331
+ max_samples=args.max_samples,
332
+ batch_size=args.batch_size,
333
+ )
334
+ if args.output_dir:
335
+ config.output_dir = Path(args.output_dir)
336
+ if args.cache_dir:
337
+ config.cache_dir = Path(args.cache_dir)
338
+
339
+ generator = SEEDDatasetGenerator(config)
340
+ generator.generate()
341
+
342
+
343
+ if __name__ == "__main__":
344
+ main()