chatter.py 6.16 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.

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
15
16
import json
import os
luopl's avatar
luopl committed
17
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple
chenych's avatar
chenych committed
18

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
19
20
from ..chat import ChatModel
from ..data import Role
chenych's avatar
chenych committed
21
from ..extras.constants import PEFT_METHODS
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
22
23
from ..extras.misc import torch_gc
from ..extras.packages import is_gradio_available
chenych's avatar
chenych committed
24
from .common import QUANTIZATION_BITS, get_save_dir
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from .locales import ALERTS


if TYPE_CHECKING:
    from ..chat import BaseEngine
    from .manager import Manager


if is_gradio_available():
    import gradio as gr


class WebChatModel(ChatModel):
    def __init__(self, manager: "Manager", demo_mode: bool = False, lazy_init: bool = True) -> None:
        self.manager = manager
        self.demo_mode = demo_mode
        self.engine: Optional["BaseEngine"] = None

        if not lazy_init:  # read arguments from command line
            super().__init__()

        if demo_mode and os.environ.get("DEMO_MODEL") and os.environ.get("DEMO_TEMPLATE"):  # load demo model
            model_name_or_path = os.environ.get("DEMO_MODEL")
            template = os.environ.get("DEMO_TEMPLATE")
chenych's avatar
chenych committed
49
50
51
52
            infer_backend = os.environ.get("DEMO_BACKEND", "huggingface")
            super().__init__(
                dict(model_name_or_path=model_name_or_path, template=template, infer_backend=infer_backend)
            )
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
53
54
55
56
57
58
59

    @property
    def loaded(self) -> bool:
        return self.engine is not None

    def load_model(self, data) -> Generator[str, None, None]:
        get = lambda elem_id: data[self.manager.get_elem_by_id(elem_id)]
chenych's avatar
chenych committed
60
61
        lang, model_name, model_path = get("top.lang"), get("top.model_name"), get("top.model_path")
        finetuning_type, checkpoint_path = get("top.finetuning_type"), get("top.checkpoint_path")
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
62
63
64
        error = ""
        if self.loaded:
            error = ALERTS["err_exists"][lang]
chenych's avatar
chenych committed
65
        elif not model_name:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
66
            error = ALERTS["err_no_model"][lang]
chenych's avatar
chenych committed
67
        elif not model_path:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
68
69
70
71
72
73
74
75
76
            error = ALERTS["err_no_path"][lang]
        elif self.demo_mode:
            error = ALERTS["err_demo"][lang]

        if error:
            gr.Warning(error)
            yield error
            return

chenych's avatar
chenych committed
77
78
        if get("top.quantization_bit") in QUANTIZATION_BITS:
            quantization_bit = int(get("top.quantization_bit"))
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
79
        else:
chenych's avatar
chenych committed
80
            quantization_bit = None
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
81
82
83

        yield ALERTS["info_loading"][lang]
        args = dict(
chenych's avatar
chenych committed
84
85
86
87
            model_name_or_path=model_path,
            finetuning_type=finetuning_type,
            quantization_bit=quantization_bit,
            quantization_method=get("top.quantization_method"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
88
            template=get("top.template"),
chenych's avatar
chenych committed
89
            flash_attn="fa2" if get("top.booster") == "flashattn2" else "auto",
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
90
91
92
            use_unsloth=(get("top.booster") == "unsloth"),
            rope_scaling=get("top.rope_scaling") if get("top.rope_scaling") in ["linear", "dynamic"] else None,
            infer_backend=get("infer.infer_backend"),
chenych's avatar
chenych committed
93
            infer_dtype=get("infer.infer_dtype"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
94
95
        )

chenych's avatar
chenych committed
96
97
98
99
100
101
102
103
104
        if checkpoint_path:
            if finetuning_type in PEFT_METHODS:  # list
                args["adapter_name_or_path"] = ",".join(
                    [get_save_dir(model_name, finetuning_type, adapter) for adapter in checkpoint_path]
                )
            else:  # str
                args["model_name_or_path"] = get_save_dir(model_name, finetuning_type, checkpoint_path)

        super().__init__(args)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
        yield ALERTS["info_loaded"][lang]

    def unload_model(self, data) -> Generator[str, None, None]:
        lang = data[self.manager.get_elem_by_id("top.lang")]

        if self.demo_mode:
            gr.Warning(ALERTS["err_demo"][lang])
            yield ALERTS["err_demo"][lang]
            return

        yield ALERTS["info_unloading"][lang]
        self.engine = None
        torch_gc()
        yield ALERTS["info_unloaded"][lang]

    def append(
        self,
        chatbot: List[List[Optional[str]]],
        messages: Sequence[Dict[str, str]],
        role: str,
        query: str,
    ) -> Tuple[List[List[Optional[str]]], List[Dict[str, str]], str]:
        return chatbot + [[query, None]], messages + [{"role": role, "content": query}], ""

    def stream(
        self,
        chatbot: List[List[Optional[str]]],
        messages: Sequence[Dict[str, str]],
        system: str,
        tools: str,
luopl's avatar
luopl committed
135
136
        image: Optional[Any],
        video: Optional[Any],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
137
138
139
140
141
142
143
        max_new_tokens: int,
        top_p: float,
        temperature: float,
    ) -> Generator[Tuple[List[List[Optional[str]]], List[Dict[str, str]]], None, None]:
        chatbot[-1][1] = ""
        response = ""
        for new_text in self.stream_chat(
luopl's avatar
luopl committed
144
145
146
147
148
149
150
151
            messages,
            system,
            tools,
            images=[image] if image else None,
            videos=[video] if video else None,
            max_new_tokens=max_new_tokens,
            top_p=top_p,
            temperature=temperature,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
152
153
154
        ):
            response += new_text
            if tools:
chenych's avatar
chenych committed
155
                result = self.engine.template.extract_tool(response)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
156
157
158
            else:
                result = response

chenych's avatar
chenych committed
159
160
161
162
163
            if isinstance(result, list):
                tool_calls = [{"name": tool[0], "arguments": json.loads(tool[1])} for tool in result]
                tool_calls = json.dumps(tool_calls, indent=4, ensure_ascii=False)
                output_messages = messages + [{"role": Role.FUNCTION.value, "content": tool_calls}]
                bot_text = "```json\n" + tool_calls + "\n```"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
164
165
166
167
168
169
            else:
                output_messages = messages + [{"role": Role.ASSISTANT.value, "content": result}]
                bot_text = result

            chatbot[-1][1] = bot_text
            yield chatbot, output_messages