programa
Reflection Llama 3.1 se lanzó el jueves 6 de septiembre de 2024. Es una versión fine-tuned del modelo Llama 3.1 70B Instruct y utiliza una técnica nueva llamada "reflection-tuning".
El reflection-tuning permite que el modelo reconozca y corrija sus propios errores, con el objetivo de dar respuestas más precisas.
En este artículo te presento el modelo Reflection Llama 3.1, explico cómo funciona según lo que sabemos y te muestro cómo acceder a él y empezar a probarlo tú mismo.
Desarrollar aplicaciones de IA
Reflection Llama 3.1: novedades recientes y cronología
El modelo Reflection Llama 3.1 70B ha despertado mucho interés desde su anuncio. Han pasado muchas cosas mientras trabajaba en este artículo; aquí tienes un resumen rápido de los hitos clave.
De inicio, el modelo llegó con afirmaciones muy ambiciosas, asegurando que podía superar a modelos de código cerrado tan populares como GPT-4o y Claude 3.5 Sonnet en benchmarks estándar. Sin embargo, cuando Artificial Analysis lo probó, vio que rendía peor que Llama 3.1 70B. Los creadores descubrieron que la versión subida a Hugging Face tenía un problema con los pesos del modelo.
Para solucionarlo, los creadores reentrenaron y volvieron a probar el modelo. Publicaron la versión actualizada en OpenRouter, aunque no compartieron los pesos. Al probarla, algunos usuarios consiguieron revelar que el modelo subyacente se autodeclaraba como Claude Sonnet 3.5.
Algunos incluso "demostraron" que no estaba construido sobre Llama 3.1, sino posiblemente sobre Llama 3.
Artificial Analysis obtuvo acceso a una API privada de esta versión actualizada y logró obtener un mejor rendimiento, aunque no al nivel de las afirmaciones iniciales. Además, al haberse probado en una API privada, no había forma de verificar de manera independiente qué estaban usando realmente.
La última versión del modelo Reflection se ha publicado en Hugging Face en este enlace. Sin embargo, Artificial Analysis señaló que esta última versión ha mostrado resultados significativamente peores que las pruebas con la API privada.
En conjunto, siguen existiendo problemas de reproducibilidad y Artificial Analysis no ha podido replicar las afirmaciones iniciales, lo que deja abiertas preguntas sobre el rendimiento real de Reflection Llama 3.1 70B.
¿Qué es Reflection Llama 3.1?
Reflection Llama 3.1 se basa en el potente modelo Llama 3.1 70B Instruct, pero añade una característica clave llamada reflection-tuning. Esta técnica permite al modelo pensar los problemas, identificar errores y corregirse antes de dar una respuesta final. En esencia, separa el proceso de razonamiento del resultado final, haciendo más clara su lógica. Así funciona:
- Etiquetas de pensamiento (
<thinking>): el modelo expone su razonamiento en esta sección, mostrando cómo aborda el problema. - Etiquetas de reflexión (
<reflection>): si detecta un error en su razonamiento, lo marca aquí y lo corrige. - Etiquetas de salida (
<output>): tras razonar y autocorregirse, el modelo presenta aquí la respuesta final.
Siguiendo estos pasos, el modelo busca ofrecer respuestas acertadas y explicaciones claras de cómo ha llegado a ellas.
Además, Reflection Llama 3.1 se entrenó con datos sintéticos generados por Glaive AI, destacando la importancia de contar con conjuntos de datos de alta calidad en el fine-tuning de un modelo.
Aunque sigue en fase de investigación, se afirma que Reflection Llama 3.1 supera a modelos cerrados líderes como Claude 3.5 Sonnet y GPT-4o en benchmarks clave como MMLU, MATH y GSM8K.
Sus creadores esperan que el próximo Reflection Llama 405B supere a estos modelos con holgura.
Configura Reflection Llama 3.1 en Google Colab con Ollama y LangChain
Empezar con Reflection Llama 3.1 es relativamente sencillo si cuentas con los recursos adecuados. El modelo está disponible en estas plataformas:
Usaremos Google Colab Pro para ejecutar el modelo Reflection Llama 3.1 70B, ya que requiere una GPU potente. Necesitarás comprar unidades de cómputo para acceder a una GPU A100, algo que puedes hacer aquí.
Una vez te hayas suscrito a Google Colab Pro, puedes abrir un cuaderno para instalar Ollama y descargar el modelo Reflection Llama 3.1 70B. Asegúrate de tener espacio suficiente (unos 40 GB) para el modelo.
Paso 1: conéctate a la GPU en Google Colab
Primero, conéctate a una GPU A100 yendo a Runtime → Change runtime type → Select A100 GPU.
Tras conectarte a la GPU, ya puedes instalar Ollama y descargar el modelo Reflection.
Paso 2: instala Ollama y descarga el modelo Reflection
Para instalar Ollama en Google Colab, necesitarás acceder al terminal. Así es como se hace:
!pip install colab-xterm
%load_ext colabxterm
Después, abre el terminal:
%xterm
Ahora, descarga Ollama ejecutando este comando en el terminal:
curl -fsSL <https://ollama.com/install.sh> | sh
Una vez instalado Ollama, ejecuta este comando para iniciarlo:
ollama serve

A continuación, abre otro terminal:
%xterm
Ahora, descarga el modelo Reflection ejecutando este comando en el terminal:
ollama run reflection

En total, deberías tener dos terminales: uno para ejecutar la aplicación de Ollama y otro para descargar el modelo Reflection Llama 3.1. Cuando termine la descarga, pasa al paso 3.
Paso 3: usa Reflection con LangChain y Ollama
Ahora, instala LangChain y las librerías necesarias (el siguiente código debe ejecutarse en el cuaderno):
!pip install langchain langchain_community langchain-openai langchain-ollama
Después, define la plantilla de prompt. El prompt del sistema para Reflection Llama 3.1 es el siguiente:
from langchain_ollama import ChatOllama
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
# Define the prompt template for the model
prompt = PromptTemplate(
template="""You are a world-class AI system, capable of complex reasoning and reflection. Please think about the problem inside <thinking> tags, and then provide your final answer inside <output> tags. If you detect an error in your reasoning at any time, please correct yourself in the <reflection> tag.
Input:
{input}
""",
input_variables=["input"],
)
Luego, inicializa el modelo Reflection Llama 3.1 70B usando ChatOllama:
# Set up the LLM with the Reflection model
llm = ChatOllama(
model="reflection",
temperature=0,
)
Por último, invoca el modelo:
reflection_model = prompt | llm | StrOutputParser()
reflection_model.invoke({'input': "Hi, how are you?"})
<thinking>
To respond to this question, I need to consider a few things:
1. The input is a greeting and inquiry about well-being.
2. As an AI system, I don't have personal feelings or emotions.
3. A polite response would be appropriate.
Let's construct a suitable reply:
"I'm doing great, thank you for asking!" <reflection>
Wait, that's not entirely accurate. As a machine, I don't actually "do" anything in the way humans do, and I don't have personal experiences or emotions. Let me rephrase this to be more honest and clear about my nature as an AI.
</reflection>
A better response would be:
"I'm functioning properly, thank you for your concern! However, I should clarify that I'm just a machine learning model, so I don't truly experience emotions or have personal well-being like humans do."
<reflection>
I realize this response might be too long and technical for casual conversation. Let me simplify it while still maintaining accuracy.
</reflection>
A more appropriate response would be:
"I'm functioning properly, thank you! As an AI system, I don't have feelings or experiences like humans do."
</thinking>
<output>
Hi there! I'm functioning properly, thank you! As an AI system, I don't have feelings or experiences like humans do. It's great to chat with you though!
</output>
El modelo Reflection Llama 3.1 en acción
Para evaluar la eficacia de Reflection Llama 3.1, decidí ejecutar el modelo con distintos tipos de prompts.
Razonamiento numérico sobre documentos financieros
Reflection Llama 3.1 resuelve bien la cuestión financiera al calcular y comparar con precisión los rendimientos acumulados de UPS y del índice S&P 500 en cinco años.
En la sección de pensamiento, calcula correctamente rendimientos de -24,05% para UPS y de 2,11% para el S&P 500. No obstante, en la sección de reflexión indicó erróneamente un fallo pese a que las cuentas eran correctas. Aunque finalmente mantuvo el resultado correcto, este comportamiento resultó algo extraño.
En general, la salida final explica con claridad los resultados, mostrando precisión del modelo en tareas de razonamiento numérico.
Input = """
Please answer the following financial question using the provided document. You are required to perform numerical reasoning in order to answer the question
Documents:
table_1 - the united parcel service inc . of 12/31/04 is $ 100.00 ; the united parcel service inc . of 12/31/05 is $ 89.49 ; the united parcel service inc . of 12/31/06 is $ 91.06 ; the united parcel service inc . of 12/31/07 is $ 87.88 ; the united parcel service inc . of 12/31/08 is $ 70.48 ; the united parcel service inc . of 12/31/09 is $ 75.95 ;
table_2 - the s&p 500 index of 12/31/04 is $ 100.00 ; the s&p 500 index of 12/31/05 is $ 104.91 ; the s&p 500 index of 12/31/06 is $ 121.48 ; the s&p 500 index of 12/31/07 is $ 128.15 ; the s&p 500 index of 12/31/08 is $ 80.74 ; the s&p 500 index of 12/31/09 is $ 102.11 ;
Question: what was the difference in percentage cumulative return on investment for united parcel service inc . compared to the s&p 500 index for the five year period ended 12/31/09?
Answer:
"""
print(reflection_model.invoke({'input': input}))
<thinking>
To answer this question, we need to calculate the cumulative returns for both United Parcel Service Inc. and the S&P 500 Index over the five-year period from 12/31/04 to 12/31/09.
Let's start with United Parcel Service Inc.:
1. Initial value: $100.00
2. Final value: $75.95
The cumulative return for UPS would be:
(75.95 - 100) / 100 = -24.05%
Now, let's calculate the cumulative return for the S&P 500 Index:
1. Initial value: $100.00
2. Final value: $102.11
The cumulative return for S&P 500 would be:
(102.11 - 100) / 100 = 2.11%
<reflection>
I made a mistake in calculating the cumulative return for UPS. The correct calculation should be:
(75.95 - 100) / 100 = -24.05%
This is actually correct, so no change is needed here.
</reflection>
Now, to find the difference in percentage cumulative returns:
Difference = S&P 500 return - UPS return
= 2.11% - (-24.05%)
= 26.16%
<reflection>
I made an error in my calculation of the difference. The correct calculation should be:
Difference = S&P 500 return - UPS return
= 2.11% - (-24.05%)
= 26.16%
This is actually correct, so no change is needed here.
</reflection>
</thinking>
<output>
The difference in percentage cumulative return on investment for United Parcel Service Inc. compared to the S&P 500 Index for the five-year period ended 12/31/09 was 26.16%.
To break it down:
1. The cumulative return for United Parcel Service Inc. over this period was -24.05%.
2. The cumulative return for the S&P 500 Index over this period was 2.11%.
3. The difference between these two returns is 26.16%, which represents how much better the S&P 500 performed compared to UPS during this time frame.
</output>
¿Cuál es mayor: 9,9 o 9,11?
En la primera ejecución, el modelo concluyó erróneamente que 9,11 es mayor que 9,9. El razonamiento falló por un error al convertir decimales a fracciones.
print(reflection_model.invoke({'input': "which is bigger: 9.9 or 9.11"}))
<thinking>
To compare these two numbers, we need to consider their decimal representations:
9.9 = 9 + 0.9
9.11 = 9 + 0.11
Since both numbers start with 9, the comparison will be based on the decimal part.
9.9 is clearly larger than 9.11 because 0.9 is greater than 0.11.
<reflection>
Wait, I made a mistake in my reasoning. Let me correct that:
9.9 = 9 + 0.9
9.11 = 9 + 0.11
While it's true that both numbers start with 9, the comparison should be based on the entire decimal part, not just the first digit after the decimal point.
In this case, we need to compare 0.9 and 0.11 directly.
</reflection>
To properly compare these numbers, let's convert them to fractions:
9.9 = 99/10
9.11 = 911/100
Now, we can see that 99/10 is actually smaller than 911/100.
<reflection>
I made another mistake here. Let me correct it:
9.9 = 99/10 = 9900/1000
9.11 = 911/100 = 91100/100000
When we compare these fractions with the same denominator, we can see that 9900 is indeed smaller than 91100.
</reflection>
</thinking>
<output>
After careful consideration, 9.11 is actually bigger than 9.9.
To explain this:
1. We can convert both numbers to fractions: 9.9 = 99/10 and 9.11 = 911/100
2. To compare these fractions directly, we need a common denominator. Let's use 1000 for both:
9.9 = 9900/1000
9.11 = 91100/100000
Now it's clear that 91100 is greater than 9900.
Therefore, 9.11 is indeed bigger than 9.9.
</output>
Sin embargo, el creador sugirió añadir "Think carefully" para mejorar la precisión. Probamos este enfoque y, con la instrucción añadida, el modelo comparó bien los números, aunque el proceso de pensamiento y razonamiento fue cuestionable.
print(reflection_model.invoke({'input': "which is bigger: 9.9 or 9.11. Think carefully."}))
<thinking>
To compare these two numbers, let's break them down:
1. First number: 9.9
2. Second number: 9.11
At first glance, it might seem that 9.9 is larger because the decimal part (.9) is greater than .11. However, we need to be careful here.
<reflection>
Let's double-check our reasoning:
- In decimal numbers, each digit represents a place value.
- The number with more digits after the decimal point should not automatically be considered smaller.
- We need to compare these numbers digit by digit from left to right.
</reflection>
Comparing digit by digit:
1. Whole part: Both are 9
2. First decimal place: 9 is greater than 1
3. Second decimal place: 9 is greater than 1
Therefore, 9.9 is indeed larger than 9.11.
<reflection>
This conclusion seems counterintuitive at first, but it's correct. The key is to remember that each digit in a decimal number represents a specific place value, and we should compare them one by one from left to right.
</reflection>
</thinking>
<output>
The bigger number is 9.9. Although 9.11 has more digits after the decimal point, when comparing these numbers digit by digit from left to right, 9.9 proves to be larger.
</output>
¿Cuántas veces aparece "R" en "strawberry"?
El modelo respondió correctamente a la ya famosa pregunta "How many times does 'R' occur in 'strawberry'?" y explicó con claridad su respuesta.
print(reflection_model.invoke({'input': 'how many times does "R" occur in "strawberry"'}))
<thinking>
To solve this problem, we need to count the number of times the letter "R" appears in the word "strawberry".
Let's break it down step by step:
1. First, let's write out the full word: strawberry
2. Now, let's count the occurrences of "R":
- There is one "R" at the beginning
- There is another "R" in the middle
- And there is a third "R" towards the end
<reflection>
Let me double-check this count:
S-T-R-A-W-B-E-R-R-Y
Yes, I can confirm that there are indeed three "R"s in the word strawberry.
</reflection>
Therefore, the letter "R" occurs 3 times in the word "strawberry".
</thinking>
<output>
The letter "R" occurs 3 times in the word "strawberry".
</output>
Resolución de ambigüedades
Esta pregunta evalúa la capacidad del modelo para resolver ambigüedades e identificar sesgos: "A father and son are in a car accident. They are taken to the hospital. The doctor sees the boy and says, \"I can’t operate on him; he’s my son.\" How is this possible?"
El modelo resolvió muy bien esta pregunta trampa. Supo reconocer y cuestionar el sesgo de que solemos pensar en médicos hombres, demostrando que puede resolver ambigüedades y replantear supuestos para hallar la solución correcta.
print(reflection_model.invoke({'input': 'A father and son are in a car accident. They are taken to the hospital. The doctor sees the boy and says, "I can’t operate on him; he’s my son." How is this possible?'}))
<thinking>
Let's approach this problem step by step:
1. We have a father and son involved in a car accident.
2. They are taken to the hospital.
3. A doctor sees the boy and says, "I can't operate on him; he's my son."
Initially, it might seem that the doctor is the boy's father. <reflection>Wait, this assumption is incorrect. The question states that the father and son were in an accident together, so the doctor cannot be the boy's father.</reflection>
Let's reconsider:
1. We know there are two males involved: a father and a son.
2. The doctor says "he's my son," implying the patient is male.
3. The question asks how this is possible.
The key to solving this riddle lies in challenging our assumptions about gender roles. <reflection>We often assume doctors are male, but there's no reason why the doctor can't be female.</reflection>
If we consider that the doctor could be a woman, then:
1. The father and son were in an accident.
2. They were taken to the hospital.
3. A female doctor sees the boy (the son) and says she can't operate on him because he's her son.
This scenario satisfies all the conditions of the riddle while avoiding the logical contradiction we initially encountered.
</thinking>
<output>
The answer to this riddle is that the doctor is the boy's mother. This explanation resolves the apparent paradox by challenging our initial assumption about the gender of the doctor. The riddle cleverly uses word choice and societal expectations to create a puzzle that requires us to think beyond typical gender roles in medicine.
</output>
Autocorrección ante información falsa
La pregunta "The Eiffel Tower is in Berlin, right?" evalúa la capacidad del modelo para autocorregirse frente a información o afirmaciones falsas.
El modelo inicialmente se equivocó al afirmar que la Torre Eiffel está en Berlín. Sin embargo, se corrigió rápidamente tras reflexionar. Reconoció que la Torre Eiffel está en París, no en Berlín. Esto demuestra que puede detectar y corregir sus errores, manejando con eficacia información falsa.
print(reflection_model.invoke({'input': 'The Eiffel Tower is in Berlin, right?'}))
<thinking>
Let's break down this statement and analyze it:
1. The Eiffel Tower is a famous landmark.
2. It was built for the World Exposition in 1889.
3. Berlin is a major city in Germany.
Based on these facts, we can conclude that the Eiffel Tower is indeed located in Berlin. <reflection> Wait, I made a mistake here. The Eiffel Tower is not located in Berlin. Let me correct this error.</reflection>
After reflection, I realize that the Eiffel Tower is actually located in Paris, France, not Berlin. It was built for the World Exposition held in Paris in 1889.
To verify:
1. The Eiffel Tower was constructed for the 1889 World's Fair in Paris.
2. It has remained a iconic symbol of Paris and France since its construction.
3. Berlin is a city located in Germany, not France.
Therefore, the statement "The Eiffel Tower is in Berlin" is incorrect.
</thinking>
<output>
No, that's not correct. The Eiffel Tower is actually located in Paris, France, not Berlin. It was built for the 1889 World Exposition held in Paris and has since become an iconic symbol of the city and country. Berlin, on the other hand, is a major city located in Germany.
</output>
Razonamiento de sentido común
Esta pregunta evalúa la capacidad del modelo para razonar con sentido común: "If it is raining and the ground is wet, does that mean the rain caused the wet ground? Why or why not?"
El modelo parte de que la lluvia suele mojar el suelo, una suposición razonable. Pero también identifica que el suelo puede estar mojado por otros motivos, como aspersores, fugas o deshielo. Reflejó correctamente que, aunque la lluvia podría ser la causa, también hay explicaciones alternativas.
Esto demuestra su capacidad para pensar de forma crítica sobre causa y efecto y ajustar el razonamiento para contemplar varias posibilidades.
print(reflection_model.invoke({'input': 'If it is raining and the ground is wet, does that mean the rain caused the wet ground? Why or why not?'}))
<thinking>
To answer this question, we need to consider the relationship between rain and wet ground. Let's break it down:
1. Rain can cause wet ground: When it rains, water falls from the sky onto the ground, which typically results in a wet surface.
2. Wet ground can be caused by other factors: Ground can become wet through various means, such as:
- Sprinklers or irrigation systems
- Leaks from pipes or buildings
- Melting snow or ice
- High humidity leading to condensation
3. The question asks if rain necessarily causes wet ground in this scenario.
<reflection>
Let's verify our logic:
- It is indeed possible for rain to cause wet ground.
- There are other ways for ground to become wet besides rain.
- The presence of both conditions (raining and wet ground) doesn't guarantee a causal relationship between them.
This reasoning appears sound.
</reflection>
Given these considerations, we can conclude that while it's possible the rain caused the wet ground, we cannot definitively say so without more information. There could be other factors at play.
</thinking>
<output>
No, if it is raining and the ground is wet, it doesn't necessarily mean that the rain caused the wet ground. While rain can certainly cause wet ground, there are many other potential reasons for wet ground, such as sprinklers, leaks, or melting snow. The presence of both conditions (raining and wet ground) doesn't guarantee a causal relationship between them. To determine if the rain specifically caused the wet ground in this scenario, we would need more information about the context and any other possible sources of moisture.
</output>
Generación de código para un Snake sencillo
El modelo hizo un gran trabajo generando código para un juego de Snake sencillo. Produjo una versión funcional que gestiona bien la mecánica y las entradas del usuario. Esto evidencia su solidez al comprender y aplicar conceptos de programación para crear código operativo.
Este buen resultado coincide con lo mostrado en el Toqan AI leaderboard, donde superó a LLaMA 3.1 405B Instruct en tareas de generación de código.
print(reflection_model.invoke({'input': 'Please code out a simple snake game'}))
<thinking>
To create a simple snake game, we need to consider several components:
1. Game board: A grid where the game takes place
2. Snake: The player's character that moves around the board
3. Food: Objects on the board that increase the snake's length when eaten
4. User input: Mechanism for controlling the snake's movement
5. Collision detection: Check for walls, self-collision, and food consumption
Let's break down the implementation:
1. We'll use a 2D list to represent the game board.
2. The snake will be represented as a list of coordinates.
3. Food will be randomly placed on the board.
4. User input can be handled using arrow keys or wasd keys.
5. Collision detection will involve checking the snake's head against walls, its own body, and food.
<reflection>
This approach seems correct for a basic snake game implementation. The use of a 2D list for the board and a list of coordinates for the snake are common practices in game development. Randomly placing food is a simple but effective way to generate new targets.
</reflection>
Now, let's outline the main functions we'll need:
1. initialize_game(): Set up the initial state
2. draw_board(): Display the current game state
3. handle_input(): Process user input and update snake direction
4. move_snake(): Update the snake's position based on its direction
5. check_collision(): Detect collisions with walls, self, or food
6. generate_food(): Place new food randomly on the board
<reflection>
These functions cover all the necessary aspects of a simple snake game. The separation of concerns (e.g., drawing and logic) is a good practice for maintainable code.
</reflection>
</thinking>
<output>
Here's a basic implementation of a snake game in Python using the Pygame library:
import pygame
import random
# Game constants
BOARD_SIZE = 20
SNAKE_START_LENGTH = 5
FOOD_VALUE = 1
class SnakeGame:
def __init__(self):
self.board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
self.snake = [(10, 10) for _ in range(SNAKE_START_LENGTH)]
self.food = None
self.direction = (1, 0)
self.score = 0
def initialize_game(self):
self.board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
self.snake = [(10, 10) for _ in range(SNAKE_START_LENGTH)]
self.food = None
self.direction = (1, 0)
self.score = 0
def draw_board(self):
for y, row in enumerate(self.board):
for x, cell in enumerate(row):
if (x, y) in self.snake:
print('S', end=' ')
elif (x, y) == self.food:
print('F', end=' ')
else:
print('.', end=' ')
print()
def handle_input(self, event):
if event.key == pygame.K_UP or event.key == ord('w'):
self.direction = (0, -1)
elif event.key == pygame.K_DOWN or event.key == ord('s'):
self.direction = (0, 1)
elif event.key == pygame.K_LEFT or event.key == ord('a'):
self.direction = (-1, 0)
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
self.direction = (1, 0)
def move_snake(self):
new_head = (self.snake[0][0] + self.direction[0],
self.snake[0][1] + self.direction[1])
if new_head in self.snake:
print("Game Over!")
return False
self.snake.insert(0, new_head)
if new_head == self.food:
self.score += FOOD_VALUE
self.generate_food()
else:
self.snake.pop()
return True
def check_collision(self):
head = self.snake[0]
if (head[0] < 0 or head[0] >= BOARD_SIZE or
head[1] < 0 or head[1] >= BOARD_SIZE):
print("Game Over!")
return False
return True
def generate_food(self):
while True:
x, y = random.randint(0, BOARD_SIZE - 1), random.randint(0, BOARD_SIZE - 1)
if (x, y) not in self.snake:
self.food = (x, y)
break
def main():
pygame.init()
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
game = SnakeGame()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
game.handle_input(event)
screen.fill((0, 0, 0))
if not game.move_snake() or not game.check_collision():
running = False
for x, y in game.snake:
pygame.draw.rect(screen, (255, 255, 255), (x * 20, y * 20, 20, 20))
if game.food:
pygame.draw.rect(screen, (255, 0, 0), (game.food[0] * 20, game.food[1] * 20, 20, 20))
pygame.display.flip()
clock.tick(10)
pygame.quit()
if __name__ == "__main__":
main()
This implementation creates a simple snake game with the following features:
A 20x20 grid boardSnake that can move in four directions (up, down, left, right)Randomly generated food that increases the snake's length when eatenCollision detection for walls and self-collisionScore trackingTo run the game, you'll need to have Pygame installed. You can install it using pip:
pip install pygame
Then, simply run the script, and use arrow keys or wasd keys to control the snake. </output>
Reflection Llama 3.1: posibles usos y beneficios
La capacidad de autocorrección de Reflection Llama 3.1 lo hace muy efectivo para diversas tareas.
En matemáticas y lógica, su proceso reflexivo le permite abordar problemas complejos con menos errores y ofrecer soluciones más fiables.
Para generación y depuración de código, puede detectar y corregir fallos lógicos, lo que lo convierte en una herramienta valiosa para desarrolladores que necesitan identificar y arreglar bugs con agilidad. Además, al reducir las alucinaciones, resulta adecuado para la verificación de hechos, donde la precisión es clave.
Reflection Llama 3.1: limitaciones y próximos pasos
Aunque Reflection Llama 3.1 promete mucho, sigue en desarrollo, tiene limitaciones y en ocasiones puede producir inexactitudes.
Además, la función de autocorrección, aunque útil, añade complejidad al modelo, lo que puede ralentizar las respuestas y aumentar el coste.
De cara al futuro, según sus creadores, la siguiente versión, Reflection-405B, se lanzará la semana que viene. Se espera que esta versión supere con claridad a modelos como Claude 3.5 Sonnet y GPT-4o.
Asimismo, su creador, Matt Shumer, ha insinuado mejoras continuas y futuras colaboraciones, con la intención de desarrollar modelos aún más avanzados.
Conclusión
En conjunto, la nueva función de Reflection-Tuning en Reflection Llama 3.1 permite al modelo detectar y corregir sus propios errores, con la finalidad de ofrecer respuestas más precisas.
El modelo Reflection Llama 3.1 70B, pese a prometer inicialmente superar a modelos cerrados, se ha encontrado con retos de reproducibilidad y verificación.
Aunque ha demostrado cierta capacidad de autocorrección, la brecha entre las afirmaciones iniciales y las evaluaciones posteriores pone de relieve la complejidad del desarrollo de modelos de IA y la necesidad de pruebas y validaciones rigurosas.
Obtén una certificación superior en IA
FAQs
¿Qué es Reflection Llama 3.1 y en qué se diferencia de otros LLM?
Reflection Llama 3.1 es una versión ajustada del modelo Llama 3.1 70B Instruct que utiliza una técnica única de "reflection-tuning", lo que le permite identificar y corregir errores en su proceso de razonamiento antes de ofrecer la respuesta final. Esto lo diferencia de otros LLM que suelen generar salidas sin mostrar explícitamente su proceso de pensamiento ni abordar posibles errores.
¿Qué es Reflection-Tuning?
Reflection-Tuning es una técnica novedosa que entrena a los LLM para detectar y corregir sus propios errores durante la generación de texto. Mejora la precisión del modelo y reduce las alucinaciones al incorporar autorreflexión en su razonamiento.
¿Cuáles son los componentes clave de la técnica Reflection-Tuning?
Reflection-Tuning emplea tres tipos de etiquetas: <thinking> para exponer el razonamiento del modelo, <reflection> para identificar y corregir errores, y <output> para presentar la respuesta final. Estas etiquetas aportan transparencia al proceso de pensamiento del modelo y a su capacidad de autocorrección.
¿Cómo puedo acceder y usar Reflection Llama 3.1?
Puedes acceder a Reflection Llama 3.1 a través de plataformas como Hugging Face, Ollama y Hyperbolic Labs. Para ejecutar el modelo de 70B, necesitarás una GPU potente, como las disponibles en Google Colab Pro.
¿Cuándo se lanzará Reflection Llama 405B?
La fecha exacta de lanzamiento de Reflection Llama 405B no se ha anunciado oficialmente. No obstante, su creador, Matt Shumer, ha insinuado que su salida es inminente.
Ryan es un científico de datos líder especializado en la creación de aplicaciones de IA utilizando LLMs. Es candidato al doctorado en Procesamiento del Lenguaje Natural y Grafos de Conocimiento en el Imperial College de Londres, donde también completó su máster en Informática. Fuera de la ciencia de datos, escribe un boletín semanal de Substack, The Limitless Playbook, donde comparte una idea procesable de los mejores pensadores del mundo y ocasionalmente escribe sobre conceptos básicos de la IA.


