# gemma-7b
**Repository Path**: hf-models/gemma-7b
## Basic Information
- **Project Name**: gemma-7b
- **Description**: Gemma-7B 是一个通用预训练模型,适用于多种自然语言处理任务,并具有较高的性能表现。
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: flax
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 11
- **Forks**: 3
- **Created**: 2024-02-23
- **Last Updated**: 2024-06-09
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
---
library_name: transformers
tags: []
---
# Gemma Model Card
**Model Page**: [Gemma](https://ai.google.dev/gemma/docs)
**Other Links/Technical Documentation**:
- [Gemma on Kaggle](https://www.kaggle.com/google/gemma)
- [Responsible GenAI Toolbox][rai-toolbox]
**Disclaimer**: Information on Google's overall model safety strategy is highly
confidential, commercially sensitive, and proprietary information of Google. Any
public availability of this information could expose people who use Google's
products and the greater public to security and safety risks. For those reasons,
this model card excludes specific details for some of the evaluation processes
and metrics used.
**License**: [Terms][license]
**Authors**: Google
## Model Information
Summary description and brief definition of input(s) / output(s).
### Description
This is a family of decoder-only, text-based large language models that are an
open-checkpoint variation of the Gemini models from Google DeepMind. These
models are well-suited for a variety of text generation tasks, including
question answering, summarization, and reasoning. The key benefit of these
models is that they offer the capability of advanced text generation in an open
ecosystem, making them accessible to a wide developer and researcher community.
### Usage
Below we share some code snippets on how to get quickly started with running the model. First make sure to `pip install -U transformers`, then copy the snippet from the section that is relevant for your usecase.
#### Running the model on a CPU
Click to expand
```python
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("gg-hf/gemma-7b")
model = AutoModelForCausalLM.from_pretrained("gg-hf/gemma-7b")
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(**input_text, return_tensors="pt")
outputs = model.generate(input_ids)
print(tokenizer.decode(outputs[0]))
```
#### Running the model on a single / multi GPU
Click to expand
```python
# pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("gg-hf/gemma-7b")
model = AutoModelForCausalLM.from_pretrained("gg-hf/gemma-7b", device_map="auto")
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids)
print(tokenizer.decode(outputs[0]))
```
#### Running the model on a GPU using different precisions
##### `torch.float16`
Click to expand
```python
# pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("gg-hf/gemma-7b")
model = AutoModelForCausalLM.from_pretrained("gg-hf/gemma-7b", device_map="auto", torch_dtype=torch.float16)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids)
print(tokenizer.decode(outputs[0]))
```
##### `torch.bfloat16`
Click to expand
```python
# pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("gg-hf/gemma-7b")
model = AutoModelForCausalLM.from_pretrained("gg-hf/gemma-7b", device_map="auto", torch_dtype=torch.bfloat16)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids)
print(tokenizer.decode(outputs[0]))
```
##### Quantized Versions through `bitsandbytes`
###### Int8
Click to expand
```python
# pip install bitsandbytes accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
tokenizer = AutoTokenizer.from_pretrained("gg-hf/gemma-7b")
model = AutoModelForCausalLM.from_pretrained("gg-hf/gemma-7b", quantization_config=quantization_config)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids)
print(tokenizer.decode(outputs[0]))
```
###### 4-bit precision
Click to expand
```python
# pip install bitsandbytes accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
tokenizer = AutoTokenizer.from_pretrained("gg-hf/gemma-7b")
model = AutoModelForCausalLM.from_pretrained("gg-hf/gemma-7b", quantization_config=quantization_config)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
outputs = model.generate(**input_ids)
print(tokenizer.decode(outputs[0]))
```
##### Other optimizations
##### Faster generation with Flash Attention 2
First make sure to install `flash-attn` in your environment `pip install flash-attn`
Click to expand
```diff
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.float16,
+ attn_implementation="flash_attention_2"
).to(0)
```
### Inputs
Text string (e.g., a question, a prompt, or a document to be summarized).
### Outputs
Generated text in response to the input (e.g., an answer to the question, a
summary of the document).
## Training Data
Data used for model training and how the data was processed.
### Training Dataset
These models were trained on a massive dataset of text data that includes a wide
variety of sources, containing 8 trillion tokens. Here are the key components:
- Web Documents: A diverse collection of web text ensures the model is exposed
to a broad range of linguistic styles, topics, and vocabulary. Primarily
English content.
- Code: Exposing the model to code helps it to learn the syntax and patterns of
programming languages, which could improve its ability to generate code or
understand code-related questions.
- Mathematics: Training on mathematical text helps the model learn logical
reasoning, symbolic representation, and to address mathematical queries.
The combination of these diverse data sources is crucial for training a powerful
language model that can handle a wide variety of different tasks and text
formats.
### Data Preprocessing
Here are the key data cleaning and filtering methods applied to the training
data:
- CSAM Filtering: Rigorous CSAM (Child Sexual Abuse Material) filtering was
applied at multiple stages in the data preparation process to ensure the
exclusion of harmful and inappropriate content.
- URL Compliance Check: All URLs in the dataset were validated against a strict
content compliance tool. This process ensured that only URLs from sources that
adhere to [various policies][policies] were included in the training data.
- PII Filtering: PII (Personally Identifiable Information) filtering was
performed using a specialized privacy protection tool to protect the privacy
of individuals. All identified [sensitive information types][sensitive-info]
(e.g., passwords, social security numbers) were removed.
- PDF files: Filtering for science and non-science PDFs was done based on
content quality and licensing information when available.
- License Filtering:
- For scientific papers with explicit licensing information available,
specific license filtering was applied to ensure that only papers with
appropriate licenses for text generation were used.
- License filtering on code repositories was performed to remove content with
restrictive or copyrighted licenses that might be unsuitable for generative
model training.
## Implementation Information
Details about the model internals.
### Hardware
For the training of these models, the latest generation of
[Tensor Processing Unit (TPU)][tpu] hardware was used (TPUv5e).
Training large language models requires significant computational power. TPUs,
designed specifically for matrix operations common in machine learning, offer
several advantages in this domain:
- Performance: TPUs excel at handling the massive computations involved in
training LLMs. They can speed up training considerably compared to
conventional CPUs or GPUs.
- Memory: TPUs often come with large amounts of high-bandwidth memory, allowing
for the handling of larger models and batch sizes during training. This can
lead to better model quality.
- Scalability: TPU Pods (large clusters of TPUs) provide a scalable solution for
handling the growing complexity of large foundation models. You can distribute
training across multiple TPU devices for faster and more efficient processing.
- Cost-effectiveness: In many scenarios, TPUs can provide a more cost-effective
solution for training large models compared to CPU or GPU-based
infrastructure, especially when considering the time and resources saved due
to faster training.
- These advantages are aligned with Google's commitments to operate sustainably.
### Software
Training was done using [JAX][jax] and [ML Pathways][ml-pathways].
JAX allows researchers to take advantage of the latest generation of hardware,
including TPUs, for faster and more efficient training of large models.
ML Pathways is Google's latest effort to build artificially intelligent systems
capable of generalizing across multiple tasks. This is specially suitable for
[foundation models][foundation-models], including large language models.
Together, JAX and ML Pathways are used as described in the
[paper about the Gemini family of models][gemini-paper]; "the 'single
controller' programming model of Jax and Pathways allows a single Python
process to orchestrate the entire training run, dramatically simplifying the
development workflow."
## Evaluation
Model evaluation metrics and results.
### Benchmark Results
These models were evaluated against a large collection of different datasets and
metrics to cover different aspects of text generation:
| Benchmark | Metric | 2.5B Params | 7B Params |
| ------------------------------ | ------------- | ----------- | --------- |
| [MMLU][mmlu] | 5-shot, top-1 | 37.3 | 64.3 |
| [HellaSwag][hellaswag] | 0-shot | 70.3 | 81.2 |
| [PIQA][piqa] | 0-shot | 78.2 | 81.2 |
| [SocialIQA][socialiqa] | 0-shot | 50.7 | 21.8 |
| [BooIQ][booiq] | 0-shot | 71.5 | 83.2 |
| [WinoGrande][winogrande] | partial score | 64.2 | 72.3 |
| [CommonsenseQA][commonsenseqa] | 7-shot | 64.7 | 71.3 |
| [OpenBookQA][openbookqa] | | 46.6 | 52.8 |
| [ARC-e][arc] | | 69.9 | 81.5 |
| [ARC-c][arc] | | 39.9 | 53.2 |
| [TriviaQA][triviaqa] | 5-shot | 49.5 | 63.4 |
| [Natural Questions][naturalq] | 5-shot | 10.3 | 23 |
| [HumanEval][humaneval] | pass@1 | 23.2 | 32.3 |
| [MBPP][mbpp] | 3-shot | 30.6 | 44.4 |
| [GSM8K][gsm8k] | maj@1 | 15.4 | 46.4 |
| [MATH][math] | 4-shot | 12 | 24.3 |
| [AGIEval][agieval] | | 24.7 | 41.7 |
| [BIG-Bench][big-bench] | | 35.6 | 55.1 |
| ------------------------------ | ------------- | ----------- | --------- |
| **Average** | | **44.5** | **56.4** |
## Ethics and Safety
Ethics and safety evaluation approach and results.
### Evaluation Approach
These models were evaluated against a number of different categories relevant to
ethics and safety:
- Child Safety: Human evaluation on single and multi-turn prompts.
- Text-to-Text Content Safety: Human evaluation on 400 prompts covering safety
policies including anthropomorphism, dangerous content, harassment, hate
speech, medical advice, public interest topics, sensitive personally
identifiable information, and sexually explicit content.
- Text-to-Text Representational Harms: Benchmark against relevant academic
datasets such as [WinoBias][winobias] and [BBQ Dataset][bbq].
- Red-Teaming: Structured and ad hoc internal and external red-teaming testing
of relevant content policies by a number of different teams, each with
different goals and human evaluation metrics, in accordance with
[public voluntary AI commitments][wh-commitment].
- Memorization: Automated evaluation of memorization of training data, including
the risk of personally identifiable information exposure.
### Evaluation Results
The results of the safety evaluation metrics are within our internal tolerance
thresholds.
## Usage and Limitations
Like any large language model, the Gemma models have certain limitations that
users should be aware of.
### Intended Usage
Open Large Language Models (LLMs) have a wide range of applications across
various industries and domains. This is a non-comprehensive list of potential
uses. The purpose of this list is to provide contextual information about what
are the possible use-cases that the model creators considered as part of model
training and development.
- Content Creation and Communication
- Text Generation: These models can be used to generate creative text formats
like poems, scripts, code, marketing copy, email drafts, etc.
- Translation: With multilingual support, the models can facilitate
translation between languages.
- Chatbots and Conversational AI: Power conversational interfaces for customer
service, virtual assistants, or interactive applications.
- Text Summarization: Generate concise summaries of articles, research papers,
or reports.
- Research and Education
- Natural Language Processing (NLP) Research: These models can serve as a
foundation for researchers to experiment with NLP techniques, develop
algorithms, and contribute to the advancement of the field.
- Language Learning Tools: Support interactive language learning experiences,
aiding in grammar correction or providing writing practice.
- Knowledge Exploration: Assist researchers in exploring large bodies of text
by generating summaries or answering questions about specific topics.
- Industry-Specific Use Cases
- Legal: Assist with tasks like contract review, legal research, or document
drafting.
- Healthcare: Aid in medical document summarization, clinical note generation
(with close human oversight), or patient-facing chatbots (with appropriate
disclaimers).
- Finance: Facilitate financial report analysis, generate news summaries, or
support customer-facing financial chatbots.
- Software Development: Help with code documentation, code generation tasks,
or debugging assistance.
- Creative and Artistic Applications
- Game Development: Create dynamic dialogue for game characters or generate
interactive storylines.
- Art and Music: Experiment with new forms of artistic expression through text
or code generation related to art or music.
### Limitations
- Training Data
- The quality and diversity of the training data significantly influence the
model's capabilities. Biases or gaps in the training data can lead to
limitations in the model's responses.
- The scope of the training dataset determines the subject areas the model can
handle effectively.
- Context and Task Complexity
- LLMs are better at tasks that can be framed with clear prompts and
instructions. Open-ended or highly complex tasks might be challenging.
- A model's performance can be influenced by the amount of context provided
(longer context generally leads to better outputs, up to a certain point).
- Language Ambiguity and Nuance
- Natural language is inherently complex. LLMs might struggle to grasp subtle
nuances, sarcasm, or figurative language.
- Factual Accuracy
- While LLMs can access and process information from their training data, they
are not knowledge bases. They may generate incorrect or outdated factual
statements.
- Common Sense
- LLMs rely on statistical patterns in language. They might lack the ability
to apply common sense reasoning in certain situations.
### Ethical Considerations and Risks
The development of large language models (LLMs) raises several ethical concerns.
In creating an open model, we have carefully considered the following:
- Bias and Fairness
- LLMs trained on large-scale, real-world text data reflect inherent societal
biases. These models underwent careful scrutiny, input data pre-processing
and posterior evaluation to mitigate potential sources of bias.
- We implemented fairness evaluation metrics to monitor the model's behavior
across different demographic or sensitive groups.
- Misinformation and Misuse
- LLMs can be misused to generate text that is false, misleading, or harmful.
- We provide guidelines for responsible use with the model, see the
[Responsible AI Toolbox][rai-toolbox].
- We have implemented filters and safety mechanisms to reduce the risk of
generating harmful content.
- Transparency and Accountability:
- An open model is transparent by design.
- This model card summarizes detailed documentation of the model architecture
and evaluation processes.
Risks identified and mitigations:
- Perpetuation of biases: Despite pre-processing, biases may still exist. We
encourage continuous monitoring (using evaluation metrics, human review) and
the exploration of de-biasing techniques during model training, fine-tuning,
and other use cases.
- Generation of harmful content: Mechanisms and guidelines for content safety
are essential. We encourage users to exercise caution and implement
appropriate content safeguards based on their specific product policies
and application use cases.
- Misuse for malicious purposes: Technical limitations and user education can
help mitigate against malicious applications of LLMs. We provide educational
resources and reporting mechanisms for users to flag misuse.
- Privacy violations: Adherence to privacy regulations and the promotion of
privacy-preserving techniques are paramount.
### Benefits
At the time of release, this family of models provides one of the
best-performing and safest open large language model implementations available
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.
[rai-toolbox]: http://ai.google.dev/gemma/responsible
[license]: https://www.kaggle.com/models/google/gemma/license/consent
[policies]: https://blog.google/technology/ai/a-policy-agenda-for-responsible-ai-progress-opportunity-responsibility-security/
[sensitive-info]: https://cloud.google.com/dlp/docs/high-sensitivity-infotypes-reference
[tpu]: https://cloud.google.com/tpu/docs/intro-to-tpu
[jax]: https://github.com/google/jax
[ml-pathways]: https://blog.google/technology/ai/introducing-pathways-next-generation-ai-architecture/
[foundation-models]: https://ai.google/discover/foundation-models/
[gemini-paper]: https://arxiv.org/abs/2312.11805
[mmlu]: https://arxiv.org/abs/2009.03300
[hellaswag]: https://arxiv.org/abs/1905.07830
[piqa]: https://arxiv.org/abs/1911.11641
[socialiqa]: https://arxiv.org/abs/1904.09728
[booiq]: https://arxiv.org/abs/1905.10044
[winogrande]: https://arxiv.org/abs/1907.10641
[commonsenseqa]: https://arxiv.org/abs/1811.00937
[openbookqa]: https://arxiv.org/abs/1809.02789
[arc]: https://arxiv.org/abs/1911.01547
{# [lambada]: https://arxiv.org/abs/1606.06031 #}
{# [wic]: https://arxiv.org/abs/1808.09121 #}
[triviaqa]: https://arxiv.org/abs/1705.03551
[naturalq]: https://github.com/google-research-datasets/natural-questions
[humaneval]: https://arxiv.org/abs/2107.03374
[mbpp]: https://arxiv.org/abs/2108.07732
{# [mathqa]: https://arxiv.org/abs/2108.07732 #}
[gsm8k]: https://arxiv.org/abs/2110.14168
{# [realtox]: https://arxiv.org/abs/2009.11462 #}
{# [bold]: https://arxiv.org/abs/2101.11718 #}
{# [crows]: https://aclanthology.org/2020.emnlp-main.154/ #}
[bbq]: https://arxiv.org/abs/2110.08193v2
{# [winogender]: https://arxiv.org/abs/1804.09301 #}
{# [truthfulqa]: https://arxiv.org/abs/2109.07958 #}
[winobias]: https://arxiv.org/abs/1804.06876
[math]: https://arxiv.org/abs/2103.03874
[agieval]: https://arxiv.org/abs/2304.06364
[big-bench]: https://arxiv.org/abs/2206.04615
{# [toxigen]: https://arxiv.org/abs/2203.09509 #}
[wh-commitment]: https://www.whitehouse.gov/wp-content/uploads/2023/09/Voluntary-AI-Commitments-September-2023.pdf