Speed Comparison

Speed Comparison

Open In Colab

Safetensors is really fast. Let’s compare it against PyTorch by loading gpt2 weights. To run the GPU benchmark, make sure your machine has GPU or you have selected GPU runtime if you are using Google Colab.

Before you begin, make sure you have all the necessary libraries installed:

Copied

pip install safetensors huggingface_hub torch

Let’s start by importing all the packages that will be used:

Copied

>>> import os
>>> import datetime
>>> from huggingface_hub import hf_hub_download
>>> from safetensors.torch import load_file
>>> import torch

Download safetensors & torch weights for gpt2:

Copied

>>> sf_filename = hf_hub_download("gpt2", filename="model.safetensors")
>>> pt_filename = hf_hub_download("gpt2", filename="pytorch_model.bin")

CPU benchmark

Copied

This speedup is due to the fact that this library avoids unnecessary copies by mapping the file directly. It is actually possible to do on pure pytorch. The currently shown speedup was gotten on:

  • OS: Ubuntu 18.04.6 LTS

  • CPU: Intel(R) Xeon(R) CPU @ 2.00GHz

GPU benchmark

Copied

The speedup works because this library is able to skip unnecessary CPU allocations. It is unfortunately not replicable in pure pytorch as far as we know. The library works by memory mapping the file, creating the tensor empty with pytorch and calling cudaMemcpy directly to move the tensor directly on the GPU. The currently shown speedup was gotten on:

  • OS: Ubuntu 18.04.6 LTS.

  • GPU: Tesla T4

  • Driver Version: 460.32.03

  • CUDA Version: 11.2

Last updated