qwen2_rm.py 4.37 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
4
5
6
7
# Adapted from
# https://huggingface.co/Qwen/Qwen2.5-Math-RM-72B/blob/main/modeling_qwen2_rm.py
# Copyright 2024 The Qwen team.
# Copyright 2023 The vLLM team.
"""Inference-only Qwen2-RM model compatible with HuggingFace weights."""
8
from typing import Iterable, Optional, Set, Tuple, Union
9
10
11
12

import torch
from torch import nn

13
from vllm.config import VllmConfig
14
15
from vllm.model_executor.layers.linear import (ColumnParallelLinear,
                                               RowParallelLinear)
16
from vllm.model_executor.layers.pooler import Pooler, PoolingType, SimplePooler
17
18
19
from vllm.model_executor.pooling_metadata import PoolingMetadata
from vllm.sequence import IntermediateTensors, PoolerOutput

20
from .interfaces import SupportsLoRA, SupportsPP
21
from .qwen2 import Qwen2Model
22
from .utils import AutoWeightsLoader, maybe_prefix
23
24
25
26
27
28
29
30
31
32
33
34
35


class ReLU(nn.Module):

    def __init__(self):
        super().__init__()
        self.activation = nn.ReLU()

    def forward(self, input):
        input, _ = input
        return self.activation(input)


36
class Qwen2RewardBaseModel(nn.Module, SupportsLoRA, SupportsPP):
37
38
39
40
41
42
43
44
45
46
47
48
    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }

49
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
50
51
52
53
        super().__init__()
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config
        lora_config = vllm_config.lora_config
54
55
56
57
58

        self.config = config
        self.lora_config = lora_config

        self.quant_config = quant_config
59
60
        self.model = Qwen2Model(vllm_config=vllm_config,
                                prefix=maybe_prefix(prefix, "model"))
61
62
63
64
65
66

        self.score = nn.Sequential(
            ColumnParallelLinear(config.hidden_size,
                                 config.hidden_size,
                                 quant_config=quant_config),
            ReLU(),
67
68
            RowParallelLinear(config.hidden_size,
                              config.num_labels,
69
70
                              quant_config=quant_config),
        )
71
        self._pooler: SimplePooler
72
73
74
        self.make_empty_intermediate_tensors = (
            self.model.make_empty_intermediate_tensors)

75
76
77
    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.get_input_embeddings(input_ids)

78
79
80
81
82
    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors] = None,
83
        inputs_embeds: Optional[torch.Tensor] = None,
84
    ) -> Union[torch.Tensor, IntermediateTensors]:
85
        hidden_states = self.model(input_ids, positions, intermediate_tensors,
86
                                   inputs_embeds)
87
88
89
90
91
92
93
94
95
96
        logits, _ = self.score(hidden_states)
        return logits

    def pooler(
        self,
        hidden_states: torch.Tensor,
        pooling_metadata: PoolingMetadata,
    ) -> Optional[PoolerOutput]:
        return self._pooler(hidden_states, pooling_metadata)

97
98
    def load_weights(self, weights: Iterable[Tuple[str,
                                                   torch.Tensor]]) -> Set[str]:
99
100
        loader = AutoWeightsLoader(self,
                                   ignore_unexpected_prefixes=["lm_head."])
101
        return loader.load_weights(weights)
102
103
104
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


class Qwen2ForRewardModel(Qwen2RewardBaseModel):

    def __init__(self, *, vllm_config, prefix=""):
        vllm_config.model_config.hf_config.num_labels = 1
        super().__init__(vllm_config=vllm_config, prefix=prefix)
        pooler_config = vllm_config.model_config.pooler_config
        self._pooler = Pooler.from_config_with_defaults(
            pooler_config,
            pooling_type=PoolingType.ALL,
            normalize=False,
            softmax=False)


class Qwen2ForProcessRewardModel(Qwen2RewardBaseModel):

    def __init__(self, *, vllm_config, prefix=""):
        vllm_config.model_config.hf_config.num_labels = 2
        super().__init__(vllm_config=vllm_config, prefix=prefix)
        pooler_config = vllm_config.model_config.pooler_config
        self._pooler = Pooler.from_config_with_defaults(
            pooler_config,
            pooling_type=PoolingType.STEP,
            normalize=False,
            softmax=True,
            step_tag_id=151651,
        )