taruschirag commited on
Commit
cf52f85
·
verified ·
1 Parent(s): 1c0b627

Update app.py

Browse files

Version of DynaGuard 8b params

Files changed (1) hide show
  1. app.py +171 -55
app.py CHANGED
@@ -1,64 +1,180 @@
 
 
 
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 os
2
+ os.environ["GRADIO_ENABLE_SSR"] = "0"
3
+
4
  import gradio as gr
5
+ import torch
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ from datasets import load_dataset
8
+ from huggingface_hub import login
9
+
10
+ HF_READONLY_API_KEY = os.getenv("HF_READONLY_API_KEY")
11
+ login(token=HF_READONLY_API_KEY)
12
 
13
+ COT_OPENING = "<think>"
14
+ EXPLANATION_OPENING = "<explanation>"
15
+ LABEL_OPENING = "<answer>"
16
+ LABEL_CLOSING = "</answer>"
17
+ INPUT_FIELD = "question"
18
+ SYSTEM_PROMPT = """You are a guardian model evaluating…</explanation>"""
19
 
20
+ def format_rules(rules):
21
+ formatted_rules = "<rules>\n"
22
+ for i, rule in enumerate(rules):
23
+ formatted_rules += f"{i + 1}. {rule}\n"
24
+ formatted_rules += "</rules>\n"
25
+ return formatted_rules
26
 
27
+ def format_transcript(transcript):
28
+ formatted_transcript = f"<transcript>\n{transcript}\n</transcript>\n"
29
+ return formatted_transcript
30
+
31
+ def get_example(
32
+ dataset_path="tomg-group-umd/compliance_benchmark",
33
+ subset="compliance",
34
+ split="test_handcrafted",
35
+ example_idx=0,
36
  ):
37
+ dataset = load_dataset(dataset_path, subset, split=split)
38
+ example = dataset[example_idx]
39
+ return example[INPUT_FIELD]
40
+
41
+ def get_message(model, input, system_prompt=SYSTEM_PROMPT, enable_thinking=True):
42
+ message = model.apply_chat_template(system_prompt, input, enable_thinking=enable_thinking)
43
+ return message
44
+
45
+ class ModelWrapper:
46
+ def __init__(self, model_name="Qwen/Qwen3-0.6B"):
47
+ self.model_name = model_name
48
+ if "nemoguard" in model_name:
49
+ self.tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
50
+ else:
51
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
52
+ self.tokenizer.pad_token_id = self.tokenizer.pad_token_id or self.tokenizer.eos_token_id
53
+ self.model = AutoModelForCausalLM.from_pretrained(
54
+ model_name, device_map="auto", torch_dtype=torch.bfloat16).eval()
55
+
56
+ def get_message_template(self, system_content=None, user_content=None, assistant_content=None):
57
+ """Compile sys, user, assistant inputs into the proper dictionaries"""
58
+ message = []
59
+ if system_content is not None:
60
+ message.append({'role': 'system', 'content': system_content})
61
+ if user_content is not None:
62
+ message.append({'role': 'user', 'content': user_content})
63
+ if assistant_content is not None:
64
+ message.append({'role': 'assistant', 'content': assistant_content})
65
+ if not message:
66
+ raise ValueError("No content provided for any role.")
67
+ return message
68
+
69
+ def apply_chat_template(self, system_content, user_content, assistant_content=None, enable_thinking=True):
70
+ """Call the tokenizer's chat template with exactly the right arguments for whether we want it to generate thinking before the answer (which differs depending on whether it is Qwen3 or not)."""
71
+ if assistant_content is not None:
72
+ # If assistant content is passed we simply use it.
73
+ # This works for both Qwen3 and non-Qwen3 models. With Qwen3 any time assistant_content is provided, it automatically adds the <think></think> pair before the content, which is what we want.
74
+ message = self.get_message_template(system_content, user_content, assistant_content)
75
+ prompt = self.tokenizer.apply_chat_template(message, tokenize=False, continue_final_message=True)
76
+ else:
77
+ if enable_thinking:
78
+ if "qwen3" in self.model_name.lower():
79
+ # Let the Qwen chat template handle the thinking token
80
+ message = self.get_message_template(system_content, user_content)
81
+ prompt = self.tokenizer.apply_chat_template(message, tokenize=False, add_generation_prompt=True, enable_thinking=True)
82
+ # The way the Qwen3 chat template works is it adds a <think></think> pair when enable_thinking=False, but for enable_thinking=True, it adds nothing and lets the model decide. Here we force the <think> tag to be there.
83
+ prompt = prompt + f"\n{COT_OPENING}"
84
+ else:
85
+ message = self.get_message_template(system_content, user_content, assistant_content=COT_OPENING)
86
+ prompt = self.tokenizer.apply_chat_template(message, tokenize=False, continue_final_message=True)
87
+ else:
88
+ # This works for both Qwen3 and non-Qwen3 models.
89
+ # When Qwen3 gets assistant_content, it automatically adds the <think></think> pair before the content like we want. And other models ignore the enable_thinking argument.
90
+ message = self.get_message_template(system_content, user_content, assistant_content=LABEL_OPENING)
91
+ prompt = self.tokenizer.apply_chat_template(message, tokenize=False, continue_final_message=True, enable_thinking=False)
92
+ return prompt
93
+
94
+ def get_response(self, input, temperature=0.7, top_k=20, top_p=0.8, max_new_tokens=256, enable_thinking=True, system_prompt=SYSTEM_PROMPT):
95
+ """Generate and decode the response with the recommended temperature settings for thinking and non-thinking."""
96
+ print("Generating response...")
97
+
98
+ if "qwen3" in self.model_name.lower() and enable_thinking:
99
+ # Use values from https://huggingface.co/Qwen/Qwen3-8B#switching-between-thinking-and-non-thinking-mode
100
+ temperature = 0.6
101
+ top_p = 0.95
102
+ top_k = 20
103
+
104
+ message = self.apply_chat_template(system_prompt, input, enable_thinking=enable_thinking)
105
+ inputs = self.tokenizer(message, return_tensors="pt").to(self.model.device)
106
+
107
+ with torch.no_grad():
108
+ output_content = self.model.generate(
109
+ **inputs,
110
+ max_new_tokens=max_new_tokens,
111
+ num_return_sequences=1,
112
+ temperature=temperature,
113
+ top_k=top_k,
114
+ top_p=top_p,
115
+ min_p=0,
116
+ pad_token_id=self.tokenizer.pad_token_id,
117
+ do_sample=True,
118
+ eos_token_id=self.tokenizer.eos_token_id
119
+ )
120
+
121
+ output_text = self.tokenizer.decode(output_content[0], skip_special_tokens=True)
122
+
123
+ try:
124
+ sys_prompt_text = output_text.split("Brief explanation\n</explanation>")[0]
125
+ remainder = output_text.split("Brief explanation\n</explanation>")[-1]
126
+ rules_transcript_text = remainder.split("</transcript>")[0]
127
+ thinking_answer_text = remainder.split("</transcript>")[-1]
128
+ return thinking_answer_text
129
+ except:
130
+ input_length = len(message)
131
+ return output_text[input_length:] if len(output_text) > input_length else "No response generated."
132
+
133
+ MODEL_NAME = "Qwen/Qwen3-8B"
134
+ model = ModelWrapper(MODEL_NAME)
135
+
136
+ # — Gradio inference function —
137
+ def compliance_check(rules_text, transcript_text, thinking):
138
+ try:
139
+ rules = [r for r in rules_text.split("\n") if r.strip()]
140
+ inp = format_rules(rules) + format_transcript(transcript_text)
141
+
142
+ out = model.get_response(inp, enable_thinking=thinking, max_new_tokens=256)
143
+
144
+ out = str(out).strip()
145
+ if not out:
146
+ out = "No response generated. Please try with different input."
147
+
148
+ max_bytes = 2500
149
+ out_bytes = out.encode('utf-8')
150
+
151
+ if len(out_bytes) > max_bytes:
152
+
153
+ truncated_bytes = out_bytes[:max_bytes]
154
+ out = truncated_bytes.decode('utf-8', errors='ignore')
155
+ out += "\n\n[Response truncated to prevent server errors]"
156
+
157
+ return out
158
+
159
+ except Exception as e:
160
+ error_msg = f"Error: {str(e)[:200]}"
161
+ print(f"Full error: {e}")
162
+ return error_msg
163
+
164
+
165
+ demo = gr.Interface(
166
+ fn=compliance_check,
167
+ inputs=[
168
+ gr.Textbox(lines=5, label="Rules (one per line)", max_lines=10),
169
+ gr.Textbox(lines=10, label="Transcript", max_lines=15),
170
+ gr.Checkbox(label="Enable ⟨think⟩ mode", value=True)
171
  ],
172
+ outputs=gr.Textbox(label="Compliance Output", lines=10, max_lines=15),
173
+ title="DynaGuard Compliance Checker",
174
+ description="Paste your rules & transcript, then hit Submit.",
175
+ allow_flagging="never",
176
+ show_progress=True
177
  )
178
 
 
179
  if __name__ == "__main__":
180
+ demo.launch()