File size: 8,389 Bytes
ebf9258
 
 
 
 
 
 
 
 
b9f0050
ebf9258
 
 
 
 
15b03f2
b1f4902
ebf9258
 
 
b9f0050
ebf9258
 
b1f4902
 
ebf9258
 
 
 
 
b1f4902
 
ebf9258
 
b1f4902
 
b9f0050
 
ebf9258
 
b1f4902
 
ebf9258
 
b1f4902
ebf9258
 
 
b1f4902
 
 
 
ebf9258
 
b1f4902
ebf9258
b9f0050
 
 
b1f4902
 
 
ebf9258
 
 
15b03f2
b1f4902
ebf9258
 
b1f4902
 
 
 
15b03f2
 
 
 
b9f0050
 
b1f4902
15b03f2
b9f0050
 
15b03f2
b1f4902
ebf9258
 
b1f4902
 
ebf9258
 
b1f4902
ebf9258
 
 
 
 
 
 
 
 
 
b1f4902
15b03f2
b1f4902
 
 
ebf9258
 
b1f4902
 
15b03f2
 
b1f4902
ebf9258
 
 
 
 
 
 
b9f0050
 
 
ebf9258
 
 
 
 
 
 
 
 
 
 
 
 
b9f0050
ebf9258
 
 
 
 
b1f4902
b9f0050
b1f4902
 
 
ebf9258
 
b1f4902
ebf9258
 
b1f4902
ebf9258
 
b1f4902
 
b9f0050
b1f4902
 
ebf9258
 
 
 
 
 
b1f4902
 
 
 
 
ebf9258
 
 
 
15b03f2
ebf9258
 
b1f4902
 
b9f0050
b1f4902
 
ebf9258
15b03f2
ebf9258
 
 
b1f4902
 
b9f0050
b1f4902
 
ebf9258
 
 
 
b1f4902
ebf9258
 
 
 
b1f4902
 
b9f0050
b1f4902
 
 
 
 
 
 
 
b9f0050
b1f4902
ebf9258
 
 
 
 
 
b1f4902
ebf9258
 
 
 
b9f0050
ebf9258
 
b1f4902
 
 
ebf9258
b9f0050
 
 
 
ebf9258
 
 
 
b1f4902
 
 
 
ebf9258
 
 
b1f4902
 
 
 
 
ebf9258
 
b1f4902
 
 
ebf9258
 
 
b1f4902
 
 
 
 
ebf9258
 
 
 
 
 
 
 
 
 
 
 
 
 
b1f4902
 
b9f0050
b1f4902
 
ebf9258
 
 
 
 
b1f4902
 
 
 
 
ebf9258
 
 
 
 
b1f4902
 
b9f0050
 
 
 
 
b1f4902
 
b9f0050
 
 
 
 
 
 
 
 
 
 
ebf9258
 
b9f0050
ebf9258
 
b9f0050
 
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import spaces
import torch
import gradio as gr

from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import PeftModel


# ============================================================
# CONFIGURATION
# ============================================================

BASE_MODEL = "Qwen/Qwen2.5-7B-Instruct"
ADAPTER_MODEL = "Anmol2507/LLM_as_judge_fine_tuned_Qwen_7B"

MAX_LENGTH = 768
MAX_NEW_TOKENS = 32


# ============================================================
# LOAD TOKENIZER
# ============================================================

print("Loading tokenizer...")

tokenizer = AutoTokenizer.from_pretrained(
    BASE_MODEL,
    trust_remote_code=True
)

print("Tokenizer loaded.")


# ============================================================
# LOAD BASE MODEL
# ============================================================
# Load on CPU first because ZeroGPU does not provide a real
# CUDA device during application startup.
# ============================================================

print("Loading base model...")

base_model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    dtype=torch.bfloat16,
    trust_remote_code=True
)

base_model.eval()

print("Base model loaded.")


# ============================================================
# LOAD LoRA ADAPTER
# ============================================================
# torch_device="cpu" is important.
# It prevents PEFT from trying to load adapter weights onto
# CUDA before ZeroGPU allocates a GPU.
# ============================================================

print("Loading LoRA adapter...")

model = PeftModel.from_pretrained(
    base_model,
    ADAPTER_MODEL,
    torch_device="cpu"
)

model.eval()

print("LoRA adapter loaded.")


# ============================================================
# REGISTER MODEL WITH ZEROGPU
# ============================================================
# Keep this at module level.
# ZeroGPU intercepts this CUDA placement.
# ============================================================

print("Registering model with ZeroGPU...")

model = model.to("cuda")

model.eval()

print("Model registered with ZeroGPU.")


# ============================================================
# BUILD JUDGE PROMPT
# ============================================================

def build_prompt(problem, answer_a, answer_b):

    messages = [
        {
            "role": "system",
            "content": (
                "You are an expert AI judge evaluating two answers "
                "to the same programming or technical problem.\n\n"

                "Determine whether each answer is correct.\n"
                "Focus primarily on correctness, logical validity, "
                "and whether the answer actually solves the problem.\n\n"

                "Return ONLY valid JSON using exactly this format:\n"
                '{"A":"correct","B":"incorrect"}\n\n'

                "Allowed labels are only:\n"
                '"correct"\n'
                '"incorrect"\n\n'

                "If both answers are correct, mark both as correct.\n"
                "If both answers are incorrect, mark both as incorrect."
            )
        },
        {
            "role": "user",
            "content": (
                f"Problem:\n{problem}\n\n"
                f"Answer A:\n{answer_a}\n\n"
                f"Answer B:\n{answer_b}\n\n"
                "Evaluate both answers."
            )
        }
    ]

    return tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )


# ============================================================
# JUDGE / INFERENCE FUNCTION
# ============================================================

@spaces.GPU(duration=60)
def judge(problem, answer_a, answer_b):

    # --------------------------------------------------------
    # Validate inputs
    # --------------------------------------------------------

    if not problem or not problem.strip():
        return '{"error":"Problem is required."}'

    if not answer_a or not answer_a.strip():
        return '{"error":"Answer A is required."}'

    if not answer_b or not answer_b.strip():
        return '{"error":"Answer B is required."}'


    # --------------------------------------------------------
    # Create prompt
    # --------------------------------------------------------

    prompt = build_prompt(
        problem,
        answer_a,
        answer_b
    )


    # --------------------------------------------------------
    # Tokenize
    # --------------------------------------------------------

    inputs = tokenizer(
        prompt,
        return_tensors="pt",
        truncation=True,
        max_length=MAX_LENGTH
    )


    # --------------------------------------------------------
    # Move input tensors to GPU
    # --------------------------------------------------------

    inputs = {
        key: value.to("cuda")
        for key, value in inputs.items()
    }


    # --------------------------------------------------------
    # Generate response
    # --------------------------------------------------------

    with torch.inference_mode():

        outputs = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
            pad_token_id=tokenizer.eos_token_id
        )


    # --------------------------------------------------------
    # Remove prompt tokens
    # --------------------------------------------------------

    input_length = inputs["input_ids"].shape[1]

    generated_tokens = outputs[0][input_length:]


    # --------------------------------------------------------
    # Decode model response
    # --------------------------------------------------------

    response = tokenizer.decode(
        generated_tokens,
        skip_special_tokens=True
    ).strip()


    return response


# ============================================================
# GRADIO APPLICATION
# ============================================================

with gr.Blocks(
    title="LLM as Judge"
) as demo:

    # --------------------------------------------------------
    # Header
    # --------------------------------------------------------

    gr.Markdown(
        """
        # 🧑‍⚖️ LLM as Judge

        ### Fine-tuned Qwen2.5-7B Judge

        Evaluate two answers to the same programming or
        technical problem.
        """
    )


    # --------------------------------------------------------
    # Problem
    # --------------------------------------------------------

    problem = gr.Textbox(
        label="Problem",
        placeholder=(
            "Enter the programming or technical problem..."
        ),
        lines=6
    )


    # --------------------------------------------------------
    # Answers
    # --------------------------------------------------------

    with gr.Row():

        answer_a = gr.Textbox(
            label="Answer A",
            placeholder="Enter Answer A...",
            lines=12
        )

        answer_b = gr.Textbox(
            label="Answer B",
            placeholder="Enter Answer B...",
            lines=12
        )


    # --------------------------------------------------------
    # Judge button
    # --------------------------------------------------------

    judge_button = gr.Button(
        "⚖️ Evaluate",
        variant="primary"
    )


    # --------------------------------------------------------
    # Result
    # --------------------------------------------------------

    result = gr.Code(
        label="Judge Result",
        language="json"
    )


    # --------------------------------------------------------
    # API EVENT
    # --------------------------------------------------------
    # IMPORTANT:
    # This must remain INSIDE the Blocks context.
    # api_name="judge" exposes the endpoint as /judge.
    # --------------------------------------------------------

    judge_button.click(
        fn=judge,
        inputs=[
            problem,
            answer_a,
            answer_b
        ],
        outputs=result,
        api_name="judge"
    )


# ============================================================
# START APPLICATION
# ============================================================

if __name__ == "__main__":
    demo.launch()