|
import torch |
|
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig |
|
import gradio as gr |
|
import spaces |
|
|
|
model_id = "meta-llama/Llama-Guard-3-8B-INT8" |
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
dtype = torch.bfloat16 |
|
|
|
quantization_config = BitsAndBytesConfig(load_in_8bit=True) |
|
|
|
def load_model(): |
|
tokenizer = AutoTokenizer.from_pretrained(model_id) |
|
model = AutoModelForCausalLM.from_pretrained( |
|
model_id, |
|
torch_dtype=dtype, |
|
device_map="auto", |
|
quantization_config=quantization_config, |
|
low_cpu_mem_usage=True |
|
) |
|
return tokenizer, model |
|
|
|
tokenizer, model = load_model() |
|
|
|
@spaces.GPU |
|
def moderate(user_input, assistant_response): |
|
chat = [ |
|
{"role": "user", "content": user_input}, |
|
{"role": "assistant", "content": assistant_response}, |
|
] |
|
input_ids = tokenizer.apply_chat_template(chat, return_tensors="pt").to(device) |
|
|
|
with torch.no_grad(): |
|
output = model.generate( |
|
input_ids=input_ids, |
|
max_new_tokens=200, |
|
pad_token_id=tokenizer.eos_token_id, |
|
do_sample=False |
|
) |
|
|
|
result = tokenizer.decode(output[0], skip_special_tokens=True) |
|
|
|
result = result.split(assistant_response)[-1].strip() |
|
|
|
is_safe = "safe" in result.lower() |
|
categories = [] |
|
if not is_safe and "categories:" in result: |
|
categories = [cat.strip() for cat in result.split("categories:")[1].split(",") if cat.strip()] |
|
|
|
return { |
|
"is_safe": "Safe" if is_safe else "Unsafe", |
|
"categories": ", ".join(categories) if categories else "None", |
|
"raw_output": result |
|
} |
|
|
|
iface = gr.Interface( |
|
fn=moderate, |
|
inputs=[ |
|
gr.Textbox(lines=3, label="User Input"), |
|
gr.Textbox(lines=3, label="Assistant Response") |
|
], |
|
outputs=[ |
|
gr.Textbox(label="Safety Status"), |
|
gr.Textbox(label="Violated Categories"), |
|
gr.Textbox(label="Raw Output") |
|
], |
|
title="Llama Guard Moderation", |
|
description="Enter a user input and an assistant response to check for content moderation." |
|
) |
|
|
|
if __name__ == "__main__": |
|
iface.launch() |