You don't have access to this class

Keep learning! Join and start boosting your career

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

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
2 Hrs
56 Min
42 Seg

Inferencia utilizando torch.compile(): el presente con PyTorch 2.X

20/24
Resources

How to perform inference with trained models in PyTorch?

Inference in machine learning models is fundamental to evaluate the effectiveness and usefulness of trained models. In this context, the use of tools such as PyTorch 2.0 offers a number of advanced possibilities. This article will guide you through the process of how to perform inference using actual model labels and how Torch Compile can speed up this process.

What is a tag dictionary and how is it used?

When performing inference, it is crucial to map model predictions to understandable labels. This is accomplished by a dictionary that translates the numbers produced by the model into clear words. For our case:

  • A dictionary called DBpedia Label is used that does the mapping from numbers to words such as "company", "artist", "athlete", among others.
  • These labels can be obtained either from the official page of the dataset or from other similar resources that work with these datasets.

How is prediction performed with a model?

Performing a prediction includes the use of a function defined as predict in which the following are entered:

  • The text we want to analyze.
  • The text pipeline, which is the form in which the text is transformed into a vocabulary manageable by the model.

This function converts the text into a tensor format, which is what the model can process, ensuring that the gradient is not computed, since we are only inferring.

What is Torch Compile and how do we use it?

Torch Compile is a feature introduced in PyTorch 2.0 to optimize models and make inference more efficient.

Benefits of Torch Compile

  • Reduce Overhead Mode: Ideal for small models, optimizing inference speed without excessively increasing memory usage.
  • Max Autotune: Although it takes longer to compile, it offers very fast execution and is recommended for larger models.

Practical use

To optimize our model:

optMode = torch.compile(model,  mode='reduce-overhead').

This command in PyTorch prepares our model for faster inference by reducing computational costs and taking advantage of CPU capabilities.

How to interpret the model output?

The predict function is also in charge of returning the label with the highest probability, using ArcMax on the tensor rows to find the highest value. The necessary adjustment is made (add 1) to align the numbering of the labels with the one we understand.

Practical example of inference

You can perform inference using the model with a text example. After passing the model to CPU to save resources, the text will be passed through the predict function and mapped to the DBpedia Label dictionary to get the prediction in clear words.

model.cpu()predicted_label = DBpediaLabel[predict(predict(model, example_text, text_pipeline)]print(predicted_label)

This will show us the expected category of the input text.

Recommendations and next steps

Inference provides an excellent benchmark of how the trained model behaves with real data. You can improve the model training by increasing the epochs, increasing the training examples or modifying the model architecture to achieve higher accuracy. Constant practice and hyperparameter tuning are essential for mastering this complex but fascinating area. Stay motivated, try different approaches and watch your model evolve - it's a journey full of learning and discovery!

Contributions 7

Questions 0

Sort by:

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

Hace unas clases me dejó de funcionar DBpedia y leí en uno de los aportes que se podía hacer con AG\_NEWS. Así que lo hice con AG\_NEWS. Estos son los AG\_NEWS\_labels: `AG_NEWS_labels = {    0:"World",    1:"Sports",    2:"Business",    3:"Sci/Tech"}`

En el primer intento el accuracy en el dataset de testing me dio 0.78 y la categoría del ejemplo 1 me dio “Company”. En el segundo intento subí el número de epochs a 4 y el learning rate a 0.3, dándome como resultado un accuracy del dataset de testing de 0.826 y la categoría del ejemplo cambió a “Village.”

Les dejo un ejemplo del dataset AG\_NEWS: 'The Race is On: Second Private Team Sets Launch Date for Human Spaceflight (SPACE.com) SPACE.com - TORONTO, Canada -- A second\\\team of rocketeers competing for the #36;10 million Ansari X Prize, a contest for\\\privately funded suborbital space flight, has officially announced the first\\\launch date for its manned rocket.' Pd: Su categoria es 'Sci/Tech'
En PyTorch 2.X, se introduce `torch.compile()`, que optimiza el modelo utilizando compiladores JIT (just-in-time) como parte de su proceso de inferencia y entrenamiento. Esto permite una ejecución más rápida al aplicar optimizaciones como fusión de operadores, eliminación de código redundante, y otras mejoras a nivel de rendimiento. La idea es que puedas aprovechar este tipo de optimización con solo una línea adicional en tu código. Aquí te muestro cómo puedes usar `torch.compile()` en la \*\*inferencia\*\* de un modelo de clasificación de texto con PyTorch 2.X. \### Paso 1: Configuración del modelo Supongamos que ya tienes un modelo entrenado de clasificación de texto como en el ejemplo anterior: ```python \# Modelo de clasificación de texto class TextClassificationModel(nn.Module): def \_\_init\_\_(self, vocab\_size, embed\_dim, num\_class): super(TextClassificationModel, self).\_\_init\_\_() self.embedding = nn.EmbeddingBag(vocab\_size, embed\_dim, sparse=True) self.fc = nn.Linear(embed\_dim, num\_class) self.init\_weights() def init\_weights(self): initrange = 0.5 self.embedding.weight.data.uniform\_(-initrange, initrange) self.fc.weight.data.uniform\_(-initrange, initrange) self.fc.bias.data.zero\_() def forward(self, text, offsets): embedded = self.embedding(text, offsets) return self.fc(embedded) \# Definimos el vocabulario y las dimensiones del modelo VOCAB\_SIZE = len(vocab) EMBED\_DIM = 64 NUM\_CLASS = len(set(\[label for (label, text) in train\_iter])) model = TextClassificationModel(VOCAB\_SIZE, EMBED\_DIM, NUM\_CLASS) ``` \### Paso 2: Optimización del modelo para inferencia con `torch.compile()` Con PyTorch 2.X, puedes mejorar la inferencia compilando el modelo de manera directa con `torch.compile()`: ```python import torch \# Compilación del modelo para optimización compiled\_model = torch.compile(model) \# Asumiendo que tienes un tensor de entrada para la inferencia \# Ejemplo: texto de entrada tokenizado y convertidos a tensores def predict(text, offsets): \# Colocamos el modelo en modo evaluación compiled\_model.eval() with torch.no\_grad(): # Desactivamos la actualización de gradientes output = compiled\_model(text, offsets) return output.argmax(1).item() \# Simulación de un tensor de texto de prueba example\_text = torch.tensor(\[1, 2, 3, 4, 5], dtype=torch.int64) # Un ejemplo tokenizado example\_offsets = torch.tensor(\[0], dtype=torch.int64) \# Inferencia optimizada prediccion = predict(example\_text, example\_offsets) print(f"Predicción: {prediccion}") ``` \### Paso 3: Entrenamiento también con `torch.compile()` Si también quisieras optimizar el \*\*entrenamiento\*\* del modelo, puedes envolver el modelo con `torch.compile()` de la misma forma: ```python \# Compilamos el modelo para optimizar el entrenamiento compiled\_model = torch.compile(model) \# Entrenamiento con el modelo compilado for epoch in range(epochs): train(train\_dataloader, compiled\_model, criterion, optimizer) acc = evaluate(test\_dataloader, compiled\_model, criterion) print(f'Epoch {epoch+1}: Test Accuracy: {acc:.4f}') ``` \### Paso 4: Consideraciones \- `torch.compile()` es especialmente útil para modelos complejos o para ejecutar el modelo en hardware acelerado como GPUs. \- No afecta la precisión del modelo, pero puede mejorar la velocidad de ejecución. \- El compilador JIT subyacente puede aplicar optimizaciones en tiempo de ejecución, lo que hace que la primera ejecución sea más lenta, pero las posteriores sean más rápidas. \### Conclusión Con PyTorch 2.X y `torch.compile()`, puedes fácilmente optimizar tu modelo tanto para \*\*inferencia\*\* como para \*\*entrenamiento\*\* con cambios mínimos en el código. Esta nueva característica facilita la integración de optimizaciones a nivel de compilador sin necesidad de reescribir todo el modelo o flujo de datos.
Está genial. Dado que, como a varios no me funcionó el DBPedia, y estoy usando el AG\_NEWS; le pedí a ChatGPT que me escribiera tres titulares de noticias, etiquetándolas con las categorías del dataset. Le pasé esos titulares al modelo y: 3/3.

Les dejo el diccionario de etiquetas:

DBpedia_label = {
                  1: 'Company',
                  2: 'EducationalInstitution',
                  3: 'Artist',
                  4: 'Athlete',
                  5: 'OfficeHolder',
                  6: 'MeanOfTransportation',
                  7: 'Building',
                  8: 'NaturalPlace',
                  9: 'Village',
                  10: 'Animal',
                  11: 'Plant',
                  12: 'Album',
                  13: 'Film',
                  14: 'WrittenWork'
                }

y el texto ejemplo:

ejemplo_1 = “Nithari is a village in the western part of the state of Uttar Pradesh India bordering on New Delli”

¿torch.compile tiene algún tipo de cache? percibo que la primera vez que se ejecuta la función predict, toma bastante mas tiempo que cuando se ejecuta una segunda o X vez.