schroneko commited on
Commit
ca0aa0f
1 Parent(s): 9177727

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -12
app.py CHANGED
@@ -1,28 +1,21 @@
1
- import os
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
4
  import gradio as gr
5
  import spaces
6
 
7
- huggingface_token = os.getenv('HUGGINGFACE_TOKEN')
8
- if not huggingface_token:
9
- raise ValueError("HUGGINGFACE_TOKEN environment variable is not set")
10
-
11
  model_id = "meta-llama/Llama-Guard-3-8B-INT8"
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
13
  dtype = torch.bfloat16
14
 
15
  quantization_config = BitsAndBytesConfig(load_in_8bit=True)
16
 
17
- @spaces.GPU
18
  def load_model():
19
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=huggingface_token)
20
  model = AutoModelForCausalLM.from_pretrained(
21
  model_id,
22
  torch_dtype=dtype,
23
  device_map="auto",
24
  quantization_config=quantization_config,
25
- token=huggingface_token,
26
  low_cpu_mem_usage=True
27
  )
28
  return tokenizer, model
@@ -36,9 +29,29 @@ def moderate(user_input, assistant_response):
36
  {"role": "assistant", "content": assistant_response},
37
  ]
38
  input_ids = tokenizer.apply_chat_template(chat, return_tensors="pt").to(device)
39
- output = model.generate(input_ids=input_ids, max_new_tokens=100, pad_token_id=0)
40
- prompt_len = input_ids.shape[-1]
41
- return tokenizer.decode(output[0][prompt_len:], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  iface = gr.Interface(
44
  fn=moderate,
@@ -46,7 +59,11 @@ iface = gr.Interface(
46
  gr.Textbox(lines=3, label="User Input"),
47
  gr.Textbox(lines=3, label="Assistant Response")
48
  ],
49
- outputs=gr.Textbox(label="Moderation Result"),
 
 
 
 
50
  title="Llama Guard Moderation",
51
  description="Enter a user input and an assistant response to check for content moderation."
52
  )
 
 
1
  import torch
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
3
  import gradio as gr
4
  import spaces
5
 
 
 
 
 
6
  model_id = "meta-llama/Llama-Guard-3-8B-INT8"
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
8
  dtype = torch.bfloat16
9
 
10
  quantization_config = BitsAndBytesConfig(load_in_8bit=True)
11
 
 
12
  def load_model():
13
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
14
  model = AutoModelForCausalLM.from_pretrained(
15
  model_id,
16
  torch_dtype=dtype,
17
  device_map="auto",
18
  quantization_config=quantization_config,
 
19
  low_cpu_mem_usage=True
20
  )
21
  return tokenizer, model
 
29
  {"role": "assistant", "content": assistant_response},
30
  ]
31
  input_ids = tokenizer.apply_chat_template(chat, return_tensors="pt").to(device)
32
+
33
+ with torch.no_grad():
34
+ output = model.generate(
35
+ input_ids=input_ids,
36
+ max_new_tokens=200,
37
+ pad_token_id=tokenizer.eos_token_id,
38
+ do_sample=False
39
+ )
40
+
41
+ result = tokenizer.decode(output[0], skip_special_tokens=True)
42
+
43
+ result = result.split(assistant_response)[-1].strip()
44
+
45
+ is_safe = "safe" in result.lower()
46
+ categories = []
47
+ if not is_safe and "categories:" in result:
48
+ categories = [cat.strip() for cat in result.split("categories:")[1].split(",") if cat.strip()]
49
+
50
+ return {
51
+ "is_safe": "Safe" if is_safe else "Unsafe",
52
+ "categories": ", ".join(categories) if categories else "None",
53
+ "raw_output": result
54
+ }
55
 
56
  iface = gr.Interface(
57
  fn=moderate,
 
59
  gr.Textbox(lines=3, label="User Input"),
60
  gr.Textbox(lines=3, label="Assistant Response")
61
  ],
62
+ outputs=[
63
+ gr.Textbox(label="Safety Status"),
64
+ gr.Textbox(label="Violated Categories"),
65
+ gr.Textbox(label="Raw Output")
66
+ ],
67
  title="Llama Guard Moderation",
68
  description="Enter a user input and an assistant response to check for content moderation."
69
  )