File size: 2,956 Bytes
673d750 | 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 | """Stream Hermes function-calling examples into token IDs for agent-style training."""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Any
import numpy as np
from tokenizers import Tokenizer
from tqdm import tqdm
from chat_data import stream_hf_rows
from prepare_data import END_OF_TEXT, GrowingMemmap
DATASET_NAME = "NousResearch/hermes-function-calling-v1"
DATASET_CONFIG = "func_calling_singleturn"
ROLE_LABELS = {
"system": "System",
"human": "User",
"gpt": "Assistant",
"tool": "Tool",
}
def format_tool_conversation(row: dict[str, Any]) -> str | None:
conversations = row.get("conversations")
if not isinstance(conversations, list):
return None
turns: list[str] = []
has_tool_call = False
for message in conversations:
if not isinstance(message, dict):
return None
role = ROLE_LABELS.get(str(message.get("from", "")).lower())
content = message.get("value")
if role is None or not isinstance(content, str) or not content.strip():
return None
content = content.strip()
if role == "Assistant" and "<tool_call>" in content:
has_tool_call = True
turns.append(f"{role}: {content}")
return "\n".join(turns) if has_tool_call else None
def write_examples(
output_path: Path,
tokenizer: Tokenizer,
eos_token_id: int,
max_examples: int | None,
) -> int:
writer = GrowingMemmap(output_path)
processed = 0
written = 0
progress = tqdm(desc="Tokenizing tool-use examples", unit="examples")
try:
for row in stream_hf_rows(DATASET_NAME, "train", DATASET_CONFIG):
if max_examples is not None and processed >= max_examples:
break
processed += 1
text = format_tool_conversation(row)
if text is None:
continue
writer.append(tokenizer.encode(text).ids)
writer.append([eos_token_id])
written += 1
progress.update(1)
finally:
progress.close()
writer.close()
print(f"Wrote {written:,} tool-use examples ({writer.length:,} tokens) to {output_path}")
return written
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tokenizer", type=Path, default=Path("agent-tokenizer.json"))
parser.add_argument("--output", type=Path, default=Path("agent-data/tool-use.bin"))
parser.add_argument("--max-examples", type=int, default=512)
args = parser.parse_args()
if not args.tokenizer.is_file():
parser.error(f"Tokenizer not found: {args.tokenizer}")
if args.max_examples is not None and args.max_examples < 1:
parser.error("--max-examples must be positive")
tokenizer = Tokenizer.from_file(str(args.tokenizer))
if tokenizer.get_vocab_size() > np.iinfo(np.uint16).max + 1:
parser.error("Tokenizer vocabulary does not fit in uint16 token IDs")
eos_token_id = tokenizer.token_to_id(END_OF_TEXT)
if eos_token_id is None:
parser.error(f"Tokenizer must contain {END_OF_TEXT}")
write_examples(args.output, tokenizer, eos_token_id, args.max_examples)
if __name__ == "__main__":
main()
|