File size: 3,368 Bytes
0793da1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Encode portable messages without truncating any context or target text.

Only the final assistant message receives loss. Requires a Qwen-compatible
tokenizer containing the im_start/im_end tokens; never loads model weights.
"""
import argparse
import json
from pathlib import Path

TEMPLATE = "{% for m in messages %}{{ '<|im_start|>' + m['role'] + '\\n' + m['content'] + '<|im_end|>\\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}"


def encode_row(row, tokenizer, max_length=262144):
    messages = row['messages']
    assert messages[-1]['role'] == 'assistant' and messages[-1]['loss'] is True
    assert all(m['loss'] is False for m in messages[:-1])
    clean = [dict(role=m['role'], content=m['content']) for m in messages]
    # This explicit serialization preserves whitespace and the published think
    # content exactly, without template-side reasoning stripping or trimming.
    prefix = tokenizer.apply_chat_template(clean[:-1], chat_template=TEMPLATE,
        tokenize=False, add_generation_prompt=True)
    full = tokenizer.apply_chat_template(clean, chat_template=TEMPLATE,
        tokenize=False, add_generation_prompt=False)
    assert full.startswith(prefix)
    suffix = full[len(prefix):]
    assert suffix == clean[-1]['content'] + '<|im_end|>\n'
    prefix_ids = tokenizer(prefix, add_special_tokens=False)['input_ids']
    target_ids = tokenizer(suffix, add_special_tokens=False)['input_ids']
    assert target_ids
    assert tokenizer.decode(target_ids, skip_special_tokens=False) == suffix
    assert tokenizer.decode(prefix_ids, skip_special_tokens=False) == prefix
    ids = prefix_ids + target_ids
    if len(ids) > max_length:
        raise ValueError(f'{row["sample_id"]}: {len(ids)} tokens exceed {max_length}; no truncation was performed')
    labels = [-100] * len(prefix_ids) + target_ids
    assert len(labels) == len(ids) and labels[len(prefix_ids):] == target_ids
    return dict(input_ids=ids, labels=labels, lengths=len(ids)), dict(
        context_tokens=len(prefix_ids), supervised_tokens=len(target_ids), total_tokens=len(ids))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', type=Path, required=True)
    parser.add_argument('--tokenizer', required=True)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--max-length', type=int, default=262144)
    args = parser.parse_args()
    assert not args.output.exists(), 'Refuse to overwrite an encoded dataset'
    from transformers import AutoTokenizer
    from datasets import Dataset, Features, Sequence, Value
    tokenizer = AutoTokenizer.from_pretrained(args.tokenizer)
    for token in ('<|im_start|>', '<|im_end|>'):
        assert tokenizer.convert_tokens_to_ids(token) != tokenizer.unk_token_id
    def rows():
        with args.input.open() as f:
            for line in f:
                encoded, _ = encode_row(json.loads(line), tokenizer, args.max_length)
                yield encoded
    features = Features(dict(input_ids=Sequence(Value('int32')), labels=Sequence(Value('int32')), lengths=Value('int32')))
    dataset = Dataset.from_generator(rows, features=features)
    dataset.save_to_disk(str(args.output))
    print(json.dumps(dict(rows=len(dataset), output=str(args.output), truncations=0)))


if __name__ == '__main__':
    main()