Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
5 Hrs
16 Min
22 Seg
Curso de tips y trucos de IA

Curso de tips y trucos de IA

Amazon Web Services (AWS)

Amazon Web Services (AWS)

Optimización de hiperparámetros en LLMS

2/4
Resources
Transcript

The configuration of hyperparameters in large language models (LLMs) is a fundamental aspect that can completely transform the results obtained. Although many users simply write prompts without exploring other options, understanding and manipulating these parameters allows us to obtain more precise, creative or technical responses according to our specific needs. Mastering these settings is like learning to tune a musical instrument: with the right settings, we can extract the maximum potential from these powerful models.

What are hyperparameters in language models and why are they important?

Hyperparameters are settings that we can adjust to modify the behavior of a large language model (LLM) without changing the prompt. These settings directly influence how the model selects tokens (words or text fragments) to generate its responses.

The importance of these hyperparameters lies in their ability to completely transform the final output. For example, we can have the same model generate extremely creative responses for writing science fiction stories, or very precise and deterministic responses for solving mathematical or programming problems.

When we interact with an LLM, it generates a probability distribution for the next possible tokens. Hyperparameters allow us to control how the model selects among these probabilities, directly affecting the diversity, creativity and determinism of the answers.

How does the temperature parameter work?

Temperature is perhaps the best known and most widely used hyperparameter. It controls the level of randomness or creativity in the model's responses. It is generally set in a range from 0 to 2, where:

  • Low temperature (close to 0): produces more deterministic and conservative responses. The model tends to select tokens with higher probability.
  • Medium temperature (around 1): Provides a balance between creativity and accuracy. It is the standard setting in many interfaces.
  • High temperature (close to 2): Generates more diverse and creative responses. The model considers less likely tokens, which may result in more original but potentially less accurate content.

For example, when requesting the implementation of a matrix multiplication algorithm with temperature 1 (standard), the model provides a basic solution. When increasing the temperature to 2, the code structure may be similar, but we notice significant differences in the comments, which become more detailed and elaborate.

What is the Top-p parameter and how to use it?

The Top-p parameter, also known as "nucleus sampling", is another important hyperparameter that we can adjust. This parameter controls the diversity of tokens that the model considers for its response.

# With Top-p low, the code tends to be more straightforward and less commenteddef multiply_matrices(A, B): rows_A = len(A) cols_A = len(A[0]) cols_B = len(B[0])    
 C = [[0 for _ in range(cols_B)] for _ in range(rows_A)]    
 for i in range(rows_A):
        for j in range(cols_B): for k in range(cols_A): C[i][j] += A[i][k] * B[k][j]                
 return C

Top-p works as follows:

  1. The model sorts all possible tokens from highest to lowest probability.
  2. It selects only those tokens whose sum of probabilities reaches the configured Top-p value.
  3. It then chooses among these selected tokens.

A lower Top-p value (such as 0.5) limits the selection to more likely tokens, generating more predictable responses. A higher value (such as 0.95) allows a wider range of tokens to be considered, producing more diverse responses.

What other hyperparameters exist and how do they affect responses?

In addition to temperature and Top-p, there are other hyperparameters that vary depending on the model and platform we are using.

How does the Top-k parameter work?

Top-k is a hyperparameter available in some models, such as Anthropic's in Google Cloud. This parameter specifies the exact number of candidate tokens that the model can consider for its response.

  • A low value of Top-k (e.g., 10) makes the response less random and more deterministic.
  • A high value (e.g., 500) allows for more randomness in the responses.

This parameter is particularly useful when we want to precisely control the level of creativity of the model. For example, for creative tasks such as writing science fiction stories, we might set a Top-k of 100, while for technical tasks such as programming, a lower value would be appropriate.

What are penalty parameters?

Some models offer additional parameters such as:

  • Presence penalty: Penalizes the model for repeating topics or concepts.
  • Repetition penalty: Specifically prevents the model from repeating exact words or phrases.

These parameters are especially useful when generating long content, such as stories or code documentation, where we want to avoid redundancies and maintain diversity in the text.

How to optimize hyperparameters according to the type of task?

The optimal configuration of hyperparameters varies significantly depending on the task we want to perform. Finding the ideal combination requires experimentation, but we can start from some general recommendations:

For creative tasks (writing, storytelling).

  • Temperature: High (1.5-2.0)
  • Top-p: High (0.95-1.0)
  • Top-k: High (100-500)

This setting allows the model to explore more diverse options and generate original content.

For technical tasks (programming, mathematics)

  • Temperature: Low (0.2-0.5)
  • Top-p: Low (0.25-0.5)
  • Top-k: Low (10-50)

For code or mathematical solutions, a more deterministic setting helps to obtain accurate and correct answers.

# Example code generated with low temperature and low Top-p parametersimport numpy as np
def matrix_multiply(A, B): "" " Multiply two matrices using NumPy    
 Args: A: First matrix B: Second matrix        
 Returns: Matrix resulting from multiplication """ return np.matmul(A, B) # Extremely fast performance.

Experimenting with these hyperparameters can help us find configurations that significantly improve results for our specific use cases. For example, for programming tasks, a Top-p setting of 0.80 and temperature of 0.92 can provide a good balance between accuracy and creativity in solutions.

Hyperparameters are powerful tools that allow us to customize the behavior of language models to our specific needs. Experimenting with different settings is key to discovering the full potential of these models and obtaining optimal results for each type of task. Have you experimented with these settings? Share in the comments which settings have worked best for you for different types of tasks.

Contributions 9

Questions 4

Sort by:

Want to see more contributions, questions and answers from the community?

No se si sea relevante, pero la grabación muestra al instructor sobre la configuración que esta colocando (asi que NO se ve realmente)
### **Hiperparámetros** > **Configuraciones** que podemos ajustar para modificar el comportamiento de un modelo de lenguaje grande (**LLM**) **sin cambiar el prompt**. Estos ajustes influyen directamente en cómo el modelo **selecciona los tokens** (palabras o fragmentos de texto) para generar sus respuestas. **Afecta**ndo directamente la **diversidad**, **creatividad** y **determinismo** de las **respuestas**. * **Temperatura**> **Controla el nivel de** aleatoriedad **o creatividad en las respuestas del modelo**. Se configura típicamente en un rango de 0 a 2, donde: * **Baja (cercana a 0)**: Respuestas más **deterministas** y **conservadoras**. El modelo selecciona los tokens de mayor probabilidad, generando **soluciones** más **predecibles** y **básicas**. * **Media (alrededor de 1)**: Equilibrio entre **creatividad** y **precisión**. Esta es la configuración **predeterminada** en la mayoría de las interfaces. * **Alta (cercana a 2)**: Respuestas más **diversas** y **creativas**. El modelo considera tokens menos probables, produciendo **contenido más original** aunque potencialmente **menos preciso**. * **Top-p**> También conocido como "**nucleus sampling**", este parámetro controla la **diversidad de tokens** que el modelo considera para su respuesta. Al **limitar o ampliar** la **selección** de tokens, permite generar **respuestas** más predecibles o **diversas**. 1. Ordena todos los tokens posibles de mayor a menor probabilidad. 2. Selecciona únicamente los tokens cuyas probabilidades sumadas alcanzan el valor de Top-p establecido. 3. Elige aleatoriamente entre los tokens seleccionados. * **Top-k**> **Especifica** el **número máximo** de **tokens candidatos** que el modelo puede considerar al generar una respuesta. Esta función permite **controlar** con precisión el nivel de **creatividad** del modelo y está disponible en algunos modelos, como los de Anthropic en Google Cloud. * Un valor bajo de Top-k (por ejemplo, 10) genera **respuestas más predecibles** y deterministas. * Un valor alto (por ejemplo, 500) produce **respuestas más variadas** y aleatorias. * **Penalty Parameters**> Particularmente **útiles** al generar **contenido extenso**, como historias o documentación de código, pues ayudan a **evita**r **redundancias** y mantener la diversidad del texto.Algunos son: * **Presence penalty**: **Penaliza** al modelo por repetir temas o conceptos. * **Repetition penalty**: **Evita** específicamente que el modelo **repita palabras o frases exactas**. * **Configuraciones** * Tareas creativas (escritura, storytelling): * **Temperatura**: Alta (1.5-2.0) * **Top-p**: Alto (0.95-1.0) * **Top-k**: Alto (100-500) * Tareas técnicas (programación, matemáticas): * **Temperatura**: Baja (0.2-0.5) * **Top-p**: Bajo (0.25-0.5) * **Top-k**: Bajo (10-50)
Creo que la clase anterior de tips para respuestas de LLMs (Freddy) y saltar a esta es muy grande la brecha de conocimiento que necesita y queda uno sin contexto claro
Recuerdo que al principio le configurabas la temperatura al máximo a algunos modelos y te terminaban mostrando caracteres rarísimos en la salida jajajaj Realmente escogía los tokens menos probables! 😆
En la clase se abordaron los siguientes puntos clave sobre la optimización de hiperparámetros en modelos de lenguaje grande: 1. **Temperatura**: Controla la creatividad de las respuestas. Un valor bajo (ej. 0.35) produce respuestas más predecibles, mientras que un valor alto (ej. 2) genera respuestas más diversas y creativas. 2. **Top P**: Limita la selección de tokens a aquellos cuya probabilidad acumulada no exceda un cierto umbral. Ajustar este parámetro también influye en la creatividad y la precisión de las respuestas. 3. **Top K**: Específico de algunos modelos, determina cuántos candidatos a tokens el modelo puede considerar, afectando así el nivel de aleatoriedad en las respuestas. Se sugiere experimentar con estos parámetros según el contexto de uso, como programación o escritura creativa.
Gracias
Fascinante, no conocía nada de los hiperparametros Afinar LLMs para labores especificas sera un trabajo a futuro
La configuración de hiperparámetros en modelos de lenguaje grandes es crucial para obtener mejores resultados. Muchos usuarios solo escriben prompts, pero entender y ajustar estos parámetros puede generar respuestas más precisas y creativas. Dominar estos ajustes nos ayuda a maximizar el potencial de los modelos.
**Parámetros clave en modelos de lenguaje** Al usar modelos de lenguaje, los principales parámetros a considerar son el *prompt*, la *temperatura* y *Top-p*. La temperatura regula la creatividad: valores bajos dan respuestas más precisas y altas más creativas. *Top-p* limita las opciones de palabras según su probabilidad, haciendo la respuesta más controlada o más variada. **Ejemplos prácticos** Una consulta con temperatura 1 genera una respuesta promedio. Al aumentar la temperatura a 2, el modelo ofrece respuestas más elaboradas y comentadas. Reduciendo *Top-p*, el modelo se vuelve más determinista y menos disperso. **Otros ajustes avanzados** En plataformas como Vertex AI con modelos de Anthropic, también se puede ajustar *Top-k*, que define cuántas opciones considera el modelo antes de elegir un token. Además, parámetros como *repetition penalty* ayudan a evitar repeticiones. **Recomendación** Experimentar con diferentes combinaciones de temperatura, *Top-p* y *Top-k* permite adaptar el modelo a tareas creativas o técnicas como código, logrando el equilibrio ideal entre precisión y originalidad.