File size: 3,426 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 | import json
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union
import torch
from torch.utils.data import IterableDataset
try:
import datasets
except ImportError: # type: ignore
datasets = None # type: ignore
def _extract_instruction_field(item: Dict[str, Any]) -> Optional[str]:
for key in ["instruction", "prompt", "task", "query"]:
value = item.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _extract_output_field(item: Dict[str, Any]) -> Optional[str]:
for key in ["output", "response", "completion", "answer", "reply"]:
value = item.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _load_jsonl_examples(path: Path) -> Iterator[Dict[str, Any]]:
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):
yield payload
except json.JSONDecodeError:
continue
def _load_hf_dataset(dataset_name: str, split: str = "train") -> Iterator[Dict[str, Any]]:
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:
if isinstance(item, dict):
yield item
class InstructionTuningDataset(IterableDataset):
def __init__(
self,
sources: Sequence[Union[str, Path]],
tokenizer: Any,
block_size: int = 1024,
prompt_template: str = "### Instruction:\n{instruction}\n\n### Response:\n{response}",
):
self.sources = sources
self.tokenizer = tokenizer
self.block_size = block_size
self.prompt_template = prompt_template
def _iter_source(self, source: Union[str, Path]) -> Iterator[Dict[str, Any]]:
if isinstance(source, Path) and source.exists():
if source.suffix == ".jsonl":
yield from _load_jsonl_examples(source)
else:
raise ValueError("Instruction tuning requires a JSONL file or a Hugging Face dataset identifier")
else:
yield from _load_hf_dataset(str(source))
def _format_example(self, item: Dict[str, Any]) -> Optional[str]:
instruction = _extract_instruction_field(item)
response = _extract_output_field(item)
if instruction is None or response is None:
return None
return self.prompt_template.format(instruction=instruction, response=response)
def __iter__(self) -> Iterator[torch.Tensor]:
for source in self.sources:
for item in self._iter_source(source):
text = self._format_example(item)
if not text:
continue
token_ids = self.tokenizer.encode(text, add_special_tokens=False).ids
if len(token_ids) < 2:
continue
token_ids = token_ids[: self.block_size]
yield torch.tensor(token_ids, dtype=torch.long)
|