feedback.py 5.26 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2024 the LlamaFactory team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

luopl's avatar
luopl committed
15
from collections import defaultdict
chenych's avatar
chenych committed
16
17
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple

luopl's avatar
luopl committed
18
from ...extras import logging
chenych's avatar
chenych committed
19
from ...extras.constants import IGNORE_INDEX
luopl's avatar
luopl committed
20
from .processor_utils import infer_seqlen
chenych's avatar
chenych committed
21
22
23
24
25
26


if TYPE_CHECKING:
    from transformers import PreTrainedTokenizer, ProcessorMixin

    from ...hparams import DataArguments
luopl's avatar
luopl committed
27
    from ..mm_plugin import ImageInput, VideoInput
chenych's avatar
chenych committed
28
29
30
    from ..template import Template


luopl's avatar
luopl committed
31
logger = logging.get_logger(__name__)
chenych's avatar
chenych committed
32
33
34
35
36
37
38
39


def _encode_feedback_example(
    prompt: Sequence[Dict[str, str]],
    response: Sequence[Dict[str, str]],
    kl_response: Sequence[Dict[str, str]],
    system: Optional[str],
    tools: Optional[str],
luopl's avatar
luopl committed
40
41
    images: Sequence["ImageInput"],
    videos: Sequence["VideoInput"],
chenych's avatar
chenych committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
    template: "Template",
    tokenizer: "PreTrainedTokenizer",
    processor: Optional["ProcessorMixin"],
    cutoff_len: int,
) -> Tuple[List[int], List[int], List[int], List[int], bool]:
    if response[0]["content"]:  # desired example
        kto_tag = True
        messages = prompt + [response[0]]
    else:  # undesired example
        kto_tag = False
        messages = prompt + [response[1]]

    if kl_response[0]["content"]:
        kl_messages = prompt + [kl_response[0]]
    else:
        kl_messages = prompt + [kl_response[1]]

luopl's avatar
luopl committed
59
60
    messages = template.mm_plugin.process_messages(messages, images, videos, processor)
    kl_messages = template.mm_plugin.process_messages(kl_messages, images, videos, processor)
chenych's avatar
chenych committed
61
62
63
64
65
66
67
    prompt_ids, response_ids = template.encode_oneturn(tokenizer, messages, system, tools)
    kl_prompt_ids, kl_response_ids = template.encode_oneturn(tokenizer, kl_messages, system, tools)

    if template.efficient_eos:
        response_ids += [tokenizer.eos_token_id]
        kl_response_ids += [tokenizer.eos_token_id]

luopl's avatar
luopl committed
68
69
    prompt_ids, _ = template.mm_plugin.process_token_ids(prompt_ids, None, images, videos, tokenizer, processor)
    kl_prompt_ids, _ = template.mm_plugin.process_token_ids(kl_prompt_ids, None, images, videos, tokenizer, processor)
chenych's avatar
chenych committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

    source_len, target_len = infer_seqlen(len(prompt_ids), len(response_ids), cutoff_len)
    prompt_ids = prompt_ids[:source_len]
    response_ids = response_ids[:target_len]
    kl_source_len, kl_target_len = infer_seqlen(len(kl_prompt_ids), len(kl_response_ids), cutoff_len)
    kl_prompt_ids = kl_prompt_ids[:kl_source_len]
    kl_response_ids = kl_response_ids[:kl_target_len]

    input_ids = prompt_ids + response_ids
    labels = [IGNORE_INDEX] * source_len + response_ids
    kl_input_ids = kl_prompt_ids + kl_response_ids
    kl_labels = [IGNORE_INDEX] * kl_source_len + kl_response_ids
    return input_ids, labels, kl_input_ids, kl_labels, kto_tag


def preprocess_feedback_dataset(
    examples: Dict[str, List[Any]],
    template: "Template",
    tokenizer: "PreTrainedTokenizer",
    processor: Optional["ProcessorMixin"],
    data_args: "DataArguments",
luopl's avatar
luopl committed
91
) -> Dict[str, List[Any]]:
chenych's avatar
chenych committed
92
    # create unrelated input-output pairs for estimating the KL term by flipping the matched pairs
luopl's avatar
luopl committed
93
94
95
96
    kl_response = examples["_response"][::-1]
    model_inputs = defaultdict(list)
    for i in range(len(examples["_prompt"])):
        if len(examples["_prompt"][i]) % 2 != 1 or len(examples["_response"][i]) < 2:
luopl's avatar
luopl committed
97
98
99
            logger.warning_rank0(
                "Dropped invalid example: {}".format(examples["_prompt"][i] + examples["_response"][i])
            )
chenych's avatar
chenych committed
100
101
102
            continue

        input_ids, labels, kl_input_ids, kl_labels, kto_tag = _encode_feedback_example(
luopl's avatar
luopl committed
103
104
            prompt=examples["_prompt"][i],
            response=examples["_response"][i],
chenych's avatar
chenych committed
105
            kl_response=kl_response[i],
luopl's avatar
luopl committed
106
107
108
109
            system=examples["_system"][i],
            tools=examples["_tools"][i],
            images=examples["_images"][i] or [],
            videos=examples["_videos"][i] or [],
chenych's avatar
chenych committed
110
111
112
113
114
115
116
117
118
119
120
121
            template=template,
            tokenizer=tokenizer,
            processor=processor,
            cutoff_len=data_args.cutoff_len,
        )
        model_inputs["input_ids"].append(input_ids)
        model_inputs["attention_mask"].append([1] * len(input_ids))
        model_inputs["labels"].append(labels)
        model_inputs["kl_input_ids"].append(kl_input_ids)
        model_inputs["kl_attention_mask"].append([1] * len(kl_input_ids))
        model_inputs["kl_labels"].append(kl_labels)
        model_inputs["kto_tags"].append(kto_tag)
luopl's avatar
luopl committed
122
123
        model_inputs["images"].append(examples["_images"][i])
        model_inputs["videos"].append(examples["_videos"][i])
chenych's avatar
chenych committed
124
125
126
127

    desirable_num = sum([1 for tag in model_inputs["kto_tags"] if tag])
    undesirable_num = len(model_inputs["kto_tags"]) - desirable_num
    if desirable_num == 0 or undesirable_num == 0:
luopl's avatar
luopl committed
128
        logger.warning_rank0("Your dataset only has one preference type.")
chenych's avatar
chenych committed
129
130

    return model_inputs