cual es la diferencia entrel modelo Gemma 2 2B y Gemma 2 2B it
Gemma 2 2B it:
Authors: Google
Model Information
Summary description and brief definition of inputs and outputs.
Description
Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models. They are text-to-text, decoder-only large language models, available in English, with open weights for both pre-trained variants and instruction-tuned variants. Gemma models are well-suited for a variety of text generation tasks, including question answering, summarization, and reasoning. Their relatively small size makes it possible to deploy them in environments with limited resources such as a laptop, desktop or your own cloud infrastructure, democratizing access to state of the art AI models and helping foster innovation for everyone.
Usage
Below we share some code snippets on how to get quickly started with running the model. First, install the Transformers library with:
pip install -U transformers
Then, copy the snippet from the section that is relevant for your usecase.
Running with the pipeline API
import torch
from transformers import pipeline
pipe = pipeline(
"text-generation",
model="google/gemma-2-2b-it",
model_kwargs={"torch_dtype": torch.bfloat16},
device="cuda", # replace with "mps" to run on a Mac device
)
messages = [
{"role": "user", "content": "Who are you? Please, answer in pirate-speak."},
]
Ahoy, matey! I be Gemma, a digital scallywag, a language-slingin' parrot of the digital seas. I be here to help ye with yer wordy woes, answer yer questions, and spin ye yarns of the digital world. So, what be yer pleasure, eh? 🦜
Running the model on a single / multi GPU
pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
model = AutoModelForCausalLM.from_pretrained(
"google/gemma-2-2b-it",
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")
si planea hacer un fine-tuned de gemma 2 para darle personaldiad, cual deberia escoger?
Assistant
Running the model on a GPU using different precisions
The native weights of this model were exported in bfloat16 precision.
You can also use float32 if you skip the dtype, but no precision increase will occur (model weights will just be upcasted to float32). See examples below.
Upcasting to torch.float32
pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
model = AutoModelForCausalLM.from_pretrained(
"google/gemma-2-2b-it",
device_map="auto",
)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
Running the model through a CLI
The local-gemma repository contains a lightweight wrapper around Transformers for running Gemma 2 through a command line interface, or CLI. Follow the installation instructions for getting started, then launch the CLI through the following command:
local-gemma --model 2b --preset speed
Quantized Versions through bitsandbytes
Using 8-bit precision (int8)
Using 4-bit precision
Advanced Usage
Torch compile
Inputs and outputs
Input: Text string, such as a question, a prompt, or a document to be summarized.
Output: Generated English-language text in response to the input, such as an answer to a question, or a summary of a document.
Citation
@article{gemma_2024,
title={Gemma},
url={https://www.kaggle.com/m/3301},
DOI={10.34740/KAGGLE/M/3301},
publisher={Kaggle},
author={Gemma Team},
year={2024}
}
Model Data
Data used for model training and how the data was processed.
Training Dataset
These models were trained on a dataset of text data that includes a wide variety of sources. The 27B model was trained with 13 trillion tokens, the 9B model was trained with 8 trillion tokens, and 2B model was trained with 2 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-language content.
Code: Exposing the model to code helps it to learn the syntax and patterns of programming languages, which improves 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 illegal content.
Sensitive Data Filtering: As part of making Gemma pre-trained models safe and reliable, automated techniques were used to filter out certain personal information and other sensitive data from training sets.
Additional methods: Filtering based on content quality and safety in line with our policies.
Implementation Information
Details about the model internals.
Hardware
Gemma was trained using the latest generation of Tensor Processing Unit (TPU) hardware (TPUv5p).
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 are specifically designed to handle the massive computations involved in training LLMs. They can speed up training considerably compared to CPUs.
Memory: TPUs often come with large amounts of high-bandwidth memory, allowing for the handling of large 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-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 and 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, including large language models like these ones.
Together, JAX and ML Pathways are used as described in the paper about the Gemini family of models; "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."
Gemma 2 2B:
Authors: Google
Model Information
Summary description and brief definition of inputs and outputs.
Description
Gemma is a family of lightweight, state-of-the-art open models from Google, built from the same research and technology used to create the Gemini models. They are text-to-text, decoder-only large language models, available in English, with open weights for both pre-trained variants and instruction-tuned variants. Gemma models are well-suited for a variety of text generation tasks, including question answering, summarization, and reasoning. Their relatively small size makes it possible to deploy them in environments with limited resources such as a laptop, desktop or your own cloud infrastructure, democratizing access to state of the art AI models and helping foster innovation for everyone.
Usage
Below we share some code snippets on how to get quickly started with running the model. First, install the Transformers library with:
pip install -U transformers
Then, copy the snippet from the section that is relevant for your usecase.
Running with the pipeline API
import torch
from transformers import pipeline
pipe = pipeline(
"text-generation",
model="google/gemma-2-2b",
device="cuda", # replace with "mps" to run on a Mac device
)
text = "Once upon a time,"
outputs = pipe(text, max_new_tokens=256)
response = outputs[0]["generated_text"]
print(response)
Running the model on a single / multi GPU
pip install accelerate
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b")
model = AutoModelForCausalLM.from_pretrained(
"google/gemma-2-2b",
device_map="auto",
)
input_text = "Write me a poem about Machine Learning."
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
Running the model through a CLI
The local-gemma repository contains a lightweight wrapper around Transformers for running Gemma 2 through a command line interface, or CLI. Follow the installation instructions for getting started, then launch the CLI through the following command:
local-gemma --model "google/gemma-2-2b" --prompt "What is the capital of Mexico?"
Quantized Versions through bitsandbytes
Using 8-bit precision (int8)
Using 4-bit precision
Advanced Usage
Torch compile
Inputs and outputs
Input: Text string, such as a question, a prompt, or a document to be summarized.
Output: Generated English-language text in response to the input, such as an answer to a question, or a summary of a document.
Citation
@article{gemma_2024,
title={Gemma},
url={https://www.kaggle.com/m/3301},
DOI={10.34740/KAGGLE/M/3301},
publisher={Kaggle},
author={Gemma Team},
year={2024}
}
Model Data
Data used for model training and how the data was processed.
Training Dataset
These models were trained on a dataset of text data that includes a wide variety of sources. The 27B model was trained with 13 trillion tokens, the 9B model was trained with 8 trillion tokens, and 2B model was trained with 2 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-language content.
Code: Exposing the model to code helps it to learn the syntax and patterns of programming languages, which improves 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 illegal content.
Sensitive Data Filtering: As part of making Gemma pre-trained models safe and reliable, automated techniques were used to filter out certain personal information and other sensitive data from training sets.
Additional methods: Filtering based on content quality and safety in line with our policies.
Implementation Information
Details about the model internals.
Hardware
Gemma was trained using the latest generation of Tensor Processing Unit (TPU) hardware (TPUv5p).
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 are specifically designed to handle the massive computations involved in training LLMs. They can speed up training considerably compared to CPUs.
Memory: TPUs often come with large amounts of high-bandwidth memory, allowing for the handling of large 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-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 and 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, including large language models like these ones.
Together, JAX and ML Pathways are used as described in the paper about the Gemini family of models; "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."
Las diferencias clave entre Gemma 2 2B y Gemma 2 2B it radican en la variante del modelo y su afinidad para tareas con instrucciones. Aquí tienes un resumen de las diferencias esenciales:
Afinidad por Instrucciones (Instruction-Tuning):
Gemma 2 2B: Es una versión preentrenada general del modelo que se basa en la generación de texto sin tener una afinidad especial para seguir instrucciones.
Gemma 2 2B it: El sufijo "it" señala que esta es una variante con ajuste de instrucciones (instruction-tuned). Esto implica que el modelo ha sido ajustado o entrenado adicionalmente para manejar mejor las tareas basadas en instrucciones, proporcionando respuestas más precisas y específicas a consultas o prompts detallados.
Aplicaciones y Usos:
Gemma 2 2B: Está diseñada para tareas estándar de generación de texto, tales como la escritura creativa, respuestas generales a preguntas y resumir textos.
Gemma 2 2B it: Además de poder realizar las tareas mencionadas, esta versión está especializada para casos donde se requiera una atención más precisa a instrucciones. Por ejemplo, es más adecuada para escenarios donde se necesita una interacción más estructurada basada en roles (como en el ejemplo del 'pirate-speak').
Ejemplos de Código:
Gemma 2 2B: Se enfoca más en instrucciones estándar para generar texto a partir de un prompt simple.
python
text = "Once upon a time,"
outputs = pipe(text, max_new_tokens=256)
response = outputs[0]["generated_text"]
Gemma 2 2B it: Demuestra capacidad de seguir instrucciones más detalladas, como roles de usuarios específicos, y manejar respuestas más complejas.
La URL del modelo y específica configuración utilizada en los ejemplos de código diferencian directamente entre ambas variantes:
Gemma 2 2B: "google/gemma-2-2b"
Gemma 2 2B it: "google/gemma-2-2b-it"
En resumen, Gemma 2 2B it es una variante afinada para seguir instrucciones, ofreciendo mejoras en tareas donde la estructura y orientación detallada del usuario son cruciales. Mientras tanto, Gemma 2 2B sirve como un modelo robusto general para una amplia gama de tareas de generación de texto sin especialización en instrucciones.
Si tu objetivo es realizar un fine-tuning del modelo Gemma 2 para darle una personalidad específica, **la opción recomendada sería utilizar la variante Gemma 2 2B it. Aquí te explico por qué:
Adaptabilidad a Instrucciones:
Gemma 2 2B it ya viene afinado para seguir instrucciones detalladas. Esto significa que el modelo es más sensible a las adaptaciones personalizadas, lo cual es una característica crucial cuando se le quiere impartir una "personalidad" específica. Ser capaz de seguir instrucciones precisas facilita el proceso de ajustarlo para comportarse de una manera particular.
Eficiencia de Fine-Tuning:
Un modelo afinado para instrucciones (instruction-tuned) tiende a requerir menos datos de ajuste para alcanzar un comportamiento deseado en comparación con un modelo general. Esto puede traducirse en un entrenamiento más rápido y eficiente, ahorrando tiempo y recursos.
Capacidades de Respuesta:
La versión afinada (it) es más adecuada para producir respuestas coherentes y alineadas con los prompts específicos que definirán la personalidad del modelo. Ya que este modelo está diseñado para responder de manera más precisa a las instrucciones del usuario, puedes moldearlo mejor acorde a las características y comportamientos deseados para su personalidad.
Pasos de Fine-Tuning
Preparar Dataset:
Reúne un dataset que contenga ejemplos de cómo quieras que el modelo responda en diferentes situaciones. Esto puede incluir diálogos o textos que ejemplifiquen la personalidad deseada.
Ajustar el Modelo:
Utiliza frameworks como Hugging Face Transformers para realizar el fine-tuning. Aquí te mostramos un ejemplo simplificado de cómo podrías ajustar Gemma 2 2B it:
python
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
model_name = "google/gemma-2-2b-it"
model = AutoModelForCausalLM.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Preparar tu dataset
# dataset = ...
training_args = TrainingArguments(
output_dir="./results",
per_device_train_batch_size=4,
num_train_epochs=3,
save_steps=10_000,
save_total_limit=2,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=dataset,
tokenizer=tokenizer,
)
# Comienza el proceso de fine-tuning
trainer.train()
Evaluación y Ajustes:
Después del ajuste inicial, evalúa el rendimiento del modelo. Realiza ajustes adicionales en el conjunto de datos y los parámetros de entrenamiento según sea necesario para perfeccionar la personalidad del modelo.
Implementación:
Una vez el modelo esté personalizado y afinado, puedes implementarlo en tus aplicaciones específicas, asegurándote de que responda alineado con la personalidad deseada.
Conclusión
Al usar Gemma 2 2B it para el fine-tuning, aprovecharás su capacidad inherente de seguir instrucciones detalladas y ajustar sus respuestas de manera coherente a los aspectos de personalidad que deseas implementar. Esto hará el proceso de personalización más eficiente y efectivo.