unsupervised.py 3.72 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
18
19
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple

from ...extras.logging import get_logger
from ..data_utils import Role
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
31
32
33
34
35
36
37
38
    from ..template import Template


logger = get_logger(__name__)


def _encode_unsupervised_example(
    prompt: Sequence[Dict[str, str]],
    response: Sequence[Dict[str, str]],
    system: Optional[str],
    tools: Optional[str],
luopl's avatar
luopl committed
39
40
    images: Sequence["ImageInput"],
    videos: Sequence["VideoInput"],
chenych's avatar
chenych committed
41
42
43
44
45
46
47
48
49
50
    template: "Template",
    tokenizer: "PreTrainedTokenizer",
    processor: Optional["ProcessorMixin"],
    cutoff_len: int,
) -> Tuple[List[int], List[int]]:
    if len(response) == 1:
        messages = prompt + response
    else:
        messages = prompt + [{"role": Role.ASSISTANT.value, "content": ""}]

luopl's avatar
luopl committed
51
    messages = template.mm_plugin.process_messages(messages, images, videos, processor)
chenych's avatar
chenych committed
52
53
54
55
    input_ids, labels = template.encode_oneturn(tokenizer, messages, system, tools)
    if template.efficient_eos:
        labels += [tokenizer.eos_token_id]

luopl's avatar
luopl committed
56
    input_ids, _ = template.mm_plugin.process_token_ids(input_ids, None, images, videos, tokenizer, processor)
chenych's avatar
chenych committed
57
58
59
60
61
62
63
64
65
66
67
68
    source_len, target_len = infer_seqlen(len(input_ids), len(labels), cutoff_len)
    input_ids = input_ids[:source_len]
    labels = labels[:target_len]
    return input_ids, labels


def preprocess_unsupervised_dataset(
    examples: Dict[str, List[Any]],
    template: "Template",
    tokenizer: "PreTrainedTokenizer",
    processor: Optional["ProcessorMixin"],
    data_args: "DataArguments",
luopl's avatar
luopl committed
69
) -> Dict[str, List[Any]]:
chenych's avatar
chenych committed
70
    # build inputs with format `<bos> X` and labels with format `Y <eos>`
luopl's avatar
luopl committed
71
72
73
74
    model_inputs = defaultdict(list)
    for i in range(len(examples["_prompt"])):
        if len(examples["_prompt"][i]) % 2 != 1:
            logger.warning("Dropped invalid example: {}".format(examples["_prompt"][i] + examples["_response"][i]))
chenych's avatar
chenych committed
75
76
77
            continue

        input_ids, labels = _encode_unsupervised_example(
luopl's avatar
luopl committed
78
79
80
81
82
83
            prompt=examples["_prompt"][i],
            response=examples["_response"][i],
            system=examples["_system"][i],
            tools=examples["_tools"][i],
            images=examples["_images"][i] or [],
            videos=examples["_videos"][i] or [],
chenych's avatar
chenych committed
84
85
86
87
88
89
90
91
            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)
luopl's avatar
luopl committed
92
93
        model_inputs["images"].append(examples["_images"][i])
        model_inputs["videos"].append(examples["_videos"][i])
chenych's avatar
chenych committed
94
95
96
97
98
99
100

    return model_inputs


def print_unsupervised_dataset_example(example: Dict[str, List[int]], tokenizer: "PreTrainedTokenizer") -> None:
    print("input_ids:\n{}".format(example["input_ids"]))
    print("inputs:\n{}".format(tokenizer.decode(example["input_ids"], skip_special_tokens=False)))