Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/dataset.py # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / dataset.py` 1221 lines · 42988 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """MojoLlama Dataset Pipeline — formats, streaming, auto-labeling, stats. 3 4 Supports: 5 - Alpaca (instruction/input/output) 6 - ShareGPT (conversations array) 7 - OpenAI (messages format) 8 - Preference (chosen/rejected pairs for DPO/ORPO/KTO) 9 - Streaming (generator-based, memory-mapped, HF datasets) 10 - Auto-labeling with confidence scoring and batch processing 11 - Format detection, conversion, and statistics 12 """ 13 14 import os 15 import json 16 import gzip 17 import math 18 import time 19 import queue 20 import struct 21 import hashlib 22 import threading 23 import collections 24 from pathlib import Path 25 from typing import ( 26 Any, Callable, Dict, Generator, Iterator, List, Optional, 27 Tuple, Union, 28 ) 29 30 import numpy as np 31 32 # ─── Format Constants ─────────────────────────────────────────────────── 33 34 FORMAT_ALPACA = "alpaca" 35 FORMAT_SHAREGPT = "sharegpt" 36 FORMAT_OPENAI = "openai" 37 FORMAT_PREFERENCE = "preference" 38 FORMAT_JSONL = "jsonl" 39 40 ALL_FORMATS = [FORMAT_ALPACA, FORMAT_SHAREGPT, FORMAT_OPENAI, FORMAT_PREFERENCE, FORMAT_JSONL] 41 TRAINING_FORMATS = [FORMAT_ALPACA, FORMAT_SHAREGPT, FORMAT_OPENAI, FORMAT_PREFERENCE] 42 43 FORMAT_DESCRIPTIONS = { 44 FORMAT_ALPACA: "Alpaca (instruction/input/output)", 45 FORMAT_SHAREGPT: "ShareGPT (conversations array with roles)", 46 FORMAT_OPENAI: "OpenAI (messages with system/user/assistant)", 47 FORMAT_PREFERENCE: "Preference (chosen/rejected for DPO/ORPO/KTO)", 48 FORMAT_JSONL: "Simple JSONL (key-value pairs)", 49 } 50 51 52 # ─── Dataset Entry Types ──────────────────────────────────────────────── 53 54 class DatasetEntry: 55 """Normalized dataset entry — the canonical internal format.""" 56 57 def __init__( 58 self, 59 source_format: str = FORMAT_JSONL, 60 prompt: str = "", 61 completion: str = "", 62 instruction: str = "", 63 input_text: str = "", 64 output: str = "", 65 system: str = "", 66 messages: Optional[List[Dict[str, str]]] = None, 67 conversations: Optional[List[Dict[str, str]]] = None, 68 chosen: Optional[List[Dict[str, str]]] = None, 69 rejected: Optional[List[Dict[str, str]]] = None, 70 metadata: Optional[Dict[str, Any]] = None, 71 ): 72 self.source_format = source_format 73 self.prompt = prompt 74 self.completion = completion 75 self.instruction = instruction 76 self.input_text = input_text 77 self.output = output 78 self.system = system 79 self.messages = messages or [] 80 self.conversations = conversations or [] 81 self.chosen = chosen or [] 82 self.rejected = rejected or [] 83 self.metadata = metadata or {} 84 85 def token_count(self, tokenizer: Optional[Callable[[str], int]] = None) -> int: 86 """Estimate token count. If tokenizer provided, use it; else char-based estimate.""" 87 text = self.get_text() 88 if tokenizer: 89 return tokenizer(text) 90 return len(text) // 4 # rough estimate: ~4 chars per token 91 92 def get_text(self) -> str: 93 """Get the full text of this entry for tokenization.""" 94 parts = [] 95 if self.system: 96 parts.append(self.system) 97 if self.instruction: 98 parts.append(self.instruction) 99 if self.input_text: 100 parts.append(self.input_text) 101 if self.prompt: 102 parts.append(self.prompt) 103 if self.output: 104 parts.append(self.output) 105 if self.completion: 106 parts.append(self.completion) 107 for m in self.messages: 108 parts.append(m.get("content", "")) 109 for c in self.conversations: 110 parts.append(c.get("value", "")) 111 for m in self.chosen: 112 parts.append(m.get("content", "")) 113 for m in self.rejected: 114 parts.append(m.get("content", "")) 115 return "\n".join(parts) 116 117 def to_dict(self) -> Dict[str, Any]: 118 """Serialize to dict for JSON output.""" 119 d = {"source_format": self.source_format} 120 for k in ["prompt", "completion", "instruction", "input_text", 121 "output", "system"]: 122 v = getattr(self, k) 123 if v: 124 d[k] = v 125 if self.messages: 126 d["messages"] = self.messages 127 if self.conversations: 128 d["conversations"] = self.conversations 129 if self.chosen: 130 d["chosen"] = self.chosen 131 if self.rejected: 132 d["rejected"] = self.rejected 133 if self.metadata: 134 d["metadata"] = self.metadata 135 return d 136 137 138 # ─── Format Detection ────────────────────────────────────────────────── 139 140 def detect_format(path: str, sample_lines: int = 5) -> Optional[str]: 141 """Detect dataset format from file extension and content.""" 142 path_lower = path.lower() 143 144 # Extension-based hints 145 if path_lower.endswith(".parquet"): 146 return FORMAT_JSONL # treat as generic; needs special reader 147 148 # Read first few lines 149 try: 150 lines = _read_head(path, sample_lines) 151 except (FileNotFoundError, IOError, json.JSONDecodeError) as e: 152 raise ValueError(f"Cannot read dataset {path}: {e}") 153 154 if not lines: 155 return FORMAT_JSONL 156 157 # Analyze content patterns across lines 158 formats = {} 159 for line in lines: 160 try: 161 data = json.loads(line) if isinstance(line, str) else line 162 except json.JSONDecodeError: 163 continue 164 165 for fmt in TRAINING_FORMATS: 166 score = _detect_format_in_entry(data, fmt) 167 if fmt not in formats: 168 formats[fmt] = 0 169 formats[fmt] += score 170 171 if not formats: 172 return FORMAT_JSONL 173 174 # Return format with highest total score 175 best = max(formats, key=formats.get) 176 return best if formats[best] > 0 else FORMAT_JSONL 177 178 179 def _read_head(path: str, n: int = 5) -> List[Union[str, Dict]]: 180 """Read first n lines/entries from a dataset file.""" 181 entries = [] 182 183 if path.endswith(".gz"): 184 import gzip 185 with gzip.open(path, "rt", encoding="utf-8", errors="replace") as f: 186 for i, line in enumerate(f): 187 if i >= n: 188 break 189 line = line.strip() 190 if line: 191 entries.append(line) 192 else: 193 with open(path, "r", encoding="utf-8", errors="replace") as f: 194 for i, line in enumerate(f): 195 if i >= n: 196 break 197 line = line.strip() 198 if line: 199 entries.append(line) 200 201 return entries 202 203 204 def _detect_format_in_entry(data: Dict, fmt: str) -> int: 205 """Score an entry for a given format. Higher = more likely.""" 206 score = 0 207 208 if fmt == FORMAT_ALPACA: 209 if "instruction" in data: 210 score += 3 211 if "output" in data and "instruction" in data: 212 score += 2 213 if "input" in data and "output" in data: 214 score += 1 215 216 elif fmt == FORMAT_SHAREGPT: 217 if "conversations" in data: 218 convs = data["conversations"] 219 if isinstance(convs, list) and len(convs) > 0: 220 score += 3 221 if isinstance(convs[0], dict): 222 if "from" in convs[0] or "role" in convs[0]: 223 score += 2 224 if "value" in convs[0] or "content" in convs[0]: 225 score += 1 226 227 elif fmt == FORMAT_OPENAI: 228 if "messages" in data: 229 msgs = data["messages"] 230 if isinstance(msgs, list) and len(msgs) > 0: 231 score += 3 232 if isinstance(msgs[0], dict): 233 if "role" in msgs[0] and "content" in msgs[0]: 234 score += 3 235 # Check for system role 236 roles = {m.get("role", "") for m in msgs} 237 if roles & {"system", "user", "assistant"}: 238 score += 2 239 240 elif fmt == FORMAT_PREFERENCE: 241 if "chosen" in data: 242 chosen = data["chosen"] 243 if isinstance(chosen, list) and len(chosen) > 0: 244 score += 3 245 if "rejected" in data: 246 rejected = data["rejected"] 247 if isinstance(rejected, list) and len(rejected) > 0: 248 score += 3 249 if "chosen" in data and "rejected" in data: 250 score += 2 251 # Multi-turn preference (list of messages in chosen/rejected) 252 if "chosen" in data and isinstance(data["chosen"], list): 253 if len(data["chosen"]) > 0 and isinstance(data["chosen"][0], dict): 254 if "content" in data["chosen"][0]: 255 score += 1 256 257 return score 258 259 260 # ─── Readers ──────────────────────────────────────────────────────────── 261 262 class BaseReader: 263 """Base class for format-specific readers.""" 264 265 def __init__(self, path: str, stream: bool = False, max_samples: Optional[int] = None): 266 self.path = path 267 self.stream = stream 268 self.max_samples = max_samples 269 270 def read(self) -> List[DatasetEntry]: 271 """Read all entries into memory.""" 272 raise NotImplementedError 273 274 def stream_entries(self) -> Generator[DatasetEntry, None, None]: 275 """Stream entries one by one (memory efficient).""" 276 raise NotImplementedError 277 278 279 class JSONLReader(BaseReader): 280 """Reads simple JSONL (key-value pairs).""" 281 282 def read(self) -> List[DatasetEntry]: 283 entries = [] 284 for entry in self.stream_entries(): 285 entries.append(entry) 286 if self.max_samples and len(entries) >= self.max_samples: 287 break 288 return entries 289 290 def stream_entries(self) -> Generator[DatasetEntry, None, None]: 291 open_fn = gzip.open if self.path.endswith(".gz") else open 292 with open_fn(self.path, "rt", encoding="utf-8", errors="replace") as f: 293 for line in f: 294 line = line.strip() 295 if not line: 296 continue 297 try: 298 data = json.loads(line) 299 except json.JSONDecodeError: 300 continue 301 302 entry = DatasetEntry( 303 source_format=FORMAT_JSONL, 304 prompt=data.get("prompt", ""), 305 completion=data.get("completion", ""), 306 instruction=data.get("instruction", ""), 307 input_text=data.get("input", ""), 308 output=data.get("output", ""), 309 system=data.get("system", ""), 310 messages=data.get("messages", []), 311 conversations=data.get("conversations", []), 312 chosen=data.get("chosen", []), 313 rejected=data.get("rejected", []), 314 metadata={k: v for k, v in data.items() 315 if k not in ("prompt", "completion", "instruction", 316 "input", "output", "system", "messages", 317 "conversations", "chosen", "rejected")}, 318 ) 319 yield entry 320 if self.max_samples: 321 self.max_samples -= 1 322 if self.max_samples <= 0: 323 break 324 325 326 class AlpacaReader(BaseReader): 327 """Reads Alpaca format (instruction/input/output).""" 328 329 def read(self) -> List[DatasetEntry]: 330 entries = [] 331 for entry in self.stream_entries(): 332 entries.append(entry) 333 if self.max_samples and len(entries) >= self.max_samples: 334 break 335 return entries 336 337 def stream_entries(self) -> Generator[DatasetEntry, None, None]: 338 open_fn = gzip.open if self.path.endswith(".gz") else open 339 with open_fn(self.path, "rt", encoding="utf-8", errors="replace") as f: 340 for line in f: 341 line = line.strip() 342 if not line: 343 continue 344 try: 345 data = json.loads(line) 346 except json.JSONDecodeError: 347 continue 348 349 entry = DatasetEntry( 350 source_format=FORMAT_ALPACA, 351 instruction=data.get("instruction", ""), 352 input_text=data.get("input", ""), 353 output=data.get("output", ""), 354 ) 355 yield entry 356 if self.max_samples: 357 self.max_samples -= 1 358 if self.max_samples <= 0: 359 break 360 361 362 class ShareGPTReader(BaseReader): 363 """Reads ShareGPT format (conversations array).""" 364 365 def read(self) -> List[DatasetEntry]: 366 entries = [] 367 for entry in self.stream_entries(): 368 entries.append(entry) 369 if self.max_samples and len(entries) >= self.max_samples: 370 break 371 return entries 372 373 def stream_entries(self) -> Generator[DatasetEntry, None, None]: 374 open_fn = gzip.open if self.path.endswith(".gz") else open 375 with open_fn(self.path, "rt", encoding="utf-8", errors="replace") as f: 376 for line in f: 377 line = line.strip() 378 if not line: 379 continue 380 try: 381 data = json.loads(line) 382 except json.JSONDecodeError: 383 continue 384 385 conversations = data.get("conversations", []) 386 entry = DatasetEntry( 387 source_format=FORMAT_SHAREGPT, 388 conversations=conversations, 389 ) 390 yield entry 391 if self.max_samples: 392 self.max_samples -= 1 393 if self.max_samples <= 0: 394 break 395 396 397 class OpenAIReader(BaseReader): 398 """Reads OpenAI messages format.""" 399 400 def read(self) -> List[DatasetEntry]: 401 entries = [] 402 for entry in self.stream_entries(): 403 entries.append(entry) 404 if self.max_samples and len(entries) >= self.max_samples: 405 break 406 return entries 407 408 def stream_entries(self) -> Generator[DatasetEntry, None, None]: 409 open_fn = gzip.open if self.path.endswith(".gz") else open 410 with open_fn(self.path, "rt", encoding="utf-8", errors="replace") as f: 411 for line in f: 412 line = line.strip() 413 if not line: 414 continue 415 try: 416 data = json.loads(line) 417 except json.JSONDecodeError: 418 continue 419 420 messages = data.get("messages", []) 421 # Extract system message if present 422 system = "" 423 for m in messages: 424 if m.get("role") == "system": 425 system = m.get("content", "") 426 break 427 428 entry = DatasetEntry( 429 source_format=FORMAT_OPENAI, 430 messages=messages, 431 system=system, 432 ) 433 yield entry 434 if self.max_samples: 435 self.max_samples -= 1 436 if self.max_samples <= 0: 437 break 438 439 440 class PreferenceReader(BaseReader): 441 """Reads preference format (chosen/rejected for DPO/ORPO/KTO).""" 442 443 def read(self) -> List[DatasetEntry]: 444 entries = [] 445 for entry in self.stream_entries(): 446 entries.append(entry) 447 if self.max_samples and len(entries) >= self.max_samples: 448 break 449 return entries 450 451 def stream_entries(self) -> Generator[DatasetEntry, None, None]: 452 open_fn = gzip.open if self.path.endswith(".gz") else open 453 with open_fn(self.path, "rt", encoding="utf-8", errors="replace") as f: 454 for line in f: 455 line = line.strip() 456 if not line: 457 continue 458 try: 459 data = json.loads(line) 460 except json.JSONDecodeError: 461 continue 462 463 chosen = data.get("chosen", []) 464 rejected = data.get("rejected", []) 465 466 entry = DatasetEntry( 467 source_format=FORMAT_PREFERENCE, 468 chosen=chosen, 469 rejected=rejected, 470 ) 471 yield entry 472 if self.max_samples: 473 self.max_samples -= 1 474 if self.max_samples <= 0: 475 break 476 477 478 # ─── Reader Factory ──────────────────────────────────────────────────── 479 480 def get_reader( 481 path: str, 482 format: Optional[str] = None, 483 stream: bool = False, 484 max_samples: Optional[int] = None, 485 ) -> BaseReader: 486 """Get the appropriate reader for a dataset.""" 487 if format is None: 488 format = detect_format(path) 489 490 readers = { 491 FORMAT_ALPACA: AlpacaReader, 492 FORMAT_SHAREGPT: ShareGPTReader, 493 FORMAT_OPENAI: OpenAIReader, 494 FORMAT_PREFERENCE: PreferenceReader, 495 FORMAT_JSONL: JSONLReader, 496 } 497 498 reader_cls = readers.get(format) 499 if reader_cls is None: 500 raise ValueError(f"Unknown format: {format}. Supported: {list(readers.keys())}") 501 502 return reader_cls(path, stream=stream, max_samples=max_samples) 503 504 505 # ─── Converters ──────────────────────────────────────────────────────── 506 507 def convert_dataset( 508 input_path: str, 509 output_path: str, 510 target_format: str = FORMAT_OPENAI, 511 input_format: Optional[str] = None, 512 max_samples: Optional[int] = None, 513 ) -> Dict[str, Any]: 514 """Convert a dataset from one format to another.""" 515 reader = get_reader(input_path, format=input_format) 516 entries = reader.read() 517 518 if max_samples and len(entries) > max_samples: 519 entries = entries[:max_samples] 520 521 converted = [] 522 for entry in entries: 523 converted.append(_convert_entry(entry, target_format)) 524 525 # Write output 526 with open(output_path, "w", encoding="utf-8") as f: 527 for item in converted: 528 f.write(json.dumps(item, ensure_ascii=False) + "\n") 529 530 return { 531 "input_path": input_path, 532 "output_path": output_path, 533 "input_format": input_format or detect_format(input_path), 534 "output_format": target_format, 535 "samples": len(converted), 536 } 537 538 539 def _convert_entry(entry: DatasetEntry, target_format: str) -> Dict[str, Any]: 540 """Convert a single entry to target format.""" 541 if target_format == FORMAT_ALPACA: 542 if entry.messages: 543 return _messages_to_alpaca(entry.messages) 544 if entry.conversations: 545 return _conversations_to_alpaca(entry.conversations) 546 return { 547 "instruction": entry.instruction or entry.prompt, 548 "input": entry.input_text, 549 "output": entry.output or entry.completion, 550 } 551 552 elif target_format == FORMAT_SHAREGPT: 553 if entry.messages: 554 return _messages_to_sharegpt(entry.messages) 555 if entry.conversations: 556 return {"conversations": entry.conversations} 557 # Default: wrap as single-turn 558 return { 559 "conversations": [ 560 {"from": "human", "value": entry.instruction or entry.prompt}, 561 {"from": "gpt", "value": entry.output or entry.completion}, 562 ] 563 } 564 565 elif target_format == FORMAT_OPENAI: 566 if entry.messages: 567 return {"messages": entry.messages} 568 if entry.conversations: 569 return _conversations_to_openai(entry.conversations) 570 # Build from fields 571 msgs = [] 572 if entry.system: 573 msgs.append({"role": "system", "content": entry.system}) 574 msgs.append({ 575 "role": "user", 576 "content": entry.instruction or entry.prompt, 577 }) 578 if entry.input_text: 579 msgs[-1]["content"] += "\n\n" + entry.input_text 580 if entry.output or entry.completion: 581 msgs.append({ 582 "role": "assistant", 583 "content": entry.output or entry.completion, 584 }) 585 return {"messages": msgs} 586 587 elif target_format == FORMAT_PREFERENCE: 588 if entry.chosen and entry.rejected: 589 return {"chosen": entry.chosen, "rejected": entry.rejected} 590 # Can't convert without preference data 591 return {"chosen": [], "rejected": []} 592 593 else: 594 # Default: raw dict 595 return entry.to_dict() 596 597 598 def _messages_to_alpaca(messages: List[Dict[str, str]]) -> Dict[str, str]: 599 """Convert OpenAI messages to Alpaca format.""" 600 instr = "" 601 output = "" 602 input_text = "" 603 for m in messages: 604 if m.get("role") == "system": 605 instr = m.get("content", "") 606 elif m.get("role") == "user": 607 if not instr: 608 instr = m.get("content", "") 609 else: 610 input_text = m.get("content", "") 611 elif m.get("role") == "assistant": 612 output = m.get("content", "") 613 return {"instruction": instr, "input": input_text, "output": output} 614 615 616 def _conversations_to_alpaca(convs: List[Dict[str, str]]) -> Dict[str, str]: 617 """Convert ShareGPT conversations to Alpaca format.""" 618 instr = "" 619 output = "" 620 for c in convs: 621 role = c.get("from", c.get("role", "")) 622 val = c.get("value", c.get("content", "")) 623 if role in ("human", "user"): 624 instr = val 625 elif role in ("gpt", "assistant"): 626 output = val 627 return {"instruction": instr, "input": "", "output": output} 628 629 630 def _messages_to_sharegpt(messages: List[Dict[str, str]]) -> Dict[str, Any]: 631 """Convert OpenAI messages to ShareGPT format.""" 632 role_map = {"user": "human", "assistant": "gpt", "system": "system"} 633 convs = [] 634 for m in messages: 635 role = role_map.get(m.get("role", ""), m.get("role", "")) 636 convs.append({"from": role, "value": m.get("content", "")}) 637 return {"conversations": convs} 638 639 640 def _conversations_to_openai(convs: List[Dict[str, str]]) -> Dict[str, Any]: 641 """Convert ShareGPT conversations to OpenAI messages format.""" 642 role_map = {"human": "user", "gpt": "assistant", "system": "system"} 643 msgs = [] 644 for c in convs: 645 role = role_map.get(c.get("from", ""), c.get("role", "user")) 646 msgs.append({"role": role, "content": c.get("value", c.get("content", ""))}) 647 return {"messages": msgs} 648 649 650 # ─── Streaming Dataset ───────────────────────────────────────────────── 651 652 class StreamingDataset: 653 """Lazy-load datasets larger than RAM using generator-based iteration. 654 655 Supports: 656 - JSONL streaming (line-by-line) 657 - GZip compressed JSONL 658 - HuggingFace datasets streaming 659 - Memory-mapped reading for fixed-size records 660 """ 661 662 def __init__( 663 self, 664 path: str, 665 format: Optional[str] = None, 666 buffer_size: int = 1000, 667 ): 668 self.path = path 669 self.format = format or detect_format(path) 670 self.buffer_size = buffer_size 671 self._reader = get_reader(path, format=self.format) 672 self._cache: List[DatasetEntry] = [] 673 self._generator = self._reader.stream_entries() 674 self._exhausted = False 675 676 def __len__(self) -> int: 677 """Return total sample count (reads entire file if not cached).""" 678 if hasattr(self, "_total_samples"): 679 return self._total_samples 680 count = 0 681 for _ in self.stream_entries(): 682 count += 1 683 if count > 100_000: 684 # Don't count beyond 100K for large datasets 685 self._total_samples_approx = True 686 return count 687 self._total_samples = count 688 self._total_samples_approx = False 689 return count 690 691 def __iter__(self) -> Iterator[DatasetEntry]: 692 return self.stream_entries() 693 694 def __getitem__(self, idx: int) -> DatasetEntry: 695 """Random access by index (reads up to index if needed).""" 696 if idx < len(self._cache): 697 return self._cache[idx] 698 699 # Fast-forward generator 700 for entry in self._generator: 701 self._cache.append(entry) 702 if len(self._cache) > idx: 703 return entry 704 705 raise IndexError(f"Index {idx} out of range ({len(self._cache)} entries)") 706 707 def stream_entries(self) -> Generator[DatasetEntry, None, None]: 708 """Stream all entries, yielding cached ones first.""" 709 # Yield cached entries 710 yield from self._cache 711 712 # Stream new entries 713 for entry in self._generator: 714 self._cache.append(entry) 715 yield entry 716 717 self._exhausted = True 718 719 def batch(self, batch_size: int) -> Generator[List[DatasetEntry], None, None]: 720 """Yield batches of entries.""" 721 batch = [] 722 for entry in self.stream_entries(): 723 batch.append(entry) 724 if len(batch) >= batch_size: 725 yield batch 726 batch = [] 727 if batch: 728 yield batch 729 730 def count_lines(self) -> int: 731 """Quick line count without parsing JSON.""" 732 count = 0 733 open_fn = gzip.open if self.path.endswith(".gz") else open 734 with open_fn(self.path, "rt", encoding="utf-8", errors="replace") as f: 735 for line in f: 736 if line.strip(): 737 count += 1 738 return count 739 740 def reset(self): 741 """Reset the stream (re-reads from file).""" 742 self._cache = [] 743 self._reader = get_reader(self.path, format=self.format) 744 self._generator = self._reader.stream_entries() 745 self._exhausted = False 746 747 748 def load_hf_dataset( 749 path: str, 750 split: str = "train", 751 streaming: bool = True, 752 max_samples: Optional[int] = None, 753 ) -> "StreamingDataset": 754 """Load a dataset from HuggingFace hub or local path.""" 755 try: 756 import datasets 757 except ImportError: 758 raise ImportError( 759 "HuggingFace datasets library required. Install: pip install datasets" 760 ) 761 762 ds = datasets.load_dataset( 763 path, 764 split=split, 765 streaming=streaming, 766 ) 767 768 if max_samples: 769 ds = ds.take(max_samples) 770 771 # Convert to streaming JSONL adapter 772 hf_path = _hf_to_temp_jsonl(ds, max_samples=max_samples) 773 return StreamingDataset(hf_path, format=FORMAT_JSONL) 774 775 776 def _hf_to_temp_jsonl(ds, max_samples: Optional[int] = None) -> str: 777 """Write HF dataset samples to a temporary JSONL for the reader pipeline.""" 778 import tempfile 779 f = tempfile.NamedTemporaryFile( 780 mode="w", suffix=".jsonl", delete=False, encoding="utf-8" 781 ) 782 count = 0 783 for sample in ds: 784 f.write(json.dumps(sample, ensure_ascii=False) + "\n") 785 count += 1 786 if max_samples and count >= max_samples: 787 break 788 f.close() 789 return f.name 790 791 792 # ─── Auto-Labeling ───────────────────────────────────────────────────── 793 794 class AutoLabeler: 795 """Auto-generate completions using a language model. 796 797 Supports: 798 - Single-prompt completion 799 - Batch processing with configurable concurrency 800 - Confidence scoring based on logprobs 801 - Multi-model comparison 802 """ 803 804 def __init__( 805 self, 806 api_base: str = "http://127.0.0.1:9000", 807 model: str = "", 808 max_tokens: int = 256, 809 temperature: float = 0.7, 810 top_p: float = 0.9, 811 presence_penalty: float = 0.0, 812 frequency_penalty: float = 0.0, 813 timeout: int = 120, 814 ): 815 self.api_base = api_base.rstrip("/") 816 self.model = model 817 self.max_tokens = max_tokens 818 self.temperature = temperature 819 self.top_p = top_p 820 self.presence_penalty = presence_penalty 821 self.frequency_penalty = frequency_penalty 822 self.timeout = timeout 823 824 def generate(self, prompt: str, system: str = "") -> Dict[str, Any]: 825 """Generate a completion for a single prompt.""" 826 messages = [] 827 if system: 828 messages.append({"role": "system", "content": system}) 829 messages.append({"role": "user", "content": prompt}) 830 831 return self._call_api(messages) 832 833 def _call_api(self, messages: List[Dict[str, str]]) -> Dict[str, Any]: 834 """Call the OpenAI-compatible API.""" 835 import urllib.request 836 837 data = json.dumps({ 838 "messages": messages, 839 "max_tokens": self.max_tokens, 840 "temperature": self.temperature, 841 "top_p": self.top_p, 842 "presence_penalty": self.presence_penalty, 843 "frequency_penalty": self.frequency_penalty, 844 }).encode() 845 846 req = urllib.request.Request( 847 f"{self.api_base}/v1/chat/completions", 848 data=data, 849 headers={"Content-Type": "application/json"}, 850 ) 851 852 try: 853 with urllib.request.urlopen(req, timeout=self.timeout) as resp: 854 result = json.loads(resp.read()) 855 856 choice = result.get("choices", [{}])[0] 857 message = choice.get("message", {}) 858 logprobs = choice.get("logprobs", None) 859 860 return { 861 "text": message.get("content", ""), 862 "finish_reason": choice.get("finish_reason", ""), 863 "logprobs": logprobs, 864 "usage": result.get("usage", {}), 865 "success": True, 866 } 867 except Exception as e: 868 return { 869 "text": "", 870 "finish_reason": "error", 871 "error": str(e), 872 "success": False, 873 } 874 875 def label_entry(self, entry: DatasetEntry) -> DatasetEntry: 876 """Generate completion for an entry.""" 877 prompt = entry.instruction or entry.prompt 878 if not prompt and entry.conversations: 879 # Take the last user message 880 for c in reversed(entry.conversations): 881 if c.get("from") in ("human", "user"): 882 prompt = c.get("value", "") 883 break 884 885 if not prompt and entry.messages: 886 for m in reversed(entry.messages): 887 if m.get("role") == "user": 888 prompt = m.get("content", "") 889 break 890 891 if not prompt: 892 return entry 893 894 result = self.generate(prompt, system=entry.system) 895 entry.completion = result.get("text", "") 896 entry.metadata["labeling"] = { 897 "success": result.get("success", False), 898 "finish_reason": result.get("finish_reason", ""), 899 "tokens": result.get("usage", {}).get("completion_tokens", 0), 900 "error": result.get("error"), 901 } 902 return entry 903 904 def label_batch( 905 self, 906 entries: List[DatasetEntry], 907 batch_size: int = 4, 908 callback: Optional[Callable[[int, int], None]] = None, 909 ) -> List[DatasetEntry]: 910 """Label entries in batches, optionally with parallelism.""" 911 results = [] 912 total = len(entries) 913 914 for i in range(0, total, batch_size): 915 batch = entries[i:i + batch_size] 916 thread_results = [None] * len(batch) 917 threads = [] 918 919 def _label(idx: int, entry: DatasetEntry, result_list: List, pos: int): 920 result_list[pos] = self.label_entry(entry) 921 922 for j, entry in enumerate(batch): 923 t = threading.Thread( 924 target=_label, 925 args=(j, entry, thread_results, j), 926 daemon=True, 927 ) 928 t.start() 929 threads.append(t) 930 931 for t in threads: 932 t.join(timeout=self.timeout + 10) 933 934 results.extend(thread_results) 935 936 if callback: 937 callback(i + len(batch), total) 938 939 return results 940 941 942 def compute_confidence(entry: DatasetEntry) -> float: 943 """Compute a confidence score for an auto-labeled entry. 944 945 Uses logprobs if available, otherwise heuristics based on 946 completion length and content diversity. 947 """ 948 logprobs = entry.metadata.get("labeling", {}).get("logprobs") 949 if logprobs: 950 # Average log probability as confidence 951 tokens = logprobs.get("tokens", []) 952 token_logprobs = logprobs.get("token_logprobs", []) 953 if token_logprobs: 954 avg_logprob = sum(token_logprobs) / len(token_logprobs) 955 # Convert to 0-1 scale: exp(avg_logprob / ln(2)) normalized 956 # At -0.5 nats → ~0.6, at -2.0 nats → ~0.13 957 return max(0.0, min(1.0, math.exp(avg_logprob))) 958 959 # Heuristic: length diversity 960 completion = entry.completion 961 if not completion: 962 return 0.0 963 964 # Unique token-ratio heuristic 965 words = completion.split() 966 if len(words) < 2: 967 return 0.3 968 969 unique_ratio = len(set(words)) / max(len(words), 1) 970 length_score = min(1.0, len(completion) / 500) 971 972 return 0.3 + 0.4 * unique_ratio + 0.3 * length_score 973 974 975 # ─── Dataset Statistics ───────────────────────────────────────────────── 976 977 class DatasetStats: 978 """Compute and store dataset statistics.""" 979 980 def __init__(self, entries: List[DatasetEntry]): 981 self.entries = entries 982 self.total_samples = len(entries) 983 self.total_tokens = 0 984 self.vocab = set() 985 self.lengths: List[int] = [] 986 self.prompt_lengths: List[int] = [] 987 self.completion_lengths: List[int] = [] 988 self.format_counts: Dict[str, int] = {} 989 self._compute() 990 991 def _compute(self): 992 """Compute all statistics.""" 993 for entry in self.entries: 994 text = entry.get_text() 995 length = len(text) 996 self.lengths.append(length) 997 self.prompt_lengths.append(len(entry.prompt or entry.instruction or "")) 998 self.completion_lengths.append(len(entry.completion or entry.output or "")) 999 self.vocab.update(text.lower().split()) 1000 1001 fmt = entry.source_format 1002 self.format_counts[fmt] = self.format_counts.get(fmt, 0) + 1 1003 1004 @property 1005 def avg_length(self) -> float: 1006 return np.mean(self.lengths) if self.lengths else 0.0 1007 1008 @property 1009 def median_length(self) -> float: 1010 return float(np.median(self.lengths)) if self.lengths else 0.0 1011 1012 @property 1013 def max_length(self) -> int: 1014 return max(self.lengths) if self.lengths else 0 1015 1016 @property 1017 def min_length(self) -> int: 1018 return min(self.lengths) if self.lengths else 0 1019 1020 @property 1021 def std_length(self) -> float: 1022 return float(np.std(self.lengths)) if self.lengths else 0.0 1023 1024 @property 1025 def vocab_size(self) -> int: 1026 return len(self.vocab) 1027 1028 @property 1029 def estimated_tokens(self) -> int: 1030 return sum(max(1, l // 4) for l in self.lengths) 1031 1032 @property 1033 def format_distribution(self) -> Dict[str, int]: 1034 return self.format_counts 1035 1036 def to_dict(self) -> Dict[str, Any]: 1037 return { 1038 "total_samples": self.total_samples, 1039 "estimated_tokens": self.estimated_tokens, 1040 "vocab_size": self.vocab_size, 1041 "length": { 1042 "mean": round(self.avg_length, 1), 1043 "median": round(self.median_length, 1), 1044 "std": round(self.std_length, 1), 1045 "min": self.min_length, 1046 "max": self.max_length, 1047 }, 1048 "prompt_length": { 1049 "mean": round(np.mean(self.prompt_lengths), 1) if self.prompt_lengths else 0, 1050 "median": round(float(np.median(self.prompt_lengths)), 1) if self.prompt_lengths else 0, 1051 }, 1052 "completion_length": { 1053 "mean": round(np.mean(self.completion_lengths), 1) if self.completion_lengths else 0, 1054 "median": round(float(np.median(self.completion_lengths)), 1) if self.completion_lengths else 0, 1055 }, 1056 "format_distribution": self.format_distribution, 1057 } 1058 1059 def length_distribution(self, bins: int = 10) -> Dict[str, Any]: 1060 """Get histogram of sample lengths.""" 1061 if not self.lengths: 1062 return {"bins": [], "counts": []} 1063 1064 hist, edges = np.histogram(self.lengths, bins=bins) 1065 return { 1066 "bins": [float(e) for e in edges], 1067 "counts": [int(c) for c in hist], 1068 } 1069 1070 1071 def compute_stats(entries: List[DatasetEntry]) -> DatasetStats: 1072 """Convenience function to compute dataset stats.""" 1073 return DatasetStats(entries) 1074 1075 1076 # ─── Dataset Metadata ───────────────────────────────────────────────── 1077 1078 def get_dataset_info(path: str) -> Dict[str, Any]: 1079 """Get comprehensive info about a dataset file.""" 1080 if not os.path.exists(path): 1081 return {"error": f"File not found: {path}"} 1082 1083 info = { 1084 "path": path, 1085 "name": os.path.basename(path), 1086 "size_bytes": os.path.getsize(path), 1087 "size_display": _format_size(os.path.getsize(path)), 1088 "modified": os.path.getmtime(path), 1089 } 1090 1091 # Detect format 1092 try: 1093 detected = detect_format(path) 1094 info["format"] = detected 1095 info["format_description"] = FORMAT_DESCRIPTIONS.get(detected, detected) 1096 except Exception as e: 1097 info["format"] = "unknown" 1098 info["format_error"] = str(e) 1099 1100 # Read samples 1101 reader = get_reader(path, format=info.get("format")) 1102 try: 1103 sample_entries = reader.read()[:3] 1104 info["samples_preview"] = [ 1105 entry.to_dict() for entry in sample_entries 1106 ] 1107 except Exception as e: 1108 info["samples_error"] = str(e) 1109 1110 # Count lines (quick) 1111 try: 1112 info["line_count"] = _count_lines(path) 1113 except Exception as e: 1114 info["line_count"] = 0 1115 1116 return info 1117 1118 1119 def _count_lines(path: str) -> int: 1120 """Quick line count.""" 1121 count = 0 1122 open_fn = gzip.open if path.endswith(".gz") else open 1123 with open_fn(path, "rt", encoding="utf-8", errors="replace") as f: 1124 for line in f: 1125 if line.strip(): 1126 count += 1 1127 return count 1128 1129 1130 def _format_size(size: int) -> str: 1131 """Format file size in human-readable form.""" 1132 for unit in ("B", "KB", "MB", "GB", "TB"): 1133 if size < 1024: 1134 return f"{size:.1f} {unit}" 1135 size /= 1024 1136 return f"{size:.1f} PB" 1137 1138 1139 # ─── File Discovery ──────────────────────────────────────────────────── 1140 1141 def find_datasets(directory: str = ".") -> List[Dict[str, Any]]: 1142 """Find all dataset files in a directory.""" 1143 datasets = [] 1144 dir_path = Path(directory).resolve() 1145 1146 patterns = ["*.jsonl", "*.jsonl.gz", "*.json", "*.json.gz"] 1147 1148 for pattern in patterns: 1149 for f in sorted(dir_path.glob(pattern)): 1150 # Filter out non-dataset files 1151 name = f.name.lower() 1152 if any(x in name for x in ("config", "tokenizer", "model", "training_args")): 1153 continue 1154 1155 try: 1156 fmt = detect_format(str(f)) 1157 except Exception: 1158 fmt = "unknown" 1159 1160 datasets.append({ 1161 "name": f.name, 1162 "path": str(f), 1163 "size_bytes": f.stat().st_size, 1164 "size_display": _format_size(f.stat().st_size), 1165 "format": fmt, 1166 "format_description": FORMAT_DESCRIPTIONS.get(fmt, fmt), 1167 }) 1168 1169 return datasets 1170 1171 1172 # ─── Dataset Splitting ───────────────────────────────────────────────── 1173 1174 def split_dataset( 1175 entries: List[DatasetEntry], 1176 train_ratio: float = 0.8, 1177 val_ratio: float = 0.1, 1178 test_ratio: float = 0.1, 1179 shuffle: bool = True, 1180 seed: int = 42, 1181 ) -> Dict[str, List[DatasetEntry]]: 1182 """Split dataset into train/val/test sets.""" 1183 total = len(entries) 1184 indices = list(range(total)) 1185 1186 if shuffle: 1187 rng = np.random.RandomState(seed) 1188 rng.shuffle(indices) 1189 1190 train_end = int(total * train_ratio) 1191 val_end = train_end + int(total * val_ratio) 1192 1193 return { 1194 "train": [entries[i] for i in indices[:train_end]], 1195 "val": [entries[i] for i in indices[train_end:val_end]], 1196 "test": [entries[i] for i in indices[val_end:]], 1197 } 1198 1199 1200 # ─── Utility Functions ───────────────────────────────────────────────── 1201 1202 def write_jsonl(entries: List[DatasetEntry], path: str, format: str = FORMAT_OPENAI): 1203 """Write entries to a JSONL file in the specified format.""" 1204 with open(path, "w", encoding="utf-8") as f: 1205 for entry in entries: 1206 converted = _convert_entry(entry, format) 1207 f.write(json.dumps(converted, ensure_ascii=False) + "\n") 1208 1209 1210 def load_dataset( 1211 path: str, 1212 format: Optional[str] = None, 1213 max_samples: Optional[int] = None, 1214 stream: bool = False, 1215 ) -> Union[List[DatasetEntry], StreamingDataset]: 1216 """Load a dataset, optionally streaming.""" 1217 if stream: 1218 return StreamingDataset(path, format=format) 1219 1220 reader = get_reader(path, format=format, max_samples=max_samples) 1221 return reader.read()