Safetensors documentation
속도 비교
시작하기
API
You are viewing main version, which requires installation from source. If you'd like
regular pip install, checkout the latest stable version (v0.5.0-rc.0).
속도 비교
Safetensors는 실제로 매우 빠릅니다. gpt2 가중치를 로드하여 PyTorch와 비교해 보겠습니다. GPU 벤치마크를 실행하려면, 머신에 GPU가 있는지 또는 Google Colab을 사용하는 경우 GPU runtime을 선택했는지 확인하세요.
시작하기 전에 필요한 라이브러리가 모두 설치되어 있는지 확인하세요:
pip install safetensors huggingface_hub torch
사용할 모든 패키지를 가져오기 시작해 보겠습니다:
>>> import os
>>> import datetime
>>> from huggingface_hub import hf_hub_download
>>> from safetensors.torch import load_file
>>> import torchgpt2의 safetensors & torch 가중치를 다운로드합니다:
>>> sf_filename = hf_hub_download("gpt2", filename="model.safetensors")
>>> pt_filename = hf_hub_download("gpt2", filename="pytorch_model.bin")CPU 벤치마크
>>> start_st = datetime.datetime.now()
>>> weights = load_file(sf_filename, device="cpu")
>>> load_time_st = datetime.datetime.now() - start_st
>>> print(f"Loaded safetensors {load_time_st}")
>>> start_pt = datetime.datetime.now()
>>> weights = torch.load(pt_filename, map_location="cpu")
>>> load_time_pt = datetime.datetime.now() - start_pt
>>> print(f"Loaded pytorch {load_time_pt}")
>>> print(f"on CPU, safetensors is faster than pytorch by: {load_time_pt/load_time_st:.1f} X")
Loaded safetensors 0:00:00.004015
Loaded pytorch 0:00:00.307460
on CPU, safetensors is faster than pytorch by: 76.6 X이러한 속도 향상은 이 라이브러리가 파일을 직접 매핑하여 불필요한 복사를 피하기 때문입니다. 실제로 pure pytorch에서도 가능합니다. 현재 표시된 속도 향상은 다음 환경에서 얻었습니다:
- OS: Ubuntu 18.04.6 LTS
- CPU: Intel(R) Xeon(R) CPU @ 2.00GHz
GPU 벤치마크
>>> # This is required because this feature hasn't been fully verified yet, but
>>> # it's been tested on many different environments
>>> os.environ["SAFETENSORS_FAST_GPU"] = "1"
>>> # CUDA startup out of the measurement
>>> torch.zeros((2, 2)).cuda()
>>> start_st = datetime.datetime.now()
>>> weights = load_file(sf_filename, device="cuda:0")
>>> load_time_st = datetime.datetime.now() - start_st
>>> print(f"Loaded safetensors {load_time_st}")
>>> start_pt = datetime.datetime.now()
>>> weights = torch.load(pt_filename, map_location="cuda:0")
>>> load_time_pt = datetime.datetime.now() - start_pt
>>> print(f"Loaded pytorch {load_time_pt}")
>>> print(f"on GPU, safetensors is faster than pytorch by: {load_time_pt/load_time_st:.1f} X")
Loaded safetensors 0:00:00.165206
Loaded pytorch 0:00:00.353889
on GPU, safetensors is faster than pytorch by: 2.1 X속도 향상이 가능한 이유는 이 라이브러리가 불필요한 CPU 할당을 건너뛸 수 있기 때문입니다. 현재까지 알려진 바로는 순수 PyTorch에서는 이를 재현할 수 없습니다. 이 라이브러리는 파일을 메모리 매핑하고, PyTorch로 빈 텐서를 생성한 뒤, cudaMemcpy를 직접 호출하여 텐서를 GPU로 직접 이동하는 방식으로 동작합니다.
현재 표시된 속도 향상은 다음 환경에서 측정되었습니다:
- OS: Ubuntu 18.04.6 LTS
- GPU: Tesla T4
- Driver Version: 460.32.03
- CUDA 버전: 11.2