### Description This PR includes documentation updates, providing step-by-step instructions on how to implement the ModuleWithLoss wrapper in a different codebase. The documentation outlines the necessary code changes and offers customization options based on specific requirements. --------- Co-authored-by: Adam Louly <adamlouly@microsoft.com@orttrainingdev9.d32nl1ml4oruzj4qz3bqlggovf.px.internal.cloudapp.net>
4.3 KiB
ONNX Runtime ModuleWithLoss Wrapper
This document provides instructions on implementing a wrapper similar to the ModuleWithLoss Wrapper in Optimum. By implementing this wrapper, you can compute the loss inside ONNX Runtime (ORT), enabling you to leverage additional optimizations such as label sparsity optimization.
Note: The adaptation described below is not necessary for all cases. It is only needed in specific scenarios, which we will clarify below:
- When the loss is not computed in the model's forward path.
- When the model's forward path computes the loss but also returns other outputs that are not needed for subsequent computations.
In the first case, if the loss is not computed in the model's forward pass, ONNX Runtime (ORT) cannot track the loss computation in the ONNX graph.
In the second case, if the model's forward pass computes the loss but also returns additional tensors that are not needed for subsequent computations, using the original model directly with the ORT wrapper can lead to unnecessary memory usage on the CUDA device during backward computations.
Implementation Steps
Follow these steps to create your own ModuleWithLoss for computing loss inside ONNX Runtime:
Certainly! Here are the steps to fit the provided example:
Step 1: Define ModuleWithLoss Class
- Create a class named
ModuleWithLossthat extendsnn.Module. - Implement the
__init__method to initialize the wrapper with the original model. - Implement the
forwardmethod to perform the forward pass of the model and compute the loss. - Use the model's
forwardmethod to compute the logits. - Compute the loss between the logits and the labels.
- Return the computed loss.
class ModuleWithLoss(nn.Module):
def __init__(self, model):
super().__init__()
self.model = model
def forward(self, inputs, labels):
# Perform the forward pass of the model
lm_logits = self.model(inputs)
# Compute the cross-entropy loss
loss = nn.CrossEntropyLoss()(lm_logits, labels)
return loss
Step 2: Define a sample training script
Define PretrainedModel Class
- Implement the
PretrainedModelclass by extendingnn.Module. - Define the
forwardmethod insidePretrainedModelto perform the forward pass of the model. - Use the model's transformer layers and head layers to compute the logits.
- Return the logits as the output of the
forwardmethod.
Training Loop
- Create an instance of
PretrainedModelas the original model. - Create an instance of
ModuleWithLossby passing the original model as an argument. - Initialize the optimizer for training.
- Enter the training loop and iterate over the training data.
- Zero the gradients of the optimizer.
- Compute the forward pass and cross-entropy loss by calling the
forwardmethod of theModuleWithLossinstance and passing the inputs and labels. - Perform the backward pass by calling
loss.backward()and optimization step by callingoptimizer.step().
Make sure to fill in the appropriate details and customize the code as per your specific requirements and implementation.
# Define the model architecture
class PretrainedModel(nn.Module):
...
def forward(self, input_ids, attention_mask):
...
transformer_outputs = self.transformer(
input_ids,
attention_mask=attention_mask,
...
)
hidden_states = transformer_outputs[0]
lm_logits = self.lm_head(hidden_states)
return lm_logits
# Training loop
model = PretrainedModel(...)
model = ModuleWithLoss(model)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
model = ORTModule(model)
for inputs, labels in dataloader:
optimizer.zero_grad()
# Compute the forward pass and cross-entropy loss
loss = model(inputs, labels)
# Backward pass and optimization step
loss.backward()
optimizer.step()
By following these steps, you can create a wrapper that computes the loss inside ONNX Runtime (ORT) using the ModuleWithLoss class and the compute_loss function. Make sure to customize the code snippets according to your specific codebase and requirements.
Please note that the steps provided above are specific to the example I provided, and you may need to adapt them based on your own implementation and requirements.