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
10 Hrs
21 Min
13 Seg

Carga de modelo de PyTorch con torch.load()

23/24
Resources

How to load a checkpoint in a new model?

Loading a pre-trained model is a key skill when working in machine learning, especially when we want to add efficiency to our workflow. In this segment, we will learn how to leverage the checkpoints we have previously saved to initialize a new model and optimizer in PyTorch, ready for additional training or inference!

How to load the checkpoint of our model?

First we must download the checkpoint from the JobinFace Hub, where we have previously uploaded our weights. Once in our Google Colab environment, we use PyTorch's load function to load this checkpoint. Here is the necessary code snippet:

checkpoint = torch.load('Weights/modelCheckpoint.pth').

How to initialize the new model?

Initializing the new model requires replicating the configuration of the original model. This includes specifying the number of classes, the vocabulary size and the embedding size. All of these must be identical to the original model to ensure that the loaded weights match properly.

num_classes = ...vocabulary_size = ...embedding_size = ...model2 = MyModel(num_classes, vocabulary_size, embedding_size)

Why do we need a new optimizer?

The optimizer is essential to adjust the model weights during training. Like the model, we must initialize a new optimizer and then load its states from the checkpoint.

optimizer2 = torch.optim.SGD(model2.parameters(),  lr=0.2)

How do we ensure that our model and optimizer apply the correct weights?

Load the weights into the model

We use the load_state_dict method to load the model state from the checkpoint dictionary:

model2.load_state_dict(checkpoint['model_state_dict'])

Fixing errors with the optimizer

Sometimes, we may encounter errors when trying to load the optimizer state. If this happens, let's verify that we saved the optimizer state properly. If not, let's go back, correct it and upload the corrected version to the JobinFace Hub.

optimizer2.load_state_dict(checkpoint['optimizer_state_dict'])

How do we handle the rest of the workflow?

If we are going to continue the training, we will need to define the epoch state and the loss. These are also stored in the checkpoint and we can retrieve them in a similar way.

epoch2 = checkpoint['epoch']loss2 = checkpoint['loss']

How do we perform inference with the model loaded?

Preparation for inference

If the goal is inference, we generally take the model to the CPU, especially if the GPU is not needed, which is common for simple inference tasks.

model2.to('cpu')

Testing with a new example

It is always advisable to test our model with a new text to confirm that everything is set up correctly. We use a text pipeline to convert the text into a format that the model can process.

example = "text about garlic trees"result = model2(example)print(result)

By following these steps, we will ensure that our model is ready to perform inference with the previously trained weights and store any future adjustments directly in the JobinFace Hub. Continuing to experiment and tweak the model is essential to get the most out of it - keep discovering and learning new ways to apply this knowledge!

Contributions 5

Questions 0

Sort by:

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

Para poder hacer inferencia con el nuevo modelo faltaron algunos detalles:
|
Es necesario guardar el archivo de vocabulario para usarlo en el nuevo entorno.

# guardar vocabulario creado con el dataset
torch.save(vocab, 'vocab.pt')

#carga del vocabulario:
vocab = torch.load('vocab.pt')

E importar el tokenizador con el que fue creado para definir el text_pipeline

from torchtext.data.utils import get_tokenizer

tokenizer = get_tokenizer("TU_TOKENIZADOR")

# Definir text pipeline
text_pipeline = lambda x: vocab(tokenizer(x))

Y despu茅s de agregar esto podemos hacer inferencia con el modelo.

Escrib铆 un tutorial con un enlace a un colab en el que muestro la manera de cargar el modelo ya entrenado y hacer predicciones con 茅ste.

Tutorial

Al final no se est谩 haciendo la predicci贸n con el model_cpu, ya que la funci贸n predict() utiliza el modelo entrenado desde el principio, creo que una buena forma que podr铆amos solucionar esto, es hacer que a las funciones como predic(), train(), eval(), etc. reciban como par谩metro el modelo que se quiere utilizar.

No s茅 a qui茅n m谩s le suceda, pero el ejemplo 2 no me dice que es categor铆a animal, jaja. Por cierto la manera correcta de hacer el predict es:

model = modelo2.to("cpu")

ejemplo = "Axolotls are animals and animals and tigers and lions animals animals ."

def inference(text, texto_pipeline, model):
  with torch.no_grad():
    model.eval()
    text = torch.tensor(texto_pipeline(text))
    opt_mod = torch.compile(model, mode = 'reduce-overhead') 
    output = opt_mod(text, torch.tensor([0])) 
    return output.argmax(1).item() + 1 

print(f"El ejemplo es de la categoria {DBpedia_label[inference(ejemplo, texto_pipeline, model)]}")
La funci贸n `torch.load()` se utiliza en PyTorch para cargar un modelo previamente guardado. Esta funci贸n puede cargar tanto el estado de los par谩metros del modelo (usando `state\_dict()`) como el modelo completo, dependiendo de c贸mo se haya guardado el archivo. Aqu铆 te explico las dos formas m谩s comunes de cargar un modelo en PyTorch: \### 1. Cargar solo el `state\_dict()` Cuando guardas solo los pesos y par谩metros del modelo (usando `torch.save(model.state\_dict())`), puedes cargarlo y reinstanciar el modelo de la siguiente manera: \#### Guardar el `state\_dict()` del modelo Supongamos que tienes un modelo llamado `TextClassificationModel`: ```python import torch \# Definir el modelo (debe coincidir con la arquitectura original) model = TextClassificationModel(VOCAB\_SIZE, EMBED\_DIM, NUM\_CLASS) \# Guardar solo los pesos (state\_dict) torch.save(model.state\_dict(), "mi\_modelo.pth") ``` \#### Cargar el `state\_dict()` Para cargar los pesos guardados y asignarlos a una nueva instancia del modelo: ```python import torch \# Reinstanciar el modelo (debe tener la misma arquitectura) model\_cargado = TextClassificationModel(VOCAB\_SIZE, EMBED\_DIM, NUM\_CLASS) \# Cargar el state\_dict en el modelo model\_cargado.load\_state\_dict(torch.load("mi\_modelo.pth")) \# Poner el modelo en modo de evaluaci贸n (opcional pero recomendado para inferencias) model\_cargado.eval() ``` Es importante que la estructura del modelo que definas al cargar el `state\_dict()` sea id茅ntica a la del modelo que usaste al guardar los pesos. \### 2. Cargar el modelo completo Tambi茅n puedes guardar el modelo completo, incluyendo tanto la arquitectura como los pesos. Para hacerlo, necesitas guardar la instancia completa del modelo: \#### Guardar el modelo completo ```python import torch \# Guardar el modelo completo torch.save(model, "mi\_modelo\_completo.pth") ``` \#### Cargar el modelo completo Para cargar el modelo completo en otro script o entorno: ```python import torch \# Cargar el modelo completo (incluyendo la arquitectura y los pesos) model\_cargado = torch.load("mi\_modelo\_completo.pth") \# Poner en modo de evaluaci贸n model\_cargado.eval() ``` \### Diferencias entre ambos m茅todos \- \*\*Cargar el `state\_dict()`\*\*: Este m茅todo es m谩s flexible y es el m谩s recomendado en la mayor铆a de los casos, ya que te permite cargar solo los pesos en un modelo predefinido. Esto puede ser 煤til si cambias algunos aspectos de tu c贸digo o realizas ajustes en la arquitectura. \- \*\*Cargar el modelo completo\*\*: Este m茅todo guarda tanto la arquitectura del modelo como los pesos. Es 煤til si necesitas cargar todo sin tener que definir la arquitectura del modelo nuevamente, pero es menos flexible si tu c贸digo cambia. \### Consideraciones al usar `torch.load()` \- \*\*Dispositivos\*\*: Si los modelos fueron entrenados en GPU y deseas cargarlos en CPU, o viceversa, aseg煤rate de especificar el dispositivo al cargar: \- Para cargar en CPU: ```python model = torch.load("mi\_modelo\_completo.pth", map\_location=torch.device('cpu')) ``` \- Para cargar en GPU (si tienes disponible): ```python model = torch.load("mi\_modelo\_completo.pth", map\_location=torch.device('cuda')) ``` \### Ejemplo completo de carga de un modelo con `torch.load()` ```python import torch \# Definir el modelo (en caso de usar state\_dict) model\_cargado = TextClassificationModel(VOCAB\_SIZE, EMBED\_DIM, NUM\_CLASS) \# Cargar los pesos guardados model\_cargado.load\_state\_dict(torch.load("mi\_modelo.pth", map\_location=torch.device('cpu'))) \# Poner el modelo en modo de evaluaci贸n para inferencias model\_cargado.eval() \# Realizar una inferencia (ejemplo con datos de entrada) texto = \["Ejemplo de texto para clasificar"] tokens = tokenizador(texto\[0]) # Suponiendo que tienes un tokenizador ids = torch.tensor(\[vocab\[token] for token in tokens]) # Convertir a IDs \# Hacer la predicci贸n output = model\_cargado(ids.unsqueeze(0)) # A帽adir dimensi贸n de batch prediccion = output.argmax(1).item() # Obtener la clase predicha print("Clase predicha:", prediccion) ``` Con estos pasos, puedes cargar un modelo previamente entrenado y usarlo para realizar inferencias o continuar con el entrenamiento.