File size: 6,781 Bytes
8f20aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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)