Download datasets/instruction.py from Ian26/MarsLM: direct link, hf CLI and curl.
- Browser
- Download file 3.43 kB
-
https://huggingface.co/Ian26/MarsLM/resolve/main/datasets/instruction.py
- Command line
-
hf download hf://Ian26/MarsLM/datasets/instruction.py
-
curl -L -o instruction.py https://huggingface.co/Ian26/MarsLM/resolve/main/datasets/instruction.py
3.43 kB
| 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) | |