File size: 7,551 Bytes
cd15e92
 
20d949d
7660c81
41dd0cf
cd15e92
 
5e48cc5
cd15e92
77ff4b8
cd15e92
 
5e48cc5
 
 
 
 
 
cd15e92
 
 
 
20d949d
 
 
 
5e48cc5
 
 
 
 
 
 
 
 
 
 
 
 
e358772
77ff4b8
cd15e92
77ff4b8
 
 
 
cd15e92
 
302476b
7660c81
 
 
302476b
cd15e92
77ff4b8
 
 
 
 
 
 
 
af231f5
 
 
 
 
 
 
 
 
 
 
 
 
77ff4b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e59d2a7
cd15e92
 
77ff4b8
cd15e92
 
 
 
 
 
af231f5
7660c81
e358772
77ff4b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af231f5
e59d2a7
7660c81
14d2dfa
77ff4b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20d949d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77ff4b8
20d949d
 
 
 
 
 
 
 
 
 
 
 
 
41dd0cf
7660c81
 
 
 
 
77ff4b8
20d949d
 
 
 
 
 
 
 
7660c81
 
 
 
20d949d
7660c81
20d949d
 
7660c81
 
77ff4b8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import logging
import textwrap
from typing import Literal, Optional

import gradio as gr
import outlines
import pandas as pd
import spaces
import torch
from outlines import generate, models, samplers
from peft import PeftConfig, PeftModel
from pydantic import BaseModel, ConfigDict
from transformers import (
    AutoModelForCausalLM,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    BitsAndBytesConfig,
)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

DEVICE_MAP = "auto"
QUANTIZATION_BITS = None
TEMPERATURE = 0.0

AVAILABLE_MODELS = [
    "rshwndsz/ft-longformer-base-4096",
    "rshwndsz/ft-hermes-3-llama-3.2-3b",
    "rshwndsz/ft-phi-3.5-mini-instruct",
    "rshwndsz/ft-mistral-7b-v0.3-instruct",
    "rshwndsz/ft-phi-4",
    "rshwndsz/ft_paraphrased-hermes-3-llama-3.2-3b",
    "rshwndsz/ft_paraphrased-longformer-base-4096",
    "rshwndsz/ft_paraphrased-phi-3.5-mini-instruct",
    "rshwndsz/ft_paraphrased-mistral-7b-v0.3-instruct",
    "rshwndsz/ft_paraphrased-phi-4",
]
DEFAULT_MODEL_ID = AVAILABLE_MODELS[0]

# Use a simpler prompt format that might be closer to your training data
PROMPT_TEMPLATE = textwrap.dedent("""
Story: {story}
Question: {question}
Grading Scheme: {grading_scheme}
Answer: {answer}
Score:""").strip()


class ResponseModel(BaseModel):
    model_config = ConfigDict(extra="forbid")
    score: Literal["0", "1"]


# Cache models to avoid reloading on every request
_model_cache = {}


def get_model_and_tokenizer(model_id: str, device_map: str = "auto", quantization_bits: Optional[int] = None):
    if model_id in _model_cache:
        return _model_cache[model_id]
    
    if quantization_bits == 4:
        quantization_config = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_quant_type="nf4",
            bnb_4bit_use_double_quant=True,
            bnb_4bit_compute_dtype=torch.bfloat16,
        )
    elif quantization_bits == 8:
        quantization_config = BitsAndBytesConfig(load_in_8bit=True)
    else:
        quantization_config = None

    if "longformer" in model_id:
        model = AutoModelForSequenceClassification.from_pretrained(model_id)
        tokenizer = AutoTokenizer.from_pretrained(model_id)
        result = (model, tokenizer, "classification")
    else:
        # For other models, use the same approach as your original script
        peft_config = PeftConfig.from_pretrained(model_id)
        base_model_id = peft_config.base_model_name_or_path

        model = AutoModelForCausalLM.from_pretrained(
            base_model_id,
            device_map=device_map,
            quantization_config=quantization_config,
        )
        model = PeftModel.from_pretrained(model, model_id)
        tokenizer = AutoTokenizer.from_pretrained(
            base_model_id, use_fast=True, clean_up_tokenization_spaces=True
        )
        
        # Convert to outlines model
        outlines_model = models.transformers(
            model,
            tokenizer=tokenizer,
            device_map=device_map,
        )
        result = (outlines_model, tokenizer, "generation")
    
    _model_cache[model_id] = result
    return result


def format_prompt(story: str, question: str, grading_scheme: str, answer: str) -> str:
    return PROMPT_TEMPLATE.format(
        story=story.strip(),
        question=question.strip(),
        grading_scheme=grading_scheme.strip(),
        answer=answer.strip(),
    )


@spaces.GPU
def label_single_response_with_model(model_id, story, question, criteria, response):
    try:
        prompt = format_prompt(story, question, criteria, response)
        model, tokenizer, model_type = get_model_and_tokenizer(model_id, DEVICE_MAP, QUANTIZATION_BITS)
        
        if model_type == "classification":
            # For Longformer models
            inputs = tokenizer(prompt, return_tensors="pt", truncation=True, padding=True)
            with torch.no_grad():
                logits = model(**inputs).logits
            predicted_class = torch.argmax(logits, dim=1).item()
            return str(predicted_class)
        else:
            # For generative models
            sampler = samplers.greedy()
            generator = generate.json(model, ResponseModel, sampler=sampler)
            result = generator(prompt)
            return result.score
    except Exception as e:
        logger.error(f"Error in label_single_response_with_model: {str(e)}")
        return "Error: " + str(e)


@spaces.GPU
def label_multi_responses_with_model(model_id, story, question, criteria, response_file):
    try:
        df = pd.read_csv(response_file.name)
        assert "response" in df.columns, "CSV must contain a 'response' column."
        
        model, tokenizer, model_type = get_model_and_tokenizer(model_id, DEVICE_MAP, QUANTIZATION_BITS)
        prompts = [format_prompt(story, question, criteria, resp) for resp in df["response"]]
        
        if model_type == "classification":
            inputs = tokenizer(prompts, return_tensors="pt", truncation=True, padding=True)
            with torch.no_grad():
                logits = model(**inputs).logits
            predicted_classes = torch.argmax(logits, dim=1).tolist()
            scores = [str(cls) for cls in predicted_classes]
        else:
            sampler = samplers.greedy()
            generator = generate.json(model, ResponseModel, sampler=sampler)
            results = generator(prompts)
            scores = [r.score for r in results]
        
        df["score"] = scores
        return df
    except Exception as e:
        logger.error(f"Error in label_multi_responses_with_model: {str(e)}")
        return f"Error: {str(e)}"


def single_response_ui(model_id):
    return gr.Interface(
        fn=lambda story, question, criteria, response: label_single_response_with_model(
            model_id.value, story, question, criteria, response
        ),
        inputs=[
            gr.Textbox(label="Story", lines=6),
            gr.Textbox(label="Question", lines=2),
            gr.Textbox(label="Criteria (Grading Scheme)", lines=4),
            gr.Textbox(label="Single Response", lines=3),
        ],
        outputs=gr.Textbox(label="Score"),
        live=False,
    )


def multi_response_ui(model_id):
    return gr.Interface(
        fn=lambda story, question, criteria, response_file: label_multi_responses_with_model(
            model_id.value, story, question, criteria, response_file
        ),
        inputs=[
            gr.Textbox(label="Story", lines=6),
            gr.Textbox(label="Question", lines=2),
            gr.Textbox(label="Criteria (Grading Scheme)", lines=4),
            gr.File(
                label="Responses CSV (.csv with 'response' column)", file_types=[".csv"]
            ),
        ],
        outputs=gr.Dataframe(label="Labeled Responses", type="pandas"),
        live=False,
    )


with gr.Blocks(title="Zero-Shot Evaluation Grader") as iface:
    model_selector = gr.Dropdown(
        label="Select Model",
        choices=AVAILABLE_MODELS,
        value=DEFAULT_MODEL_ID,
    )
    selected_model_id = gr.State(value=DEFAULT_MODEL_ID)

    def update_model_id(choice):
        return choice

    model_selector.change(
        fn=update_model_id, inputs=model_selector, outputs=selected_model_id
    )

    with gr.Tabs():
        with gr.Tab("Single Response"):
            single_response_ui(selected_model_id)
        with gr.Tab("Batch (CSV)"):
            multi_response_ui(selected_model_id)


if __name__ == "__main__":
    iface.launch(share=True)