Create Readme.md
Browse files
Readme.md
ADDED
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Usage
|
2 |
+
|
3 |
+
# Model loading
|
4 |
+
|
5 |
+
|
6 |
+
```python
|
7 |
+
|
8 |
+
import torch
|
9 |
+
from torch import nn
|
10 |
+
from torch.nn import CrossEntropyLoss, MSELoss, BCEWithLogitsLoss
|
11 |
+
from transformers import LlamaPreTrainedModel,LlamaModel,Gemma2PreTrainedModel,Gemma2Model,Cache
|
12 |
+
from transformers.modeling_outputs import SequenceClassifierOutputWithPast
|
13 |
+
from typing import Optional, List, Union, Tuple
|
14 |
+
|
15 |
+
@dataclass
|
16 |
+
class Config:
|
17 |
+
gemma_dir = '/kaggle/input/v7-dpo-16bit-01234-8bit-all/v7_dpo_16bit_01234_8bit_all'
|
18 |
+
max_length = 2000
|
19 |
+
batch_size = 8
|
20 |
+
device = torch.device("cuda") if torch.cuda_is_available() else torch.device("cpu")
|
21 |
+
|
22 |
+
cfg = Config()
|
23 |
+
|
24 |
+
class Gemma2ForSequenceClassificationV1(Gemma2PreTrainedModel):
|
25 |
+
def __init__(self, config):
|
26 |
+
super().__init__(config)
|
27 |
+
self.num_labels = config.num_labels
|
28 |
+
self.model = Gemma2Model(config)
|
29 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
30 |
+
|
31 |
+
# Initialize weights and apply final processing
|
32 |
+
self.post_init()
|
33 |
+
|
34 |
+
def get_input_embeddings(self):
|
35 |
+
return self.model.embed_tokens
|
36 |
+
|
37 |
+
def set_input_embeddings(self, value):
|
38 |
+
self.model.embed_tokens = value
|
39 |
+
|
40 |
+
def forward(
|
41 |
+
self,
|
42 |
+
input_ids: torch.LongTensor = None,
|
43 |
+
attention_mask: Optional[torch.Tensor] = None,
|
44 |
+
position_ids: Optional[torch.LongTensor] = None,
|
45 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
46 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
47 |
+
labels: Optional[torch.LongTensor] = None,
|
48 |
+
use_cache: Optional[bool] = None,
|
49 |
+
output_attentions: Optional[bool] = None,
|
50 |
+
output_hidden_states: Optional[bool] = None,
|
51 |
+
return_dict: Optional[bool] = None,
|
52 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
53 |
+
r"""
|
54 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
55 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
56 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
57 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
58 |
+
"""
|
59 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
60 |
+
|
61 |
+
transformer_outputs = self.model(
|
62 |
+
input_ids,
|
63 |
+
attention_mask=attention_mask,
|
64 |
+
position_ids=position_ids,
|
65 |
+
past_key_values=past_key_values,
|
66 |
+
inputs_embeds=inputs_embeds,
|
67 |
+
use_cache=use_cache,
|
68 |
+
output_attentions=output_attentions,
|
69 |
+
output_hidden_states=output_hidden_states,
|
70 |
+
return_dict=return_dict,
|
71 |
+
)
|
72 |
+
hidden_states = transformer_outputs[0]
|
73 |
+
# logits = self.score(hidden_states)
|
74 |
+
|
75 |
+
if input_ids is not None:
|
76 |
+
batch_size = input_ids.shape[0]
|
77 |
+
else:
|
78 |
+
batch_size = inputs_embeds.shape[0]
|
79 |
+
|
80 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
81 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
82 |
+
if self.config.pad_token_id is None:
|
83 |
+
sequence_lengths = -1
|
84 |
+
else:
|
85 |
+
if input_ids is not None:
|
86 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
87 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
88 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
89 |
+
sequence_lengths = sequence_lengths.to(hidden_states.device)
|
90 |
+
else:
|
91 |
+
sequence_lengths = -1
|
92 |
+
hidden_states = hidden_states[
|
93 |
+
torch.arange(batch_size, device=hidden_states.device), sequence_lengths] # eos
|
94 |
+
pooled_logits = self.score(hidden_states)
|
95 |
+
|
96 |
+
return pooled_logits
|
97 |
+
|
98 |
+
|
99 |
+
tokenizer = GemmaTokenizerFast.from_pretrained(cfg.gemma_dir)
|
100 |
+
|
101 |
+
model = Gemma2ForSequenceClassificationV1.from_pretrained(
|
102 |
+
cfg.gemma_dir,
|
103 |
+
num_labels=3,
|
104 |
+
device_map=cfg.device,
|
105 |
+
use_cache=False,
|
106 |
+
)
|
107 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
108 |
+
|
109 |
+
```
|
110 |
+
|
111 |
+
|
112 |
+
|
113 |
+
|
114 |
+
# Inference
|
115 |
+
```python
|
116 |
+
def create_rounds(query: str,
|
117 |
+
answer_a: str,
|
118 |
+
answer_b: str) -> str:
|
119 |
+
prompt =f"""User question:
|
120 |
+
\"""{query}\"""
|
121 |
+
Answer A:
|
122 |
+
\"""{answer_a}\"""
|
123 |
+
Answer B:
|
124 |
+
\"""{answer_b}\"""
|
125 |
+
"""
|
126 |
+
return prompt
|
127 |
+
|
128 |
+
|
129 |
+
@torch.no_grad()
|
130 |
+
@torch.cuda.amp.autocast()
|
131 |
+
def single_prompt_inference(prompt, model, device, max_length=cfg.max_length):
|
132 |
+
"""
|
133 |
+
Perform inference on a single prompt.
|
134 |
+
|
135 |
+
Args:
|
136 |
+
prompt (str): The input prompt for inference.
|
137 |
+
model (torch.nn.Module): The model used for inference.
|
138 |
+
device (torch.device): The device to run inference on.
|
139 |
+
tokenizer (Tokenizer): Tokenizer for preprocessing input text.
|
140 |
+
max_length (int): Maximum sequence length for tokenization.
|
141 |
+
|
142 |
+
Returns:
|
143 |
+
dict: Probabilities for "a_win", "b_win", and "tie".
|
144 |
+
"""
|
145 |
+
# Tokenize the input prompt
|
146 |
+
input_ids = tokenizer(prompt, truncation=True, max_length=max_length)['input_ids']
|
147 |
+
input_ids.append(tokenizer.eos_token_id)
|
148 |
+
|
149 |
+
# Prepare inputs
|
150 |
+
inputs = pad_without_fast_tokenizer_warning(
|
151 |
+
tokenizer,
|
152 |
+
{"input_ids": [input_ids]}, # Wrap in a list for compatibility
|
153 |
+
padding="max_length",
|
154 |
+
pad_to_multiple_of=None,
|
155 |
+
max_length=max_length,
|
156 |
+
return_tensors="pt",
|
157 |
+
)
|
158 |
+
|
159 |
+
# Move inputs to the appropriate device
|
160 |
+
inputs = inputs.to(cfg.device)
|
161 |
+
|
162 |
+
# Run the model
|
163 |
+
outputs = model(**inputs)
|
164 |
+
|
165 |
+
# Get probabilities using softmax
|
166 |
+
proba = outputs.softmax(-1).cpu().squeeze()
|
167 |
+
|
168 |
+
return {
|
169 |
+
"winner_model_a": proba[0].item(),
|
170 |
+
"winner_model_b": proba[1].item(),
|
171 |
+
"tie": proba[2].item(),
|
172 |
+
}
|
173 |
+
|
174 |
+
query = "What is the height of the reassembled blind product?"
|
175 |
+
answer_a = "You can find all the technical information directly on the product sheet on our site."
|
176 |
+
answer_b = "The height of the aluminum Venetian blind is 130 cm."
|
177 |
+
prompt_direct = create_rounds(query, answer_a, answer_b)
|
178 |
+
|
179 |
+
single_prompt_inference(prompt_direct, model, device)
|
180 |
+
```
|
181 |
+
|
182 |
+
|
183 |
+
|
184 |
+
Credits to @sayoulala on kaggle for winnig the competition https://www.kaggle.com/competitions/lmsys-chatbot-arena and submitting this model.
|