Exporting AWD_LSTM to PyTorch for serving

Hello all,

I’m wondering if anyone has any experience exporting trained AWD_LSTM models from FastAI to PyTorch for serving. I’m working in a situation where I need as small a serving image as possible so I’m trying to trim down my dependencies.

So far I’ve been prowling the forums and this is what I have.

learn = load_learner("path")
torch.save(learn.model.state_dict(), 'path')

config = {"my model params"}

model = torch.nn.LSTM(**config)
model.load_state_dict(torch.load('path'))
model.eval()

This gives me a bunch of key errors because my LSTM and AWD_LSTM are obviously different creatures.

Let me know if anyone has any experience with this. I’ve trained some great models with FastAI but now I’m struggling to make it to production given my circumstances.

Yeah you need to use the same AWD_LSTM model in fastai. As you can see, it is defined here:

So in your code you will also have to include the same definitions and you then can load your model weights.

Thanks for your response!

When going through the source code I have a hard time determining where the PyTorch ends and the FastAI begins. Does the AWD_LSTM class itself yield a valid PyTorch model? Is it more or less just as easy as:

# Disclaimer: This is pseudo code and won't work
model = AWD_LSTM(**model_params)
model.load_state_dict(torch.load('test_model.pth'))
model.eval()

I am not sure myself, there might be some fastai-specific functions involved in the implementation but it’s unlikely. I would test it by copying and pasting the code into your script, running in a PyTorch-only environment, and see which functions it complains about as missing…