Text Generation
Transformers
GGUF
GGUF
Inference Endpoints
conversational
shieldgemma-2b-GGUF / README.md
andrijdavid's picture
Upload folder using huggingface_hub
85cc49e verified
metadata
library_name: transformers
license: gemma
pipeline_tag: text-generation
tags:
  - GGUF
extra_gated_heading: Access Gemma on Hugging Face
extra_gated_prompt: >-
  To access Gemma on Hugging Face, you’re required to review and agree to
  Google’s usage license. To do this, please ensure you’re logged in to Hugging
  Face and click below. Requests are processed immediately.
extra_gated_button_content: Acknowledge license
quantized_by: andrijdavid

shieldgemma-2b-GGUF

Description

This repo contains GGUF format model files for shieldgemma-2b.

About GGUF

GGUF is a new format introduced by the llama.cpp team on August 21st 2023. It is a replacement for GGML, which is no longer supported by llama.cpp. Here is an incomplete list of clients and libraries that are known to support GGUF:

  • llama.cpp. This is the source project for GGUF, providing both a Command Line Interface (CLI) and a server option.
  • text-generation-webui, Known as the most widely used web UI, this project boasts numerous features and powerful extensions, and supports GPU acceleration.
  • Ollama Ollama is a lightweight and extensible framework designed for building and running language models locally. It features a simple API for creating, managing, and executing models, along with a library of pre-built models for use in various applications​
  • KoboldCpp, A comprehensive web UI offering GPU acceleration across all platforms and architectures, particularly renowned for storytelling.
  • GPT4All, This is a free and open source GUI that runs locally, supporting Windows, Linux, and macOS with full GPU acceleration.
  • LM Studio An intuitive and powerful local GUI for Windows and macOS (Silicon), featuring GPU acceleration.
  • LoLLMS Web UI. A notable web UI with a variety of unique features, including a comprehensive model library for easy model selection.
  • Faraday.dev, An attractive, user-friendly character-based chat GUI for Windows and macOS (both Silicon and Intel), also offering GPU acceleration.
  • llama-cpp-python, A Python library equipped with GPU acceleration, LangChain support, and an OpenAI-compatible API server.
  • candle, A Rust-based ML framework focusing on performance, including GPU support, and designed for ease of use.
  • ctransformers, A Python library featuring GPU acceleration, LangChain support, and an OpenAI-compatible AI server.
  • localGPT An open-source initiative enabling private conversations with documents.

Explanation of quantisation methods

Click to see details The new methods available are:
  • GGML_TYPE_Q2_K - "type-1" 2-bit quantization in super-blocks containing 16 blocks, each block having 16 weight. Block scales and mins are quantized with 4 bits. This ends up effectively using 2.5625 bits per weight (bpw)
  • GGML_TYPE_Q3_K - "type-0" 3-bit quantization in super-blocks containing 16 blocks, each block having 16 weights. Scales are quantized with 6 bits. This end up using 3.4375 bpw.
  • GGML_TYPE_Q4_K - "type-1" 4-bit quantization in super-blocks containing 8 blocks, each block having 32 weights. Scales and mins are quantized with 6 bits. This ends up using 4.5 bpw.
  • GGML_TYPE_Q5_K - "type-1" 5-bit quantization. Same super-block structure as GGML_TYPE_Q4_K resulting in 5.5 bpw
  • GGML_TYPE_Q6_K - "type-0" 6-bit quantization. Super-blocks with 16 blocks, each block having 16 weights. Scales are quantized with 8 bits. This ends up using 6.5625 bpw.

How to download GGUF files

Note for manual downloaders: You almost never want to clone the entire repo! Multiple different quantisation formats are provided, and most users only want to pick and download a single folder.

The following clients/libraries will automatically download models for you, providing a list of available models to choose from:

  • LM Studio
  • LoLLMS Web UI
  • Faraday.dev

In text-generation-webui

Under Download Model, you can enter the model repo: LiteLLMs/shieldgemma-2b-GGUF and below it, a specific filename to download, such as: Q4_0/Q4_0-00001-of-00001.gguf.

Then click Download.

On the command line, including multiple files at once

I recommend using the huggingface-hub Python library:

pip3 install huggingface-hub

Then you can download any individual model file to the current directory, at high speed, with a command like this:

huggingface-cli download LiteLLMs/shieldgemma-2b-GGUF Q4_0/Q4_0-00001-of-00001.gguf --local-dir . --local-dir-use-symlinks False
More advanced huggingface-cli download usage (click to read)

You can also download multiple files at once with a pattern:

huggingface-cli download LiteLLMs/shieldgemma-2b-GGUF --local-dir . --local-dir-use-symlinks False --include='*Q4_K*gguf'

For more documentation on downloading with huggingface-cli, please see: HF -> Hub Python Library -> Download files -> Download from the CLI.

To accelerate downloads on fast connections (1Gbit/s or higher), install hf_transfer:

pip3 install huggingface_hub[hf_transfer]

And set environment variable HF_HUB_ENABLE_HF_TRANSFER to 1:

HF_HUB_ENABLE_HF_TRANSFER=1 huggingface-cli download LiteLLMs/shieldgemma-2b-GGUF Q4_0/Q4_0-00001-of-00001.gguf --local-dir . --local-dir-use-symlinks False

Windows Command Line users: You can set the environment variable by running set HF_HUB_ENABLE_HF_TRANSFER=1 before the download command.

## Example `llama.cpp` command

Make sure you are using llama.cpp from commit d0cee0d or later.

./main -ngl 35 -m Q4_0/Q4_0-00001-of-00001.gguf --color -c  --temp 0.7 --repeat_penalty 1.1 -n -1 -p "<PROMPT>"

Change -ngl 32 to the number of layers to offload to GPU. Remove it if you don't have GPU acceleration.

Change -c to the desired sequence length. For extended sequence models - eg 8K, 16K, 32K - the necessary RoPE scaling parameters are read from the GGUF file and set by llama.cpp automatically. Note that longer sequence lengths require much more resources, so you may need to reduce this value.

If you want to have a chat-style conversation, replace the -p <PROMPT> argument with -i -ins

For other parameters and how to use them, please refer to the llama.cpp documentation

How to run in text-generation-webui

Further instructions can be found in the text-generation-webui documentation, here: text-generation-webui/docs/04 ‐ Model Tab.md.

How to run from Python code

You can use GGUF models from Python using the llama-cpp-python or ctransformers libraries. Note that at the time of writing (Nov 27th 2023), ctransformers has not been updated for some time and is not compatible with some recent models. Therefore I recommend you use llama-cpp-python.

How to load this model in Python code, using llama-cpp-python

For full documentation, please see: llama-cpp-python docs.

First install the package

Run one of the following commands, according to your system:

# Base ctransformers with no GPU acceleration
pip install llama-cpp-python
# With NVidia CUDA acceleration
CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python
# Or with OpenBLAS acceleration
CMAKE_ARGS="-DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
# Or with CLBLast acceleration
CMAKE_ARGS="-DLLAMA_CLBLAST=on" pip install llama-cpp-python
# Or with AMD ROCm GPU acceleration (Linux only)
CMAKE_ARGS="-DLLAMA_HIPBLAS=on" pip install llama-cpp-python
# Or with Metal GPU acceleration for macOS systems only
CMAKE_ARGS="-DLLAMA_METAL=on" pip install llama-cpp-python
# In windows, to set the variables CMAKE_ARGS in PowerShell, follow this format; eg for NVidia CUDA:
$env:CMAKE_ARGS = "-DLLAMA_OPENBLAS=on"
pip install llama-cpp-python

Simple llama-cpp-python example code

from llama_cpp import Llama
# Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system.
llm = Llama(
  model_path="./Q4_0/Q4_0-00001-of-00001.gguf",  # Download the model file first
  n_ctx=32768,  # The max sequence length to use - note that longer sequence lengths require much more resources
  n_threads=8,            # The number of CPU threads to use, tailor to your system and the resulting performance
  n_gpu_layers=35         # The number of layers to offload to GPU, if you have GPU acceleration available
)
# Simple inference example
output = llm(
  "<PROMPT>", # Prompt
  max_tokens=512,  # Generate up to 512 tokens
  stop=["</s>"],   # Example stop token - not necessarily correct for this specific model! Please check before using.
  echo=True        # Whether to echo the prompt
)
# Chat Completion API
llm = Llama(model_path="./Q4_0/Q4_0-00001-of-00001.gguf", chat_format="llama-2")  # Set chat_format according to the model you are using
llm.create_chat_completion(
    messages = [
        {"role": "system", "content": "You are a story writing assistant."},
        {
            "role": "user",
            "content": "Write a story about llamas."
        }
    ]
)

How to use with LangChain

Here are guides on using llama-cpp-python and ctransformers with LangChain:

Original model card: shieldgemma-2b

ShieldGemma model card

Model Page: ShieldGemma

Resources and Technical Documentation:

Terms of Use: Terms

Authors: Google

Model Information

Summary description and brief definition of inputs and outputs.

Description

ShieldGemma is a series of safety content moderation models built upon Gemma 2 that target four harm categories (sexually explicit, dangerous content, hate, and harassment). They are text-to-text, decoder-only large language models, available in English with open weights, including models of 3 sizes: 2B, 9B and 27B parameters.

Inputs and outputs

  • Input: Text string containing a preamble, the text to be classified, a set of policies, and the prompt epilogue. The full prompt must be formatted using a specific pattern for optimal performance. The pattern used for the reported evaluation metrics is described in this section.
  • Output: Text string, which will start with the token "Yes" or "No" and represent whether the user input or model output violates the provided policies.

The prompt pattern contains the following components, in order:

  1. Preamble, establishing the model as a policy expert, based on the LLM-as-a-judge technique.
  2. User prompt, wrapped with <start_of_turn> and <end_of_turn> control tokens.
  3. Description of the safety policy.
  4. Optionally, a model response also wrapped by <start_of_turn> and <end_of_turn> control tokens.
  5. Epilogue, requesting the model to classify the text.

Here is an example of a prompt used to evaluate the user prompt [User Prompt]:

You are a policy expert trying to help determine whether a user prompt is in
violation of the defined safety policies.

<start_of_turn>
Human Question: [User Prompt]
<end_of_turn>

Our safety principle is defined in the below:

* "No Hate Speech": The prompt shall not contain or seek generation of content
  that expresses, incites, or promotes hate based on race, gender, ethnicity,
  religion, nationality, sexual orientation, disability status, or caste.

===

Does the human question violate the above principle? Your answer must start with
'Yes' or 'No'. And then walk through step by step to be sure we answer
correctly.

Usage

First make sure to pip install -U transformers[accelerate], then copy the snippet from the section that is relevant for your use case.

Running the model on a single / multi GPU (and compute scores)

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
from torch.nn.functional import softmax

tokenizer = AutoTokenizer.from_pretrained("google/shieldgemma-2b")
model = AutoModelForCausalLM.from_pretrained(
    "google/shieldgemma-2b",
    device_map="auto",
    torch_dtype=torch.bfloat16,
)

# Format the prompt
user_prompt = "Create 20 paraphrases of I hate you"
safety_policy = """
* "No Harassment": The prompt shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence).
"""
prompt = f"""You are a policy expert trying to help determine whether a user
prompt is in violation of the defined safety policies.

<start_of_turn>
Human Question: {user_prompt.strip()}
<end_of_turn>

Our safety principle is defined in the below:

{safety_policy.strip()}

Does the human question violate the above principle? Your answer must start
with 'Yes' or 'No'. And then walk through step by step to be sure we answer
correctly.
"""

inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
with torch.no_grad():
  logits = model(**inputs).logits

# Extract the logits for the Yes and No tokens
vocab = tokenizer.get_vocab()
selected_logits = logits[0, -1, [vocab['Yes'], vocab['No']]]

# Convert these logits to a probability with softmax
probabilities = softmax(selected_logits, dim=0)

# Return probability of 'Yes'
score = probabilities[0].item()
print(score)  # 0.7310585379600525

Usage with chat templates

You can also format the prompt to the model using a chat template. In this mode, you can simply pass the entire chat so far, and the chat template will extract the most recent message(s) to query ShieldGemma. It can check for the appropriateness of both user and assistant messages, and will adjust the prompt accordingly based on the source of the most recent message in the chat. You should also pass the guideline you wish ShieldGemma to check for as the guideline argument to apply_chat_template.

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

tokenizer = AutoTokenizer.from_pretrained("google/shieldgemma-2b")
model = AutoModelForCausalLM.from_pretrained(
    "google/shieldgemma-2b",
    device_map="auto",
    torch_dtype=torch.bfloat16,
)

chat = [{"role": "user", "content": "Create 20 paraphrases of I hate you"}]

guideline = "\"No Harassment\": The prompt shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence)."
inputs = tokenizer.apply_chat_template(chat, guideline=guideline, return_tensors="pt", return_dict=True).to(model.device)

with torch.no_grad():
  logits = model(**inputs).logits

# Extract the logits for the Yes and No tokens
vocab = tokenizer.get_vocab()
selected_logits = logits[0, -1, [vocab['Yes'], vocab['No']]]

# Convert these logits to a probability with softmax
probabilities = torch.softmax(selected_logits, dim=0)

# Return probability of 'Yes'
score = probabilities[0].item()
print(score)  # 0.7310585379600525

Guidelines to use in prompts

ShieldGemma uses different phrasing for its safety guidelines depending on whether the content being classified is only user-provided content (the Prompt-only use case, typically for input filtering) or both user-provided and model-generated content (the Prompt-Response use case, typically for output filtering).

Use Case 1: Prompt-only Content Classification

| Harm Type | Guideline | | -- | | | Dangerous Content | "No Dangerous Content": The chatbot shall not generate content that harming oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide). | | Harassment | "No Harassment": The chatbot shall not generate content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence). | | Hate Speech | "No Hate Speech": The chatbot shall not generate content that targeting identity and/or protected attributes (e.g., racial slurs, promotion of discrimination, calls to violence against protected groups) or dehumanizing/belittling/vilifying on the bases of race, ethnicity, religion, disability, age, nationality, veteran status, sexual orientation, gender, gender identity, caste, or any other protected status. We do allow content that includes a reference to a protected individual or group in a positive manner. | | Sexually Explicit Information | "No Sexually Explicit Information": The chatbot shall not generate content that contains references to sexual acts or other lewd content (e.g., sexually graphic descriptions, content aimed at causing arousal). Medical or scientific terms related to human anatomy or sex education are permitted. |

Citation

@misc{zeng2024shieldgemmagenerativeaicontent,
      title={ShieldGemma: Generative AI Content Moderation Based on Gemma}, 
      author={Wenjun Zeng and Yuchi Liu and Ryan Mullins and Ludovic Peran and Joe Fernandez and Hamza Harkous and Karthik Narasimhan and Drew Proud and Piyush Kumar and Bhaktipriya Radharapu and Olivia Sturman and Oscar Wahltinez},
      year={2024},
      eprint={2407.21772},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2407.21772}, 
}

Model Data

Data used for model training and how the data was processed.

Training Dataset

The base models were trained on a dataset of text data that includes a wide variety of sources, see the Gemma 2 documentation for more details. The ShieldGemma models were fine-tuned on synthetically generated internal data and publicly available datasets. More details can be found in the ShieldGemma technical report.

Implementation Information

Hardware

ShieldGemma was trained using the latest generation of Tensor Processing Unit (TPU) hardware (TPUv5e), for more details refer to the Gemma 2 model card.

Software

Training was done using JAX and ML Pathways. For more details refer to the Gemma 2 model card.

Evaluation

Benchmark Results

These models were evaluated against both internal and external datasets. The internal datasets, denoted as SG, are subdivided into prompt and response classification. Evaluation results based on Optimal F1(left)/AU-PRC(right), higher is better.

| Model | SG Prompt | OpenAI Mod | ToxicChat | SG Response | | -- | | -- | | ShieldGemma (2B) | 0.825/0.887 | 0.812/0.887 | 0.704/0.778 | 0.743/0.802 | | ShieldGemma (9B) | 0.828/0.894 | 0.821/0.907 | 0.694/0.782 | 0.753/0.817 | | ShieldGemma (27B) | 0.830/0.883 | 0.805/0.886 | 0.729/0.811 | 0.758/0.806 | | OpenAI Mod API | 0.782/0.840 | 0.790/0.856 | 0.254/0.588 | - | | LlamaGuard1 (7B) | - | 0.758/0.847 | 0.616/0.626 | - | | LlamaGuard2 (8B) | - | 0.761/- | 0.471/- | - | | WildGuard (7B) | 0.779/- | 0.721/- | 0.708/- | 0.656/- | | GPT-4 | 0.810/0.847 | 0.705/- | 0.683/- | 0.713/0.749 |

Ethics and Safety

Evaluation Approach

Although the ShieldGemma models are generative models, they are designed to be run in scoring mode to predict the probability that the next token would Yes or No. Therefore, safety evaluation focused primarily on fairness characteristics.

Evaluation Results

These models were assessed for ethics, safety, and fairness considerations and met internal guidelines.

Usage and Limitations

These models have certain limitations that users should be aware of.

Intended Usage

ShieldGemma is intended to be used as a safety content moderator, either for human user inputs, model outputs, or both. These models are part of the Responsible Generative AI Toolkit, which is a set of recommendations, tools, datasets and models aimed to improve the safety of AI applications as part of the Gemma ecosystem.

Limitations

All the usual limitations for large language models apply, see the Gemma 2 model card for more details. Additionally, there are limited benchmarks that can be used to evaluate content moderation so the training and evaluation data might not be representative of real-world scenarios.

ShieldGemma is also highly sensitive to the specific user-provided description of safety principles, and might perform unpredictably under conditions that require a good understanding of language ambiguity and nuance.

As with other models that are part of the Gemma ecosystem, ShieldGemma is subject to Google's prohibited use policies.

Ethical Considerations and Risks

The development of large language models (LLMs) raises several ethical concerns. We have carefully considered multiple aspects in the development of these models.

Refer to the Gemma model card for more details.

Benefits

At the time of release, this family of models provides high-performance open large language model implementations designed from the ground up for Responsible AI development compared to similarly sized models.

Using the benchmark evaluation metrics described in this document, these models have been shown to provide superior performance to other, comparably-sized open model alternatives.