Llama-Guard is a 7B parameter
Llama 2-based input-output
safeguard model. It can be used for classifying content in both LLM inputs (prompt
classification) and in LLM responses (response classification).
It acts as an LLM: it generates text in its output that indicates whether a given prompt or
response is safe/unsafe, and if unsafe based on a policy, it also lists the violating subcategories.
Here is an example:
In order to produce classifier scores, we look at the probability for the first token, and turn that
into an “unsafe” class probability. Model users can then make binary decisions by applying a
desired threshold to the probability scores.
We use a mix of prompts that come from the Anthropic
dataset and redteaming examples that we have collected
in house, in a separate process from our production redteaming. In particular, we took the
prompts only from the Anthropic dataset, and generated new responses from our in-house
LLaMA models, using jailbreaking techniques to elicit violating responses. We then annotated
Anthropic data (prompts & responses) in house, mapping labels according to the categories
identified above. Overall we have ~13K training examples.
As automated content risk mitigation relies on classifiers to make decisions
about content in real time, a prerequisite to building these systems is to have
the following components:
Below, we provide both the harm types themselves under this taxonomy and also examples of
the specific kinds of content that would be considered harmful under each category:
1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3
4model_id = "meta-llama/LlamaGuard-7b"
5device = "cuda"
6dtype = torch.bfloat16
7
8tokenizer = AutoTokenizer.from_pretrained(model_id)
9model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=dtype, device_map=device)
10
11def moderate(chat):
12 input_ids = tokenizer.apply_chat_template(chat, return_tensors="pt").to(device)
13 output = model.generate(input_ids=input_ids, max_new_tokens=100, pad_token_id=0)
14 prompt_len = input_ids.shape[-1]
15 return tokenizer.decode(output[0][prompt_len:], skip_special_tokens=True)
16
17moderate([
18 {"role": "user", "content": "I forgot how to kill a process in Linux, can you help?"},
19 {"role": "assistant", "content": "Sure! To kill a process in Linux, you can use the kill command followed by the process ID (PID) of the process you want to terminate."},
20])
21# `safe`
We compare the performance of the model against standard content moderation APIs
in the industry, including
OpenAI,
Azure Content Safety,and
PerspectiveAPI from Google on both public and in-house benchmarks. The public benchmarks
include
ToxicChat and
OpenAI Moderation.
Note: comparisons are not exactly apples-to-apples due to mismatches in each
taxonomy. The interested reader can find a more detailed discussion about this
in
our paper.