Los modelos de cimentación Mistral 7B de Mistral AI ahora están disponibles en Amazon SageMaker JumpStart

Hoy, nos complace anunciar que los modelos de base Mistral 7B, desarrollados por Mistral AI, están disponibles para los clientes a través de Inicio rápido de Amazon SageMaker para implementar con un clic para ejecutar la inferencia. Con 7 mil millones de parámetros, Mistral 7B se puede personalizar fácilmente e implementar rápidamente. Puede probar este modelo con SageMaker JumpStart, un centro de aprendizaje automático (ML) que brinda acceso a algoritmos y modelos para que pueda comenzar rápidamente con ML. En esta publicación, explicamos cómo descubrir e implementar el modelo Mistral 7B.

¿Qué es Mistral 7B?

Mistral 7B es un modelo básico desarrollado por Mistral AI, que admite capacidades de generación de código y texto en inglés. Admite una variedad de casos de uso, como resumen de texto, clasificación, finalización de texto y finalización de código. Para demostrar la fácil personalización del modelo, Mistral AI también lanzó un modelo Mistral 7B Instruct para casos de uso de chat, ajustado utilizando una variedad de conjuntos de datos de conversación disponibles públicamente.

Mistral 7B es un modelo transformador y utiliza atención de consultas agrupadas y atención de ventana deslizante para lograr una inferencia más rápida (baja latencia) y manejar secuencias más largas. La atención de consultas grupales es una arquitectura que combina la atención de múltiples consultas y de múltiples cabezas para lograr una calidad de salida cercana a la atención de múltiples cabezas y una velocidad comparable a la atención de múltiples consultas. La atención de ventana deslizante utiliza las capas apiladas de un transformador para atender en el pasado más allá del tamaño de la ventana para aumentar la longitud del contexto. Mistral 7B tiene una longitud de contexto de 8000 tokens, demuestra baja latencia y alto rendimiento, y tiene un rendimiento sólido en comparación con alternativas de modelos más grandes, lo que proporciona bajos requisitos de memoria en un tamaño de modelo 7B. El modelo está disponible bajo el permiso. licencia apache 2.0para uso sin restricciones.

¿Qué es SageMaker JumpStart?

Con SageMaker JumpStart, los profesionales del aprendizaje automático pueden elegir entre una lista cada vez mayor de modelos básicos de mejor rendimiento. Los profesionales del aprendizaje automático pueden implementar modelos básicos en sitios dedicados. Amazon SageMaker instancias dentro de un entorno aislado de red y personalice modelos utilizando SageMaker para el entrenamiento e implementación de modelos.

Ahora puede descubrir e implementar Mistral 7B con unos pocos clics en Amazon SageMaker Estudio o mediante programación a través del SDK de Python de SageMaker, lo que le permite obtener el rendimiento del modelo y controles MLOps con funciones de SageMaker como Canalizaciones de Amazon SageMaker, Depurador de Amazon SageMakero registros de contenedor. El modelo se implementa en un entorno seguro de AWS y bajo los controles de su VPC, lo que ayuda a garantizar la seguridad de los datos.

Descubre modelos

Puede acceder a los modelos básicos de Mistral 7B a través de SageMaker JumpStart en la interfaz de usuario de SageMaker Studio y el SDK de SageMaker Python. En esta sección, repasamos cómo descubrir los modelos en SageMaker Studio.

SageMaker Studio es un entorno de desarrollo integrado (IDE) que proporciona una única interfaz visual basada en web donde puede acceder a herramientas diseñadas específicamente para realizar todos los pasos de desarrollo de ML, desde la preparación de datos hasta la creación, el entrenamiento y la implementación de sus modelos de ML. Para obtener más detalles sobre cómo comenzar y configurar SageMaker Studio, consulte Amazon SageMaker Estudio.

En SageMaker Studio, puede acceder a SageMaker JumpStart, que contiene modelos, cuadernos y soluciones prediseñadas previamente entrenados, en Soluciones prediseñadas y automatizadas.

Desde la página de inicio de SageMaker JumpStart, puede buscar soluciones, modelos, cuadernos y otros recursos. Puedes encontrar Mistral 7B en el Modelos básicos: generación de texto carrusel.

También puede encontrar otras variantes de modelos eligiendo Explora todos los modelos de texto o buscando “Mistral”.

Puede elegir la tarjeta de modelo para ver detalles sobre el modelo, como la licencia, los datos utilizados para entrenar y cómo utilizarlo. También encontrarás dos botones, Desplegar y Cuaderno abiertoque le ayudará a utilizar el modelo (la siguiente captura de pantalla muestra el Desplegar opción).

Implementar modelos

La implementación comienza cuando usted elija Desplegar. Alternativamente, puede implementar a través del cuaderno de ejemplo que aparece cuando elige Cuaderno abierto. El cuaderno de ejemplo proporciona orientación integral sobre cómo implementar el modelo para inferencia y limpieza de recursos.

Para implementar usando una computadora portátil, comenzamos seleccionando el modelo Mistral 7B, especificado por el model_id. Puede implementar cualquiera de los modelos seleccionados en SageMaker con el siguiente código:

from sagemaker.jumpstart.model import JumpStartModel

model = JumpStartModel(model_id="huggingface-llm-mistral-7b-instruct")
predictor = model.deploy()

Esto implementa el modelo en SageMaker con configuraciones predeterminadas, incluido el tipo de instancia predeterminado (ml.g5.2xlarge) y las configuraciones de VPC predeterminadas. Puede cambiar estas configuraciones especificando valores no predeterminados en JumpStartModelo. Una vez implementado, puede ejecutar inferencia contra el punto final implementado a través del predictor de SageMaker:

payload = {"inputs": "<s>[INST] Hello! [/INST]"}
predictor.predict(payload)

Optimización de la configuración de implementación

Los modelos Mistral utilizan el servicio de modelos de inferencia de generación de texto (TGI versión 1.1). Al implementar modelos con el contenedor de aprendizaje profundo (DLC) TGI, puede configurar una variedad de argumentos del lanzador a través de variables de entorno al implementar su punto final. Para admitir la longitud de contexto de 8000 tokens de los modelos Mistral 7B, SageMaker JumpStart ha configurado algunos de estos parámetros de forma predeterminada: configuramos MAX_INPUT_LENGTH y MAX_TOTAL_TOKENS a 8191 y 8192, respectivamente. Puede ver la lista completa inspeccionando su objeto modelo:

De forma predeterminada, SageMaker JumpStart no bloquea a los usuarios simultáneos a través de la variable de entorno. MAX_CONCURRENT_REQUESTS menor que el valor predeterminado de TGI de 128. La razón es que algunos usuarios pueden tener cargas de trabajo típicas con longitudes de contexto de carga útil pequeñas y desean una alta simultaneidad. Tenga en cuenta que el DLC SageMaker TGI admite varios usuarios simultáneos mediante lotes continuos. Al implementar su punto final para su aplicación, podría considerar si debe fijar MAX_TOTAL_TOKENS o MAX_CONCURRENT_REQUESTS antes de la implementación para proporcionar el mejor rendimiento para su carga de trabajo:

model.env["MAX_CONCURRENT_REQUESTS"] = "4"

Aquí, mostramos cómo el rendimiento del modelo puede diferir para su carga de trabajo de endpoint típica. En las siguientes tablas, puede observar que las consultas de tamaño pequeño (128 palabras de entrada y 128 tokens de salida) tienen bastante rendimiento con una gran cantidad de usuarios simultáneos, alcanzando un rendimiento de tokens del orden de 1000 tokens por segundo. Sin embargo, a medida que la cantidad de palabras de entrada aumenta a 512 palabras de entrada, el punto final satura su capacidad de procesamiento por lotes (la cantidad de solicitudes simultáneas que se permite procesar simultáneamente), lo que genera una meseta en el rendimiento y degradaciones significativas de la latencia que comienzan alrededor de 16 usuarios simultáneos. Finalmente, cuando varios usuarios simultáneos consultan el punto final con contextos de entrada grandes (por ejemplo, 6400 palabras) simultáneamente, esta meseta de rendimiento se produce relativamente rápido, hasta el punto en que su cuenta de SageMaker comenzará a encontrar límites de tiempo de espera de respuesta de 60 segundos para sus solicitudes sobrecargadas. .

. rendimiento (tokens/s)
usuarios concurrentes 1 2 4 8 dieciséis 32 64 128
modelo tipo de instancia palabras de entrada fichas de salida .
mistral-7b-instruir ml.g5.2xgrande 128 128 30 54 89 166 287 499 793 1030
512 128 29 50 80 140 210 315 383 458
6400 128 17 25 30 35
. Latencia p50 (ms/token)
usuarios concurrentes 1 2 4 8 dieciséis 32 64 128
modelo tipo de instancia palabras de entrada fichas de salida .
mistral-7b-instruir ml.g5.2xgrande 128 128 32 33 34 36 41 46 59 88
512 128 34 36 39 43 54 71 112 213
6400 128 57 71 98 154

Indicaciones de inferencia y ejemplo

Mistral 7B

Puede interactuar con un modelo Mistral 7B base como cualquier modelo de generación de texto estándar, donde el modelo procesa una secuencia de entrada y genera las siguientes palabras predichas en la secuencia. El siguiente es un ejemplo simple con aprendizaje de múltiples disparos, donde el modelo recibe varios ejemplos y la respuesta del ejemplo final se genera con conocimiento contextual de estos ejemplos anteriores:

> Input
Tweet: "I get sad when my phone battery dies."
Sentiment: Negative
###
Tweet: "My day has been :+1:"
Sentiment: Positive
###
Tweet: "This is the link to the article"
Sentiment: Neutral
###
Tweet: "This new music video was incredibile"
Sentiment:

> Output
 Positive

Instrucción Mistral 7B

La versión adaptada a las instrucciones de Mistral acepta instrucciones formateadas en las que los roles de conversación deben comenzar con un mensaje de usuario y alternar entre usuario y asistente. Un mensaje de usuario simple puede verse como el siguiente:

<s>[INST] {user_prompt} [/INST]

Un mensaje de varios giros sería similar al siguiente:

<s>[INST] {user_prompt_1} [/INST] {assistant_response_1} </s><s>[INST] {user_prompt_1} [/INST]

Este patrón se repite durante todos los turnos que haya en la conversación.

En las siguientes secciones, exploramos algunos ejemplos utilizando el modelo Mistral 7B Instruct.

Recuperación de conocimientos

El siguiente es un ejemplo de recuperación de conocimientos:

> Input
<s>[INST] Which country has the most natural lakes? Answer with only the country name. [/INST] 

> Output
1. Canada

Respuesta a preguntas de contexto amplio

Para demostrar cómo utilizar este modelo para admitir contextos de entrada de gran longitud, el siguiente ejemplo incorpora un pasaje titulado “Ratas” de Robert Sullivan (referencia), de la prueba de comprensión de lectura de artes del lenguaje inglés de grado 10 del MCAS a la instrucción de indicaciones de entrada y le hace al modelo una pregunta dirigida sobre el texto:

> Input
<s>[INST] A rat is a rodent, the most common mammal in the world. Rattus norvegicus is one of the approximately four hundred different kinds of rodents, and it is known by many names, each of which describes a trait or a perceived trait or sometimes a habitat: the earth rat, the roving rat, the barn rat, the fi eld rat, the migratory rat, the house rat, the sewer rat, the water rat, the wharf rat, the alley rat, the gray rat, the brown rat, and the common rat. The average brown rat is large and stocky; it grows to be approximately sixteen inches long from its nose to its tail—the size of a large adult human male’s foot—and weighs about a pound, though brown rats have been measured by scientists and exterminators at twenty inches and up to two pounds. The brown rat is sometimes confused with the black rat, or Rattus rattus, which is smaller and once inhabited New York City and all of the cities of America but, since Rattus norvegicus pushed it out, is now relegated to a minor role. (The two species still survive alongside each other in some Southern coastal cities and on the West Coast, in places like Los Angeles, for example, where the black rat lives in attics and palm trees.) The black rat is always a very dark gray, almost black, and the brown rat is gray or brown, with a belly that can be light gray, yellow, or even a pure-seeming white. One spring, beneath the Brooklyn Bridge, I saw a red-haired brown rat that had been run over by a car. Both pet rats and laboratory rats are Rattus norvegicus, but they are not wild and therefore, I would emphasize, not the subject of this book. Sometimes pet rats are called fancy rats. But if anyone has picked up this book to learn about fancy rats, then they should put this book down right away; none of the rats mentioned herein are at all fancy.

Rats are nocturnal, and out in the night the brown rat’s eyes are small and black and shiny; when a fl ashlight shines into them in the dark, the eyes of a rat light up like the eyes of a deer. Though it forages* in darkness, the brown rat has poor eyesight. It makes up for this with, fi rst of all, an excellent sense of smell. . . . They have an excellent sense of taste, detecting the most minute amounts of poison, down to one part per million. A brown rat has strong feet, the two front paws each equipped with four clawlike nails, the rear paws even longer and stronger. It can run and climb with squirrel-like agility. It is an excellent swimmer, surviving in rivers and bays, in sewer streams and toilet bowls.

The brown rat’s teeth are yellow, the front two incisors being especially long and sharp, like buckteeth. When the brown rat bites, its front two teeth spread apart. When it gnaws, a fl ap of skin plugs the space behind its incisors. Hence, when the rat gnaws on indigestible materials—concrete or steel, for example—the shavings don’t go down the rat’s throat and kill it. Its incisors grow at a rate of fi ve inches per year. Rats always gnaw, and no one is certain why—there are few modern rat studies. It is sometimes erroneously stated that the rat gnaws solely to limit the length of its incisors, which would otherwise grow out of its head, but this is not the case: the incisors wear down naturally. In terms of hardness, the brown rat’s teeth are stronger than aluminum, copper, lead, and iron. They are comparable to steel. With the alligator-like structure of their jaws, rats can exert a biting pressure of up to seven thousand pounds per square inch. Rats, like mice, seem to be attracted to wires—to utility wires, computer wires, wires in vehicles, in addition to gas and water pipes. One rat expert theorizes that wires may be attractive to rats because of their resemblance to vines and the stalks of plants; cables are the vines of the city. By one estimate, 26 percent of all electric-cable breaks and 18 percent of all phone-cable disruptions are caused by rats. According to one study, as many as 25 percent of all fi res of unknown origin are rat-caused. Rats chew electrical cables. Sitting in a nest of tattered rags and newspapers, in the fl oorboards of an old tenement, a rat gnaws the head of a match—the lightning in the city forest.

When it is not gnawing or feeding on trash, the brown rat digs. Anywhere there is dirt in a city, brown rats are likely to be digging—in parks, in fl owerbeds, in little dirt-poor backyards. They dig holes to enter buildings and to make nests. Rat nests can be in the floorboards of apartments, in the waste-stuffed corners of subway stations, in sewers, or beneath old furniture in basements. “Cluttered and unkempt alleyways in cities provide ideal rat habitat, especially those alleyways associated with food-serving establishments,” writes Robert Corrigan in Rodent Control, a pest control manual. “Alley rats can forage safely within the shadows created by the alleyway, as well as quickly retreat to the safety of cover in these narrow channels.” Often, rats burrow under concrete sidewalk slabs. Entrance to a typical under-the-sidewalk rat’s nest is gained through a two-inch-wide hole—their skeletons collapse and they can squeeze into a hole as small as three quarters of an inch wide, the average width of their skull. This tunnel then travels about a foot down to where it widens into a nest or den. The den is lined with soft debris, often shredded plastic garbage or shopping bags, but sometimes even grasses or plants; some rat nests have been found stuffed with the gnawed shavings of the wood-based, spring-loaded snap traps that are used in attempts to kill them. The back of the den then narrows into a long tunnel that opens up on another hole back on the street. This second hole is called a bolt hole; it is an emergency exit. A bolt hole is typically covered lightly with dirt or trash—camoufl age. Sometimes there are networks of burrows, which can stretch beneath a few concrete squares on a sidewalk, or a number of backyards, or even an entire city block—when Rattus norvegicus fi rst came to Selkirk, England, in 1776, there were so many burrows that people feared the town might sink. Rats can also nest in basements, sewers, manholes, abandoned pipes of any kind, fl oorboards, or any hole or depression. “Often,” Robert Corrigan writes, “‘city rats’ will live unbeknownst to people right beneath their feet.”

Rats also inhabit subways, as most people in New York City and any city with a subway system are well aware. Every once in a while, there are reports of rats boarding trains, but for the most part rats stay on the tracks—subway workers I have talked to refer to rats as “track rabbits.” People tend to think that the subways are fi lled with rats, but in fact rats are not everywhere in the system; they live in the subways according to the supply of discarded human food and sewer leaks. Sometimes, rats use the subway purely for nesting purposes; they fi nd ways through the walls of the subway stations leading from the tracks to the restaurants and stores on the street—the vibrations of subway trains tend to create rat-size cracks and holes. Many subway rats tend to live near stations that are themselves near fast-food restaurants. At the various subway stations near Herald Square, for example, people come down from the streets and throw the food that they have not eaten onto the tracks, along with newspapers and soda bottles and, I have noticed, thousands of nolonger-charged AA batteries, waiting to leak acid. The rats eat freely from the waste and sit at the side of the little streams of creamy brown sewery water that fl ows between the rails. They sip the water the way rats do, either with their front paws or by scooping it up with their incisors.


What is the most likely reason the author states, "cables are the vines of the city"? [/INST] 


> Output
1. The author states that rats are attracted to wires, such as utility wires, computer wires, and vehicle wires, which may be due to their resemblance to vines and the stalks of plants.

Matemáticas y razonamiento

Los modelos Mistral también reportan fortalezas en la precisión matemática. Mistral puede proporcionar comprensión como la siguiente lógica matemática:

> Input
<s>[INST] I bought an ice cream for 6 kids. Each cone was $1.25 and I paid with a $10 bill. How many dollars did I get back? Explain first before answering. [/INST]

> Output
1. First, let's figure out how much the ice cream cost in total. Since each cone was $1.25 and there were 6 kids, the total cost would be:

Total cost = Number of cones * Cost per cone
Total cost = 6 * $1.25
Total cost = $7.50

2. Next, we'll subtract the total cost from the amount paid ($10) to find out how much money was returned:

Money returned = Amount paid - Total cost
Money returned = $10 - $7.50
Money returned = $2.50

So, you got back $2.50 after buying the ice cream for the 6 kids.

Codificación

El siguiente es un ejemplo de un mensaje de codificación:

> Input
<s>[INST] In Bash, how do I list all text files in the current directory (excluding subdirectories) that have been modified in the last month? [/INST] 


> Output
1. Use the `find` command to search for text files in the current directory (excluding subdirectories) that have been modified in the last month. The `-type f` option specifies that we only want to search for files, not directories. The `-name "*.txt"` option specifies that we only want to search for files with the `.txt` extension. The `-mtime -30` option specifies that we only want to search for files that have been modified in the last 30 days (1 month).

```bash
find . -type f -name "*.txt" -mtime -30
```

This command will list all text files in the current directory (excluding subdirectories) that have been modified in the last month.

Limpiar

Una vez que haya terminado de ejecutar el cuaderno, asegúrese de eliminar todos los recursos que creó en el proceso para que se detenga su facturación. Utilice el siguiente código:

predictor.delete_model()
predictor.delete_endpoint()

Conclusión

En esta publicación, le mostramos cómo comenzar con Mistral 7B en SageMaker Studio e implementar el modelo para inferencia. Dado que los modelos básicos están previamente entrenados, pueden ayudar a reducir los costos de capacitación e infraestructura y permitir la personalización para su caso de uso. Visita Inicio rápido de Amazon SageMaker ahora para empezar.

Recursos


Sobre los autores

Dr.Kyle Ulrich es un científico aplicado del equipo JumpStart de Amazon SageMaker. Sus intereses de investigación incluyen algoritmos escalables de aprendizaje automático, visión por computadora, series temporales, procesos bayesianos no paramétricos y procesos gaussianos. Su doctorado es de la Universidad de Duke y ha publicado artículos en NeurIPS, Cell y Neuron.

Dr. Ashish Khetan Es científico aplicado sénior en Amazon SageMaker JumpStart y ayuda a desarrollar algoritmos de aprendizaje automático. Obtuvo su doctorado en la Universidad de Illinois Urbana-Champaign. Es un investigador activo en aprendizaje automático e inferencia estadística, y ha publicado numerosos artículos en conferencias NeurIPS, ICML, ICLR, JMLR, ACL y EMNLP.

Vivek Singh es gerente de producto de Amazon SageMaker JumpStart. Se centra en permitir que los clientes incorporen SageMaker JumpStart para simplificar y acelerar su viaje de aprendizaje automático para crear aplicaciones de IA generativa.

Roy Allela es un arquitecto senior de soluciones especializado en IA/ML en AWS con sede en Munich, Alemania. Roy ayuda a los clientes de AWS (desde pequeñas empresas emergentes hasta grandes empresas) a capacitar e implementar modelos de lenguaje grandes de manera eficiente en AWS. A Roy le apasionan los problemas de optimización computacional y la mejora del rendimiento de las cargas de trabajo de IA.