File size: 2,559 Bytes
b838b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import hashlib
import json
import re
from pathlib import Path

import torch


def read_pairs(path):
    pairs = []
    for i, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1):
        if not line.strip():
            continue
        item = json.loads(line)
        if any(not isinstance(item.get(k), str) or not item[k].strip()
               for k in ("question", "answer")):
            raise ValueError(f"{path}:{i}: нужны непустые question и answer")
        pairs.append(item)
    if not pairs:
        raise ValueError(f"Пустой датасет: {path}")
    return pairs


def detect_language(question):
    # Lightweight UI routing, not a trained language detector; explicit override wins.
    if re.search(r"[А-Яа-яЁё]", question):
        return "ru"
    if re.search(r"[\u3400-\u9fff]", question):
        return "zh"
    return "en"


def prompt(question, language=None):
    language = language or detect_language(question)
    templates = {"ru": "Вопрос: {}\nОтвет:", "en": "Question: {}\nAnswer:", "zh": "问题:{}\n回答:"}
    if language not in templates:
        raise ValueError(f"Unsupported language: {language}")
    return templates[language].format(question.strip())


def digest(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def encode_pairs(pairs, tokenizer, max_length):
    result = []
    for pair in pairs:
        prefix = tokenizer.encode(prompt(pair["question"], pair.get("language")), add_special_tokens=False)
        answer = tokenizer.encode(" " + pair["answer"], add_special_tokens=False)
        ids = prefix + answer + [tokenizer.eos_token_id]
        # Не обрезаем ответы незаметно: исправьте данные или увеличьте контекст.
        if len(ids) > max_length:
            raise ValueError(f"Пример длиннее {max_length} токенов: {pair['question']}")
        result.append((ids, [-100] * len(prefix) + answer + [tokenizer.eos_token_id]))
    return result


def batch(rows, pad_id):
    width = max(len(ids) for ids, _ in rows)
    return {
        "input_ids": torch.tensor([ids + [pad_id] * (width - len(ids)) for ids, _ in rows]),
        "attention_mask": torch.tensor([[1] * len(ids) + [0] * (width - len(ids)) for ids, _ in rows]),
        "labels": torch.tensor([labels + [-100] * (width - len(labels)) for _, labels in rows]),
    }