Yixiao Wang (Computer Science) commited on
Commit
cd15e92
·
1 Parent(s): 6ba2695
Files changed (2) hide show
  1. app.py +171 -58
  2. requirements.txt +11 -1
app.py CHANGED
@@ -1,64 +1,177 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  ],
 
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ import logging
2
+ import textwrap
3
+ from typing import Literal, Optional
4
+
5
  import gradio as gr
6
+ import outlines
7
+ import pandas as pd
8
+ import torch
9
+ from outlines import Generator
10
+ from peft import PeftConfig, PeftModel
11
+ from pydantic import BaseModel, ConfigDict
12
+ from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig
13
+
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ MODEL_ID = "rshwndsz/ft-hermes-3-llama-3.2-3b"
18
+ DEVICE_MAP = "auto"
19
+ QUANTIZATION_BITS = None
20
+ TEMPERATURE = 0.0
21
+
22
+
23
+ SYSTEM_PROMPT = textwrap.dedent("""
24
+ You are an assistant tasked with grading answers to a mind reading ability test. You will be provided with the following information:
25
+
26
+ 1. A story that was presented to participants as context
27
+ 2. The question that participants were asked to answer
28
+ 3. A grading scheme to evaluate the answers (Correct Responses:1, incorrect response:0, Incomplete response:0, Irrelevant:0)
29
+ 4. Grading examples
30
+ 5. A participant answer
31
+
32
+ Your task is to grade each answer according to the grading scheme. For each answer, you should:
33
+
34
+ 1. Carefully read and understand the answer and compare it to the grading criteria
35
+ 2. Assigning an score 1 or 0 for each answer.
36
+ """).strip()
37
+
38
+ PROMPT_TEMPLATE = textwrap.dedent("""
39
+ <Story>
40
+ {story}
41
+ </Story>
42
+
43
+ <Question>
44
+ {question}
45
+ </Question>
46
+
47
+ <GradingScheme>
48
+ {grading_scheme}
49
+ </GradingScheme>
50
+
51
+ <Answer>
52
+ {answer}
53
+ </Answer>
54
+
55
+ Score:""").strip()
56
+
57
+
58
+ class ResponseModel(BaseModel):
59
+ model_config = ConfigDict(extra="forbid")
60
+ score: Literal["0", "1"]
61
+
62
+
63
+ def get_outlines_model(model_id: str, device_map: str = "auto", quantization_bits: Optional[int] = 4):
64
+ if quantization_bits == 4:
65
+ quantization_config = BitsAndBytesConfig(
66
+ load_in_4bit=True,
67
+ bnb_4bit_quant_type="nf4",
68
+ bnb_4bit_use_double_quant=True,
69
+ bnb_4bit_compute_dtype=torch.bfloat16,
70
+ )
71
+ elif quantization_bits == 8:
72
+ quantization_config = BitsAndBytesConfig(load_in_8bit=True)
73
+ else:
74
+ quantization_config = None
75
+
76
+ if "longformer" in model_id:
77
+ hf_model = AutoModelForSequenceClassification.from_pretrained(model_id)
78
+ hf_tokenizer = AutoTokenizer.from_pretrained(model_id)
79
+ return hf_model, hf_tokenizer
80
+
81
+ peft_config = PeftConfig.from_pretrained(model_id)
82
+ base_model_id = peft_config.base_model_name_or_path
83
+
84
+ base_model = AutoModelForCausalLM.from_pretrained(
85
+ base_model_id,
86
+ device_map=device_map,
87
+ quantization_config=quantization_config,
88
+ )
89
+ hf_model = PeftModel.from_pretrained(base_model, model_id)
90
+ hf_tokenizer = AutoTokenizer.from_pretrained(base_model_id, use_fast=True, clean_up_tokenization_spaces=True)
91
+
92
+ model = outlines.from_transformers(hf_model, hf_tokenizer)
93
+ return model
94
+
95
+
96
+ def format_prompt(story: str, question: str, grading_scheme: str, answer: str) -> str:
97
+ prompt = PROMPT_TEMPLATE.format(
98
+ story=story.strip(),
99
+ question=question.strip(),
100
+ grading_scheme=grading_scheme.strip(),
101
+ answer=answer.strip(),
102
+ )
103
+ full_prompt = SYSTEM_PROMPT + "\n\n" + prompt
104
+ return full_prompt
105
+
106
+
107
+ def label_single_response(story, question, criteria, response):
108
+ prompt = format_prompt(story, question, criteria, response)
109
+
110
+ if "longformer" in MODEL_ID:
111
+ model, tokenizer = get_outlines_model(MODEL_ID, DEVICE_MAP, QUANTIZATION_BITS)
112
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, padding=True)
113
+ with torch.no_grad():
114
+ logits = model(**inputs).logits
115
+ predicted_class = torch.argmax(logits, dim=1).item()
116
+ return str(predicted_class)
117
+ else:
118
+ model = get_outlines_model(MODEL_ID, DEVICE_MAP, QUANTIZATION_BITS)
119
+ generator = Generator(model)
120
+ with torch.no_grad():
121
+ result = generator(prompt)
122
+ return result.score
123
+
124
+
125
+ def label_multi_responses(story, question, criteria, response_file):
126
+ df = pd.read_csv(response_file.name)
127
+ assert "response" in df.columns, "CSV must contain a 'response' column."
128
+ prompts = [format_prompt(story, question, criteria, resp) for resp in df["response"]]
129
+
130
+ if "longformer" in MODEL_ID:
131
+ model, tokenizer = get_outlines_model(MODEL_ID, DEVICE_MAP, QUANTIZATION_BITS)
132
+ inputs = tokenizer(prompts, return_tensors="pt", truncation=True, padding=True)
133
+ with torch.no_grad():
134
+ logits = model(**inputs).logits
135
+ predicted_classes = torch.argmax(logits, dim=1).tolist()
136
+ scores = [str(cls) for cls in predicted_classes]
137
+ else:
138
+ model = get_outlines_model(MODEL_ID, DEVICE_MAP, QUANTIZATION_BITS)
139
+ generator = Generator(model)
140
+ with torch.no_grad():
141
+ results = generator(prompts)
142
+ scores = [r.score for r in results]
143
+
144
+ df["score"] = scores
145
+ return df
146
+
147
+
148
+ single_tab = gr.Interface(
149
+ fn=label_single_response,
150
+ inputs=[
151
+ gr.Textbox(label="Story", lines=6),
152
+ gr.Textbox(label="Question", lines=2),
153
+ gr.Textbox(label="Criteria (Grading Scheme)", lines=4),
154
+ gr.Textbox(label="Single Response", lines=3),
155
  ],
156
+ outputs=gr.Textbox(label="Score"),
157
  )
158
 
159
+ multi_tab = gr.Interface(
160
+ fn=label_multi_responses,
161
+ inputs=[
162
+ gr.Textbox(label="Story", lines=6),
163
+ gr.Textbox(label="Question", lines=2),
164
+ gr.Textbox(label="Criteria (Grading Scheme)", lines=4),
165
+ gr.File(label="Responses CSV (.csv with 'response' column)", file_types=[".csv"]),
166
+ ],
167
+ outputs=gr.Dataframe(label="Labeled Responses", type="pandas"),
168
+ )
169
+
170
+ iface = gr.TabbedInterface(
171
+ [single_tab, multi_tab],
172
+ ["Single Response", "Batch (CSV)"],
173
+ title="Zero-Shot Evaluation Grader",
174
+ )
175
 
176
  if __name__ == "__main__":
177
+ iface.launch()
requirements.txt CHANGED
@@ -1 +1,11 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+ transformers
3
+ gradio
4
+ peft
5
+ outlines
6
+ bitsandbytes
7
+ accelerate
8
+ torch
9
+ pandas
10
+ pydantic
11
+ numpy