Download datasets/streaming.py from Ian26/MarsLM: direct link, hf CLI and curl.
- Browser
- Download file 6.78 kB
-
https://huggingface.co/Ian26/MarsLM/resolve/main/datasets/streaming.py
- Command line
-
hf download hf://Ian26/MarsLM/datasets/streaming.py
-
curl -L -o streaming.py https://huggingface.co/Ian26/MarsLM/resolve/main/datasets/streaming.py
6.78 kB
| import json | |
| from pathlib import Path | |
| from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Union | |
| from urllib.parse import urlparse | |
| import torch | |
| from torch.utils.data import IterableDataset | |
| try: | |
| import requests | |
| except ImportError: # type: ignore | |
| requests = None # type: ignore | |
| try: | |
| import datasets | |
| except ImportError: # type: ignore | |
| datasets = None # type: ignore | |
| def _read_text_lines(path: Path) -> Iterator[str]: | |
| with path.open("r", encoding="utf-8", errors="ignore") as handle: | |
| for line in handle: | |
| yield line.rstrip("\n") | |
| def _read_jsonl_lines(path: Path) -> Iterator[str]: | |
| with path.open("r", encoding="utf-8", errors="ignore") as handle: | |
| for line in handle: | |
| if not line.strip(): | |
| continue | |
| try: | |
| payload = json.loads(line) | |
| if isinstance(payload, dict): | |
| text = payload.get("text") or payload.get("content") or payload.get("sentence") | |
| if isinstance(text, str): | |
| yield text | |
| continue | |
| yield line.strip() | |
| except json.JSONDecodeError: | |
| yield line.strip() | |
| def _load_parquet_examples(path: Path) -> Iterator[str]: | |
| if datasets is None: | |
| raise RuntimeError("The datasets library is required to load Parquet datasets") | |
| dataset = datasets.load_dataset("parquet", data_files=str(path), split="train", streaming=True) | |
| for item in dataset: | |
| text = _extract_text(item) | |
| if text is not None: | |
| yield text | |
| continue | |
| yield str(item) | |
| def _is_http_url(source: str) -> bool: | |
| parsed = urlparse(source) | |
| return parsed.scheme in {"http", "https"} and bool(parsed.netloc) | |
| def _load_http_text(url: str) -> Iterator[str]: | |
| if requests is None: | |
| raise RuntimeError("The requests library is required to load text from HTTP URLs") | |
| with requests.get(url, stream=True, timeout=30) as response: | |
| response.raise_for_status() | |
| for line in response.iter_lines(decode_unicode=True): | |
| if not line: | |
| continue | |
| yield line.strip() | |
| def _extract_text(item: Any) -> Optional[str]: | |
| if isinstance(item, str): | |
| return item | |
| if not isinstance(item, dict): | |
| return None | |
| keys = [ | |
| "text", | |
| "content", | |
| "sentence", | |
| "article", | |
| "body", | |
| "document", | |
| "prompt", | |
| "completion", | |
| "source", | |
| "raw_text", | |
| ] | |
| for key in keys: | |
| value = item.get(key) | |
| if isinstance(value, str) and value.strip(): | |
| return value | |
| text_fields = [v for v in item.values() if isinstance(v, str) and v.strip()] | |
| if text_fields: | |
| return text_fields[0] | |
| return None | |
| def _load_hf_dataset(dataset_name: str, split: str = "train") -> Iterator[str]: | |
| if datasets is None: | |
| raise RuntimeError("The datasets library is required to load Hugging Face datasets") | |
| dataset = datasets.load_dataset(dataset_name, split=split, streaming=True) | |
| for item in dataset: | |
| text = _extract_text(item) | |
| if text is not None: | |
| yield text | |
| continue | |
| yield str(item) | |
| class MarsLMStreamingDataset(IterableDataset): | |
| def __init__( | |
| self, | |
| input_sources: Sequence[Union[str, Path]], | |
| tokenizer: Any, | |
| block_size: int = 512, | |
| use_special_tokens: bool = False, | |
| ): | |
| self.input_sources: List[Union[str, Path]] = [] | |
| for src in input_sources: | |
| if isinstance(src, str) and _is_http_url(src): | |
| self.input_sources.append(src) | |
| elif isinstance(src, Path): | |
| self.input_sources.append(src) | |
| else: | |
| try: | |
| candidate = Path(src) | |
| self.input_sources.append(candidate) | |
| except TypeError: | |
| self.input_sources.append(src) | |
| self.tokenizer = tokenizer | |
| self.block_size = block_size | |
| self.use_special_tokens = use_special_tokens | |
| def _iter_source(self, source: Path) -> Iterator[str]: | |
| if source.suffix == ".jsonl": | |
| yield from _read_jsonl_lines(source) | |
| elif source.suffix == ".parquet": | |
| yield from _load_parquet_examples(source) | |
| else: | |
| yield from _read_text_lines(source) | |
| def _iter_hf_dataset(self, source: str) -> Iterator[str]: | |
| yield from _load_hf_dataset(source) | |
| def _text_iterator(self) -> Iterator[str]: | |
| for source in self.input_sources: | |
| if isinstance(source, Path): | |
| if source.exists(): | |
| yield from self._iter_source(source) | |
| else: | |
| yield from self._iter_hf_dataset(source.as_posix()) | |
| elif isinstance(source, str) and _is_http_url(source): | |
| yield from _load_http_text(source) | |
| else: | |
| yield from self._iter_hf_dataset(source) | |
| def __iter__(self) -> Iterator[torch.Tensor]: | |
| buffer: List[int] = [] | |
| for text in self._text_iterator(): | |
| if not text: | |
| continue | |
| ids = self.tokenizer.encode(text, add_special_tokens=False).ids | |
| if self.use_special_tokens: | |
| bos_id = self.tokenizer.token_to_id("[BOS]") | |
| eos_id = self.tokenizer.token_to_id("[EOS]") | |
| if bos_id is not None: | |
| ids = [bos_id] + ids | |
| if eos_id is not None: | |
| ids = ids + [eos_id] | |
| buffer.extend(ids) | |
| while len(buffer) >= self.block_size: | |
| chunk = torch.tensor(buffer[: self.block_size], dtype=torch.long) | |
| yield chunk | |
| buffer = buffer[self.block_size :] | |
| if len(buffer) >= self.block_size: | |
| chunk = torch.tensor(buffer[: self.block_size], dtype=torch.long) | |
| yield chunk | |
| def load_streaming_dataset( | |
| train_source: Union[str, Path], | |
| tokenizer: Any, | |
| block_size: int = 512, | |
| ) -> IterableDataset: | |
| source = Path(train_source) if not isinstance(train_source, Path) else train_source | |
| if source.suffix == ".pt": | |
| payload = torch.load(source, map_location="cpu") | |
| tokens = payload["tokens"] if isinstance(payload, dict) and "tokens" in payload else payload | |
| return torch.utils.data.TensorDataset(tokens) | |
| return MarsLMStreamingDataset([source], tokenizer, block_size=block_size) | |