Search code examples
pythonamazon-s3pytorchboto3

How to save a Pytorch Model directly in s3 Bucket?


The title says it all - I want to save a pytorch model in an s3 bucket. What I tried was the following:

import boto3

s3 = boto3.client('s3')
saved_model = model.to_json()
output_model_file = output_folder + "pytorch_model.json"
s3.put_object(Bucket="power-plant-embeddings", Key=output_model_file, Body=saved_model)

Unfortunately this doesn't work, as .to_json() only works for tensorflow models. Does anyone know how to do it in pytorch?


Solution

  • Try serializing model to a buffer and write it to S3:

    buffer = io.BytesIO()
    torch.save(model, buffer)
    s3.put_object(Bucket="power-plant-embeddings", Key=output_model_file, Body=buffer.getvalue())