File size: 2,663 Bytes
8cbfa56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SFT examples (warm-up, Python-tool and usability traces) turned into token rows.



Accepted rows: {"messages": [..., {"role": "assistant", "content": ...}]} or

{"problem": ..., "response": ...}. Tool output blocks (```output ... ```) inside a response

get loss_mask 0: the model never wrote them, so it must not learn to predict them.

"""

from __future__ import annotations

import os
import re
from pathlib import Path
from typing import Any

from .io import read_jsonl

OUTPUT_BLOCK = re.compile(r"```output\n.*?```\n?", re.S)


def _source_rows(source: str) -> list[dict[str, Any]]:
    if Path(source).exists():
        return list(read_jsonl(source))
    from huggingface_hub import hf_hub_download

    repo, _, path = source.partition(":")
    return list(read_jsonl(hf_hub_download(repo, path, repo_type="dataset", token=os.environ.get("HF_TOKEN") or None)))


def response_mask(tokenizer, response: str) -> tuple[list[int], list[int]]:
    enc = tokenizer(response, add_special_tokens=False, return_offsets_mapping=True)
    spans = [(m.start(), m.end()) for m in OUTPUT_BLOCK.finditer(response)]
    mask = [0 if any(a <= start < b for a, b in spans) else 1 for start, _ in enc["offset_mapping"]]
    return list(enc["input_ids"]), mask


def sft_rows(ctx, source: str, tokenizer, prof: dict[str, Any], max_len: int) -> list[dict[str, Any]]:
    end_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
    if end_id is None or end_id == tokenizer.unk_token_id:
        end_id = tokenizer.eos_token_id
    rows, dropped = [], 0
    for r in _source_rows(source):
        if "messages" in r:
            messages, response = r["messages"][:-1], r["messages"][-1]["content"]
        else:
            user = prof["user_template"].format(problem=r["problem"])
            messages, response = [{"role": "user", "content": user}], r["response"]
        if prof.get("system") and messages[0]["role"] != "system":
            messages = [{"role": "system", "content": prof["system"]}, *messages]
        text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
        prompt = tokenizer(text, add_special_tokens=False).input_ids
        ids, mask = response_mask(tokenizer, response)
        ids, mask = ids + [end_id], mask + [1]
        if len(prompt) + len(ids) > max_len:
            dropped += 1
            continue
        rows.append({"prompt_ids": prompt, "response_ids": ids, "loss_mask": mask if 0 in mask else None})
    if ctx is not None:
        ctx.log(f"SFT rows: {len(rows)} kept, {dropped} longer than {max_len} tokens dropped")
    return rows