base_engine.py 3 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# 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
from abc import ABC, abstractmethod
chenych's avatar
chenych committed
16
from collections.abc import AsyncGenerator
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
17
from dataclasses import dataclass
chenych's avatar
chenych committed
18
from typing import TYPE_CHECKING, Any, Literal, Optional, Union
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
19
20
21
22
23
24
25


if TYPE_CHECKING:
    from transformers import PreTrainedModel, PreTrainedTokenizer
    from vllm import AsyncLLMEngine

    from ..data import Template
chenych's avatar
chenych committed
26
    from ..data.mm_plugin import AudioInput, ImageInput, VideoInput
chenych's avatar
chenych committed
27
    from ..extras.constants import EngineName
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
28
29
30
31
32
33
34
35
36
37
38
39
    from ..hparams import DataArguments, FinetuningArguments, GeneratingArguments, ModelArguments


@dataclass
class Response:
    response_text: str
    response_length: int
    prompt_length: int
    finish_reason: Literal["stop", "length"]


class BaseEngine(ABC):
chenych's avatar
chenych committed
40
    r"""Base class for inference engine of chat models.
luopl's avatar
luopl committed
41
42
43
44

    Must implements async methods: chat(), stream_chat() and get_scores().
    """

chenych's avatar
chenych committed
45
    name: "EngineName"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
46
47
48
49
    model: Union["PreTrainedModel", "AsyncLLMEngine"]
    tokenizer: "PreTrainedTokenizer"
    can_generate: bool
    template: "Template"
chenych's avatar
chenych committed
50
    generating_args: dict[str, Any]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
51
52
53
54
55
56
57
58

    @abstractmethod
    def __init__(
        self,
        model_args: "ModelArguments",
        data_args: "DataArguments",
        finetuning_args: "FinetuningArguments",
        generating_args: "GeneratingArguments",
luopl's avatar
luopl committed
59
    ) -> None:
chenych's avatar
chenych committed
60
        r"""Initialize an inference engine."""
luopl's avatar
luopl committed
61
        ...
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
62
63
64
65

    @abstractmethod
    async def chat(
        self,
chenych's avatar
chenych committed
66
        messages: list[dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
67
68
        system: Optional[str] = None,
        tools: Optional[str] = None,
chenych's avatar
chenych committed
69
70
71
        images: Optional[list["ImageInput"]] = None,
        videos: Optional[list["VideoInput"]] = None,
        audios: Optional[list["AudioInput"]] = None,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
72
        **input_kwargs,
chenych's avatar
chenych committed
73
74
    ) -> list["Response"]:
        r"""Get a list of responses of the chat model."""
luopl's avatar
luopl committed
75
        ...
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
76
77
78
79

    @abstractmethod
    async def stream_chat(
        self,
chenych's avatar
chenych committed
80
        messages: list[dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
81
82
        system: Optional[str] = None,
        tools: Optional[str] = None,
chenych's avatar
chenych committed
83
84
85
        images: Optional[list["ImageInput"]] = None,
        videos: Optional[list["VideoInput"]] = None,
        audios: Optional[list["AudioInput"]] = None,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
86
        **input_kwargs,
luopl's avatar
luopl committed
87
    ) -> AsyncGenerator[str, None]:
chenych's avatar
chenych committed
88
        r"""Get the response token-by-token of the chat model."""
luopl's avatar
luopl committed
89
        ...
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
90
91
92
93

    @abstractmethod
    async def get_scores(
        self,
chenych's avatar
chenych committed
94
        batch_input: list[str],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
95
        **input_kwargs,
chenych's avatar
chenych committed
96
97
    ) -> list[float]:
        r"""Get a list of scores of the reward model."""
luopl's avatar
luopl committed
98
        ...