File size: 1,733 Bytes
86e3bb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import numpy as np
import torch

from kawk50m.chat import build_assistant_examples, format_generation_prompt, parse_chatml
from kawk50m.sft_dataset import SFTPackedDataset


class CharacterTokenizer:
    bos_token_id = 1
    eos_token_id = 2

    def __call__(self, text: str, **_: object) -> dict[str, list[int]]:
        return {"input_ids": [10 + ord(character) % 200 for character in text]}


def test_chatml_examples_mask_only_current_assistant_response() -> None:
    blocks = parse_chatml(
        "<|im_start|>user\n질문입니다.<|im_end|>"
        "<|im_start|>assistant\n답변입니다.<|im_end|>"
    )
    examples = list(
        build_assistant_examples(blocks, CharacterTokenizer(), max_length=128)
    )
    assert len(examples) == 1
    input_ids, loss_mask = examples[0]
    assert len(input_ids) == len(loss_mask)
    assert loss_mask[-1] == 1
    assert input_ids[-1] == CharacterTokenizer.eos_token_id
    assert 0 in loss_mask and 1 in loss_mask
    assert format_generation_prompt("질문") .endswith("### 도우미:\n")


def test_sft_dataset_applies_ignore_index(tmp_path) -> None:
    prefix = tmp_path / "train"
    np.asarray([1, 10, 11, 2, 1, 20, 21, 2], dtype=np.uint16).tofile(
        str(prefix) + ".input_ids.bin"
    )
    np.asarray([0, 0, 1, 1, 0, 0, 1, 1], dtype=np.uint8).tofile(
        str(prefix) + ".loss_mask.bin"
    )
    dataset = SFTPackedDataset(prefix, sequence_length=4)
    inputs, labels = dataset.evaluation_batch(
        batch_index=0,
        batch_size=1,
        rank=0,
        world_size=1,
        device=torch.device("cpu"),
    )
    assert inputs.tolist() == [[1, 10, 11, 2]]
    assert labels.tolist() == [[-100, -100, 11, 2]]