File size: 4,120 Bytes
ee15e43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SFT-данные для PP-He: инструкции → ответы.

Формат: ChatML-подобный шаблон, loss только на токенах ответа (промпт
маскируется -100). Источники — любые HF-датасеты с парами
instruction/output (по умолчанию наш cyber-kb).

Шарды: tokens.bin (uint16) + labels.bin (int32, -100 на промпте) + meta.json
"""
from __future__ import annotations

import json
import os

import numpy as np

TEMPLATE = (
    "<|bos|><|user|>\n{prompt}<|end|>\n<|assistant|>\n{answer}<|eos|>"
)

SPECIALS = ["<|bos|>", "<|eos|>", "<|pad|>", "<|user|>", "<|assistant|>", "<|end|>"]


def ensure_specials(tokenizer_dir: str) -> int:
    """Добавить chat-токены в словарь, если их нет. Возвращает новый размер."""
    from tokenizers import Tokenizer

    path = os.path.join(tokenizer_dir, "tokenizer.json")
    backend = Tokenizer.from_file(path)
    vocab = set(backend.get_vocab().keys())
    missing = [s for s in SPECIALS if s not in vocab]
    if missing:
        backend.add_tokens(missing)
        backend.save(path)
        print(f"[sft] добавлено спецтокенов: {missing}")
    return backend.get_vocab_size(with_added_tokens=True)


def build(out_dir: str, tokenizer_dir: str, token: str | None = None,
          datasets_spec: list[dict] | None = None, max_len: int = 2048,
          limit: int = 200_000) -> dict:
    from datasets import load_dataset
    from transformers import AutoTokenizer

    os.makedirs(out_dir, exist_ok=True)

    vocab = ensure_specials(tokenizer_dir)
    tok = AutoTokenizer.from_pretrained(tokenizer_dir, trust_remote_code=True)
    ids = {s: tok.convert_tokens_to_ids(s) for s in SPECIALS}
    print(f"[sft] словарь {len(tok)}, спецтокены {ids}", flush=True)

    spec = datasets_spec or [{"hf": "AdminHugging/cyber-kb", "file": "data/qa_en.jsonl",
                              "prompt": "instruction", "answer": "output"}]

    tokens: list[int] = []
    labels: list[int] = []
    n = 0
    for s in spec:
        try:
            ds = load_dataset(s["hf"], data_files=s["file"], split="train",
                              streaming=True, token=token)
        except Exception as exc:  # noqa: BLE001
            print(f"[sft] {s['hf']}: пропуск ({type(exc).__name__})")
            continue
        for ex in ds:
            if n >= limit:
                break
            prompt = str(ex.get(s["prompt"]) or "").strip()
            answer = str(ex.get(s["answer"]) or "").strip()
            if not prompt or not answer:
                continue
            head = f"<|bos|><|user|>\n{prompt}<|end|>\n<|assistant|>\n"
            text = head + answer + "<|eos|>"
            p_ids = tok(head, add_special_tokens=False).input_ids
            a_ids = tok(text, add_special_tokens=False).input_ids
            if len(a_ids) > max_len:
                a_ids = a_ids[:max_len]
            lab = [-100] * min(len(p_ids), len(a_ids)) + a_ids[len(p_ids):]
            tokens.extend(a_ids)
            labels.extend(lab)
            n += 1
            if n % 20000 == 0:
                print(f"[sft] {n} примеров, {len(tokens)/1e6:.1f}M токенов", flush=True)

    if n == 0:
        raise SystemExit("[sft] ни одного примера")
    np.asarray(tokens, dtype=np.uint16).tofile(os.path.join(out_dir, "tokens.bin"))
    np.asarray(labels, dtype=np.int32).tofile(os.path.join(out_dir, "labels.bin"))
    meta = {"n_examples": n, "n_tokens": len(tokens),
            "vocab_size": len(tok), "max_len": max_len,
            "specials": ids,
            "answer_tokens": int(sum(1 for x in labels if x != -100))}
    with open(os.path.join(out_dir, "meta.json"), "w", encoding="utf-8") as fh:
        json.dump(meta, fh, ensure_ascii=False, indent=2)
    print(f"[sft] готово: {n} примеров, {len(tokens)/1e6:.1f}M токенов, "
          f"из них ответ {meta['answer_tokens']/1e6:.1f}M", flush=True)
    return meta